From b89e433eb57584023e3939553df4f45c314920a6 Mon Sep 17 00:00:00 2001 From: lemondead1 Date: Sun, 30 Oct 2022 03:42:08 +0300 Subject: [PATCH 01/10] Fixed #731 --- .../client/gui2/inventory/GuiSubmitStation.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java b/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java index 4cfbf6d61..e03edb2fd 100644 --- a/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java +++ b/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java @@ -157,8 +157,10 @@ public void onButtonClick() @Override public void onButtonClick() { - tile.setupTask(QuestingAPI.getQuestingUUID(mc.player), quests.get(selQuest).getValue(), tasks.get(selTask).getValue()); - NetStationEdit.setupStation(tile.getPos(), selQuest, selTask); + DBEntry selQuestEntry = quests.get(selQuest); + DBEntry selTaskEntry = tasks.get(selTask); + tile.setupTask(QuestingAPI.getQuestingUUID(mc.player), selQuestEntry.getValue(), selTaskEntry.getValue()); + NetStationEdit.setupStation(tile.getPos(), selQuestEntry.getID(), selTaskEntry.getID()); refreshTaskPanel(); } }; From fe59750864d22d2b2e11bf3038fc24be7a73122a Mon Sep 17 00:00:00 2001 From: Olexy Date: Fri, 1 Sep 2023 01:54:23 +0300 Subject: [PATCH 02/10] Moved to a newer gradle version, reformatted the whole project, partially rewrote TileSubmitStation, changed IFluidTask and IItemTask apis (sorry), added IEnergyTask, fixed some TileSubmitStation networking bugs. --- build.gradle | 101 +- gradle.properties | 10 +- gradle/wrapper/gradle-wrapper.properties | 2 +- settings.gradle | 8 + .../java/betterquesting/api/api/ApiKey.java | 4 +- .../betterquesting/api/api/ApiReference.java | 40 +- .../betterquesting/api/api/QuestingAPI.java | 112 +- .../api/client/gui/misc/INeedsRefresh.java | 5 +- .../api/client/gui/misc/IVolatileScreen.java | 2 +- .../api/client/importers/IImportRegistry.java | 8 +- .../api/client/importers/IImporter.java | 16 +- .../api/client/toolbox/IToolRegistry.java | 11 +- .../api/client/toolbox/IToolboxTool.java | 74 +- .../betterquesting/api/enums/EnumLogic.java | 55 +- .../api/enums/EnumPartyStatus.java | 9 +- .../api/enums/EnumQuestState.java | 11 +- .../api/enums/EnumQuestVisibility.java | 15 +- .../api/events/DatabaseEvent.java | 84 +- .../api/events/NbtDocEvent.java | 47 +- .../betterquesting/api/events/QuestEvent.java | 75 +- .../betterquesting/api/misc/ICallback.java | 5 +- .../betterquesting/api/nbt_doc/INbtDoc.java | 23 +- .../api/nbt_doc/NbtDocBasic.java | 79 +- .../api/network/IPacketRegistry.java | 26 +- .../api/network/IPacketSender.java | 25 +- .../api/network/QuestingPacket.java | 36 +- .../java/betterquesting/api/package-info.java | 1 + .../api/placeholders/EntityPlaceholder.java | 80 +- .../api/placeholders/FluidPlaceholder.java | 15 +- .../api/placeholders/ItemPlaceholder.java | 98 +- .../placeholders/PlaceholderConverter.java | 154 +- .../rewards/FactoryRewardPlaceholder.java | 53 +- .../rewards/RewardPlaceholder.java | 113 +- .../tasks/FactoryTaskPlaceholder.java | 53 +- .../placeholders/tasks/TaskPlaceholder.java | 171 +- .../api/properties/IPropertyContainer.java | 23 +- .../api/properties/IPropertyType.java | 15 +- .../api/properties/NativeProps.java | 139 +- .../properties/basic/PropertyTypeBase.java | 42 +- .../properties/basic/PropertyTypeBoolean.java | 60 +- .../properties/basic/PropertyTypeByte.java | 46 +- .../properties/basic/PropertyTypeDouble.java | 46 +- .../properties/basic/PropertyTypeEnum.java | 68 +- .../properties/basic/PropertyTypeFloat.java | 46 +- .../properties/basic/PropertyTypeInteger.java | 46 +- .../basic/PropertyTypeItemStack.java | 63 +- .../properties/basic/PropertyTypeLong.java | 46 +- .../properties/basic/PropertyTypeString.java | 50 +- .../betterquesting/api/questing/IQuest.java | 68 +- .../api/questing/IQuestDatabase.java | 5 +- .../api/questing/IQuestLine.java | 17 +- .../api/questing/IQuestLineDatabase.java | 28 +- .../api/questing/IQuestLineEntry.java | 34 +- .../api/questing/party/IParty.java | 29 +- .../api/questing/party/IPartyDatabase.java | 11 +- .../api/questing/rewards/IReward.java | 29 +- .../api/questing/tasks/IEnergyTask.java | 10 + .../api/questing/tasks/IFluidTask.java | 8 +- .../api/questing/tasks/IItemTask.java | 8 +- .../api/questing/tasks/ITask.java | 39 +- .../api/storage/BQ_Settings.java | 25 +- .../api/storage/ILifeDatabase.java | 12 +- .../api/storage/INameCache.java | 29 +- .../api/storage/IQuestSettings.java | 8 +- .../api/utils/BigItemStack.java | 298 ++- .../api/utils/FileExtensionFilter.java | 25 +- .../api/utils/ItemComparison.java | 473 +++-- .../betterquesting/api/utils/JsonHelper.java | 560 +++--- .../api/utils/NBTConverter.java | 705 ++++--- .../betterquesting/api/utils/RenderUtils.java | 1661 ++++++++--------- .../cache/CapabilityProviderQuestCache.java | 93 +- .../betterquesting/api2/cache/QuestCache.java | 486 +++-- .../api2/client/gui/GuiContainerCanvas.java | 799 ++++---- .../api2/client/gui/GuiScreenCanvas.java | 779 ++++---- .../api2/client/gui/GuiScreenTest.java | 87 +- .../api2/client/gui/IScene.java | 24 +- .../api2/client/gui/SceneController.java | 47 +- .../client/gui/controls/IFieldFilter.java | 11 +- .../client/gui/controls/IPanelButton.java | 16 +- .../api2/client/gui/controls/IValueIO.java | 19 +- .../api2/client/gui/controls/PanelButton.java | 507 +++-- .../client/gui/controls/PanelButtonQuest.java | 333 ++-- .../gui/controls/PanelButtonStorage.java | 69 +- .../client/gui/controls/PanelTextField.java | 1396 +++++++------- .../gui/controls/callbacks/CallbackMulti.java | 28 +- .../callbacks/CallbackNBTPrimitive.java | 195 +- .../callbacks/CallbackNBTTagString.java | 54 +- .../controls/filters/FieldFilterNumber.java | 178 +- .../controls/filters/FieldFilterString.java | 65 +- .../client/gui/controls/io/FloatSimpleIO.java | 145 +- .../client/gui/controls/io/ValueFuncIO.java | 59 +- .../client/gui/events/CommonPanelEvents.java | 14 +- .../client/gui/events/IPEventListener.java | 5 +- .../client/gui/events/PEventBroadcaster.java | 103 +- .../api2/client/gui/events/PEventEntry.java | 47 +- .../api2/client/gui/events/PanelEvent.java | 36 +- .../client/gui/events/types/PEventButton.java | 34 +- .../client/gui/events/types/PEventParty.java | 43 +- .../client/gui/events/types/PEventQuest.java | 43 +- .../api2/client/gui/help/HelpRegistry.java | 52 +- .../api2/client/gui/help/HelpTopic.java | 55 +- .../client/gui/misc/ComparatorGuiDepth.java | 19 +- .../api2/client/gui/misc/GuiAlign.java | 172 +- .../api2/client/gui/misc/GuiPadding.java | 100 +- .../api2/client/gui/misc/GuiRectLerp.java | 200 +- .../api2/client/gui/misc/GuiRectangle.java | 147 +- .../api2/client/gui/misc/GuiTransform.java | 238 ++- .../api2/client/gui/misc/IGuiRect.java | 28 +- .../api2/client/gui/misc/ProxyRect.java | 122 +- .../api2/client/gui/panels/CanvasEmpty.java | 346 ++-- .../client/gui/panels/CanvasResizeable.java | 417 ++--- .../client/gui/panels/CanvasTextured.java | 53 +- .../api2/client/gui/panels/IGuiCanvas.java | 24 +- .../api2/client/gui/panels/IGuiPanel.java | 38 +- .../api2/client/gui/panels/bars/IBarFill.java | 14 +- .../client/gui/panels/bars/IScrollBar.java | 19 +- .../client/gui/panels/bars/PanelHBarFill.java | 249 ++- .../gui/panels/bars/PanelHScrollBar.java | 361 ++-- .../client/gui/panels/bars/PanelVBarFill.java | 249 ++- .../gui/panels/bars/PanelVScrollBar.java | 357 ++-- .../panels/content/PanelEntityPreview.java | 241 ++- .../gui/panels/content/PanelFluidSlot.java | 73 +- .../gui/panels/content/PanelGeneric.java | 197 +- .../gui/panels/content/PanelItemSlot.java | 217 ++- .../client/gui/panels/content/PanelLine.java | 169 +- .../panels/content/PanelPlayerPortrait.java | 243 ++- .../gui/panels/content/PanelTextBox.java | 464 +++-- .../panels/lists/CanvasCullingManager.java | 343 ++-- .../panels/lists/CanvasEntityDatabase.java | 83 +- .../gui/panels/lists/CanvasFileDirectory.java | 112 +- .../gui/panels/lists/CanvasFluidDatabase.java | 93 +- .../gui/panels/lists/CanvasHoverTray.java | 221 +-- .../gui/panels/lists/CanvasItemDatabase.java | 156 +- .../gui/panels/lists/CanvasQuestDatabase.java | 37 +- .../gui/panels/lists/CanvasQuestLine.java | 331 ++-- .../gui/panels/lists/CanvasScrolling.java | 1068 +++++------ .../client/gui/panels/lists/CanvasSearch.java | 183 +- .../api2/client/gui/popups/PopChoice.java | 180 +- .../client/gui/popups/PopContextMenu.java | 257 ++- .../api2/client/gui/popups/PopMessage.java | 147 +- .../gui/resources/colors/GuiColorPulse.java | 139 +- .../resources/colors/GuiColorSequence.java | 104 +- .../gui/resources/colors/GuiColorStatic.java | 107 +- .../resources/colors/GuiColorTransition.java | 148 +- .../gui/resources/colors/IGuiColor.java | 22 +- .../factories/colors/FactoryColorPulse.java | 70 +- .../colors/FactoryColorSequence.java | 81 +- .../factories/colors/FactoryColorStatic.java | 60 +- .../factories/lines/FactoryLineTaxiCab.java | 68 +- .../factories/lines/FactorySimpleLine.java | 62 +- .../textures/FactoryColorTexture.java | 79 +- .../textures/FactoryEmptyTexture.java | 42 +- .../textures/FactoryLayeredTexture.java | 78 +- .../textures/FactoryPolyTextureC.java | 104 +- .../textures/FactoryPolyTextureR.java | 90 +- .../textures/FactorySimpleTexture.java | 68 +- .../textures/FactorySlicedTexture.java | 88 +- .../textures/FactorySlideShowTexture.java | 81 +- .../client/gui/resources/lines/BoxLine.java | 94 +- .../gui/resources/lines/GuiLineSequence.java | 47 +- .../client/gui/resources/lines/IGuiLine.java | 5 +- .../gui/resources/lines/LineTaxiCab.java | 162 +- .../gui/resources/lines/SimpleLine.java | 78 +- .../gui/resources/textures/ColorTexture.java | 103 +- .../gui/resources/textures/EmptyTexture.java | 41 +- .../gui/resources/textures/FluidTexture.java | 199 +- .../resources/textures/GuiTextureColored.java | 72 +- .../gui/resources/textures/IGuiTexture.java | 15 +- .../gui/resources/textures/ItemTexture.java | 152 +- .../resources/textures/LayeredTexture.java | 72 +- .../resources/textures/OreDictTexture.java | 121 +- .../gui/resources/textures/PolyTexture.java | 260 ++- .../gui/resources/textures/SimpleTexture.java | 138 +- .../gui/resources/textures/SlicedTexture.java | 497 ++--- .../resources/textures/SlideShowTexture.java | 104 +- .../api2/client/gui/themes/GuiKey.java | 36 +- .../api2/client/gui/themes/IGuiTheme.java | 30 +- .../api2/client/gui/themes/IResourceReg.java | 15 +- .../client/gui/themes/IThemeRegistry.java | 64 +- .../gui/themes/gui_args/GArgsCallback.java | 20 +- .../gui/themes/gui_args/GArgsFileBrowser.java | 29 +- .../client/gui/themes/gui_args/GArgsNBT.java | 16 +- .../client/gui/themes/gui_args/GArgsNone.java | 20 +- .../gui/themes/presets/PresetColor.java | 189 +- .../client/gui/themes/presets/PresetGUIs.java | 26 +- .../client/gui/themes/presets/PresetIcon.java | 436 +++-- .../client/gui/themes/presets/PresetLine.java | 81 +- .../gui/themes/presets/PresetTexture.java | 361 ++-- .../api2/client/toolbox/IToolTab.java | 15 +- .../betterquesting/api2/package-info.java | 1 + .../api2/registry/FunctionRegistry.java | 89 +- .../api2/registry/IFactory.java | 8 +- .../api2/registry/IFactoryData.java | 5 +- .../api2/registry/IRegistry.java | 18 +- .../api2/registry/SimpleRegistry.java | 53 +- .../betterquesting/api2/storage/DBEntry.java | 83 +- .../api2/storage/IDatabase.java | 36 +- .../api2/storage/IDatabaseNBT.java | 4 +- .../api2/storage/INBTPartial.java | 8 +- .../api2/storage/INBTProgress.java | 8 +- .../api2/storage/INBTSaveLoad.java | 8 +- .../api2/storage/SimpleDatabase.java | 226 ++- .../api2/supporter/MCLinkAPI.java | 187 +- .../api2/supporter/RgbTexture.java | 45 +- .../api2/supporter/SupporterAPI.java | 422 ++--- .../api2/supporter/SupporterDB.java | 88 +- .../api2/supporter/SupporterEntry.java | 38 +- .../supporter/mc_link/McLinkEndpoint.java | 22 +- .../supporter/theme_dlc/CatalogueEntry.java | 112 +- .../supporter/theme_dlc/ThemeCatalogue.java | 30 +- .../supporter/theme_dlc/ThemeRepository.java | 47 +- .../api2/utils/BQThreadedIO.java | 81 +- .../api2/utils/BqFontRenderer.java | 479 +++-- .../api2/utils/EntityPlayerPreview.java | 98 +- .../api2/utils/ParticipantInfo.java | 148 +- .../api2/utils/QuestLineSorter.java | 26 +- .../api2/utils/QuestTranslation.java | 26 +- .../blocks/BlockSubmitStation.java | 92 +- .../betterquesting/blocks/SSItemHandler.java | 116 -- .../blocks/TileSubmitStation.java | 905 +++++---- .../betterquesting/client/BQ_Keybindings.java | 20 +- .../client/CreativeTabQuesting.java | 39 +- .../client/QuestNotification.java | 203 +- .../client/gui/GuiBQConfig.java | 23 +- .../betterquesting/client/gui2/GuiHome.java | 289 +-- .../betterquesting/client/gui2/GuiQuest.java | 628 +++---- .../client/gui2/GuiQuestHelp.java | 126 +- .../client/gui2/GuiQuestLines.java | 806 ++++---- .../betterquesting/client/gui2/GuiThemes.java | 263 +-- .../client/gui2/editors/GuiFileBrowser.java | 417 ++--- .../client/gui2/editors/GuiImporters.java | 264 +-- .../gui2/editors/GuiPrerequisiteEditor.java | 452 ++--- .../client/gui2/editors/GuiQuestEditor.java | 447 ++--- .../gui2/editors/GuiQuestLineAddRemove.java | 488 ++--- .../gui2/editors/GuiQuestLinesEditor.java | 647 +++---- .../client/gui2/editors/GuiRewardEditor.java | 347 ++-- .../client/gui2/editors/GuiTaskEditor.java | 347 ++-- .../client/gui2/editors/GuiTextEditor.java | 167 +- .../gui2/editors/designer/GuiDesigner.java | 278 ++- .../editors/designer/PanelToolController.java | 551 +++--- .../gui2/editors/nbt/GuiEntitySelection.java | 210 ++- .../gui2/editors/nbt/GuiFluidSelection.java | 321 ++-- .../gui2/editors/nbt/GuiItemSelection.java | 393 ++-- .../client/gui2/editors/nbt/GuiNbtAdd.java | 370 ++-- .../client/gui2/editors/nbt/GuiNbtEditor.java | 187 +- .../client/gui2/editors/nbt/GuiNbtType.java | 147 +- .../gui2/editors/nbt/PanelScrollingNBT.java | 846 +++++---- .../nbt/callback/NbtEntityCallback.java | 47 +- .../nbt/callback/NbtFluidCallback.java | 47 +- .../editors/nbt/callback/NbtItemCallback.java | 47 +- .../inventory/ContainerSubmitStation.java | 316 ++-- .../gui2/inventory/GuiSubmitStation.java | 535 +++--- .../client/gui2/party/GuiPartyCreate.java | 326 ++-- .../client/gui2/party/GuiPartyInvite.java | 225 +-- .../client/gui2/party/GuiPartyManage.java | 409 ++-- .../betterquesting/client/gui3/GuiStatus.java | 187 +- .../client/importers/ImportedQuestLines.java | 211 +-- .../client/importers/ImportedQuests.java | 123 +- .../client/importers/ImporterRegistry.java | 49 +- .../renderer/EntityPlaceholderRenderer.java | 35 +- .../renderer/PlaceholderRenderFactory.java | 16 +- .../client/themes/ResourceRegistry.java | 99 +- .../client/themes/ResourceTheme.java | 308 ++- .../client/themes/ThemeRegistry.java | 587 +++--- .../client/toolbox/PanelTabMain.java | 247 +-- .../client/toolbox/ToolboxRegistry.java | 54 +- .../client/toolbox/ToolboxTabMain.java | 185 +- .../toolbox/tools/ToolboxToolComplete.java | 205 +- .../client/toolbox/tools/ToolboxToolCopy.java | 454 +++-- .../toolbox/tools/ToolboxToolDelete.java | 199 +- .../toolbox/tools/ToolboxToolFrame.java | 209 +-- .../client/toolbox/tools/ToolboxToolGrab.java | 378 ++-- .../client/toolbox/tools/ToolboxToolIcon.java | 202 +- .../client/toolbox/tools/ToolboxToolLink.java | 391 ++-- .../client/toolbox/tools/ToolboxToolNew.java | 252 ++- .../client/toolbox/tools/ToolboxToolOpen.java | 158 +- .../toolbox/tools/ToolboxToolRemove.java | 225 +-- .../toolbox/tools/ToolboxToolReset.java | 203 +- .../toolbox/tools/ToolboxToolScale.java | 467 +++-- .../client/ui_builder/CanvasBuilderUtil.java | 5 - .../client/ui_builder/ComponentPanel.java | 206 +- .../client/ui_builder/ComponentRegistry.java | 102 +- .../client/ui_builder/GuiBuilderMain.java | 1510 +++++++-------- .../commands/BQ_CommandAdmin.java | 271 ++- .../commands/BQ_CommandDebug.java | 74 +- .../commands/BQ_CommandUser.java | 265 ++- .../commands/QuestCommandBase.java | 171 +- .../commands/admin/QuestCommandComplete.java | 169 +- .../commands/admin/QuestCommandDefaults.java | 272 ++- .../commands/admin/QuestCommandDelete.java | 150 +- .../commands/admin/QuestCommandEdit.java | 136 +- .../commands/admin/QuestCommandHardcore.java | 134 +- .../commands/admin/QuestCommandLives.java | 290 ++- .../commands/admin/QuestCommandPurge.java | 95 +- .../commands/admin/QuestCommandReset.java | 243 ++- .../commands/user/QuestCommandHelp.java | 71 +- .../commands/user/QuestCommandRefresh.java | 80 +- .../commands/user/QuestCommandSPHardcore.java | 81 +- .../betterquesting/core/BetterQuesting.java | 160 +- .../betterquesting/core/ExpansionLoader.java | 59 +- .../betterquesting/core/RegEventHandler.java | 165 +- .../core/proxies/ClientProxy.java | 195 +- .../core/proxies/CommonProxy.java | 38 +- .../handlers/ConfigGuiFactory.java | 41 +- .../handlers/ConfigHandler.java | 46 +- .../betterquesting/handlers/EventHandler.java | 598 +++--- .../betterquesting/handlers/GuiHandler.java | 58 +- .../handlers/SaveLoadHandler.java | 499 +++-- .../betterquesting/items/ItemExtraLife.java | 166 +- .../betterquesting/items/ItemGuideBook.java | 56 +- .../betterquesting/legacy/ILegacyLoader.java | 8 +- .../legacy/LegacyLoaderRegistry.java | 26 +- .../legacy/v0/LegacyLoader_v0.java | 477 +++-- .../misc/QuestResourcesFile.java | 332 ++-- .../misc/QuestResourcesFolder.java | 171 +- src/main/java/betterquesting/misc/Util.java | 40 + .../network/BetterQuestingPacketHandler.java | 16 + .../network/PacketAssembly.java | 264 ++- .../network/PacketQuesting.java | 193 +- .../betterquesting/network/PacketSender.java | 132 +- .../network/PacketSetupStation.java | 77 + .../network/PacketTypeRegistry.java | 122 +- .../network/handlers/NetBulkSync.java | 131 +- .../network/handlers/NetCacheSync.java | 49 +- .../network/handlers/NetChapterEdit.java | 290 ++- .../network/handlers/NetChapterSync.java | 176 +- .../network/handlers/NetImport.java | 236 ++- .../network/handlers/NetInviteSync.java | 78 +- .../network/handlers/NetLifeSync.java | 54 +- .../network/handlers/NetNameSync.java | 223 +-- .../network/handlers/NetNotices.java | 68 +- .../network/handlers/NetPartyAction.java | 412 ++-- .../network/handlers/NetPartySync.java | 168 +- .../network/handlers/NetQuestAction.java | 126 +- .../network/handlers/NetQuestEdit.java | 334 ++-- .../network/handlers/NetQuestSync.java | 228 ++- .../network/handlers/NetSettingSync.java | 96 +- .../network/handlers/NetStationEdit.java | 79 +- .../questing/QuestDatabase.java | 199 +- .../questing/QuestInstance.java | 967 +++++----- .../betterquesting/questing/QuestLine.java | 285 ++- .../questing/QuestLineDatabase.java | 206 +- .../questing/QuestLineEntry.java | 207 +- .../questing/party/PartyInstance.java | 372 ++-- .../questing/party/PartyInvitations.java | 311 ++- .../questing/party/PartyManager.java | 165 +- .../questing/rewards/RewardRegistry.java | 118 +- .../questing/rewards/RewardStorage.java | 156 +- .../questing/tasks/TaskRegistry.java | 118 +- .../questing/tasks/TaskStorage.java | 201 +- .../betterquesting/storage/LifeDatabase.java | 107 +- .../betterquesting/storage/NameCache.java | 228 ++- .../storage/PropertyContainer.java | 150 +- .../betterquesting/storage/QuestSettings.java | 106 +- .../assets/betterquesting/lang/en_US.lang | 1 + 355 files changed, 28677 insertions(+), 31585 deletions(-) create mode 100644 settings.gradle create mode 100644 src/main/java/betterquesting/api/questing/tasks/IEnergyTask.java delete mode 100644 src/main/java/betterquesting/blocks/SSItemHandler.java delete mode 100644 src/main/java/betterquesting/client/ui_builder/CanvasBuilderUtil.java create mode 100644 src/main/java/betterquesting/misc/Util.java create mode 100644 src/main/java/betterquesting/network/BetterQuestingPacketHandler.java create mode 100644 src/main/java/betterquesting/network/PacketSetupStation.java diff --git a/build.gradle b/build.gradle index 4aff700a6..584026155 100644 --- a/build.gradle +++ b/build.gradle @@ -1,78 +1,71 @@ -buildscript { - repositories { - jcenter() - maven { - name = "forge" - url = "https://files.minecraftforge.net/maven" - } - } - dependencies { - classpath "net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT" - } +plugins { + id "maven-publish" + id "idea" + id "net.minecraftforge.gradle" version "5.+" } -apply plugin: "net.minecraftforge.gradle.forge" +minecraft { + mappings channel: "stable", version: "39-1.12" -version = modVersion -group= modGroup -archivesBaseName = modBaseName + runs { + server { + workingDirectory project.file("run") + property "forge.logging.markers", "REGISTRIES" + property "forge.logging.console.level", "debug" + } -minecraft { - version = project.forgeVersion - runDir = "run" + client { + workingDirectory project.file("run") + property "forge.logging.markers", "REGISTRIES" + property "forge.logging.console.level", "debug" + } + } +} - replace "@VERSION@", project.version - replaceIn project.modBaseClass +group "betterquesting" - // the mappings can be changed at any time, and must be in the following format. - // snapshot_YYYYMMDD snapshot are built nightly. - // stable_# stables are built at the discretion of the MCP team. - // Use non-default mappings at your own risk. they may not always work. - // simply re-run your setup task after changing the mappings to update your workspace. - mappings = project.mcpVersion - // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. +java { + toolchain { + languageVersion = JavaLanguageVersion.of(8) + } } repositories { - mavenCentral() + mavenCentral() } dependencies { + minecraft "net.minecraftforge:forge:${minecraftVersion}-${forgeVersion}" } processResources { - // this will ensure that this task is redone when the versions change. - inputs.property "version", project.version - inputs.property "mcversion", project.minecraft.version - - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include "mcmod.info" - - // replace version and mcversion - expand "version":project.version, "mcversion":project.minecraft.version + filesMatching("mcmod.info") { + expand "version": project.version, "mcversion": project.minecraftVersion } +} - // copy everything else, thats not the mcmod.info - from(sourceSets.main.resources.srcDirs) { - exclude "mcmod.info" - } +jar { + finalizedBy "reobfJar" } -task deobfJar(type: Jar) { - from sourceSets.main.output - appendix = 'deobf' +sourceSets.main { + output.resourcesDir = output.classesDirs.singleFile } -task apiJar(type: Jar) { - from(sourceSets.main.output) { - include 'betterquesting/api/**' - include 'betterquesting/api2/**' - } - appendix = 'api' +tasks.register('deobfJar', Jar) { + from sourceSets.main.output + archiveClassifier = "deobf" } - + +tasks.register('apiJar', Jar) { + from(sourceSets.main.output) { + include 'betterquesting/api/**' + include 'betterquesting/api2/**' + } + archiveClassifier = "api" +} + artifacts { - archives deobfJar - archives apiJar + archives deobfJar + archives apiJar } diff --git a/gradle.properties b/gradle.properties index 54fd46cec..ba1562011 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,3 @@ -modGroup = betterquesting -modVersion = 3.5.327 -modBaseName = BetterQuesting -modBaseClass = BetterQuesting.java - -forgeVersion = 1.12.2-14.23.5.2768 -mcpVersion = stable_39 +version=3.6.0 +minecraftVersion=1.12.2 +forgeVersion=14.23.5.2860 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2c2bbe5f9..4a71a623f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.4.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.2-bin.zip diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..558de08e8 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { url "https://maven.minecraftforge.net/" } + } +} + +rootProject.name = "BetterQuesting" diff --git a/src/main/java/betterquesting/api/api/ApiKey.java b/src/main/java/betterquesting/api/api/ApiKey.java index 047c7da16..d19f7c3fc 100644 --- a/src/main/java/betterquesting/api/api/ApiKey.java +++ b/src/main/java/betterquesting/api/api/ApiKey.java @@ -1,5 +1,3 @@ package betterquesting.api.api; -public class ApiKey -{ -} +public class ApiKey { } diff --git a/src/main/java/betterquesting/api/api/ApiReference.java b/src/main/java/betterquesting/api/api/ApiReference.java index c9d5f6a1d..9eea1c50d 100644 --- a/src/main/java/betterquesting/api/api/ApiReference.java +++ b/src/main/java/betterquesting/api/api/ApiReference.java @@ -21,24 +21,24 @@ public class ApiReference // Note to self: Don't make these client side only. It'll just crash servers regardless of which are used { - public static final ApiKey QUEST_DB = new ApiKey<>(); - public static final ApiKey LINE_DB = new ApiKey<>(); - public static final ApiKey PARTY_DB = new ApiKey<>(); - public static final ApiKey LIFE_DB = new ApiKey<>(); - - public static final ApiKey, ITask>> TASK_REG = new ApiKey<>(); - public static final ApiKey, IReward>> REWARD_REG = new ApiKey<>(); - - public static final ApiKey PACKET_SENDER = new ApiKey<>(); - public static final ApiKey PACKET_REG = new ApiKey<>(); - - public static final ApiKey SETTINGS = new ApiKey<>(); - public static final ApiKey NAME_CACHE = new ApiKey<>(); - - public static final ApiKey THEME_REG = new ApiKey<>(); - public static final ApiKey RESOURCE_REG = new ApiKey<>(); - public static final ApiKey TOOL_REG = new ApiKey<>(); - public static final ApiKey IMPORT_REG = new ApiKey<>(); - - public static final ApiKey CREATIVE_TAB = new ApiKey<>(); + public static final ApiKey QUEST_DB = new ApiKey<>(); + public static final ApiKey LINE_DB = new ApiKey<>(); + public static final ApiKey PARTY_DB = new ApiKey<>(); + public static final ApiKey LIFE_DB = new ApiKey<>(); + + public static final ApiKey, ITask>> TASK_REG = new ApiKey<>(); + public static final ApiKey, IReward>> REWARD_REG = new ApiKey<>(); + + public static final ApiKey PACKET_SENDER = new ApiKey<>(); + public static final ApiKey PACKET_REG = new ApiKey<>(); + + public static final ApiKey SETTINGS = new ApiKey<>(); + public static final ApiKey NAME_CACHE = new ApiKey<>(); + + public static final ApiKey THEME_REG = new ApiKey<>(); + public static final ApiKey RESOURCE_REG = new ApiKey<>(); + public static final ApiKey TOOL_REG = new ApiKey<>(); + public static final ApiKey IMPORT_REG = new ApiKey<>(); + + public static final ApiKey CREATIVE_TAB = new ApiKey<>(); } diff --git a/src/main/java/betterquesting/api/api/QuestingAPI.java b/src/main/java/betterquesting/api/api/QuestingAPI.java index e9dcf3592..e31acbda4 100644 --- a/src/main/java/betterquesting/api/api/QuestingAPI.java +++ b/src/main/java/betterquesting/api/api/QuestingAPI.java @@ -10,66 +10,54 @@ /** * Storage for all the questing API hooks. Includes built-in and custom APIs */ -public class QuestingAPI -{ - private static final HashMap, Object> apis = new HashMap<>(); - - public static void registerAPI(ApiKey key, T api) - { - if(key == null) - { - throw new NullPointerException("API key can not be NULL"); - } else if(api == null) - { - throw new NullPointerException("Tried to registed NULL API"); - } else if(apis.containsKey(key)) - { - throw new IllegalArgumentException("Key cannot be registered twice"); - } - - apis.put(key, api); - } - - @SuppressWarnings("unchecked") - public static T getAPI(ApiKey key) - { - Object obj = apis.get(key); - return obj == null ? null : (T)obj; - } - - /** - * This should be used over the vanilla method of obtaining the player's UUID. - * This is because offline servers do not sync UUIDs properly to the client - */ - public static UUID getQuestingUUID(EntityPlayer player) - { - if(player == null) - { - return null; - } - - if(player.world.isRemote) - { - UUID uuid = getAPI(ApiReference.NAME_CACHE).getUUID(player.getGameProfile().getName()); - - if(uuid != null) - { - return uuid; - } - } - - return player.getGameProfile().getId(); - } - - private static Logger logger = null; - - public static Logger getLogger() - { - if(logger == null) - { - logger = LogManager.getLogger("betterquesting"); - } - - return logger; - } +public class QuestingAPI { + private static final HashMap, Object> apis = new HashMap<>(); + + public static void registerAPI(ApiKey key, T api) { + if (key == null) { + throw new NullPointerException("API key can not be NULL"); + } else if (api == null) { + throw new NullPointerException("Tried to registed NULL API"); + } else if (apis.containsKey(key)) { + throw new IllegalArgumentException("Key cannot be registered twice"); + } + + apis.put(key, api); + } + + @SuppressWarnings("unchecked") + public static T getAPI(ApiKey key) { + Object obj = apis.get(key); + return obj == null ? null : (T) obj; + } + + /** + * This should be used over the vanilla method of obtaining the player's UUID. + * This is because offline servers do not sync UUIDs properly to the client + */ + public static UUID getQuestingUUID(EntityPlayer player) { + if (player == null) { + return null; + } + + if (player.world.isRemote) { + UUID uuid = getAPI(ApiReference.NAME_CACHE).getUUID(player.getGameProfile().getName()); + + if (uuid != null) { + return uuid; + } + } + + return player.getGameProfile().getId(); + } + + private static Logger logger = null; + + public static Logger getLogger() { + if (logger == null) { + logger = LogManager.getLogger("betterquesting"); + } + + return logger; + } } diff --git a/src/main/java/betterquesting/api/client/gui/misc/INeedsRefresh.java b/src/main/java/betterquesting/api/client/gui/misc/INeedsRefresh.java index a1942108f..d43accb21 100644 --- a/src/main/java/betterquesting/api/client/gui/misc/INeedsRefresh.java +++ b/src/main/java/betterquesting/api/client/gui/misc/INeedsRefresh.java @@ -1,7 +1,6 @@ package betterquesting.api.client.gui.misc; @Deprecated -public interface INeedsRefresh -{ - void refreshGui(); +public interface INeedsRefresh { + void refreshGui(); } diff --git a/src/main/java/betterquesting/api/client/gui/misc/IVolatileScreen.java b/src/main/java/betterquesting/api/client/gui/misc/IVolatileScreen.java index 865311ed9..fc73272df 100644 --- a/src/main/java/betterquesting/api/client/gui/misc/IVolatileScreen.java +++ b/src/main/java/betterquesting/api/client/gui/misc/IVolatileScreen.java @@ -4,4 +4,4 @@ * Marks questing UIs as volatile requiring confirmation to escape */ @Deprecated -public interface IVolatileScreen{} +public interface IVolatileScreen { } diff --git a/src/main/java/betterquesting/api/client/importers/IImportRegistry.java b/src/main/java/betterquesting/api/client/importers/IImportRegistry.java index 8482a5f5d..09e7b30d5 100644 --- a/src/main/java/betterquesting/api/client/importers/IImportRegistry.java +++ b/src/main/java/betterquesting/api/client/importers/IImportRegistry.java @@ -2,8 +2,8 @@ import java.util.List; -public interface IImportRegistry -{ - void registerImporter(IImporter importer); - List getImporters(); +public interface IImportRegistry { + void registerImporter(IImporter importer); + + List getImporters(); } diff --git a/src/main/java/betterquesting/api/client/importers/IImporter.java b/src/main/java/betterquesting/api/client/importers/IImporter.java index cb84a8a5a..8220c111d 100644 --- a/src/main/java/betterquesting/api/client/importers/IImporter.java +++ b/src/main/java/betterquesting/api/client/importers/IImporter.java @@ -9,12 +9,12 @@ /** * Used as a basis for quest importers */ -public interface IImporter -{ - String getUnlocalisedName(); - String getUnlocalisedDescription(); - - FileFilter getFileFilter(); - - void loadFiles(IQuestDatabase questDB, IQuestLineDatabase lineDB, File[] files); +public interface IImporter { + String getUnlocalisedName(); + + String getUnlocalisedDescription(); + + FileFilter getFileFilter(); + + void loadFiles(IQuestDatabase questDB, IQuestLineDatabase lineDB, File[] files); } \ No newline at end of file diff --git a/src/main/java/betterquesting/api/client/toolbox/IToolRegistry.java b/src/main/java/betterquesting/api/client/toolbox/IToolRegistry.java index 51ba20be3..631326962 100644 --- a/src/main/java/betterquesting/api/client/toolbox/IToolRegistry.java +++ b/src/main/java/betterquesting/api/client/toolbox/IToolRegistry.java @@ -5,9 +5,10 @@ import java.util.Collection; -public interface IToolRegistry -{ - void registerToolTab(ResourceLocation tabID, IToolTab tab); - IToolTab getTabByID(ResourceLocation tabID); - Collection getAllTabs(); +public interface IToolRegistry { + void registerToolTab(ResourceLocation tabID, IToolTab tab); + + IToolTab getTabByID(ResourceLocation tabID); + + Collection getAllTabs(); } diff --git a/src/main/java/betterquesting/api/client/toolbox/IToolboxTool.java b/src/main/java/betterquesting/api/client/toolbox/IToolboxTool.java index 9e600bc09..893b2d93a 100644 --- a/src/main/java/betterquesting/api/client/toolbox/IToolboxTool.java +++ b/src/main/java/betterquesting/api/client/toolbox/IToolboxTool.java @@ -6,31 +6,51 @@ import java.util.List; -public interface IToolboxTool -{ - /** Starts up the tool in its initial starting state */ - void initTool(CanvasQuestLine gui); - - /** Canvas has been refreshed. Restore references to buttons, etc. */ - void refresh(CanvasQuestLine gui); - - /** Shut down tool and reset values */ - void disableTool(); - - /** Draws within the relative scrolling portion of the canvas */ - void drawCanvas(int mx, int my, float partialTick); - /** Draws over the top of the canvas without being affected by scrolling */ - void drawOverlay(int mx, int my, float partialTick); - /** Fired when the tool controller has changed its multi-selection */ - void onSelection(NonNullList buttons); - - boolean onMouseClick(int mx, int my, int click); - boolean onMouseRelease(int mx, int my, int click); - boolean onMouseScroll(int mx, int my, int scroll); - boolean onKeyPressed(char c, int key); - List getTooltip(int mx, int my); - - boolean clampScrolling(); - /** Allows the tool controller to intercept some interactions to perform multi-quest selections*/ - boolean useSelection(); +public interface IToolboxTool { + /** + * Starts up the tool in its initial starting state + */ + void initTool(CanvasQuestLine gui); + + /** + * Canvas has been refreshed. Restore references to buttons, etc. + */ + void refresh(CanvasQuestLine gui); + + /** + * Shut down tool and reset values + */ + void disableTool(); + + /** + * Draws within the relative scrolling portion of the canvas + */ + void drawCanvas(int mx, int my, float partialTick); + + /** + * Draws over the top of the canvas without being affected by scrolling + */ + void drawOverlay(int mx, int my, float partialTick); + + /** + * Fired when the tool controller has changed its multi-selection + */ + void onSelection(NonNullList buttons); + + boolean onMouseClick(int mx, int my, int click); + + boolean onMouseRelease(int mx, int my, int click); + + boolean onMouseScroll(int mx, int my, int scroll); + + boolean onKeyPressed(char c, int key); + + List getTooltip(int mx, int my); + + boolean clampScrolling(); + + /** + * Allows the tool controller to intercept some interactions to perform multi-quest selections + */ + boolean useSelection(); } diff --git a/src/main/java/betterquesting/api/enums/EnumLogic.java b/src/main/java/betterquesting/api/enums/EnumLogic.java index d6259c0ef..f75420aaf 100644 --- a/src/main/java/betterquesting/api/enums/EnumLogic.java +++ b/src/main/java/betterquesting/api/enums/EnumLogic.java @@ -1,32 +1,29 @@ package betterquesting.api.enums; -public enum EnumLogic -{ - AND, // All true - NAND, // Any false - OR, // Any true - NOR, // All false - XOR, // Only one true - XNOR; // Only one false - - public boolean getResult(int inputs, int total) - { - switch(this) - { - case AND: - return inputs >= total; - case NAND: - return inputs < total; - case NOR: - return inputs == 0; - case OR: - return inputs > 0; - case XNOR: - return inputs == total - 1; - case XOR: - return inputs == 1; - default: - return false; - } - } +public enum EnumLogic { + AND, // All true + NAND, // Any false + OR, // Any true + NOR, // All false + XOR, // Only one true + XNOR; // Only one false + + public boolean getResult(int inputs, int total) { + switch (this) { + case AND: + return inputs >= total; + case NAND: + return inputs < total; + case NOR: + return inputs == 0; + case OR: + return inputs > 0; + case XNOR: + return inputs == total - 1; + case XOR: + return inputs == 1; + default: + return false; + } + } } diff --git a/src/main/java/betterquesting/api/enums/EnumPartyStatus.java b/src/main/java/betterquesting/api/enums/EnumPartyStatus.java index a434016cc..4fb79c97f 100644 --- a/src/main/java/betterquesting/api/enums/EnumPartyStatus.java +++ b/src/main/java/betterquesting/api/enums/EnumPartyStatus.java @@ -1,8 +1,7 @@ package betterquesting.api.enums; -public enum EnumPartyStatus -{ - MEMBER, - ADMIN, - OWNER +public enum EnumPartyStatus { + MEMBER, + ADMIN, + OWNER } diff --git a/src/main/java/betterquesting/api/enums/EnumQuestState.java b/src/main/java/betterquesting/api/enums/EnumQuestState.java index 4fc426137..d2598dceb 100644 --- a/src/main/java/betterquesting/api/enums/EnumQuestState.java +++ b/src/main/java/betterquesting/api/enums/EnumQuestState.java @@ -1,9 +1,8 @@ package betterquesting.api.enums; -public enum EnumQuestState -{ - LOCKED, - UNLOCKED, - UNCLAIMED, - COMPLETED; +public enum EnumQuestState { + LOCKED, + UNLOCKED, + UNCLAIMED, + COMPLETED } diff --git a/src/main/java/betterquesting/api/enums/EnumQuestVisibility.java b/src/main/java/betterquesting/api/enums/EnumQuestVisibility.java index 6fcc70682..21cc6598f 100644 --- a/src/main/java/betterquesting/api/enums/EnumQuestVisibility.java +++ b/src/main/java/betterquesting/api/enums/EnumQuestVisibility.java @@ -1,11 +1,10 @@ package betterquesting.api.enums; -public enum EnumQuestVisibility -{ - HIDDEN, - UNLOCKED, - NORMAL, - COMPLETED, - CHAIN, - ALWAYS; +public enum EnumQuestVisibility { + HIDDEN, + UNLOCKED, + NORMAL, + COMPLETED, + CHAIN, + ALWAYS } diff --git a/src/main/java/betterquesting/api/events/DatabaseEvent.java b/src/main/java/betterquesting/api/events/DatabaseEvent.java index 0c8941981..73b4b0a08 100644 --- a/src/main/java/betterquesting/api/events/DatabaseEvent.java +++ b/src/main/java/betterquesting/api/events/DatabaseEvent.java @@ -8,54 +8,44 @@ */ // TODO: Replace with a better system. Stop using this for updating screens too @Deprecated -public abstract class DatabaseEvent extends Event -{ - private final DBType TYPE; - - public DatabaseEvent(DBType type) - { - this.TYPE = type; +public abstract class DatabaseEvent extends Event { + private final DBType TYPE; + + public DatabaseEvent(DBType type) { + this.TYPE = type; + } + + public DBType getType() { + return this.TYPE; + } + + @Deprecated + public static class Update extends DatabaseEvent { + public Update(DBType type) { + super(type); } - - public DBType getType() - { - return this.TYPE; + } + + @Deprecated + public static class Load extends DatabaseEvent { + public Load(DBType type) { + super(type); } - - @Deprecated - public static class Update extends DatabaseEvent - { - public Update(DBType type) - { - super(type); - } - } - - @Deprecated - public static class Load extends DatabaseEvent - { - public Load(DBType type) - { - super(type); - } - } - - @Deprecated - public static class Save extends DatabaseEvent - { - public Save(DBType type) - { - super(type); - } - } - - public enum DBType - { - QUEST, - CHAPTER, - PARTY, - NAMES, - ALL, - OTHER + } + + @Deprecated + public static class Save extends DatabaseEvent { + public Save(DBType type) { + super(type); } + } + + public enum DBType { + QUEST, + CHAPTER, + PARTY, + NAMES, + ALL, + OTHER + } } diff --git a/src/main/java/betterquesting/api/events/NbtDocEvent.java b/src/main/java/betterquesting/api/events/NbtDocEvent.java index 06a24ae16..58c7d2b25 100644 --- a/src/main/java/betterquesting/api/events/NbtDocEvent.java +++ b/src/main/java/betterquesting/api/events/NbtDocEvent.java @@ -1,34 +1,29 @@ package betterquesting.api.events; -import net.minecraftforge.fml.common.eventhandler.Event; import betterquesting.api.nbt_doc.INbtDoc; +import net.minecraftforge.fml.common.eventhandler.Event; /** * Can be used to override the JsonDocs in the editors with custom ones. */ -public class NbtDocEvent extends Event -{ - private final INbtDoc inJdoc; - private INbtDoc outJdoc; - - public NbtDocEvent(INbtDoc jdoc) - { - inJdoc = jdoc; - outJdoc = jdoc; - } - - public INbtDoc getNbtDoc() - { - return inJdoc; - } - - public void setNewDoc(INbtDoc jdoc) - { - this.outJdoc = jdoc; - } - - public INbtDoc getNbtDocResult() - { - return outJdoc == null? inJdoc : outJdoc; - } +public class NbtDocEvent extends Event { + private final INbtDoc inJdoc; + private INbtDoc outJdoc; + + public NbtDocEvent(INbtDoc jdoc) { + inJdoc = jdoc; + outJdoc = jdoc; + } + + public INbtDoc getNbtDoc() { + return inJdoc; + } + + public void setNewDoc(INbtDoc jdoc) { + this.outJdoc = jdoc; + } + + public INbtDoc getNbtDocResult() { + return outJdoc == null ? inJdoc : outJdoc; + } } diff --git a/src/main/java/betterquesting/api/events/QuestEvent.java b/src/main/java/betterquesting/api/events/QuestEvent.java index 686669c43..7152284c8 100644 --- a/src/main/java/betterquesting/api/events/QuestEvent.java +++ b/src/main/java/betterquesting/api/events/QuestEvent.java @@ -4,45 +4,38 @@ import java.util.*; -public class QuestEvent extends Event -{ - private final Type type; - private final UUID playerID; - private final Set questIDs; - - public Set getQuestIDs() - { - return this.questIDs; - } - - public UUID getPlayerID() - { - return this.playerID; - } - - public Type getType() - { - return this.type; - } - - public QuestEvent(Type type, UUID playerID, int questID) - { - this.type = type; - this.playerID = playerID; - this.questIDs = Collections.singleton(questID); - } - - public QuestEvent(Type type, UUID playerID, Collection questIDs) - { - this.type = type; - this.playerID = playerID; - this.questIDs = Collections.unmodifiableSet(new TreeSet<>(questIDs)); - } - - public enum Type - { - COMPLETED, - UPDATED, - RESET - } +public class QuestEvent extends Event { + private final Type type; + private final UUID playerID; + private final Set questIDs; + + public Set getQuestIDs() { + return this.questIDs; + } + + public UUID getPlayerID() { + return this.playerID; + } + + public Type getType() { + return this.type; + } + + public QuestEvent(Type type, UUID playerID, int questID) { + this.type = type; + this.playerID = playerID; + this.questIDs = Collections.singleton(questID); + } + + public QuestEvent(Type type, UUID playerID, Collection questIDs) { + this.type = type; + this.playerID = playerID; + this.questIDs = Collections.unmodifiableSet(new TreeSet<>(questIDs)); + } + + public enum Type { + COMPLETED, + UPDATED, + RESET + } } diff --git a/src/main/java/betterquesting/api/misc/ICallback.java b/src/main/java/betterquesting/api/misc/ICallback.java index 8ceee75fd..156d77fa3 100644 --- a/src/main/java/betterquesting/api/misc/ICallback.java +++ b/src/main/java/betterquesting/api/misc/ICallback.java @@ -1,6 +1,5 @@ package betterquesting.api.misc; -public interface ICallback -{ - void setValue(T value); +public interface ICallback { + void setValue(T value); } \ No newline at end of file diff --git a/src/main/java/betterquesting/api/nbt_doc/INbtDoc.java b/src/main/java/betterquesting/api/nbt_doc/INbtDoc.java index 2cd10263f..1f9f1faa8 100644 --- a/src/main/java/betterquesting/api/nbt_doc/INbtDoc.java +++ b/src/main/java/betterquesting/api/nbt_doc/INbtDoc.java @@ -1,13 +1,16 @@ package betterquesting.api.nbt_doc; -/** Used to self document the NBT editors with localised tooltips and variable naming */ -public interface INbtDoc -{ - String getUnlocalisedTitle(); - - String getUnlocalisedName(String key); - String getUnlocalisedDesc(String key); - - INbtDoc getParent(); - INbtDoc getChild(String key); +/** + * Used to self document the NBT editors with localised tooltips and variable naming + */ +public interface INbtDoc { + String getUnlocalisedTitle(); + + String getUnlocalisedName(String key); + + String getUnlocalisedDesc(String key); + + INbtDoc getParent(); + + INbtDoc getChild(String key); } diff --git a/src/main/java/betterquesting/api/nbt_doc/NbtDocBasic.java b/src/main/java/betterquesting/api/nbt_doc/NbtDocBasic.java index bedf81330..6ffc18057 100644 --- a/src/main/java/betterquesting/api/nbt_doc/NbtDocBasic.java +++ b/src/main/java/betterquesting/api/nbt_doc/NbtDocBasic.java @@ -1,48 +1,41 @@ package betterquesting.api.nbt_doc; -import net.minecraftforge.common.MinecraftForge; import betterquesting.api.events.NbtDocEvent; +import net.minecraftforge.common.MinecraftForge; + +public class NbtDocBasic implements INbtDoc { + private final INbtDoc parent; + private final String prefix; + + public NbtDocBasic(INbtDoc parent, String prefix) { + this.parent = parent; + this.prefix = prefix; + } + + @Override + public String getUnlocalisedTitle() { + return prefix + ".name"; + } + + @Override + public String getUnlocalisedName(String key) { + return prefix + "." + key + ".name"; + } + + @Override + public String getUnlocalisedDesc(String key) { + return prefix + "." + key + ".desc"; + } + + @Override + public INbtDoc getParent() { + return parent; + } -public class NbtDocBasic implements INbtDoc -{ - private final INbtDoc parent; - private final String prefix; - - public NbtDocBasic(INbtDoc parent, String prefix) - { - this.parent = parent; - this.prefix = prefix; - } - - @Override - public String getUnlocalisedTitle() - { - return prefix + ".name"; - } - - @Override - public String getUnlocalisedName(String key) - { - return prefix + "." + key + ".name"; - } - - @Override - public String getUnlocalisedDesc(String key) - { - return prefix + "." + key + ".desc"; - } - - @Override - public INbtDoc getParent() - { - return parent; - } - - @Override - public INbtDoc getChild(String child) - { - NbtDocEvent event = new NbtDocEvent(new NbtDocBasic(this, prefix + "." + child)); - MinecraftForge.EVENT_BUS.post(event); - return event.getNbtDocResult(); - } + @Override + public INbtDoc getChild(String child) { + NbtDocEvent event = new NbtDocEvent(new NbtDocBasic(this, prefix + "." + child)); + MinecraftForge.EVENT_BUS.post(event); + return event.getNbtDocResult(); + } } diff --git a/src/main/java/betterquesting/api/network/IPacketRegistry.java b/src/main/java/betterquesting/api/network/IPacketRegistry.java index db0a6ba7b..ede065a62 100644 --- a/src/main/java/betterquesting/api/network/IPacketRegistry.java +++ b/src/main/java/betterquesting/api/network/IPacketRegistry.java @@ -11,17 +11,17 @@ import javax.annotation.Nullable; import java.util.function.Consumer; -public interface IPacketRegistry -{ - void registerServerHandler(@Nonnull ResourceLocation idName, @Nonnull Consumer> method); - - @SideOnly(Side.CLIENT) - void registerClientHandler(@Nonnull ResourceLocation idName, @Nonnull Consumer method); - - @Nullable - Consumer> getServerHandler(@Nonnull ResourceLocation idName); - - @Nullable - @SideOnly(Side.CLIENT) - Consumer getClientHandler(@Nonnull ResourceLocation idName); +public interface IPacketRegistry { + void registerServerHandler(@Nonnull ResourceLocation idName, + @Nonnull Consumer> method); + + @SideOnly(Side.CLIENT) + void registerClientHandler(@Nonnull ResourceLocation idName, @Nonnull Consumer method); + + @Nullable + Consumer> getServerHandler(@Nonnull ResourceLocation idName); + + @Nullable + @SideOnly(Side.CLIENT) + Consumer getClientHandler(@Nonnull ResourceLocation idName); } diff --git a/src/main/java/betterquesting/api/network/IPacketSender.java b/src/main/java/betterquesting/api/network/IPacketSender.java index 15cef921a..a59cc4c3b 100644 --- a/src/main/java/betterquesting/api/network/IPacketSender.java +++ b/src/main/java/betterquesting/api/network/IPacketSender.java @@ -3,16 +3,17 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; -public interface IPacketSender -{ - // Server to Client - void sendToPlayers(QuestingPacket payload, EntityPlayerMP... players); - void sendToAll(QuestingPacket payload); - - // Client to Server - void sendToServer(QuestingPacket payload); - - // Misc. - void sendToAround(QuestingPacket payload, TargetPoint point); - void sendToDimension(QuestingPacket payload, int dimension); +public interface IPacketSender { + // Server to Client + void sendToPlayers(QuestingPacket payload, EntityPlayerMP... players); + + void sendToAll(QuestingPacket payload); + + // Client to Server + void sendToServer(QuestingPacket payload); + + // Misc. + void sendToAround(QuestingPacket payload, TargetPoint point); + + void sendToDimension(QuestingPacket payload, int dimension); } diff --git a/src/main/java/betterquesting/api/network/QuestingPacket.java b/src/main/java/betterquesting/api/network/QuestingPacket.java index ad63d6585..f2526d93a 100644 --- a/src/main/java/betterquesting/api/network/QuestingPacket.java +++ b/src/main/java/betterquesting/api/network/QuestingPacket.java @@ -3,24 +3,20 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; -public final class QuestingPacket -{ - private final ResourceLocation handler; - private final NBTTagCompound payload; - - public QuestingPacket(ResourceLocation handler, NBTTagCompound payload) - { - this.handler = handler; - this.payload = payload; - } - - public ResourceLocation getHandler() - { - return handler; - } - - public NBTTagCompound getPayload() - { - return payload; - } +public final class QuestingPacket { + private final ResourceLocation handler; + private final NBTTagCompound payload; + + public QuestingPacket(ResourceLocation handler, NBTTagCompound payload) { + this.handler = handler; + this.payload = payload; + } + + public ResourceLocation getHandler() { + return handler; + } + + public NBTTagCompound getPayload() { + return payload; + } } diff --git a/src/main/java/betterquesting/api/package-info.java b/src/main/java/betterquesting/api/package-info.java index 3bc667dc3..53493ff96 100644 --- a/src/main/java/betterquesting/api/package-info.java +++ b/src/main/java/betterquesting/api/package-info.java @@ -1,4 +1,5 @@ @API(owner = "betterquesting", apiVersion = "3.2", provides = "BetterQuesting|API") package betterquesting.api; + import net.minecraftforge.fml.common.API; diff --git a/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java b/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java index eb56f63f2..9c11b194a 100644 --- a/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java @@ -6,48 +6,40 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -public class EntityPlaceholder extends Entity -{ - private final EntityItem eItem; - private NBTTagCompound original = new NBTTagCompound(); - - public EntityPlaceholder(World world) - { - super(world); - eItem = new EntityItem(world); - eItem.setItem(new ItemStack(ItemPlaceholder.placeholder)); - } - - public EntityPlaceholder SetOriginalTags(NBTTagCompound tags) - { - this.original = tags; - return this; - } - - public NBTTagCompound GetOriginalTags() - { - return this.original; - } - - public EntityItem GetItemEntity() - { - return eItem; - } - - @Override - protected void entityInit() - { - } - - @Override - protected void readEntityFromNBT(NBTTagCompound tags) - { - original = tags.getCompoundTag("original"); - } - - @Override - protected void writeEntityToNBT(NBTTagCompound tags) - { - tags.setTag("original", this.original); - } +public class EntityPlaceholder extends Entity { + private final EntityItem eItem; + private NBTTagCompound original = new NBTTagCompound(); + + public EntityPlaceholder(World world) { + super(world); + eItem = new EntityItem(world); + eItem.setItem(new ItemStack(ItemPlaceholder.placeholder)); + } + + public EntityPlaceholder SetOriginalTags(NBTTagCompound tags) { + this.original = tags; + return this; + } + + public NBTTagCompound GetOriginalTags() { + return this.original; + } + + public EntityItem GetItemEntity() { + return eItem; + } + + @Override + protected void entityInit() { + } + + @Override + protected void readEntityFromNBT(NBTTagCompound tags) { + original = tags.getCompoundTag("original"); + } + + @Override + protected void writeEntityToNBT(NBTTagCompound tags) { + tags.setTag("original", this.original); + } } diff --git a/src/main/java/betterquesting/api/placeholders/FluidPlaceholder.java b/src/main/java/betterquesting/api/placeholders/FluidPlaceholder.java index 2bf03c0b7..ab78fd39a 100644 --- a/src/main/java/betterquesting/api/placeholders/FluidPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/FluidPlaceholder.java @@ -3,12 +3,11 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; -public class FluidPlaceholder extends Fluid -{ - public static Fluid fluidPlaceholder = new FluidPlaceholder(); - - public FluidPlaceholder() - { - super("betterquesting.placeholder", new ResourceLocation("betterquesting:blocks/fluid_placeholder"), new ResourceLocation("betterquesting:blocks/fluid_placeholder")); - } +public class FluidPlaceholder extends Fluid { + public static final Fluid fluidPlaceholder = new FluidPlaceholder(); + + public FluidPlaceholder() { + super("betterquesting.placeholder", new ResourceLocation("betterquesting:blocks/fluid_placeholder"), + new ResourceLocation("betterquesting:blocks/fluid_placeholder")); + } } diff --git a/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java b/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java index 8e63c1307..533fc23ae 100644 --- a/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java @@ -11,59 +11,59 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; -public class ItemPlaceholder extends Item -{ - public static Item placeholder = new ItemPlaceholder(); - - // Used solely for retaining info to missing items - public ItemPlaceholder() - { - this.setTranslationKey("betterquesting.placeholder"); - } - - /** - * allows items to add custom lines of information to the mouseover description - */ - @Override - @SideOnly(Side.CLIENT) - public void addInformation(ItemStack stack, @Nullable World worldIn, List tooltip, ITooltipFlag flagIn) - { - if(!stack.hasTagCompound()) - { - tooltip.add("ERROR: Original information missing!"); - return; - } - - tooltip.add("Original ID: " + stack.getTagCompound().getString("orig_id") + "/" + stack.getTagCompound().getInteger("orig_meta")); - } +public class ItemPlaceholder extends Item { + public static final Item placeholder = new ItemPlaceholder(); - /** - * Called each tick as long the item is on a player inventory. Uses by maps to check if is on a player hand and - * update it's contents. - */ - @Override - public void onUpdate(ItemStack stack, World world, Entity entity, int slot, boolean held) + // Used solely for retaining info to missing items + public ItemPlaceholder() { + this.setTranslationKey("betterquesting.placeholder"); + } + + /** + * allows items to add custom lines of information to the mouseover description + */ + @Override + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack stack, + @Nullable World worldIn, + @Nonnull List tooltip, + @Nonnull ITooltipFlag flagIn) { + if (!stack.hasTagCompound()) { + tooltip.add("ERROR: Original information missing!"); + return; + } + + tooltip.add("Original ID: " + stack.getTagCompound().getString("orig_id") + + "/" + stack.getTagCompound().getInteger("orig_meta")); + } + + /** + * Called each tick as long the item is on a player inventory. Uses by maps to check if is on a player hand and + * update it's contents. + */ + @Override + public void onUpdate(ItemStack stack, @Nonnull World world, @Nonnull Entity entity, int slot, boolean held) { + if (!stack.hasTagCompound() || !(entity instanceof EntityPlayer) || + world.getTotalWorldTime() % 100 != 0) // Process this only once a second { - if(!stack.hasTagCompound() || !(entity instanceof EntityPlayer) || world.getTotalWorldTime()%100 != 0) // Process this only once a second - { - return; - } - - EntityPlayer player = (EntityPlayer)entity; - - NBTTagCompound tags = stack.getTagCompound(); - Item i = Item.REGISTRY.getObject(new ResourceLocation(tags.getString("orig_id"))); - int m = stack.getItemDamage() > 0? stack.getItemDamage() : tags.getInteger("orig_meta"); - NBTTagCompound t = tags.hasKey("orig_tag")? tags.getCompoundTag("orig_tag") : null; - - if(i != null) - { - ItemStack converted = new ItemStack(i, stack.getCount(), m); - converted.setTagCompound(t); - player.inventory.setInventorySlotContents(slot, converted); - } + return; + } + + EntityPlayer player = (EntityPlayer) entity; + + NBTTagCompound tags = stack.getTagCompound(); + Item i = Item.REGISTRY.getObject(new ResourceLocation(tags.getString("orig_id"))); + int m = stack.getItemDamage() > 0 ? stack.getItemDamage() : tags.getInteger("orig_meta"); + NBTTagCompound t = tags.hasKey("orig_tag") ? tags.getCompoundTag("orig_tag") : null; + + if (i != null) { + ItemStack converted = new ItemStack(i, stack.getCount(), m); + converted.setTagCompound(t); + player.inventory.setInventorySlotContents(slot, converted); } + } } diff --git a/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java b/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java index f73a57d2b..bc7cd66f0 100644 --- a/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java +++ b/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java @@ -13,87 +13,75 @@ /** * In charge of safely converting to or from placeholder objects */ -public class PlaceholderConverter -{ - public static Entity convertEntity(Entity orig, World world, NBTTagCompound nbt) - { - Entity entity = orig; - - if(orig == null) - { - entity = new EntityPlaceholder(world); - ((EntityPlaceholder)entity).SetOriginalTags(nbt); - } else if(orig instanceof EntityPlaceholder) - { - EntityPlaceholder p = (EntityPlaceholder)orig; - Entity tmp = EntityList.createEntityFromNBT(p.GetOriginalTags(), world); - entity = tmp != null? tmp : p; - } - - return entity; - } - - public static BigItemStack convertItem(Item item, String name, int count, int damage, String oreDict, NBTTagCompound nbt) - { - if(item == null) - { - BigItemStack stack = new BigItemStack(ItemPlaceholder.placeholder, count, damage).setOreDict(oreDict); - stack.SetTagCompound(new NBTTagCompound()); - stack.GetTagCompound().setString("orig_id", name); - stack.GetTagCompound().setInteger("orig_meta", damage); - if(nbt != null) stack.GetTagCompound().setTag("orig_tag", nbt); - return stack; - } else if(item == ItemPlaceholder.placeholder) - { - if(nbt != null) - { - Item restored = Item.getByNameOrId(nbt.getString("orig_id")); - - if(restored != null) - { - BigItemStack stack = new BigItemStack(restored, count, nbt.hasKey("orig_meta")? nbt.getInteger("orig_meta") : damage).setOreDict(oreDict); - if(nbt.hasKey("orig_tag")) stack.SetTagCompound(nbt.getCompoundTag("orig_tag")); - - return stack; - } else if(damage > 0 && !nbt.hasKey("orig_meta")) - { - nbt.setInteger("orig_meta", damage); - damage = 0; - } - } - } - - BigItemStack stack = new BigItemStack(item, count, damage).setOreDict(oreDict); - if(nbt != null) stack.SetTagCompound(nbt); - - return stack; - } - - public static FluidStack convertFluid(Fluid fluid, String name, int amount, NBTTagCompound nbt) - { - if(fluid == null) - { - FluidStack stack = new FluidStack(FluidPlaceholder.fluidPlaceholder, amount); - NBTTagCompound orig = new NBTTagCompound(); - orig.setString("orig_id", name); - if(nbt != null) orig.setTag("orig_tag", nbt); - stack.tag = orig; - return stack; - } else if(fluid == FluidPlaceholder.fluidPlaceholder && nbt != null) - { - Fluid restored = FluidRegistry.getFluid(nbt.getString("orig_id")); - - if(restored != null) - { - FluidStack stack = new FluidStack(restored, amount); - if(nbt.hasKey("orig_tag")) stack.tag = nbt.getCompoundTag("orig_tag"); - return stack; - } - } - - FluidStack stack = new FluidStack(fluid, amount); - if(nbt != null) stack.tag = nbt; - - return stack; - } +public class PlaceholderConverter { + public static Entity convertEntity(Entity orig, World world, NBTTagCompound nbt) { + Entity entity = orig; + + if (orig == null) { + entity = new EntityPlaceholder(world); + ((EntityPlaceholder) entity).SetOriginalTags(nbt); + } else if (orig instanceof EntityPlaceholder) { + EntityPlaceholder p = (EntityPlaceholder) orig; + Entity tmp = EntityList.createEntityFromNBT(p.GetOriginalTags(), world); + entity = tmp != null ? tmp : p; + } + + return entity; + } + + public static BigItemStack convertItem(Item item, String name, int count, int damage, String oreDict, + NBTTagCompound nbt) { + if (item == null) { + BigItemStack stack = new BigItemStack(ItemPlaceholder.placeholder, count, damage).setOreDict(oreDict); + stack.SetTagCompound(new NBTTagCompound()); + stack.GetTagCompound().setString("orig_id", name); + stack.GetTagCompound().setInteger("orig_meta", damage); + if (nbt != null) { stack.GetTagCompound().setTag("orig_tag", nbt); } + return stack; + } else if (item == ItemPlaceholder.placeholder) { + if (nbt != null) { + Item restored = Item.getByNameOrId(nbt.getString("orig_id")); + + if (restored != null) { + BigItemStack stack = new BigItemStack(restored, count, nbt.hasKey("orig_meta") ? nbt.getInteger("orig_meta") + : damage).setOreDict(oreDict); + if (nbt.hasKey("orig_tag")) { stack.SetTagCompound(nbt.getCompoundTag("orig_tag")); } + + return stack; + } else if (damage > 0 && !nbt.hasKey("orig_meta")) { + nbt.setInteger("orig_meta", damage); + damage = 0; + } + } + } + + BigItemStack stack = new BigItemStack(item, count, damage).setOreDict(oreDict); + if (nbt != null) { stack.SetTagCompound(nbt); } + + return stack; + } + + public static FluidStack convertFluid(Fluid fluid, String name, int amount, NBTTagCompound nbt) { + if (fluid == null) { + FluidStack stack = new FluidStack(FluidPlaceholder.fluidPlaceholder, amount); + NBTTagCompound orig = new NBTTagCompound(); + orig.setString("orig_id", name); + if (nbt != null) { orig.setTag("orig_tag", nbt); } + stack.tag = orig; + return stack; + } else if (fluid == FluidPlaceholder.fluidPlaceholder && nbt != null) { + Fluid restored = FluidRegistry.getFluid(nbt.getString("orig_id")); + + if (restored != null) { + FluidStack stack = new FluidStack(restored, amount); + if (nbt.hasKey("orig_tag")) { stack.tag = nbt.getCompoundTag("orig_tag"); } + return stack; + } + } + + FluidStack stack = new FluidStack(fluid, amount); + if (nbt != null) { stack.tag = nbt; } + + return stack; + } } diff --git a/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java b/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java index a84d5f105..b44032311 100644 --- a/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java @@ -4,33 +4,28 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; -public class FactoryRewardPlaceholder implements IFactoryData -{ - public static final FactoryRewardPlaceholder INSTANCE = new FactoryRewardPlaceholder(); - - private final ResourceLocation ID = new ResourceLocation("betterquesting:placeholder"); - - private FactoryRewardPlaceholder() - { - } - - @Override - public ResourceLocation getRegistryName() - { - return ID; - } - - @Override - public RewardPlaceholder createNew() - { - return new RewardPlaceholder(); - } - - @Override - public RewardPlaceholder loadFromData(NBTTagCompound nbt) - { - RewardPlaceholder reward = createNew(); - reward.readFromNBT(nbt); - return reward; - } +public class FactoryRewardPlaceholder implements IFactoryData { + public static final FactoryRewardPlaceholder INSTANCE = new FactoryRewardPlaceholder(); + + private final ResourceLocation ID = new ResourceLocation("betterquesting:placeholder"); + + private FactoryRewardPlaceholder() { + } + + @Override + public ResourceLocation getRegistryName() { + return ID; + } + + @Override + public RewardPlaceholder createNew() { + return new RewardPlaceholder(); + } + + @Override + public RewardPlaceholder loadFromData(NBTTagCompound nbt) { + RewardPlaceholder reward = createNew(); + reward.readFromNBT(nbt); + return reward; + } } diff --git a/src/main/java/betterquesting/api/placeholders/rewards/RewardPlaceholder.java b/src/main/java/betterquesting/api/placeholders/rewards/RewardPlaceholder.java index 314183303..19ceded1d 100644 --- a/src/main/java/betterquesting/api/placeholders/rewards/RewardPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/rewards/RewardPlaceholder.java @@ -10,66 +10,55 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; -public class RewardPlaceholder implements IReward -{ - private NBTTagCompound nbtSaved = new NBTTagCompound(); - - public void setRewardConfigData(NBTTagCompound nbt) - { - nbtSaved = nbt; - } - - public NBTTagCompound getRewardConfigData() - { - return nbtSaved; - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) - { - nbt.setTag("orig_data", nbtSaved); - - return nbt; - } - - @Override - public void readFromNBT(NBTTagCompound nbt) - { - nbtSaved = nbt.getCompoundTag("orig_data"); - } - - @Override - public String getUnlocalisedName() - { - return "betterquesting.placeholder"; - } - - @Override - public ResourceLocation getFactoryID() - { - return FactoryRewardPlaceholder.INSTANCE.getRegistryName(); - } - - @Override - public boolean canClaim(EntityPlayer player, DBEntry quest) - { - return false; - } - - @Override - public void claimReward(EntityPlayer player, DBEntry quest) - { - } - - @Override - public IGuiPanel getRewardGui(IGuiRect rect, DBEntry quest) - { - return null; - } - - @Override - public GuiScreen getRewardEditor(GuiScreen parent, DBEntry quest) - { - return null; - } +public class RewardPlaceholder implements IReward { + private NBTTagCompound nbtSaved = new NBTTagCompound(); + + public void setRewardConfigData(NBTTagCompound nbt) { + nbtSaved = nbt; + } + + public NBTTagCompound getRewardConfigData() { + return nbtSaved; + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + nbt.setTag("orig_data", nbtSaved); + + return nbt; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + nbtSaved = nbt.getCompoundTag("orig_data"); + } + + @Override + public String getUnlocalisedName() { + return "betterquesting.placeholder"; + } + + @Override + public ResourceLocation getFactoryID() { + return FactoryRewardPlaceholder.INSTANCE.getRegistryName(); + } + + @Override + public boolean canClaim(EntityPlayer player, DBEntry quest) { + return false; + } + + @Override + public void claimReward(EntityPlayer player, DBEntry quest) { + } + + @Override + public IGuiPanel getRewardGui(IGuiRect rect, DBEntry quest) { + return null; + } + + @Override + public GuiScreen getRewardEditor(GuiScreen parent, DBEntry quest) { + return null; + } } diff --git a/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java b/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java index 370e98eef..adf14fa02 100644 --- a/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java @@ -4,33 +4,28 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; -public class FactoryTaskPlaceholder implements IFactoryData -{ - public static final FactoryTaskPlaceholder INSTANCE = new FactoryTaskPlaceholder(); - - private final ResourceLocation ID = new ResourceLocation("betterquesting:placeholder"); - - private FactoryTaskPlaceholder() - { - } - - @Override - public ResourceLocation getRegistryName() - { - return ID; - } - - @Override - public TaskPlaceholder createNew() - { - return new TaskPlaceholder(); - } - - @Override - public TaskPlaceholder loadFromData(NBTTagCompound nbt) - { - TaskPlaceholder task = createNew(); - task.readFromNBT(nbt); - return task; - } +public class FactoryTaskPlaceholder implements IFactoryData { + public static final FactoryTaskPlaceholder INSTANCE = new FactoryTaskPlaceholder(); + + private final ResourceLocation ID = new ResourceLocation("betterquesting:placeholder"); + + private FactoryTaskPlaceholder() { + } + + @Override + public ResourceLocation getRegistryName() { + return ID; + } + + @Override + public TaskPlaceholder createNew() { + return new TaskPlaceholder(); + } + + @Override + public TaskPlaceholder loadFromData(NBTTagCompound nbt) { + TaskPlaceholder task = createNew(); + task.readFromNBT(nbt); + return task; + } } diff --git a/src/main/java/betterquesting/api/placeholders/tasks/TaskPlaceholder.java b/src/main/java/betterquesting/api/placeholders/tasks/TaskPlaceholder.java index 41bc398ff..ed68fc534 100644 --- a/src/main/java/betterquesting/api/placeholders/tasks/TaskPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/tasks/TaskPlaceholder.java @@ -14,98 +14,81 @@ import java.util.List; import java.util.UUID; -public class TaskPlaceholder implements ITask -{ - private NBTTagCompound nbtData = new NBTTagCompound(); - - public void setTaskConfigData(NBTTagCompound nbt) - { - nbtData.setTag("orig_data", nbt); - } - - public void setTaskProgressData(NBTTagCompound nbt) - { - nbtData.setTag("orig_prog", nbt); - } - - public NBTTagCompound getTaskConfigData() - { - return nbtData.getCompoundTag("orig_data"); - } - - public NBTTagCompound getTaskProgressData() - { - return nbtData.getCompoundTag("orig_prog"); - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) - { - nbt.setTag("orig_data", nbtData.getCompoundTag("orig_data")); - return nbt; - } - - @Override - public void readFromNBT(NBTTagCompound nbt) - { - nbtData.setTag("orig_data", nbt.getCompoundTag("orig_data")); - } - - @Override - public NBTTagCompound writeProgressToNBT(NBTTagCompound nbt, @Nullable List users) - { - nbt.setTag("orig_prog", nbtData.getCompoundTag("orig_prog")); - return nbt; - } - - @Override - public void readProgressFromNBT(NBTTagCompound nbt, boolean merge) - { - nbtData.setTag("orig_prog", nbt.getCompoundTag("orig_prog")); - } - - @Override - public String getUnlocalisedName() - { - return "betterquesting.placeholder"; - } - - @Override - public ResourceLocation getFactoryID() - { - return FactoryTaskPlaceholder.INSTANCE.getRegistryName(); - } - - @Override - public void detect(ParticipantInfo participant, DBEntry quest) - { - } - - @Override - public boolean isComplete(UUID uuid) - { - return false; - } - - @Override - public void setComplete(UUID uuid) - { - } - - @Override - public void resetUser(UUID uuid) - { - } - - @Override - public IGuiPanel getTaskGui(IGuiRect rect, DBEntry quest) - { - return null; - } - - @Override - public GuiScreen getTaskEditor(GuiScreen parent, DBEntry quest) - { - return null; - } +public class TaskPlaceholder implements ITask { + private final NBTTagCompound nbtData = new NBTTagCompound(); + + public void setTaskConfigData(NBTTagCompound nbt) { + nbtData.setTag("orig_data", nbt); + } + + public void setTaskProgressData(NBTTagCompound nbt) { + nbtData.setTag("orig_prog", nbt); + } + + public NBTTagCompound getTaskConfigData() { + return nbtData.getCompoundTag("orig_data"); + } + + public NBTTagCompound getTaskProgressData() { + return nbtData.getCompoundTag("orig_prog"); + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + nbt.setTag("orig_data", nbtData.getCompoundTag("orig_data")); + return nbt; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + nbtData.setTag("orig_data", nbt.getCompoundTag("orig_data")); + } + + @Override + public NBTTagCompound writeProgressToNBT(NBTTagCompound nbt, @Nullable List users) { + nbt.setTag("orig_prog", nbtData.getCompoundTag("orig_prog")); + return nbt; + } + + @Override + public void readProgressFromNBT(NBTTagCompound nbt, boolean merge) { + nbtData.setTag("orig_prog", nbt.getCompoundTag("orig_prog")); + } + + @Override + public String getUnlocalisedName() { + return "betterquesting.placeholder"; + } + + @Override + public ResourceLocation getFactoryID() { + return FactoryTaskPlaceholder.INSTANCE.getRegistryName(); + } + + @Override + public void detect(ParticipantInfo participant, DBEntry quest) { + } + + @Override + public boolean isComplete(UUID uuid) { + return false; + } + + @Override + public void setComplete(UUID uuid) { + } + + @Override + public void resetUser(UUID uuid) { + } + + @Override + public IGuiPanel getTaskGui(IGuiRect rect, DBEntry quest) { + return null; + } + + @Override + public GuiScreen getTaskEditor(GuiScreen parent, DBEntry quest) { + return null; + } } diff --git a/src/main/java/betterquesting/api/properties/IPropertyContainer.java b/src/main/java/betterquesting/api/properties/IPropertyContainer.java index 77998cb45..440a114e8 100644 --- a/src/main/java/betterquesting/api/properties/IPropertyContainer.java +++ b/src/main/java/betterquesting/api/properties/IPropertyContainer.java @@ -1,14 +1,15 @@ package betterquesting.api.properties; -public interface IPropertyContainer -{ - T getProperty(IPropertyType prop); - T getProperty(IPropertyType prop, T def); - - boolean hasProperty(IPropertyType prop); - void removeProperty(IPropertyType prop); - - void setProperty(IPropertyType prop, T value); - - void removeAllProps(); +public interface IPropertyContainer { + T getProperty(IPropertyType prop); + + T getProperty(IPropertyType prop, T def); + + boolean hasProperty(IPropertyType prop); + + void removeProperty(IPropertyType prop); + + void setProperty(IPropertyType prop, T value); + + void removeAllProps(); } \ No newline at end of file diff --git a/src/main/java/betterquesting/api/properties/IPropertyType.java b/src/main/java/betterquesting/api/properties/IPropertyType.java index b7bb17b30..b821d7595 100644 --- a/src/main/java/betterquesting/api/properties/IPropertyType.java +++ b/src/main/java/betterquesting/api/properties/IPropertyType.java @@ -3,11 +3,12 @@ import net.minecraft.nbt.NBTBase; import net.minecraft.util.ResourceLocation; -public interface IPropertyType -{ - ResourceLocation getKey(); - T getDefault(); - - T readValue(NBTBase nbt); - NBTBase writeValue(T value); +public interface IPropertyType { + ResourceLocation getKey(); + + T getDefault(); + + T readValue(NBTBase nbt); + + NBTBase writeValue(T value); } diff --git a/src/main/java/betterquesting/api/properties/NativeProps.java b/src/main/java/betterquesting/api/properties/NativeProps.java index 57e2a6e3e..042d335d3 100644 --- a/src/main/java/betterquesting/api/properties/NativeProps.java +++ b/src/main/java/betterquesting/api/properties/NativeProps.java @@ -1,66 +1,95 @@ package betterquesting.api.properties; -import net.minecraft.init.Items; -import net.minecraft.util.ResourceLocation; import betterquesting.api.enums.EnumLogic; import betterquesting.api.enums.EnumQuestVisibility; -import betterquesting.api.properties.basic.PropertyTypeBoolean; -import betterquesting.api.properties.basic.PropertyTypeEnum; -import betterquesting.api.properties.basic.PropertyTypeFloat; -import betterquesting.api.properties.basic.PropertyTypeInteger; -import betterquesting.api.properties.basic.PropertyTypeItemStack; -import betterquesting.api.properties.basic.PropertyTypeString; +import betterquesting.api.properties.basic.*; import betterquesting.api.utils.BigItemStack; +import net.minecraft.init.Items; +import net.minecraft.util.ResourceLocation; // TODO: SPLIT THIS DAMN FILE UP. It's already too big and it needs to be divided up per-purpose + /** * List of native properties used in BetterQuesting */ -public class NativeProps -{ - public static final IPropertyType NAME = new PropertyTypeString(new ResourceLocation("betterquesting:name"), "untitled.name"); - public static final IPropertyType DESC = new PropertyTypeString(new ResourceLocation("betterquesting:desc"), "untitled.desc"); - - @Deprecated - public static final IPropertyType MAIN = new PropertyTypeBoolean(new ResourceLocation("betterquesting:isMain"), false); - public static final IPropertyType GLOBAL = new PropertyTypeBoolean(new ResourceLocation("betterquesting:isGlobal"), false); - public static final IPropertyType GLOBAL_SHARE = new PropertyTypeBoolean(new ResourceLocation("betterquesting:globalShare"), false); - public static final IPropertyType SILENT = new PropertyTypeBoolean(new ResourceLocation("betterquesting:isSilent"), false); - public static final IPropertyType AUTO_CLAIM = new PropertyTypeBoolean(new ResourceLocation("betterquesting:autoClaim"), false); - public static final IPropertyType LOCKED_PROGRESS = new PropertyTypeBoolean(new ResourceLocation("betterquesting:lockedProgress"), false); - public static final IPropertyType SIMULTANEOUS = new PropertyTypeBoolean(new ResourceLocation("betterquesting:simultaneous"), false); - - public static final IPropertyType VISIBILITY = new PropertyTypeEnum<>(new ResourceLocation("betterquesting:visibility"), EnumQuestVisibility.NORMAL); - public static final IPropertyType LOGIC_TASK = new PropertyTypeEnum<>(new ResourceLocation("betterquesting:taskLogic"), EnumLogic.AND); - public static final IPropertyType LOGIC_QUEST = new PropertyTypeEnum<>(new ResourceLocation("betterquesting:questLogic"), EnumLogic.AND); - - public static final IPropertyType REPEAT_TIME = new PropertyTypeInteger(new ResourceLocation("betterquesting:repeatTime"), -1); - public static final IPropertyType REPEAT_REL = new PropertyTypeBoolean(new ResourceLocation("betterquesting:repeat_relative"), true); - - public static final IPropertyType SOUND_UNLOCK = new PropertyTypeString(new ResourceLocation("betterquesting:snd_unlock"), "minecraft:ui.button.click"); - public static final IPropertyType SOUND_UPDATE = new PropertyTypeString(new ResourceLocation("betterquesting:snd_update"), "minecraft:entity.player.levelup"); - public static final IPropertyType SOUND_COMPLETE = new PropertyTypeString(new ResourceLocation("betterquesting:snd_complete"), "minecraft:entity.player.levelup"); - - public static final IPropertyType ICON = new PropertyTypeItemStack(new ResourceLocation("betterquesting:icon"), new BigItemStack(Items.NETHER_STAR)); - //public static final IPropertyType FRAME = new PropertyTypeString(new ResourceLocation("betterquesting:frame"), ""); - - public static final IPropertyType BG_IMAGE = new PropertyTypeString(new ResourceLocation("betterquesting:bg_image"), ""); - public static final IPropertyType BG_SIZE = new PropertyTypeInteger(new ResourceLocation("betterquesting:bg_size"), 256); - - public static final IPropertyType PARTY_ENABLE = new PropertyTypeBoolean(new ResourceLocation("betterquesting:party_enable"), true); - - public static final IPropertyType HARDCORE = new PropertyTypeBoolean(new ResourceLocation("betterquesting:hardcore"), false); - public static final IPropertyType EDIT_MODE = new PropertyTypeBoolean(new ResourceLocation("betterquesting:editMode"), true); - public static final IPropertyType LIVES = new PropertyTypeInteger(new ResourceLocation("betterquesting:lives"), 1); - public static final IPropertyType LIVES_DEF = new PropertyTypeInteger(new ResourceLocation("betterquesting:livesDef"), 3); - public static final IPropertyType LIVES_MAX = new PropertyTypeInteger(new ResourceLocation("betterquesting:livesMax"), 10); - - public static final IPropertyType HOME_IMAGE = new PropertyTypeString(new ResourceLocation("betterquesting:home_image"), "betterquesting:textures/gui/default_title.png"); - public static final IPropertyType HOME_ANC_X = new PropertyTypeFloat(new ResourceLocation("betterquesting:home_anchor_x"), 0.5F); - public static final IPropertyType HOME_ANC_Y = new PropertyTypeFloat(new ResourceLocation("betterquesting:home_anchor_y"), 0F); - public static final IPropertyType HOME_OFF_X = new PropertyTypeInteger(new ResourceLocation("betterquesting:home_offset_x"), -128); - public static final IPropertyType HOME_OFF_Y = new PropertyTypeInteger(new ResourceLocation("betterquesting:home_offset_y"), 0); - - public static final IPropertyType PACK_VER = new PropertyTypeInteger(new ResourceLocation("betterquesting:pack_version"), 0); - public static final IPropertyType PACK_NAME = new PropertyTypeString(new ResourceLocation("betterquesting:pack_name"), ""); +public class NativeProps { + public static final IPropertyType NAME = + new PropertyTypeString(new ResourceLocation("betterquesting:name"), "untitled.name"); + public static final IPropertyType DESC = + new PropertyTypeString(new ResourceLocation("betterquesting:desc"), "untitled.desc"); + + @Deprecated + public static final IPropertyType MAIN = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:isMain"), false); + public static final IPropertyType GLOBAL = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:isGlobal"), false); + public static final IPropertyType GLOBAL_SHARE = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:globalShare"), false); + public static final IPropertyType SILENT = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:isSilent"), false); + public static final IPropertyType AUTO_CLAIM = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:autoClaim"), false); + public static final IPropertyType LOCKED_PROGRESS = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:lockedProgress"), false); + public static final IPropertyType SIMULTANEOUS = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:simultaneous"), false); + + public static final IPropertyType VISIBILITY = + new PropertyTypeEnum<>(new ResourceLocation("betterquesting:visibility"), EnumQuestVisibility.NORMAL); + public static final IPropertyType LOGIC_TASK = + new PropertyTypeEnum<>(new ResourceLocation("betterquesting:taskLogic"), EnumLogic.AND); + public static final IPropertyType LOGIC_QUEST = + new PropertyTypeEnum<>(new ResourceLocation("betterquesting:questLogic"), EnumLogic.AND); + + public static final IPropertyType REPEAT_TIME = + new PropertyTypeInteger(new ResourceLocation("betterquesting:repeatTime"), -1); + public static final IPropertyType REPEAT_REL = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:repeat_relative"), true); + + public static final IPropertyType SOUND_UNLOCK = + new PropertyTypeString(new ResourceLocation("betterquesting:snd_unlock"), "minecraft:ui.button.click"); + public static final IPropertyType SOUND_UPDATE = + new PropertyTypeString(new ResourceLocation("betterquesting:snd_update"), "minecraft:entity.player.levelup"); + public static final IPropertyType SOUND_COMPLETE = + new PropertyTypeString(new ResourceLocation("betterquesting:snd_complete"), "minecraft:entity.player.levelup"); + + public static final IPropertyType ICON = + new PropertyTypeItemStack(new ResourceLocation("betterquesting:icon"), new BigItemStack(Items.NETHER_STAR)); + //public static final IPropertyType FRAME = new PropertyTypeString(new ResourceLocation("betterquesting:frame"), ""); + + public static final IPropertyType BG_IMAGE = + new PropertyTypeString(new ResourceLocation("betterquesting:bg_image"), ""); + public static final IPropertyType BG_SIZE = + new PropertyTypeInteger(new ResourceLocation("betterquesting:bg_size"), 256); + + public static final IPropertyType PARTY_ENABLE = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:party_enable"), true); + + public static final IPropertyType HARDCORE = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:hardcore"), false); + public static final IPropertyType EDIT_MODE = + new PropertyTypeBoolean(new ResourceLocation("betterquesting:editMode"), true); + public static final IPropertyType LIVES = + new PropertyTypeInteger(new ResourceLocation("betterquesting:lives"), 1); + public static final IPropertyType LIVES_DEF = + new PropertyTypeInteger(new ResourceLocation("betterquesting:livesDef"), 3); + public static final IPropertyType LIVES_MAX = + new PropertyTypeInteger(new ResourceLocation("betterquesting:livesMax"), 10); + + public static final IPropertyType HOME_IMAGE = + new PropertyTypeString(new ResourceLocation("betterquesting:home_image"), + "betterquesting:textures/gui/default_title.png"); + public static final IPropertyType HOME_ANC_X = + new PropertyTypeFloat(new ResourceLocation("betterquesting:home_anchor_x"), 0.5F); + public static final IPropertyType HOME_ANC_Y = + new PropertyTypeFloat(new ResourceLocation("betterquesting:home_anchor_y"), 0F); + public static final IPropertyType HOME_OFF_X = + new PropertyTypeInteger(new ResourceLocation("betterquesting:home_offset_x"), -128); + public static final IPropertyType HOME_OFF_Y = + new PropertyTypeInteger(new ResourceLocation("betterquesting:home_offset_y"), 0); + + public static final IPropertyType PACK_VER = + new PropertyTypeInteger(new ResourceLocation("betterquesting:pack_version"), 0); + public static final IPropertyType PACK_NAME = + new PropertyTypeString(new ResourceLocation("betterquesting:pack_name"), ""); } \ No newline at end of file diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeBase.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeBase.java index b35b81fdf..8ed8267a3 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeBase.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeBase.java @@ -1,28 +1,24 @@ package betterquesting.api.properties.basic; -import net.minecraft.util.ResourceLocation; import betterquesting.api.properties.IPropertyType; +import net.minecraft.util.ResourceLocation; + +public abstract class PropertyTypeBase implements IPropertyType { + private final ResourceLocation key; + private final T def; + + public PropertyTypeBase(ResourceLocation key, T def) { + this.key = key; + this.def = def; + } + + @Override + public ResourceLocation getKey() { + return key; + } -public abstract class PropertyTypeBase implements IPropertyType -{ - private final ResourceLocation key; - private final T def; - - public PropertyTypeBase(ResourceLocation key, T def) - { - this.key = key; - this.def = def; - } - - @Override - public ResourceLocation getKey() - { - return key; - } - - @Override - public T getDefault() - { - return def; - } + @Override + public T getDefault() { + return def; + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java index 321efb9ad..d5f448f31 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java @@ -5,38 +5,30 @@ import net.minecraft.nbt.NBTTagByte; import net.minecraft.util.ResourceLocation; -public class PropertyTypeBoolean extends PropertyTypeBase -{ - public PropertyTypeBoolean(ResourceLocation key, Boolean def) - { - super(key, def); - } - - @Override - public Boolean readValue(NBTBase nbt) - { - if(nbt == null || nbt.getId() < 1 || nbt.getId() > 6) - { - return this.getDefault(); - } - - try - { - return ((NBTPrimitive)nbt).getByte() > 0; - } catch(Exception e) - { - return this.getDefault(); - } - } - - @Override - public NBTBase writeValue(Boolean value) - { - if(value == null) - { - return new NBTTagByte(this.getDefault() ? (byte)1 : (byte)0); - } - - return new NBTTagByte(value ? (byte)1 : (byte)0); - } +public class PropertyTypeBoolean extends PropertyTypeBase { + public PropertyTypeBoolean(ResourceLocation key, Boolean def) { + super(key, def); + } + + @Override + public Boolean readValue(NBTBase nbt) { + if (nbt == null || nbt.getId() < 1 || nbt.getId() > 6) { + return this.getDefault(); + } + + try { + return ((NBTPrimitive) nbt).getByte() > 0; + } catch (Exception e) { + return this.getDefault(); + } + } + + @Override + public NBTBase writeValue(Boolean value) { + if (value == null) { + return new NBTTagByte(this.getDefault() ? (byte) 1 : (byte) 0); + } + + return new NBTTagByte(value ? (byte) 1 : (byte) 0); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java index 25da46a13..7de8c7ca2 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java @@ -5,32 +5,26 @@ import net.minecraft.nbt.NBTTagByte; import net.minecraft.util.ResourceLocation; -public class PropertyTypeByte extends PropertyTypeBase -{ - public PropertyTypeByte(ResourceLocation key, Byte def) - { - super(key, def); - } +public class PropertyTypeByte extends PropertyTypeBase { + public PropertyTypeByte(ResourceLocation key, Byte def) { + super(key, def); + } - @Override - public Byte readValue(NBTBase nbt) - { - if(nbt == null || !(nbt instanceof NBTPrimitive)) - { - return this.getDefault(); - } - - return ((NBTPrimitive)nbt).getByte(); - } + @Override + public Byte readValue(NBTBase nbt) { + if (!(nbt instanceof NBTPrimitive)) { + return this.getDefault(); + } - @Override - public NBTBase writeValue(Byte value) - { - if(value == null) - { - return new NBTTagByte(this.getDefault()); - } - - return new NBTTagByte(value); - } + return ((NBTPrimitive) nbt).getByte(); + } + + @Override + public NBTBase writeValue(Byte value) { + if (value == null) { + return new NBTTagByte(this.getDefault()); + } + + return new NBTTagByte(value); + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java index 7ad65016e..eeed6ef03 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java @@ -5,32 +5,26 @@ import net.minecraft.nbt.NBTTagDouble; import net.minecraft.util.ResourceLocation; -public class PropertyTypeDouble extends PropertyTypeBase -{ - public PropertyTypeDouble(ResourceLocation key, Double def) - { - super(key, def); - } +public class PropertyTypeDouble extends PropertyTypeBase { + public PropertyTypeDouble(ResourceLocation key, Double def) { + super(key, def); + } - @Override - public Double readValue(NBTBase nbt) - { - if(nbt == null || !(nbt instanceof NBTPrimitive)) - { - return this.getDefault(); - } - - return ((NBTPrimitive)nbt).getDouble(); - } + @Override + public Double readValue(NBTBase nbt) { + if (!(nbt instanceof NBTPrimitive)) { + return this.getDefault(); + } - @Override - public NBTBase writeValue(Double value) - { - if(value == null) - { - return new NBTTagDouble(this.getDefault()); - } - - return new NBTTagDouble(value); - } + return ((NBTPrimitive) nbt).getDouble(); + } + + @Override + public NBTBase writeValue(Double value) { + if (value == null) { + return new NBTTagDouble(this.getDefault()); + } + + return new NBTTagDouble(value); + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java index 67e066f35..36fb6fa2a 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java @@ -4,42 +4,34 @@ import net.minecraft.nbt.NBTTagString; import net.minecraft.util.ResourceLocation; -public class PropertyTypeEnum> extends PropertyTypeBase -{ - private final Class eClazz; - - public PropertyTypeEnum(ResourceLocation key, E def) - { - super(key, def); - - eClazz = def.getDeclaringClass(); - } - - @Override - public E readValue(NBTBase nbt) - { - if(nbt == null || nbt.getId() != 8) - { - return this.getDefault(); - } - - try - { - return Enum.valueOf(eClazz, ((NBTTagString)nbt).getString()); - } catch(Exception e) - { - return this.getDefault(); - } - } - - @Override - public NBTBase writeValue(E value) - { - if(value == null) - { - return new NBTTagString(this.getDefault().toString()); - } - - return new NBTTagString(value.toString()); - } +public class PropertyTypeEnum> extends PropertyTypeBase { + private final Class eClazz; + + public PropertyTypeEnum(ResourceLocation key, E def) { + super(key, def); + + eClazz = def.getDeclaringClass(); + } + + @Override + public E readValue(NBTBase nbt) { + if (nbt == null || nbt.getId() != 8) { + return this.getDefault(); + } + + try { + return Enum.valueOf(eClazz, ((NBTTagString) nbt).getString()); + } catch (Exception e) { + return this.getDefault(); + } + } + + @Override + public NBTBase writeValue(E value) { + if (value == null) { + return new NBTTagString(this.getDefault().toString()); + } + + return new NBTTagString(value.toString()); + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java index 9e5e976e3..52301f3e8 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java @@ -5,32 +5,26 @@ import net.minecraft.nbt.NBTTagFloat; import net.minecraft.util.ResourceLocation; -public class PropertyTypeFloat extends PropertyTypeBase -{ - public PropertyTypeFloat(ResourceLocation key, Float def) - { - super(key, def); - } +public class PropertyTypeFloat extends PropertyTypeBase { + public PropertyTypeFloat(ResourceLocation key, Float def) { + super(key, def); + } - @Override - public Float readValue(NBTBase nbt) - { - if(nbt == null || !(nbt instanceof NBTPrimitive)) - { - return this.getDefault(); - } - - return ((NBTPrimitive)nbt).getFloat(); - } + @Override + public Float readValue(NBTBase nbt) { + if (!(nbt instanceof NBTPrimitive)) { + return this.getDefault(); + } - @Override - public NBTBase writeValue(Float value) - { - if(value == null) - { - return new NBTTagFloat(this.getDefault()); - } - - return new NBTTagFloat(value); - } + return ((NBTPrimitive) nbt).getFloat(); + } + + @Override + public NBTBase writeValue(Float value) { + if (value == null) { + return new NBTTagFloat(this.getDefault()); + } + + return new NBTTagFloat(value); + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java index 41e26bccd..366cfd8b3 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java @@ -5,32 +5,26 @@ import net.minecraft.nbt.NBTTagInt; import net.minecraft.util.ResourceLocation; -public class PropertyTypeInteger extends PropertyTypeBase -{ - public PropertyTypeInteger(ResourceLocation key, Integer def) - { - super(key, def); - } +public class PropertyTypeInteger extends PropertyTypeBase { + public PropertyTypeInteger(ResourceLocation key, Integer def) { + super(key, def); + } - @Override - public Integer readValue(NBTBase nbt) - { - if(nbt == null || !(nbt instanceof NBTPrimitive)) - { - return this.getDefault(); - } - - return ((NBTPrimitive)nbt).getInt(); - } + @Override + public Integer readValue(NBTBase nbt) { + if (!(nbt instanceof NBTPrimitive)) { + return this.getDefault(); + } - @Override - public NBTBase writeValue(Integer value) - { - if(value == null) - { - return new NBTTagInt(this.getDefault()); - } - - return new NBTTagInt(value); - } + return ((NBTPrimitive) nbt).getInt(); + } + + @Override + public NBTBase writeValue(Integer value) { + if (value == null) { + return new NBTTagInt(this.getDefault()); + } + + return new NBTTagInt(value); + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java index 76b6c16e0..e0fd6ed35 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java @@ -1,42 +1,35 @@ package betterquesting.api.properties.basic; +import betterquesting.api.utils.BigItemStack; +import betterquesting.api.utils.JsonHelper; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; -import betterquesting.api.utils.BigItemStack; -import betterquesting.api.utils.JsonHelper; -public class PropertyTypeItemStack extends PropertyTypeBase -{ - public PropertyTypeItemStack(ResourceLocation key, BigItemStack def) - { - super(key, def); - } - - @Override - public BigItemStack readValue(NBTBase nbt) - { - if(nbt == null || nbt.getId() != 10) - { - return this.getDefault(); - } - - return JsonHelper.JsonToItemStack((NBTTagCompound)nbt); - } - - @Override - public NBTBase writeValue(BigItemStack value) - { - NBTTagCompound nbt = new NBTTagCompound(); - - if(value == null || value.getBaseStack() == null) - { - getDefault().writeToNBT(nbt); - } else - { - value.writeToNBT(nbt); - } - - return nbt; - } +public class PropertyTypeItemStack extends PropertyTypeBase { + public PropertyTypeItemStack(ResourceLocation key, BigItemStack def) { + super(key, def); + } + + @Override + public BigItemStack readValue(NBTBase nbt) { + if (nbt == null || nbt.getId() != 10) { + return this.getDefault(); + } + + return JsonHelper.JsonToItemStack((NBTTagCompound) nbt); + } + + @Override + public NBTBase writeValue(BigItemStack value) { + NBTTagCompound nbt = new NBTTagCompound(); + + if (value == null || value.getBaseStack() == null) { + getDefault().writeToNBT(nbt); + } else { + value.writeToNBT(nbt); + } + + return nbt; + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java index 90cd823a2..740763599 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java @@ -5,32 +5,26 @@ import net.minecraft.nbt.NBTTagLong; import net.minecraft.util.ResourceLocation; -public class PropertyTypeLong extends PropertyTypeBase -{ - public PropertyTypeLong(ResourceLocation key, Long def) - { - super(key, def); - } +public class PropertyTypeLong extends PropertyTypeBase { + public PropertyTypeLong(ResourceLocation key, Long def) { + super(key, def); + } - @Override - public Long readValue(NBTBase nbt) - { - if(nbt == null || !(nbt instanceof NBTPrimitive)) - { - return this.getDefault(); - } - - return ((NBTPrimitive)nbt).getLong(); - } + @Override + public Long readValue(NBTBase nbt) { + if (!(nbt instanceof NBTPrimitive)) { + return this.getDefault(); + } - @Override - public NBTBase writeValue(Long value) - { - if(value == null) - { - return new NBTTagLong(this.getDefault()); - } - - return new NBTTagLong(value); - } + return ((NBTPrimitive) nbt).getLong(); + } + + @Override + public NBTBase writeValue(Long value) { + if (value == null) { + return new NBTTagLong(this.getDefault()); + } + + return new NBTTagLong(value); + } } diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java index 3484f1859..f4f92cade 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java @@ -4,32 +4,26 @@ import net.minecraft.nbt.NBTTagString; import net.minecraft.util.ResourceLocation; -public class PropertyTypeString extends PropertyTypeBase -{ - public PropertyTypeString(ResourceLocation key, String def) - { - super(key, def); - } - - @Override - public String readValue(NBTBase nbt) - { - if(nbt == null || nbt.getId() != 8) - { - return this.getDefault(); - } - - return ((NBTTagString)nbt).getString(); - } - - @Override - public NBTBase writeValue(String value) - { - if(value == null) - { - return new NBTTagString(this.getDefault()); - } - - return new NBTTagString(value); - } +public class PropertyTypeString extends PropertyTypeBase { + public PropertyTypeString(ResourceLocation key, String def) { + super(key, def); + } + + @Override + public String readValue(NBTBase nbt) { + if (nbt == null || nbt.getId() != 8) { + return this.getDefault(); + } + + return ((NBTTagString) nbt).getString(); + } + + @Override + public NBTBase writeValue(String value) { + if (value == null) { + return new NBTTagString(this.getDefault()); + } + + return new NBTTagString(value); + } } diff --git a/src/main/java/betterquesting/api/questing/IQuest.java b/src/main/java/betterquesting/api/questing/IQuest.java index 21470e6d0..dfbdb42e1 100644 --- a/src/main/java/betterquesting/api/questing/IQuest.java +++ b/src/main/java/betterquesting/api/questing/IQuest.java @@ -15,34 +15,42 @@ import javax.annotation.Nullable; import java.util.UUID; -public interface IQuest extends INBTSaveLoad, INBTProgress, IPropertyContainer -{ - EnumQuestState getState(UUID uuid); - - @Nullable - NBTTagCompound getCompletionInfo(UUID uuid); - void setCompletionInfo(UUID uuid, @Nullable NBTTagCompound nbt); - - void update(EntityPlayer player); - void detect(EntityPlayer player); - - boolean isUnlocked(UUID uuid); - boolean canSubmit(EntityPlayer player); - - boolean isComplete(UUID uuid); - void setComplete(UUID uuid, long timeStamp); - - boolean canClaim(EntityPlayer player); - boolean hasClaimed(UUID uuid); - void claimReward(EntityPlayer player); - void setClaimed(UUID uuid, long timestamp); - - void resetUser(@Nullable UUID uuid, boolean fullReset); - - IDatabaseNBT getTasks(); - IDatabaseNBT getRewards(); - - @Nonnull - int[] getRequirements(); - void setRequirements(@Nonnull int[] req); +public interface IQuest extends INBTSaveLoad, INBTProgress, IPropertyContainer { + EnumQuestState getState(UUID uuid); + + @Nullable + NBTTagCompound getCompletionInfo(UUID uuid); + + void setCompletionInfo(UUID uuid, @Nullable NBTTagCompound nbt); + + void update(EntityPlayer player); + + void detect(EntityPlayer player); + + boolean isUnlocked(UUID uuid); + + boolean canSubmit(EntityPlayer player); + + boolean isComplete(UUID uuid); + + void setComplete(UUID uuid, long timeStamp); + + boolean canClaim(EntityPlayer player); + + boolean hasClaimed(UUID uuid); + + void claimReward(EntityPlayer player); + + void setClaimed(UUID uuid, long timestamp); + + void resetUser(@Nullable UUID uuid, boolean fullReset); + + IDatabaseNBT getTasks(); + + IDatabaseNBT getRewards(); + + @Nonnull + int[] getRequirements(); + + void setRequirements(@Nonnull int[] req); } diff --git a/src/main/java/betterquesting/api/questing/IQuestDatabase.java b/src/main/java/betterquesting/api/questing/IQuestDatabase.java index 7450618be..811fe0201 100644 --- a/src/main/java/betterquesting/api/questing/IQuestDatabase.java +++ b/src/main/java/betterquesting/api/questing/IQuestDatabase.java @@ -5,7 +5,6 @@ import betterquesting.api2.storage.INBTProgress; import net.minecraft.nbt.NBTTagList; -public interface IQuestDatabase extends IDatabase, INBTPartial, INBTProgress -{ - IQuest createNew(int id); +public interface IQuestDatabase extends IDatabase, INBTPartial, INBTProgress { + IQuest createNew(int id); } diff --git a/src/main/java/betterquesting/api/questing/IQuestLine.java b/src/main/java/betterquesting/api/questing/IQuestLine.java index ab6a8e74e..db0655f7f 100644 --- a/src/main/java/betterquesting/api/questing/IQuestLine.java +++ b/src/main/java/betterquesting/api/questing/IQuestLine.java @@ -6,12 +6,13 @@ import betterquesting.api2.storage.INBTPartial; import net.minecraft.nbt.NBTTagCompound; -public interface IQuestLine extends IDatabase, INBTPartial, IPropertyContainer -{ - IQuestLineEntry createNew(int id); - - String getUnlocalisedName(); - String getUnlocalisedDescription(); - - DBEntry getEntryAt(int x, int y); +public interface IQuestLine + extends IDatabase, INBTPartial, IPropertyContainer { + IQuestLineEntry createNew(int id); + + String getUnlocalisedName(); + + String getUnlocalisedDescription(); + + DBEntry getEntryAt(int x, int y); } diff --git a/src/main/java/betterquesting/api/questing/IQuestLineDatabase.java b/src/main/java/betterquesting/api/questing/IQuestLineDatabase.java index d679a948b..6ec3262ff 100644 --- a/src/main/java/betterquesting/api/questing/IQuestLineDatabase.java +++ b/src/main/java/betterquesting/api/questing/IQuestLineDatabase.java @@ -7,18 +7,18 @@ import java.util.List; -public interface IQuestLineDatabase extends IDatabase, INBTPartial -{ - IQuestLine createNew(int id); - - /** - * Deletes quest from all quest lines - */ - void removeQuest(int questID); - - int getOrderIndex(int lineID); - void setOrderIndex(int lineID, int index); - - List> getSortedEntries(); - +public interface IQuestLineDatabase extends IDatabase, INBTPartial { + IQuestLine createNew(int id); + + /** + * Deletes quest from all quest lines + */ + void removeQuest(int questID); + + int getOrderIndex(int lineID); + + void setOrderIndex(int lineID, int index); + + List> getSortedEntries(); + } diff --git a/src/main/java/betterquesting/api/questing/IQuestLineEntry.java b/src/main/java/betterquesting/api/questing/IQuestLineEntry.java index a2a5c9aa4..e799c94c1 100644 --- a/src/main/java/betterquesting/api/questing/IQuestLineEntry.java +++ b/src/main/java/betterquesting/api/questing/IQuestLineEntry.java @@ -3,20 +3,22 @@ import betterquesting.api2.storage.INBTSaveLoad; import net.minecraft.nbt.NBTTagCompound; -public interface IQuestLineEntry extends INBTSaveLoad -{ - @Deprecated - int getSize(); - - int getSizeX(); - int getSizeY(); - int getPosX(); - int getPosY(); - - void setPosition(int posX, int posY); - - @Deprecated - void setSize(int size); - - void setSize(int sizeX, int sizeY); +public interface IQuestLineEntry extends INBTSaveLoad { + @Deprecated + int getSize(); + + int getSizeX(); + + int getSizeY(); + + int getPosX(); + + int getPosY(); + + void setPosition(int posX, int posY); + + @Deprecated + void setSize(int size); + + void setSize(int sizeX, int sizeY); } diff --git a/src/main/java/betterquesting/api/questing/party/IParty.java b/src/main/java/betterquesting/api/questing/party/IParty.java index 0626fe629..a26389f43 100644 --- a/src/main/java/betterquesting/api/questing/party/IParty.java +++ b/src/main/java/betterquesting/api/questing/party/IParty.java @@ -10,18 +10,19 @@ import java.util.List; import java.util.UUID; -public interface IParty extends INBTSaveLoad -{ - IPropertyContainer getProperties(); - - void kickUser(@Nonnull UUID uuid); - void setStatus(@Nonnull UUID uuid, @Nonnull EnumPartyStatus priv); - - @Nullable - EnumPartyStatus getStatus(@Nonnull UUID uuid); - - List getMembers(); - - NBTTagCompound writeProperties(NBTTagCompound nbt); - void readProperties(NBTTagCompound nbt); +public interface IParty extends INBTSaveLoad { + IPropertyContainer getProperties(); + + void kickUser(@Nonnull UUID uuid); + + void setStatus(@Nonnull UUID uuid, @Nonnull EnumPartyStatus priv); + + @Nullable + EnumPartyStatus getStatus(@Nonnull UUID uuid); + + List getMembers(); + + NBTTagCompound writeProperties(NBTTagCompound nbt); + + void readProperties(NBTTagCompound nbt); } diff --git a/src/main/java/betterquesting/api/questing/party/IPartyDatabase.java b/src/main/java/betterquesting/api/questing/party/IPartyDatabase.java index 80c40fe60..b5ceaa082 100644 --- a/src/main/java/betterquesting/api/questing/party/IPartyDatabase.java +++ b/src/main/java/betterquesting/api/questing/party/IPartyDatabase.java @@ -9,10 +9,9 @@ import javax.annotation.Nullable; import java.util.UUID; -public interface IPartyDatabase extends IDatabase, INBTPartial -{ - IParty createNew(int id); - - @Nullable - DBEntry getParty(@Nonnull UUID uuid); +public interface IPartyDatabase extends IDatabase, INBTPartial { + IParty createNew(int id); + + @Nullable + DBEntry getParty(@Nonnull UUID uuid); } diff --git a/src/main/java/betterquesting/api/questing/rewards/IReward.java b/src/main/java/betterquesting/api/questing/rewards/IReward.java index da4549524..833688444 100644 --- a/src/main/java/betterquesting/api/questing/rewards/IReward.java +++ b/src/main/java/betterquesting/api/questing/rewards/IReward.java @@ -14,18 +14,19 @@ import javax.annotation.Nullable; -public interface IReward extends INBTSaveLoad -{ - String getUnlocalisedName(); - ResourceLocation getFactoryID(); - - boolean canClaim(EntityPlayer player, DBEntry quest); - void claimReward(EntityPlayer player, DBEntry quest); - - @SideOnly(Side.CLIENT) - IGuiPanel getRewardGui(IGuiRect rect, DBEntry quest); - - @Nullable - @SideOnly(Side.CLIENT) - GuiScreen getRewardEditor(GuiScreen parent, DBEntry quest); +public interface IReward extends INBTSaveLoad { + String getUnlocalisedName(); + + ResourceLocation getFactoryID(); + + boolean canClaim(EntityPlayer player, DBEntry quest); + + void claimReward(EntityPlayer player, DBEntry quest); + + @SideOnly(Side.CLIENT) + IGuiPanel getRewardGui(IGuiRect rect, DBEntry quest); + + @Nullable + @SideOnly(Side.CLIENT) + GuiScreen getRewardEditor(GuiScreen parent, DBEntry quest); } diff --git a/src/main/java/betterquesting/api/questing/tasks/IEnergyTask.java b/src/main/java/betterquesting/api/questing/tasks/IEnergyTask.java new file mode 100644 index 000000000..7c81b5351 --- /dev/null +++ b/src/main/java/betterquesting/api/questing/tasks/IEnergyTask.java @@ -0,0 +1,10 @@ +package betterquesting.api.questing.tasks; + +import betterquesting.api.questing.IQuest; +import betterquesting.api2.storage.DBEntry; + +import java.util.UUID; + +public interface IEnergyTask extends ITask { + int submitEnergy(UUID owner, DBEntry quest, int energy, boolean doSubmit); +} diff --git a/src/main/java/betterquesting/api/questing/tasks/IFluidTask.java b/src/main/java/betterquesting/api/questing/tasks/IFluidTask.java index ac239976d..4f3b6aaa6 100644 --- a/src/main/java/betterquesting/api/questing/tasks/IFluidTask.java +++ b/src/main/java/betterquesting/api/questing/tasks/IFluidTask.java @@ -6,8 +6,8 @@ import java.util.UUID; -public interface IFluidTask extends ITask -{ - boolean canAcceptFluid(UUID owner, DBEntry quest, FluidStack fluid); - FluidStack submitFluid(UUID owner, DBEntry quest, FluidStack fluid); +public interface IFluidTask extends ITask { + boolean canAcceptFluid(UUID owner, DBEntry quest, FluidStack fluid); + + FluidStack submitFluid(UUID owner, DBEntry quest, FluidStack fluid, boolean doSubmit); } diff --git a/src/main/java/betterquesting/api/questing/tasks/IItemTask.java b/src/main/java/betterquesting/api/questing/tasks/IItemTask.java index cc452da59..04e5b59f9 100644 --- a/src/main/java/betterquesting/api/questing/tasks/IItemTask.java +++ b/src/main/java/betterquesting/api/questing/tasks/IItemTask.java @@ -6,8 +6,8 @@ import java.util.UUID; -public interface IItemTask extends ITask -{ - boolean canAcceptItem(UUID owner, DBEntry quest, ItemStack stack); - ItemStack submitItem(UUID owner, DBEntry quest, ItemStack stack); +public interface IItemTask extends ITask { + boolean canAcceptItem(UUID owner, DBEntry quest, ItemStack stack); + + ItemStack submitItem(UUID owner, DBEntry quest, ItemStack stack, boolean doSubmit); } diff --git a/src/main/java/betterquesting/api/questing/tasks/ITask.java b/src/main/java/betterquesting/api/questing/tasks/ITask.java index b9aba41db..b7dee5aa6 100644 --- a/src/main/java/betterquesting/api/questing/tasks/ITask.java +++ b/src/main/java/betterquesting/api/questing/tasks/ITask.java @@ -16,23 +16,24 @@ import javax.annotation.Nullable; import java.util.UUID; -public interface ITask extends INBTSaveLoad, INBTProgress -{ - String getUnlocalisedName(); - ResourceLocation getFactoryID(); - - void detect(ParticipantInfo participant, DBEntry quest); - - boolean isComplete(UUID uuid); - void setComplete(UUID uuid); - - void resetUser(@Nullable UUID uuid); - - @Nullable - @SideOnly(Side.CLIENT) - IGuiPanel getTaskGui(IGuiRect rect, DBEntry quest); - - @Nullable - @SideOnly(Side.CLIENT) - GuiScreen getTaskEditor(GuiScreen parent, DBEntry quest); +public interface ITask extends INBTSaveLoad, INBTProgress { + String getUnlocalisedName(); + + ResourceLocation getFactoryID(); + + void detect(ParticipantInfo participant, DBEntry quest); + + boolean isComplete(UUID uuid); + + void setComplete(UUID uuid); + + void resetUser(@Nullable UUID uuid); + + @Nullable + @SideOnly(Side.CLIENT) + IGuiPanel getTaskGui(IGuiRect rect, DBEntry quest); + + @Nullable + @SideOnly(Side.CLIENT) + GuiScreen getTaskEditor(GuiScreen parent, DBEntry quest); } diff --git a/src/main/java/betterquesting/api/storage/BQ_Settings.java b/src/main/java/betterquesting/api/storage/BQ_Settings.java index b4cd71059..2e4aba3ef 100644 --- a/src/main/java/betterquesting/api/storage/BQ_Settings.java +++ b/src/main/java/betterquesting/api/storage/BQ_Settings.java @@ -5,17 +5,16 @@ /** * A container for all the configurable settings in the mod */ -public class BQ_Settings -{ - /** - * The root directory of the currently loaded world/save - */ - public static File curWorldDir = null; - public static String defaultDir = "config/betterquesting/"; - - public static boolean useBookmark = true; - public static String curTheme = "betterquesting:light"; - public static int guiWidth = -1; - public static int guiHeight = -1; - public static boolean questNotices = true; +public class BQ_Settings { + /** + * The root directory of the currently loaded world/save + */ + public static File curWorldDir = null; + public static String defaultDir = "config/betterquesting/"; + + public static boolean useBookmark = true; + public static String curTheme = "betterquesting:light"; + public static int guiWidth = -1; + public static int guiHeight = -1; + public static boolean questNotices = true; } diff --git a/src/main/java/betterquesting/api/storage/ILifeDatabase.java b/src/main/java/betterquesting/api/storage/ILifeDatabase.java index 02ebeb59a..01b2f2db8 100644 --- a/src/main/java/betterquesting/api/storage/ILifeDatabase.java +++ b/src/main/java/betterquesting/api/storage/ILifeDatabase.java @@ -6,10 +6,10 @@ import javax.annotation.Nonnull; import java.util.UUID; -public interface ILifeDatabase extends INBTPartial -{ - int getLives(@Nonnull UUID uuid); - void setLives(@Nonnull UUID uuid, int value); - - void reset(); +public interface ILifeDatabase extends INBTPartial { + int getLives(@Nonnull UUID uuid); + + void setLives(@Nonnull UUID uuid, int value); + + void reset(); } diff --git a/src/main/java/betterquesting/api/storage/INameCache.java b/src/main/java/betterquesting/api/storage/INameCache.java index da1772bc1..5eebb8691 100644 --- a/src/main/java/betterquesting/api/storage/INameCache.java +++ b/src/main/java/betterquesting/api/storage/INameCache.java @@ -8,18 +8,19 @@ import java.util.List; import java.util.UUID; -public interface INameCache extends INBTPartial -{ - boolean updateName(@Nonnull EntityPlayerMP player); - String getName(@Nonnull UUID uuid); - UUID getUUID(@Nonnull String name); - - List getAllNames(); - - // Primarily used client side for GUIs - boolean isOP(@Nonnull UUID uuid); - - int size(); - - void reset(); +public interface INameCache extends INBTPartial { + boolean updateName(@Nonnull EntityPlayerMP player); + + String getName(@Nonnull UUID uuid); + + UUID getUUID(@Nonnull String name); + + List getAllNames(); + + // Primarily used client side for GUIs + boolean isOP(@Nonnull UUID uuid); + + int size(); + + void reset(); } diff --git a/src/main/java/betterquesting/api/storage/IQuestSettings.java b/src/main/java/betterquesting/api/storage/IQuestSettings.java index 95ba8aeb8..2c01942ee 100644 --- a/src/main/java/betterquesting/api/storage/IQuestSettings.java +++ b/src/main/java/betterquesting/api/storage/IQuestSettings.java @@ -4,8 +4,8 @@ import net.minecraft.entity.player.EntityPlayer; -public interface IQuestSettings extends IPropertyContainer -{ - boolean canUserEdit(EntityPlayer player); - void reset(); +public interface IQuestSettings extends IPropertyContainer { + boolean canUserEdit(EntityPlayer player); + + void reset(); } diff --git a/src/main/java/betterquesting/api/utils/BigItemStack.java b/src/main/java/betterquesting/api/utils/BigItemStack.java index 7d310263b..b13c717cd 100644 --- a/src/main/java/betterquesting/api/utils/BigItemStack.java +++ b/src/main/java/betterquesting/api/utils/BigItemStack.java @@ -16,168 +16,144 @@ * Purpose built container class for holding ItemStacks larger than 127.
* For storage purposes only! */ -public class BigItemStack -{ - private static final OreIngredient NO_ORE = new OreIngredient(""); - private final ItemStack baseStack; - public int stackSize; - private String oreDict = ""; - private OreIngredient oreIng = NO_ORE; - - public BigItemStack(ItemStack stack) - { - baseStack = stack.copy(); - this.stackSize = baseStack.getCount(); - baseStack.setCount(1); - } - - public BigItemStack(@Nonnull Block block) - { - this(block, 1); - } - - public BigItemStack(@Nonnull Block block, int amount) - { - this(block, amount, 0); - } - - public BigItemStack(@Nonnull Block block, int amount, int damage) - { - this(Item.getItemFromBlock(block), amount, damage); - } - - public BigItemStack(@Nonnull Item item) - { - this(item, 1); - } - - public BigItemStack(@Nonnull Item item, int amount) - { - this(item, amount, 0); - } - - public BigItemStack(@Nonnull Item item, int amount, int damage) - { - baseStack = new ItemStack(item, 1, damage); - this.stackSize = amount; - } - - /** - * @return ItemStack this BigItemStack is based on. Changing the base stack size does NOT affect the BigItemStack's size - */ - public ItemStack getBaseStack() - { - return baseStack; - } - - public boolean hasOreDict() - { - return !StringUtils.isNullOrEmpty(this.oreDict) && this.oreIng.getMatchingStacks().length > 0; - } - - @Nonnull - public String getOreDict() - { - return this.oreDict; +public class BigItemStack { + private static final OreIngredient NO_ORE = new OreIngredient(""); + private final ItemStack baseStack; + public int stackSize; + private String oreDict = ""; + private OreIngredient oreIng = NO_ORE; + + public BigItemStack(ItemStack stack) { + baseStack = stack.copy(); + this.stackSize = baseStack.getCount(); + baseStack.setCount(1); + } + + public BigItemStack(@Nonnull Block block) { + this(block, 1); + } + + public BigItemStack(@Nonnull Block block, int amount) { + this(block, amount, 0); + } + + public BigItemStack(@Nonnull Block block, int amount, int damage) { + this(Item.getItemFromBlock(block), amount, damage); + } + + public BigItemStack(@Nonnull Item item) { + this(item, 1); + } + + public BigItemStack(@Nonnull Item item, int amount) { + this(item, amount, 0); + } + + public BigItemStack(@Nonnull Item item, int amount, int damage) { + baseStack = new ItemStack(item, 1, damage); + this.stackSize = amount; + } + + /** + * @return ItemStack this BigItemStack is based on. Changing the base stack size does NOT affect the BigItemStack's size + */ + public ItemStack getBaseStack() { + return baseStack; + } + + public boolean hasOreDict() { + return !StringUtils.isNullOrEmpty(this.oreDict) && this.oreIng.getMatchingStacks().length > 0; + } + + @Nonnull + public String getOreDict() { + return this.oreDict; + } + + @Nonnull + public OreIngredient getOreIngredient() { + return this.oreIng; + } + + public BigItemStack setOreDict(@Nonnull String ore) { + this.oreDict = ore; + this.oreIng = ore.isEmpty() ? NO_ORE : new OreIngredient(ore); + return this; + } + + /** + * Shortcut method to the NBTTagCompound in the base ItemStack + */ + public NBTTagCompound GetTagCompound() { + return baseStack.getTagCompound(); + } + + /** + * Shortcut method to the NBTTagCompound in the base ItemStack + */ + public void SetTagCompound(NBTTagCompound tags) { + baseStack.setTagCompound(tags); + } + + /** + * Shortcut method to the NBTTagCompound in the base ItemStack + */ + public boolean HasTagCompound() { + return baseStack.hasTagCompound(); + } + + /** + * Breaks down this big stack into smaller ItemStacks for Minecraft to use (Individual stack size is dependent on the item) + */ + public List getCombinedStacks() { + List list = new ArrayList<>(); + int tmp1 = Math.max(1, stackSize); // Guarantees this method will return at least 1 item + + while (tmp1 > 0) { + int size = Math.min(tmp1, baseStack.getMaxStackSize()); + ItemStack stack = baseStack.copy(); + stack.setCount(size); + list.add(stack); + tmp1 -= size; } - - @Nonnull - public OreIngredient getOreIngredient() - { - return this.oreIng; + + return list; + } + + public BigItemStack copy() { + BigItemStack stack = new BigItemStack(baseStack.copy()); + stack.stackSize = this.stackSize; + stack.oreDict = this.oreDict; + stack.oreIng = this.oreIng; + return stack; + } + + @Override + public boolean equals(Object stack) { + if (stack instanceof ItemStack) { + return baseStack.isItemEqual((ItemStack) stack) && ItemStack.areItemStackTagsEqual(baseStack, (ItemStack) stack); + } else { + return super.equals(stack); } - - public BigItemStack setOreDict(@Nonnull String ore) - { - this.oreDict = ore; - this.oreIng = ore.length() <= 0 ? NO_ORE : new OreIngredient(ore); - return this; + } + + public BigItemStack(@Nonnull NBTTagCompound tags) // Can load normal ItemStack NBTs. Does NOT deal with placeholders + { + NBTTagCompound itemNBT = tags.copy(); + itemNBT.setInteger("Count", 1); + if (tags.hasKey("id", 99)) { + itemNBT.setString("id", "" + tags.getShort("id")); } - - /** - * Shortcut method to the NBTTagCompound in the base ItemStack - */ - public NBTTagCompound GetTagCompound() - { - return baseStack.getTagCompound(); - } - - /** - * Shortcut method to the NBTTagCompound in the base ItemStack - */ - public void SetTagCompound(NBTTagCompound tags) - { - baseStack.setTagCompound(tags); - } - - /** - * Shortcut method to the NBTTagCompound in the base ItemStack - */ - public boolean HasTagCompound() - { - return baseStack.hasTagCompound(); - } - - /** - * Breaks down this big stack into smaller ItemStacks for Minecraft to use (Individual stack size is dependent on the item) - */ - public List getCombinedStacks() - { - List list = new ArrayList<>(); - int tmp1 = Math.max(1, stackSize); // Guarantees this method will return at least 1 item - - while(tmp1 > 0) - { - int size = Math.min(tmp1, baseStack.getMaxStackSize()); - ItemStack stack = baseStack.copy(); - stack.setCount(size); - list.add(stack); - tmp1 -= size; - } - - return list; - } - - public BigItemStack copy() - { - BigItemStack stack = new BigItemStack(baseStack.copy()); - stack.stackSize = this.stackSize; - stack.oreDict = this.oreDict; - stack.oreIng = this.oreIng; - return stack; - } - - @Override - public boolean equals(Object stack) - { - if(stack instanceof ItemStack) - { - return baseStack.isItemEqual((ItemStack)stack) && ItemStack.areItemStackTagsEqual(baseStack, (ItemStack)stack); - } else - { - return super.equals(stack); - } - } - - public BigItemStack(@Nonnull NBTTagCompound tags) // Can load normal ItemStack NBTs. Does NOT deal with placeholders - { - NBTTagCompound itemNBT = tags.copy(); - itemNBT.setInteger("Count", 1); - if(tags.hasKey("id", 99)) - { - itemNBT.setString("id", "" + tags.getShort("id")); - } - this.stackSize = tags.getInteger("Count"); - this.setOreDict(tags.getString("OreDict")); - this.baseStack = new ItemStack(itemNBT); // Minecraft does the ID conversions for me - if(tags.getShort("Damage") < 0) this.baseStack.setItemDamage(OreDictionary.WILDCARD_VALUE); - } - - public NBTTagCompound writeToNBT(NBTTagCompound tags) - { - baseStack.writeToNBT(tags); - tags.setInteger("Count", stackSize); - tags.setString("OreDict", oreDict); - return tags; - } + this.stackSize = tags.getInteger("Count"); + this.setOreDict(tags.getString("OreDict")); + this.baseStack = new ItemStack(itemNBT); // Minecraft does the ID conversions for me + if (tags.getShort("Damage") < 0) { this.baseStack.setItemDamage(OreDictionary.WILDCARD_VALUE); } + } + + public NBTTagCompound writeToNBT(NBTTagCompound tags) { + baseStack.writeToNBT(tags); + tags.setInteger("Count", stackSize); + tags.setString("OreDict", oreDict); + return tags; + } } diff --git a/src/main/java/betterquesting/api/utils/FileExtensionFilter.java b/src/main/java/betterquesting/api/utils/FileExtensionFilter.java index 03feeedb1..374b529ef 100644 --- a/src/main/java/betterquesting/api/utils/FileExtensionFilter.java +++ b/src/main/java/betterquesting/api/utils/FileExtensionFilter.java @@ -3,18 +3,15 @@ import java.io.File; import java.io.FileFilter; -public class FileExtensionFilter implements FileFilter -{ - public final String ext; - - public FileExtensionFilter(String extension) - { - ext = (extension.startsWith(".")? extension : "." + extension).toLowerCase(); - } - - @Override - public boolean accept(File pathname) - { - return pathname != null && (pathname.isDirectory() || pathname.getAbsolutePath().toLowerCase().endsWith(ext)); - } +public class FileExtensionFilter implements FileFilter { + public final String ext; + + public FileExtensionFilter(String extension) { + ext = (extension.startsWith(".") ? extension : "." + extension).toLowerCase(); + } + + @Override + public boolean accept(File pathname) { + return pathname != null && (pathname.isDirectory() || pathname.getAbsolutePath().toLowerCase().endsWith(ext)); + } } diff --git a/src/main/java/betterquesting/api/utils/ItemComparison.java b/src/main/java/betterquesting/api/utils/ItemComparison.java index 2a840b343..9d9d7e88d 100644 --- a/src/main/java/betterquesting/api/utils/ItemComparison.java +++ b/src/main/java/betterquesting/api/utils/ItemComparison.java @@ -12,265 +12,240 @@ /** * Helper class for comparing ItemStacks in quests */ -@SuppressWarnings({"WeakerAccess", "unused"}) -public class ItemComparison -{ - /** - * Check whether two stacks match with optional NBT and Ore Dictionary checks - */ - public static boolean StackMatch(ItemStack stack1, ItemStack stack2, boolean nbtCheck, boolean partialNBT) - { - // Some quick checks - if(stack1 == stack2) - { - return true; - } else if(stack1 == null || stack2 == null) - { - return false; - } - - if(nbtCheck) - { - if(!partialNBT && !stack1.areCapsCompatible(stack2)) - { - return false; - } else if(!CompareNBTTag(stack1.getTagCompound(), stack2.getTagCompound(), partialNBT)) - { - return false; - } - } - - return stack1.getItem() == stack2.getItem() && (stack1.getItemDamage() == stack2.getItemDamage() || stack1.getItem().isDamageable() || stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE); +@SuppressWarnings({ "WeakerAccess", "unused" }) +public class ItemComparison { + /** + * Check whether two stacks match with optional NBT and Ore Dictionary checks + */ + public static boolean StackMatch(ItemStack stack1, ItemStack stack2, boolean nbtCheck, boolean partialNBT) { + // Some quick checks + if (stack1 == stack2) { + return true; + } else if (stack1 == null || stack2 == null) { + return false; } - - public static boolean CompareNBTTag(NBTBase tag1, NBTBase tag2, boolean partial) - { - if(isEmptyNBT(tag1) != isEmptyNBT(tag2)) // One is null, the other is not - { - return false; - } else if(isEmptyNBT(tag1)) // The opposing tag will always be null at this point if the other already is - { - return true; - } else if(!(tag1 instanceof NBTPrimitive && tag2 instanceof NBTPrimitive) && tag1.getId() != tag2.getId()) return false; // Incompatible tag types (and not a numbers we can cast) - - if(tag1 instanceof NBTTagCompound && tag2 instanceof NBTTagCompound) - { - return CompareNBTTagCompound((NBTTagCompound)tag1, (NBTTagCompound)tag2, partial); - } else if(tag1 instanceof NBTTagList && tag2 instanceof NBTTagList) - { - NBTTagList list1 = (NBTTagList)tag1; - NBTTagList list2 = (NBTTagList)tag2; - - if(list1.tagCount() > list2.tagCount() || (!partial && list1.tagCount() != list2.tagCount())) - { - return false; // Sample is missing requested tags or is not exact - } - - topLoop: - for(int i = 0; i < list1.tagCount(); i++) - { - NBTBase lt1 = list1.get(i); - - for(int j = 0; j < list2.tagCount(); j++) - { - if(CompareNBTTag(lt1, list2.get(j), partial)) - { - continue topLoop; - } - } - - return false; // Couldn't find requested tag in list - } - } else if(tag1 instanceof NBTTagIntArray && tag2 instanceof NBTTagIntArray) - { - NBTTagIntArray list1 = (NBTTagIntArray)tag1; - NBTTagIntArray list2 = (NBTTagIntArray)tag2; - - if(list1.getIntArray().length > list2.getIntArray().length || (!partial && list1.getIntArray().length != list2.getIntArray().length)) - { - return false; // Sample is missing requested tags or is not exact - } - - List usedIdxs = new ArrayList<>(); // Duplicate control - - topLoop: - for(int i = 0; i < list1.getIntArray().length; i++) - { - for(int j = 0; j < list2.getIntArray().length; j++) - { - if(!usedIdxs.contains(j) && list1.getIntArray()[i] == list2.getIntArray()[j]) - { - usedIdxs.add(j); - continue topLoop; - } - } - - return false; // Couldn't find requested integer in list - } - - return true; - } else if(tag1 instanceof NBTTagByteArray && tag2 instanceof NBTTagByteArray) - { - NBTTagByteArray list1 = (NBTTagByteArray)tag1; - NBTTagByteArray list2 = (NBTTagByteArray)tag2; - - if(list1.getByteArray().length > list2.getByteArray().length || (!partial && list1.getByteArray().length != list2.getByteArray().length)) - { - return false; // Sample is missing requested tags or is not exact for non-partial match - } - - List usedIdxs = new ArrayList<>(); // Duplicate control - - topLoop: - for(int i = 0; i < list1.getByteArray().length; i++) - { - for(int j = 0; j < list2.getByteArray().length; j++) - { - if(!usedIdxs.contains(j) && list1.getByteArray()[i] == list2.getByteArray()[j]) - { - usedIdxs.add(j); - continue topLoop; - } - } - - return false; // Couldn't find requested integer in list - } - } else if(tag1 instanceof NBTTagLongArray && tag2 instanceof NBTTagLongArray) - { - NBTTagLongArray list1 = (NBTTagLongArray)tag1; - NBTTagLongArray list2 = (NBTTagLongArray)tag2; - - final long[] la1 = NBTConverter.readLongArray(list1); - final long[] la2 = NBTConverter.readLongArray(list2); - - if(la1.length > la2.length || (!partial && la1.length != la2.length)) - { - return false; // Sample is missing requested tags or is not exact for non-partial match - } - - List usedIdxs = new ArrayList<>(); // Duplicate control - - topLoop: - for(long l : la1) - { - for(int j = 0; j < la2.length; j++) - { - if(!usedIdxs.contains(j) && l == la2[j]) - { - usedIdxs.add(j); - continue topLoop; - } - } - - return false; // Couldn't find requested integer in list - } - } else if(tag1 instanceof NBTTagString && tag2 instanceof NBTTagString) - { - return tag1.equals(tag2); - } else if(tag1 instanceof NBTPrimitive && tag2 instanceof NBTPrimitive) // Standardize numbers to not care about format - { - Number num1 = NBTConverter.getNumber(tag1); - Number num2 = NBTConverter.getNumber(tag2); - - // Check if floating point precesion needs to be preserved in comparison - if(tag1 instanceof NBTTagFloat || tag1 instanceof NBTTagDouble || tag2 instanceof NBTTagFloat || tag2 instanceof NBTTagDouble) - { - return num1.doubleValue() == num2.doubleValue(); - } else - { - return num1.longValue() == num2.longValue(); - } - } else - { - return tag1.equals(tag2); - } - - return true; + + if (nbtCheck) { + if (!partialNBT && !stack1.areCapsCompatible(stack2)) { + return false; + } else if (!CompareNBTTag(stack1.getTagCompound(), stack2.getTagCompound(), partialNBT)) { + return false; + } } - - private static boolean CompareNBTTagCompound(NBTTagCompound reqTags, NBTTagCompound sample, boolean partial) + + return stack1.getItem() == stack2.getItem() && + (stack1.getItemDamage() == stack2.getItemDamage() || stack1.getItem().isDamageable() || + stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE); + } + + public static boolean CompareNBTTag(NBTBase tag1, NBTBase tag2, boolean partial) { + if (isEmptyNBT(tag1) != isEmptyNBT(tag2)) // One is null, the other is not { - if(isEmptyNBT(reqTags) != isEmptyNBT(sample)) // One is null, the other is not - { - return false; - } else if(isEmptyNBT(reqTags)) // The opposing tag will always be null at this point if the other already is - { - return true; - } - - for(String key : reqTags.getKeySet()) - { - if(!sample.hasKey(key)) - { - return false; - } else if(!CompareNBTTag(reqTags.getTag(key), sample.getTag(key), partial)) - { - return false; - } - } - - return true; - } - - private static boolean isEmptyNBT(NBTBase tag) + return false; + } else if (isEmptyNBT(tag1)) // The opposing tag will always be null at this point if the other already is { - return tag == null || tag.isEmpty(); + return true; + } else if (!(tag1 instanceof NBTPrimitive && tag2 instanceof NBTPrimitive) && tag1.getId() != tag2.getId()) { + return false; // Incompatible tag types (and not a numbers we can cast) } - - @Deprecated - public static boolean OreDictionaryMatch(String name, ItemStack stack) + + if (tag1 instanceof NBTTagCompound && tag2 instanceof NBTTagCompound) { + return CompareNBTTagCompound((NBTTagCompound) tag1, (NBTTagCompound) tag2, partial); + } else if (tag1 instanceof NBTTagList && tag2 instanceof NBTTagList) { + NBTTagList list1 = (NBTTagList) tag1; + NBTTagList list2 = (NBTTagList) tag2; + + if (list1.tagCount() > list2.tagCount() || (!partial && list1.tagCount() != list2.tagCount())) { + return false; // Sample is missing requested tags or is not exact + } + + topLoop: + for (int i = 0; i < list1.tagCount(); i++) { + NBTBase lt1 = list1.get(i); + + for (int j = 0; j < list2.tagCount(); j++) { + if (CompareNBTTag(lt1, list2.get(j), partial)) { + continue topLoop; + } + } + + return false; // Couldn't find requested tag in list + } + } else if (tag1 instanceof NBTTagIntArray && tag2 instanceof NBTTagIntArray) { + NBTTagIntArray list1 = (NBTTagIntArray) tag1; + NBTTagIntArray list2 = (NBTTagIntArray) tag2; + + if (list1.getIntArray().length > list2.getIntArray().length || + (!partial && list1.getIntArray().length != list2.getIntArray().length)) { + return false; // Sample is missing requested tags or is not exact + } + + List usedIdxs = new ArrayList<>(); // Duplicate control + + topLoop: + for (int i = 0; i < list1.getIntArray().length; i++) { + for (int j = 0; j < list2.getIntArray().length; j++) { + if (!usedIdxs.contains(j) && list1.getIntArray()[i] == list2.getIntArray()[j]) { + usedIdxs.add(j); + continue topLoop; + } + } + + return false; // Couldn't find requested integer in list + } + + return true; + } else if (tag1 instanceof NBTTagByteArray && tag2 instanceof NBTTagByteArray) { + NBTTagByteArray list1 = (NBTTagByteArray) tag1; + NBTTagByteArray list2 = (NBTTagByteArray) tag2; + + if (list1.getByteArray().length > list2.getByteArray().length || + (!partial && list1.getByteArray().length != list2.getByteArray().length)) { + return false; // Sample is missing requested tags or is not exact for non-partial match + } + + List usedIdxs = new ArrayList<>(); // Duplicate control + + topLoop: + for (int i = 0; i < list1.getByteArray().length; i++) { + for (int j = 0; j < list2.getByteArray().length; j++) { + if (!usedIdxs.contains(j) && list1.getByteArray()[i] == list2.getByteArray()[j]) { + usedIdxs.add(j); + continue topLoop; + } + } + + return false; // Couldn't find requested integer in list + } + } else if (tag1 instanceof NBTTagLongArray && tag2 instanceof NBTTagLongArray) { + NBTTagLongArray list1 = (NBTTagLongArray) tag1; + NBTTagLongArray list2 = (NBTTagLongArray) tag2; + + final long[] la1 = NBTConverter.readLongArray(list1); + final long[] la2 = NBTConverter.readLongArray(list2); + + if (la1.length > la2.length || (!partial && la1.length != la2.length)) { + return false; // Sample is missing requested tags or is not exact for non-partial match + } + + List usedIdxs = new ArrayList<>(); // Duplicate control + + topLoop: + for (long l : la1) { + for (int j = 0; j < la2.length; j++) { + if (!usedIdxs.contains(j) && l == la2[j]) { + usedIdxs.add(j); + continue topLoop; + } + } + + return false; // Couldn't find requested integer in list + } + } else if (tag1 instanceof NBTTagString && tag2 instanceof NBTTagString) { + return tag1.equals(tag2); + } else if (tag1 instanceof NBTPrimitive && + tag2 instanceof NBTPrimitive) // Standardize numbers to not care about format { - return stack != null && !StringUtils.isNullOrEmpty(name) && new OreIngredient(name).apply(stack); + Number num1 = NBTConverter.getNumber(tag1); + Number num2 = NBTConverter.getNumber(tag2); + + // Check if floating point precesion needs to be preserved in comparison + if (tag1 instanceof NBTTagFloat || tag1 instanceof NBTTagDouble || tag2 instanceof NBTTagFloat || + tag2 instanceof NBTTagDouble) { + return num1.doubleValue() == num2.doubleValue(); + } else { + return num1.longValue() == num2.longValue(); + } + } else { + return tag1.equals(tag2); } - - @Deprecated - public static boolean OreDictionaryMatch(String name, NBTTagCompound tags, ItemStack stack, boolean nbtCheck, boolean partialNBT) + + return true; + } + + private static boolean CompareNBTTagCompound(NBTTagCompound reqTags, NBTTagCompound sample, boolean partial) { + if (isEmptyNBT(reqTags) != isEmptyNBT(sample)) // One is null, the other is not { - if(!nbtCheck) return stack != null && !StringUtils.isNullOrEmpty(name) && new OreIngredient(name).apply(stack); - return OreDictionaryMatch(new OreIngredient(name), tags, stack, nbtCheck, partialNBT); - } - - /** - * Check if the item stack is part of the ore dictionary listing with the given ore ingredient while also comparing NBT tags - */ - public static boolean OreDictionaryMatch(OreIngredient ore, NBTTagCompound tags, ItemStack stack, boolean nbtCheck, boolean partialNBT) + return false; + } else if (isEmptyNBT(reqTags)) // The opposing tag will always be null at this point if the other already is { - if(stack == null || ore == null) return false; - return ore.apply(stack) && (!nbtCheck || CompareNBTTagCompound(stack.getTagCompound(), tags, partialNBT)); + return true; } - - /** - * Check if the two stacks match directly or through ore dictionary listings - */ - @Deprecated - public static boolean AllMatch(ItemStack stack1, ItemStack stack2) - { - return AllMatch(stack1, stack2, false, false); + + for (String key : reqTags.getKeySet()) { + if (!sample.hasKey(key)) { + return false; + } else if (!CompareNBTTag(reqTags.getTag(key), sample.getTag(key), partial)) { + return false; + } } - - /** - * Check if the two stacks match directly or through ore dictionary listings - */ - public static boolean AllMatch(ItemStack stack1, ItemStack stack2, boolean nbtCheck, boolean partialNBT) - { - if(stack1 == stack2) return true; // Both null or same instance - if(stack1 == null) return false; // One is null the other is not - if(nbtCheck && !CompareNBTTagCompound(stack1.getTagCompound(), stack2.getTagCompound(), partialNBT)) return false; // NBT check failed - if(StackMatch(stack1, stack2, false, false)) return true; // Stacks are compatible (NBT was already checked at this point) - - // Final Ore Dictionary test... - int[] oreIDs1 = OreDictionary.getOreIDs(stack1); - int[] oreIDs2 = OreDictionary.getOreIDs(stack2); - - // Search all ore dictionary listings for matches - for(int i1 : oreIDs1) - { - for(int i2 : oreIDs2) - { - if(i1 == i2) return true; // Shared ore dictionary entries found - } - } - - return false; // No shared ore dictionary types + + return true; + } + + private static boolean isEmptyNBT(NBTBase tag) { + return tag == null || tag.isEmpty(); + } + + @Deprecated + public static boolean OreDictionaryMatch(String name, ItemStack stack) { + return stack != null && !StringUtils.isNullOrEmpty(name) && new OreIngredient(name).apply(stack); + } + + @Deprecated + public static boolean OreDictionaryMatch(String name, NBTTagCompound tags, ItemStack stack, boolean nbtCheck, + boolean partialNBT) { + if (!nbtCheck) { return stack != null && !StringUtils.isNullOrEmpty(name) && new OreIngredient(name).apply(stack); } + return OreDictionaryMatch(new OreIngredient(name), tags, stack, true, partialNBT); + } + + /** + * Check if the item stack is part of the ore dictionary listing with the given ore ingredient while also comparing NBT tags + */ + public static boolean OreDictionaryMatch(OreIngredient ore, NBTTagCompound tags, ItemStack stack, boolean nbtCheck, + boolean partialNBT) { + if (stack == null || ore == null) { return false; } + return ore.apply(stack) && (!nbtCheck || CompareNBTTagCompound(stack.getTagCompound(), tags, partialNBT)); + } + + /** + * Check if the two stacks match directly or through ore dictionary listings + */ + @Deprecated + public static boolean AllMatch(ItemStack stack1, ItemStack stack2) { + return AllMatch(stack1, stack2, false, false); + } + + /** + * Check if the two stacks match directly or through ore dictionary listings + */ + public static boolean AllMatch(ItemStack stack1, ItemStack stack2, boolean nbtCheck, boolean partialNBT) { + if (stack1 == stack2) { + return true; // Both null or same instance + } + if (stack1 == null) { + return false; // One is null the other is not + } + if (nbtCheck && !CompareNBTTagCompound(stack1.getTagCompound(), stack2.getTagCompound(), partialNBT)) { + return false; // NBT check failed } + if (StackMatch(stack1, stack2, false, false)) { + return true; // Stacks are compatible (NBT was already checked at this point) + } + + // Final Ore Dictionary test... + int[] oreIDs1 = OreDictionary.getOreIDs(stack1); + int[] oreIDs2 = OreDictionary.getOreIDs(stack2); + + // Search all ore dictionary listings for matches + for (int i1 : oreIDs1) { + for (int i2 : oreIDs2) { + if (i1 == i2) { + return true; // Shared ore dictionary entries found + } + } + } + + return false; // No shared ore dictionary types + } } diff --git a/src/main/java/betterquesting/api/utils/JsonHelper.java b/src/main/java/betterquesting/api/utils/JsonHelper.java index 0c62e9e5d..5a60bc8c7 100644 --- a/src/main/java/betterquesting/api/utils/JsonHelper.java +++ b/src/main/java/betterquesting/api/utils/JsonHelper.java @@ -32,311 +32,257 @@ * editing the parent JSON.
* In the event the requested item, fluid or entity is missing, a place holder will be substituted */ -public class JsonHelper -{ - public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - - public static JsonArray GetArray(@Nonnull JsonObject json, @Nonnull String id) - { - if(json.get(id) instanceof JsonArray) - { - return json.get(id).getAsJsonArray(); - } else - { - return new JsonArray(); - } - } - - public static JsonObject GetObject(@Nonnull JsonObject json, @Nonnull String id) - { - if(json.get(id) instanceof JsonObject) - { - return json.get(id).getAsJsonObject(); - } else - { - return new JsonObject(); - } - } - - public static String GetString(@Nonnull JsonObject json, @Nonnull String id, String def) - { - if(json.get(id) instanceof JsonPrimitive && json.get(id).getAsJsonPrimitive().isString()) - { - return json.get(id).getAsString(); - } else - { - return def; - } - } - - public static Number GetNumber(@Nonnull JsonObject json, @Nonnull String id, Number def) - { - if(json.get(id) instanceof JsonPrimitive) - { - try - { - return json.get(id).getAsNumber(); - } catch(Exception e) - { - return def; - } - } else - { - return def; - } - } - - public static boolean GetBoolean(@Nonnull JsonObject json, @Nonnull String id, boolean def) - { - if(json.get(id) instanceof JsonPrimitive) - { - try - { - return json.get(id).getAsBoolean(); - } catch(Exception e) - { - return def; - } - } else - { - return def; - } - } - - @SuppressWarnings("unchecked") - public static ArrayList GetUnderlyingArray(JsonArray array) - { - try - { - Field field = JsonArray.class.getDeclaredField("elements"); - field.setAccessible(true); - - return (ArrayList)field.get(array); - } catch(Exception e) - { - QuestingAPI.getLogger().log(Level.ERROR, "Unable to retrieve underlying JsonArray:", e); - } - - return null; - } - - public static void ClearCompoundTag(@Nonnull NBTTagCompound tag) - { - ArrayList list = new ArrayList<>(tag.getKeySet()); - list.forEach(tag::removeTag); - } - - public static JsonObject ReadFromFile(File file) - { - if(file == null || !file.exists()) return new JsonObject(); - - Future task = BQThreadedIO.INSTANCE.enqueue(() -> { - // NOTE: These are now split due to an edge case in the previous implementation where resource leaking can occur should the outer constructor fail - try(FileInputStream fis = new FileInputStream(file); InputStreamReader fr = new InputStreamReader(fis, StandardCharsets.UTF_8)) - { - JsonObject json = GSON.fromJson(fr, JsonObject.class); - fr.close(); - return json; - } catch(Exception e) - { - QuestingAPI.getLogger().log(Level.ERROR, "An error occured while loading JSON from file:", e); - - int i = 0; - File bkup = new File(file.getParent(), "malformed_" + file.getName() + i + ".json"); - - while(bkup.exists()) - { - bkup = new File(file.getParent(), "malformed_" + file.getName() + (++i) + ".json"); - } - - QuestingAPI.getLogger().log(Level.ERROR, "Creating backup at: " + bkup.getAbsolutePath()); - CopyPaste(file, bkup); - - return new JsonObject(); // Just a safety measure against NPEs - } - }); - - try - { - return task.get(); // Wait for other scheduled file ops to finish - } catch(Exception e) - { - QuestingAPI.getLogger().error("Unable to read from file " + file, e); - return new JsonObject(); - } - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - public static void WriteToFile(File file, JsonObject jObj) - { - final File tmp = new File(file.getAbsolutePath() + ".tmp"); - - BQThreadedIO.INSTANCE.enqueue(() -> { - try - { - if(tmp.exists()) - { - tmp.delete(); - } else if(tmp.getParentFile() != null) - { - tmp.getParentFile().mkdirs(); - } - - tmp.createNewFile(); - } catch(Exception e) - { - QuestingAPI.getLogger().error("An error occured while saving JSON to file (Directory setup):", e); - return; - } - - // NOTE: These are now split due to an edge case in the previous implementation where resource leaking can occur should the outer constructor fail - try(FileOutputStream fos = new FileOutputStream(tmp); OutputStreamWriter fw = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) - { - // Attempt writing - GSON.toJson(jObj, fw); - fw.flush(); - } catch(Exception e) - { - QuestingAPI.getLogger().error("An error occured while saving JSON to file (File write):", e); - return; - } - - // NOTE: These are now split due to an edge case in the previous implementation where resource leaking can occur should the outer constructor fail - try(FileInputStream fis = new FileInputStream(tmp); InputStreamReader fr = new InputStreamReader(fis, StandardCharsets.UTF_8)) - { - // Readback what we wrote to validate it - GSON.fromJson(fr, JsonObject.class); - } catch(Exception e) - { - QuestingAPI.getLogger().error("An error occured while saving JSON to file (Validation check):", e); - return; - } - - try - { - if(file.exists()) file.delete(); - tmp.renameTo(file); - } catch(Exception e) - { - QuestingAPI.getLogger().error("An error occured while saving JSON to file (Temp copy):", e); - } - }); - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - public static void CopyPaste(File fileIn, File fileOut) - { - if(!fileIn.exists()) return; - - try - { - if(fileOut.getParentFile() != null) fileOut.getParentFile().mkdirs(); - Files.copy(fileIn.toPath(), fileOut.toPath(), StandardCopyOption.REPLACE_EXISTING); - } catch(Exception e) - { - QuestingAPI.getLogger().log(Level.ERROR, "Failed copy paste", e); - } - } - - public static String makeFileNameSafe(String s) - { - for(char c : ChatAllowedCharacters.ILLEGAL_FILE_CHARACTERS) - { - s = s.replace(c, '_'); - } - - return s; - } - - public static boolean isItem(NBTTagCompound json) - { - if(json != null && json.hasKey("id") && json.hasKey("Count", 99) && json.hasKey("Damage", 99)) - { - if(json.hasKey("id", 8)) - { - return Item.REGISTRY.containsKey(new ResourceLocation(json.getString("id"))); - } else - { - return Item.REGISTRY.getObjectById(json.getInteger("id")) != null; - } - } - - return false; - } - - public static boolean isFluid(NBTTagCompound json) - { - return json != null && json.hasKey("FluidName", 8) && json.hasKey("Amount", 99) && FluidRegistry.getFluid(json.getString("FluidName")) != null; - } - - public static boolean isEntity(NBTTagCompound tags) - { - return tags.hasKey("id") && EntityList.isRegistered(new ResourceLocation(tags.getString("id"))); - } - - /** - * Converts a JsonObject to an ItemStack. May return a placeholder if the correct mods are not installed
- * This should be the standard way to load items into quests in order to retain all potential data - */ - public static BigItemStack JsonToItemStack(NBTTagCompound nbt) - { - Item preCheck = Item.getByNameOrId(nbt.hasKey("id", 99) ? "" + nbt.getShort("id") : nbt.getString("id")); - if(preCheck != null && preCheck != ItemPlaceholder.placeholder) return new BigItemStack(nbt); - return PlaceholderConverter.convertItem(preCheck, nbt.getString("id"), nbt.getInteger("Count"), nbt.getShort("Damage"), nbt.getString("OreDict"), !nbt.hasKey("tag", 10) ? null : nbt.getCompoundTag("tag")); - } - - /** - * Use this for quests instead of converter NBT because this doesn't use ID numbers - */ - public static NBTTagCompound ItemStackToJson(BigItemStack stack, NBTTagCompound nbt) - { - if(stack != null) stack.writeToNBT(nbt); - return nbt; - } - - public static FluidStack JsonToFluidStack(NBTTagCompound json) - { - String name = json.hasKey("FluidName", 8) ? json.getString("FluidName") : "water"; - int amount = json.getInteger("Amount"); - NBTTagCompound tags = !json.hasKey("Tag", 10) ? null : json.getCompoundTag("Tag"); - Fluid fluid = FluidRegistry.getFluid(name); - - return PlaceholderConverter.convertFluid(fluid, name, amount, tags); - } - - public static NBTTagCompound FluidStackToJson(FluidStack stack, NBTTagCompound json) - { - if(stack == null) return json; - json.setString("FluidName", FluidRegistry.getFluidName(stack)); - json.setInteger("Amount", stack.amount); - if(stack.tag != null) json.setTag("Tag", stack.tag); - return json; - } - - public static Entity JsonToEntity(NBTTagCompound tags, World world) - { - Entity entity = null; - - if(tags.hasKey("id") && EntityList.isRegistered(new ResourceLocation(tags.getString("id")))) - { - entity = EntityList.createEntityFromNBT(tags, world); - } - - return PlaceholderConverter.convertEntity(entity, world, tags); - } - - public static NBTTagCompound EntityToJson(Entity entity, NBTTagCompound json) - { - if(entity == null) - { - return json; - } - - NBTTagCompound tags = new NBTTagCompound(); - entity.writeToNBTOptional(tags); - String id = EntityList.getEntityString(entity); - tags.setString("id", id != null ? id : ""); // Some entities don't write this to file in certain cases - json.merge(tags); - return json; - } +public class JsonHelper { + public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + public static JsonArray GetArray(@Nonnull JsonObject json, @Nonnull String id) { + if (json.get(id) instanceof JsonArray) { + return json.get(id).getAsJsonArray(); + } else { + return new JsonArray(); + } + } + + public static JsonObject GetObject(@Nonnull JsonObject json, @Nonnull String id) { + if (json.get(id) instanceof JsonObject) { + return json.get(id).getAsJsonObject(); + } else { + return new JsonObject(); + } + } + + public static String GetString(@Nonnull JsonObject json, @Nonnull String id, String def) { + if (json.get(id) instanceof JsonPrimitive && json.get(id).getAsJsonPrimitive().isString()) { + return json.get(id).getAsString(); + } else { + return def; + } + } + + public static Number GetNumber(@Nonnull JsonObject json, @Nonnull String id, Number def) { + if (json.get(id) instanceof JsonPrimitive) { + try { + return json.get(id).getAsNumber(); + } catch (Exception e) { + return def; + } + } else { + return def; + } + } + + public static boolean GetBoolean(@Nonnull JsonObject json, @Nonnull String id, boolean def) { + if (json.get(id) instanceof JsonPrimitive) { + try { + return json.get(id).getAsBoolean(); + } catch (Exception e) { + return def; + } + } else { + return def; + } + } + + @SuppressWarnings("unchecked") + public static ArrayList GetUnderlyingArray(JsonArray array) { + try { + Field field = JsonArray.class.getDeclaredField("elements"); + field.setAccessible(true); + + return (ArrayList) field.get(array); + } catch (Exception e) { + QuestingAPI.getLogger().log(Level.ERROR, "Unable to retrieve underlying JsonArray:", e); + } + + return null; + } + + public static void ClearCompoundTag(@Nonnull NBTTagCompound tag) { + ArrayList list = new ArrayList<>(tag.getKeySet()); + list.forEach(tag::removeTag); + } + + public static JsonObject ReadFromFile(File file) { + if (file == null || !file.exists()) { return new JsonObject(); } + + Future task = BQThreadedIO.INSTANCE.enqueue(() -> { + // NOTE: These are now split due to an edge case in the previous implementation where resource leaking can occur should the outer constructor fail + try (FileInputStream fis = new FileInputStream(file); + InputStreamReader fr = new InputStreamReader(fis, StandardCharsets.UTF_8)) { + JsonObject json = GSON.fromJson(fr, JsonObject.class); + fr.close(); + return json; + } catch (Exception e) { + QuestingAPI.getLogger().log(Level.ERROR, "An error occured while loading JSON from file:", e); + + int i = 0; + File bkup = new File(file.getParent(), "malformed_" + file.getName() + i + ".json"); + + while (bkup.exists()) { + bkup = new File(file.getParent(), "malformed_" + file.getName() + (++i) + ".json"); + } + + QuestingAPI.getLogger().log(Level.ERROR, "Creating backup at: " + bkup.getAbsolutePath()); + CopyPaste(file, bkup); + + return new JsonObject(); // Just a safety measure against NPEs + } + }); + + try { + return task.get(); // Wait for other scheduled file ops to finish + } catch (Exception e) { + QuestingAPI.getLogger().error("Unable to read from file " + file, e); + return new JsonObject(); + } + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + public static void WriteToFile(File file, JsonObject jObj) { + final File tmp = new File(file.getAbsolutePath() + ".tmp"); + + BQThreadedIO.INSTANCE.enqueue(() -> { + try { + if (tmp.exists()) { + tmp.delete(); + } else if (tmp.getParentFile() != null) { + tmp.getParentFile().mkdirs(); + } + + tmp.createNewFile(); + } catch (Exception e) { + QuestingAPI.getLogger().error("An error occured while saving JSON to file (Directory setup):", e); + return; + } + + // NOTE: These are now split due to an edge case in the previous implementation where resource leaking can occur should the outer constructor fail + try (FileOutputStream fos = new FileOutputStream(tmp); + OutputStreamWriter fw = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) { + // Attempt writing + GSON.toJson(jObj, fw); + fw.flush(); + } catch (Exception e) { + QuestingAPI.getLogger().error("An error occured while saving JSON to file (File write):", e); + return; + } + + // NOTE: These are now split due to an edge case in the previous implementation where resource leaking can occur should the outer constructor fail + try (FileInputStream fis = new FileInputStream(tmp); + InputStreamReader fr = new InputStreamReader(fis, StandardCharsets.UTF_8)) { + // Readback what we wrote to validate it + GSON.fromJson(fr, JsonObject.class); + } catch (Exception e) { + QuestingAPI.getLogger().error("An error occured while saving JSON to file (Validation check):", e); + return; + } + + try { + if (file.exists()) { file.delete(); } + tmp.renameTo(file); + } catch (Exception e) { + QuestingAPI.getLogger().error("An error occured while saving JSON to file (Temp copy):", e); + } + }); + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + public static void CopyPaste(File fileIn, File fileOut) { + if (!fileIn.exists()) { return; } + + try { + if (fileOut.getParentFile() != null) { fileOut.getParentFile().mkdirs(); } + Files.copy(fileIn.toPath(), fileOut.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (Exception e) { + QuestingAPI.getLogger().log(Level.ERROR, "Failed copy paste", e); + } + } + + public static String makeFileNameSafe(String s) { + for (char c : ChatAllowedCharacters.ILLEGAL_FILE_CHARACTERS) { + s = s.replace(c, '_'); + } + + return s; + } + + public static boolean isItem(NBTTagCompound json) { + if (json != null && json.hasKey("id") && json.hasKey("Count", 99) && json.hasKey("Damage", 99)) { + if (json.hasKey("id", 8)) { + return Item.REGISTRY.containsKey(new ResourceLocation(json.getString("id"))); + } else { + return Item.REGISTRY.getObjectById(json.getInteger("id")) != null; + } + } + + return false; + } + + public static boolean isFluid(NBTTagCompound json) { + return json != null && json.hasKey("FluidName", 8) && json.hasKey("Amount", 99) && + FluidRegistry.getFluid(json.getString("FluidName")) != null; + } + + public static boolean isEntity(NBTTagCompound tags) { + return tags.hasKey("id") && EntityList.isRegistered(new ResourceLocation(tags.getString("id"))); + } + + /** + * Converts a JsonObject to an ItemStack. May return a placeholder if the correct mods are not installed
+ * This should be the standard way to load items into quests in order to retain all potential data + */ + public static BigItemStack JsonToItemStack(NBTTagCompound nbt) { + Item preCheck = Item.getByNameOrId(nbt.hasKey("id", 99) ? "" + nbt.getShort("id") : nbt.getString("id")); + if (preCheck != null && preCheck != ItemPlaceholder.placeholder) { return new BigItemStack(nbt); } + return PlaceholderConverter.convertItem(preCheck, nbt.getString("id"), nbt.getInteger("Count"), + nbt.getShort("Damage"), nbt.getString("OreDict"), + !nbt.hasKey("tag", 10) ? null : nbt.getCompoundTag("tag")); + } + + /** + * Use this for quests instead of converter NBT because this doesn't use ID numbers + */ + public static NBTTagCompound ItemStackToJson(BigItemStack stack, NBTTagCompound nbt) { + if (stack != null) { stack.writeToNBT(nbt); } + return nbt; + } + + public static FluidStack JsonToFluidStack(NBTTagCompound json) { + String name = json.hasKey("FluidName", 8) ? json.getString("FluidName") : "water"; + int amount = json.getInteger("Amount"); + NBTTagCompound tags = !json.hasKey("Tag", 10) ? null : json.getCompoundTag("Tag"); + Fluid fluid = FluidRegistry.getFluid(name); + + return PlaceholderConverter.convertFluid(fluid, name, amount, tags); + } + + public static NBTTagCompound FluidStackToJson(FluidStack stack, NBTTagCompound json) { + if (stack == null) { return json; } + json.setString("FluidName", FluidRegistry.getFluidName(stack)); + json.setInteger("Amount", stack.amount); + if (stack.tag != null) { json.setTag("Tag", stack.tag); } + return json; + } + + public static Entity JsonToEntity(NBTTagCompound tags, World world) { + Entity entity = null; + + if (tags.hasKey("id") && EntityList.isRegistered(new ResourceLocation(tags.getString("id")))) { + entity = EntityList.createEntityFromNBT(tags, world); + } + + return PlaceholderConverter.convertEntity(entity, world, tags); + } + + public static NBTTagCompound EntityToJson(Entity entity, NBTTagCompound json) { + if (entity == null) { + return json; + } + + NBTTagCompound tags = new NBTTagCompound(); + entity.writeToNBTOptional(tags); + String id = EntityList.getEntityString(entity); + tags.setString("id", id != null ? id : ""); // Some entities don't write this to file in certain cases + json.merge(tags); + return json; + } } diff --git a/src/main/java/betterquesting/api/utils/NBTConverter.java b/src/main/java/betterquesting/api/utils/NBTConverter.java index d38b1c8c2..bf1c0b6a8 100644 --- a/src/main/java/betterquesting/api/utils/NBTConverter.java +++ b/src/main/java/betterquesting/api/utils/NBTConverter.java @@ -10,399 +10,326 @@ import java.util.Map.Entry; -public class NBTConverter -{ - /** - * Convert NBT tags to a JSON object - */ - private static JsonElement NBTtoJSON_Base(NBTBase tag, boolean format) - { - if(tag == null) - { - return new JsonObject(); - } - - if(tag.getId() >= 1 && tag.getId() <= 6) - { - return new JsonPrimitive(getNumber(tag)); - } if(tag instanceof NBTTagString) - { - return new JsonPrimitive(((NBTTagString)tag).getString()); - } else if(tag instanceof NBTTagCompound) - { - return NBTtoJSON_Compound((NBTTagCompound)tag, new JsonObject(), format); - } else if(tag instanceof NBTTagList) - { - if(format) - { - JsonObject jAry = new JsonObject(); - - NBTTagList tagList = (NBTTagList)tag; - - for(int i = 0; i < tagList.tagCount(); i++) - { - jAry.add(i + ":" + tagList.get(i).getId(), NBTtoJSON_Base(tagList.get(i), true)); - } - - return jAry; - } else - { - JsonArray jAry = new JsonArray(); - - NBTTagList tagList = (NBTTagList)tag; - - for(NBTBase t : tagList) - { - jAry.add(NBTtoJSON_Base(t, false)); - } - - return jAry; - } - } else if(tag instanceof NBTTagByteArray) - { - JsonArray jAry = new JsonArray(); - - for(byte b : ((NBTTagByteArray)tag).getByteArray()) - { - jAry.add(new JsonPrimitive(b)); - } - - return jAry; - } else if(tag instanceof NBTTagIntArray) - { - JsonArray jAry = new JsonArray(); - - for(int i : ((NBTTagIntArray)tag).getIntArray()) - { - jAry.add(new JsonPrimitive(i)); - } - - return jAry; - } else if(tag instanceof NBTTagLongArray) - { - JsonArray jAry = new JsonArray(); - - for(long l : readLongArray((NBTTagLongArray)tag)) - { - jAry.add(new JsonPrimitive(l)); +public class NBTConverter { + /** + * Convert NBT tags to a JSON object + */ + private static JsonElement NBTtoJSON_Base(NBTBase tag, boolean format) { + if (tag == null) { + return new JsonObject(); + } + + if (tag.getId() >= 1 && tag.getId() <= 6) { + return new JsonPrimitive(getNumber(tag)); + } + if (tag instanceof NBTTagString) { + return new JsonPrimitive(((NBTTagString) tag).getString()); + } else if (tag instanceof NBTTagCompound) { + return NBTtoJSON_Compound((NBTTagCompound) tag, new JsonObject(), format); + } else if (tag instanceof NBTTagList) { + if (format) { + JsonObject jAry = new JsonObject(); + + NBTTagList tagList = (NBTTagList) tag; + + for (int i = 0; i < tagList.tagCount(); i++) { + jAry.add(i + ":" + tagList.get(i).getId(), NBTtoJSON_Base(tagList.get(i), true)); + } + + return jAry; + } else { + JsonArray jAry = new JsonArray(); + + NBTTagList tagList = (NBTTagList) tag; + + for (NBTBase t : tagList) { + jAry.add(NBTtoJSON_Base(t, false)); + } + + return jAry; + } + } else if (tag instanceof NBTTagByteArray) { + JsonArray jAry = new JsonArray(); + + for (byte b : ((NBTTagByteArray) tag).getByteArray()) { + jAry.add(new JsonPrimitive(b)); + } + + return jAry; + } else if (tag instanceof NBTTagIntArray) { + JsonArray jAry = new JsonArray(); + + for (int i : ((NBTTagIntArray) tag).getIntArray()) { + jAry.add(new JsonPrimitive(i)); + } + + return jAry; + } else if (tag instanceof NBTTagLongArray) { + JsonArray jAry = new JsonArray(); + + for (long l : readLongArray((NBTTagLongArray) tag)) { + jAry.add(new JsonPrimitive(l)); + } + + return jAry; + } else { + return new JsonObject(); // No valid types found. We'll just return this to prevent a NPE + } + } + + // The fact that this is necessary is so dumb + @SuppressWarnings("WeakerAccess") + public static long[] readLongArray(NBTTagLongArray tag) { + if (tag == null) { return new long[0]; } + + String[] entry = tag.toString().replaceAll("[\\[\\]L;]", "") + .split(","); // Cut off square braces and "L;" before splitting elements + final long[] ary = new long[entry.length]; + for (int i = 0; i < entry.length; i++) { + try { + ary[i] = Long.parseLong(entry[i]); + } catch (Exception ignored) { } + } + + return ary; + } + + public static JsonObject NBTtoJSON_Compound(NBTTagCompound parent, JsonObject jObj, boolean format) { + if (parent == null) { + return jObj; + } + + for (String key : parent.getKeySet()) { + NBTBase tag = parent.getTag(key); + + if (format) { + jObj.add(key + ":" + tag.getId(), NBTtoJSON_Base(tag, true)); + } else { + jObj.add(key, NBTtoJSON_Base(tag, false)); + } + } + + return jObj; + } + + /** + * Convert JsonObject to a NBTTagCompound + */ + public static NBTTagCompound JSONtoNBT_Object(JsonObject jObj, NBTTagCompound tags, boolean format) { + if (jObj == null) { + return tags; + } + + for (Entry entry : jObj.entrySet()) { + String key = entry.getKey(); + + if (!format) { + tags.setTag(key, JSONtoNBT_Element(entry.getValue(), (byte) 0, false)); + } else { + String[] s = key.split(":"); + byte id = 0; + + try { + id = Byte.parseByte(s[s.length - 1]); + key = key.substring(0, key.lastIndexOf(":" + id)); + } catch (Exception e) { + if (tags.hasKey(key)) { + QuestingAPI.getLogger().log(Level.WARN, "JSON/NBT formatting conflict on key '" + key + "'. Skipping..."); + continue; + } + } + + tags.setTag(key, JSONtoNBT_Element(entry.getValue(), id, true)); + } + } + + return tags; + } + + /** + * Tries to interpret the tagID from the JsonElement's contents + */ + private static NBTBase JSONtoNBT_Element(JsonElement jObj, byte id, boolean format) { + if (jObj == null) { + return new NBTTagString(); + } + + byte tagID = id <= 0 ? fallbackTagID(jObj) : id; + + try { + if (tagID == 1 && (id <= 0 || jObj.getAsJsonPrimitive().isBoolean())) // Edge case for BQ2 legacy files + { + return new NBTTagByte(jObj.getAsBoolean() ? (byte) 1 : (byte) 0); + } else if (tagID >= 1 && tagID <= 6) { + return instanceNumber(jObj.getAsNumber(), tagID); + } else if (tagID == 8) { + return new NBTTagString(jObj.getAsString()); + } else if (tagID == 10) { + return JSONtoNBT_Object(jObj.getAsJsonObject(), new NBTTagCompound(), format); + } else if (tagID == 7) // Byte array + { + JsonArray jAry = jObj.getAsJsonArray(); + + byte[] bAry = new byte[jAry.size()]; + + for (int i = 0; i < jAry.size(); i++) { + bAry[i] = jAry.get(i).getAsByte(); + } + + return new NBTTagByteArray(bAry); + } else if (tagID == 11) { + JsonArray jAry = jObj.getAsJsonArray(); + + int[] iAry = new int[jAry.size()]; + + for (int i = 0; i < jAry.size(); i++) { + iAry[i] = jAry.get(i).getAsInt(); + } + + return new NBTTagIntArray(iAry); + } else if (tagID == 12) { + JsonArray jAry = jObj.getAsJsonArray(); + + long[] lAry = new long[jAry.size()]; + + for (int i = 0; i < jAry.size(); i++) { + lAry[i] = jAry.get(i).getAsLong(); + } + + return new NBTTagLongArray(lAry); + } else if (tagID == 9) { + NBTTagList tList = new NBTTagList(); + + if (jObj.isJsonArray()) { + JsonArray jAry = jObj.getAsJsonArray(); + + for (int i = 0; i < jAry.size(); i++) { + JsonElement jElm = jAry.get(i); + tList.appendTag(JSONtoNBT_Element(jElm, (byte) 0, format)); + } + } else if (jObj.isJsonObject()) { + JsonObject jAry = jObj.getAsJsonObject(); + + for (Entry entry : jAry.entrySet()) { + try { + String[] s = entry.getKey().split(":"); + byte id2 = Byte.parseByte(s[s.length - 1]); + //String key = entry.getKey().substring(0, entry.getKey().lastIndexOf(":" + id)); + tList.appendTag(JSONtoNBT_Element(entry.getValue(), id2, format)); + } catch (Exception e) { + tList.appendTag(JSONtoNBT_Element(entry.getValue(), (byte) 0, format)); } - - return jAry; - } else - { - return new JsonObject(); // No valid types found. We'll just return this to prevent a NPE - } - } - - // The fact that this is necessary is so dumb - @SuppressWarnings("WeakerAccess") - public static long[] readLongArray(NBTTagLongArray tag) - { - if(tag == null) return new long[0]; - - String[] entry = tag.toString().replaceAll("[\\[\\]L;]","").split(","); // Cut off square braces and "L;" before splitting elements - final long[] ary = new long[entry.length]; - for(int i = 0; i < entry.length; i++) - { - try - { - ary[i] = Long.parseLong(entry[i]); - } catch(Exception ignored){} + } } - - return ary; + + return tList; + } + } catch (Exception e) { + QuestingAPI.getLogger() + .log(Level.ERROR, "An error occured while parsing JsonElement to NBTBase (" + tagID + "):", e); + } + + QuestingAPI.getLogger() + .log(Level.WARN, "Unknown NBT representation for " + jObj + " (ID: " + tagID + ")"); + return new NBTTagString(); + } + + @SuppressWarnings("WeakerAccess") + public static Number getNumber(NBTBase tag) { + if (tag instanceof NBTTagByte) { + return ((NBTTagByte) tag).getByte(); + } else if (tag instanceof NBTTagShort) { + return ((NBTTagShort) tag).getShort(); + } else if (tag instanceof NBTTagInt) { + return ((NBTTagInt) tag).getInt(); + } else if (tag instanceof NBTTagFloat) { + return ((NBTTagFloat) tag).getFloat(); + } else if (tag instanceof NBTTagDouble) { + return ((NBTTagDouble) tag).getDouble(); + } else if (tag instanceof NBTTagLong) { + return ((NBTTagLong) tag).getLong(); + } else { + return 0; + } + } + + @SuppressWarnings("WeakerAccess") + public static NBTBase instanceNumber(Number num, byte type) { + switch (type) { + case 1: + return new NBTTagByte(num.byteValue()); + case 2: + return new NBTTagShort(num.shortValue()); + case 3: + return new NBTTagInt(num.intValue()); + case 4: + return new NBTTagLong(num.longValue()); + case 5: + return new NBTTagFloat(num.floatValue()); + default: + return new NBTTagDouble(num.doubleValue()); } - - public static JsonObject NBTtoJSON_Compound(NBTTagCompound parent, JsonObject jObj, boolean format) - { - if(parent == null) - { - return jObj; - } - - for(String key : parent.getKeySet()) - { - NBTBase tag = parent.getTag(key); - - if(format) - { - jObj.add(key + ":" + tag.getId(), NBTtoJSON_Base(tag, true)); - } else - { - jObj.add(key, NBTtoJSON_Base(tag, false)); - } - } - - return jObj; - } - - /** - * Convert JsonObject to a NBTTagCompound - */ - public static NBTTagCompound JSONtoNBT_Object(JsonObject jObj, NBTTagCompound tags, boolean format) - { - if(jObj == null) - { - return tags; - } - - for(Entry entry : jObj.entrySet()) - { - String key = entry.getKey(); - - if(!format) - { - tags.setTag(key, JSONtoNBT_Element(entry.getValue(), (byte)0, false)); - } else - { - String[] s = key.split(":"); - byte id = 0; - - try - { - id = Byte.parseByte(s[s.length - 1]); - key = key.substring(0, key.lastIndexOf(":" + id)); - } catch(Exception e) - { - if(tags.hasKey(key)) - { - QuestingAPI.getLogger().log(Level.WARN, "JSON/NBT formatting conflict on key '" + key + "'. Skipping..."); - continue; - } - } - - tags.setTag(key, JSONtoNBT_Element(entry.getValue(), id, true)); - } - } - - return tags; - } - - /** - * Tries to interpret the tagID from the JsonElement's contents - */ - private static NBTBase JSONtoNBT_Element(JsonElement jObj, byte id, boolean format) - { - if(jObj == null) - { - return new NBTTagString(); - } - - byte tagID = id <= 0? fallbackTagID(jObj) : id; - - try - { - if(tagID == 1 && (id <= 0 || jObj.getAsJsonPrimitive().isBoolean())) // Edge case for BQ2 legacy files - { - return new NBTTagByte(jObj.getAsBoolean() ? (byte)1 : (byte)0); - } else if(tagID >= 1 && tagID <= 6) - { - return instanceNumber(jObj.getAsNumber(), tagID); - } else if(tagID == 8) - { - return new NBTTagString(jObj.getAsString()); - } else if(tagID == 10) - { - return JSONtoNBT_Object(jObj.getAsJsonObject(), new NBTTagCompound(), format); - } else if(tagID == 7) // Byte array - { - JsonArray jAry = jObj.getAsJsonArray(); - - byte[] bAry = new byte[jAry.size()]; - - for(int i = 0; i < jAry.size(); i++) - { - bAry[i] = jAry.get(i).getAsByte(); - } - - return new NBTTagByteArray(bAry); - } else if(tagID == 11) - { - JsonArray jAry = jObj.getAsJsonArray(); - - int[] iAry = new int[jAry.size()]; - - for(int i = 0; i < jAry.size(); i++) - { - iAry[i] = jAry.get(i).getAsInt(); - } - - return new NBTTagIntArray(iAry); - } else if(tagID == 12) - { - JsonArray jAry = jObj.getAsJsonArray(); - - long[] lAry = new long[jAry.size()]; - - for(int i = 0; i < jAry.size(); i++) + } + + private static byte fallbackTagID(JsonElement jObj) { + byte tagID = 0; + + if (jObj.isJsonPrimitive()) { + JsonPrimitive prim = jObj.getAsJsonPrimitive(); + + if (prim.isNumber()) { + if (prim.getAsString().contains( + ".")) // Just in case we'll choose the largest possible container supporting this number type (Long or Double) + { + tagID = 6; + } else { + tagID = 4; + } + } else if (prim.isBoolean()) { + tagID = 1; + } else { + tagID = 8; // Non-number primitive. Assume string + } + } else if (jObj.isJsonArray()) { + JsonArray array = jObj.getAsJsonArray(); + + for (JsonElement entry : array) { + if (entry.isJsonPrimitive() && tagID == + 0) // Note: TagLists can only support Integers, Bytes and Compounds (Strings can be stored but require special handling) + { + try { + for (JsonElement element : array) { + // Make sure all entries can be bytes + if (element.getAsLong() != element.getAsByte()) // In case casting works but overflows + { + throw new ClassCastException(); + } + } + tagID = 7; // Can be used as byte + } catch (Exception e1) { + try { + for (JsonElement element : array) { + // Make sure all entries can be integers + if (element.getAsLong() != element.getAsInt()) // In case casting works but overflows { - lAry[i] = jAry.get(i).getAsLong(); + throw new ClassCastException(); } - - return new NBTTagLongArray(lAry); - } else if(tagID == 9) - { - NBTTagList tList = new NBTTagList(); - - if(jObj.isJsonArray()) - { - JsonArray jAry = jObj.getAsJsonArray(); - - for(int i = 0; i < jAry.size(); i++) - { - JsonElement jElm = jAry.get(i); - tList.appendTag(JSONtoNBT_Element(jElm, (byte)0, format)); - } - } else if(jObj.isJsonObject()) - { - JsonObject jAry = jObj.getAsJsonObject(); - - for(Entry entry : jAry.entrySet()) - { - try - { - String[] s = entry.getKey().split(":"); - byte id2 = Byte.parseByte(s[s.length - 1]); - //String key = entry.getKey().substring(0, entry.getKey().lastIndexOf(":" + id)); - tList.appendTag(JSONtoNBT_Element(entry.getValue(), id2, format)); - } catch(Exception e) - { - tList.appendTag(JSONtoNBT_Element(entry.getValue(), (byte)0, format)); - } - } - } - - return tList; - } - } catch(Exception e) - { - QuestingAPI.getLogger().log(Level.ERROR, "An error occured while parsing JsonElement to NBTBase (" + tagID + "):", e); - } - - QuestingAPI.getLogger().log(Level.WARN, "Unknown NBT representation for " + jObj.toString() + " (ID: " + tagID + ")"); - return new NBTTagString(); - } - - @SuppressWarnings("WeakerAccess") - public static Number getNumber(NBTBase tag) - { - if(tag instanceof NBTTagByte) - { - return ((NBTTagByte)tag).getByte(); - } else if(tag instanceof NBTTagShort) - { - return ((NBTTagShort)tag).getShort(); - } else if(tag instanceof NBTTagInt) - { - return ((NBTTagInt)tag).getInt(); - } else if(tag instanceof NBTTagFloat) - { - return ((NBTTagFloat)tag).getFloat(); - } else if(tag instanceof NBTTagDouble) - { - return ((NBTTagDouble)tag).getDouble(); - } else if(tag instanceof NBTTagLong) - { - return ((NBTTagLong)tag).getLong(); - } else - { - return 0; - } - } - - @SuppressWarnings("WeakerAccess") - public static NBTBase instanceNumber(Number num, byte type) - { - switch (type) - { - case 1: - return new NBTTagByte(num.byteValue()); - case 2: - return new NBTTagShort(num.shortValue()); - case 3: - return new NBTTagInt(num.intValue()); - case 4: - return new NBTTagLong(num.longValue()); - case 5: - return new NBTTagFloat(num.floatValue()); - default: - return new NBTTagDouble(num.doubleValue()); + } + tagID = 11; + } catch (Exception e2) { + tagID = 9; // Is primitive however requires TagList interpretation + } + } + } else if (!entry.isJsonPrimitive()) { + break; } - } - - private static byte fallbackTagID(JsonElement jObj) - { - byte tagID = 0; - - if(jObj.isJsonPrimitive()) - { - JsonPrimitive prim = jObj.getAsJsonPrimitive(); - - if(prim.isNumber()) - { - if(prim.getAsString().contains(".")) // Just in case we'll choose the largest possible container supporting this number type (Long or Double) - { - tagID = 6; - } else - { - tagID = 4; - } - } else if(prim.isBoolean()) - { - tagID = 1; - } else - { - tagID = 8; // Non-number primitive. Assume string - } - } else if(jObj.isJsonArray()) - { - JsonArray array = jObj.getAsJsonArray(); - - for(JsonElement entry : array) - { - if(entry.isJsonPrimitive() && tagID == 0) // Note: TagLists can only support Integers, Bytes and Compounds (Strings can be stored but require special handling) - { - try - { - for(JsonElement element : array) - { - // Make sure all entries can be bytes - if(element.getAsLong() != element.getAsByte()) // In case casting works but overflows - { - throw new ClassCastException(); - } - } - tagID = 7; // Can be used as byte - } catch(Exception e1) - { - try - { - for(JsonElement element : array) - { - // Make sure all entries can be integers - if(element.getAsLong() != element.getAsInt()) // In case casting works but overflows - { - throw new ClassCastException(); - } - } - tagID = 11; - } catch(Exception e2) - { - tagID = 9; // Is primitive however requires TagList interpretation - } - } - } else if(!entry.isJsonPrimitive()) - { - break; - } - } - - tagID = 9; // No data to judge format. Assuming tag list - } else - { - tagID = 10; - } - - return tagID; - } + } + + tagID = 9; // No data to judge format. Assuming tag list + } else { + tagID = 10; + } + + return tagID; + } } diff --git a/src/main/java/betterquesting/api/utils/RenderUtils.java b/src/main/java/betterquesting/api/utils/RenderUtils.java index 9580eee0e..197728610 100644 --- a/src/main/java/betterquesting/api/utils/RenderUtils.java +++ b/src/main/java/betterquesting/api/utils/RenderUtils.java @@ -29,253 +29,236 @@ // TODO: Move text related stuff to its own utility class @SideOnly(Side.CLIENT) -public class RenderUtils -{ - public static final String REGEX_NUMBER = "[^\\.0123456789-]"; // I keep screwing this up so now it's reusable - - public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, String text) - { - RenderItemStack(mc, stack, x, y, text, Color.WHITE.getRGB()); - } - - public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, String text, Color color) - { - RenderItemStack(mc, stack, x, y, text, color.getRGB()); - } - - public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, String text, int color) - { - RenderItemStack(mc, stack, x, y, 16F, text, color); - } - - public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, float z, String text, int color) - { - if(stack == null || stack.isEmpty()) - { - return; - } - - GlStateManager.pushMatrix(); - RenderItem itemRender = mc.getRenderItem(); - float preZ = itemRender.zLevel; - - float r = (float)(color >> 16 & 255) / 255.0F; - float g = (float)(color >> 8 & 255) / 255.0F; - float b = (float)(color & 255) / 255.0F; - GlStateManager.color(r, g, b); - RenderHelper.enableGUIStandardItemLighting(); - GlStateManager.enableRescaleNormal(); - GlStateManager.enableDepth(); - - GlStateManager.translate(0.0F, 0.0F, z); - itemRender.zLevel = -150F; // Counters internal Z depth change so that GL translation makes sense - - FontRenderer font = stack.getItem().getFontRenderer(stack); - if (font == null) font = mc.fontRenderer; - - try - { - itemRender.renderItemAndEffectIntoGUI(stack, x, y); - - if (stack.getCount() != 1 || text != null) - { - GlStateManager.pushMatrix(); - - int w = getStringWidth(text, font); - float tx; - float ty; - float s = 1F; - - if(w > 17) - { - s = 17F / w; - tx = 0; - ty = 17 - font.FONT_HEIGHT * s; - } else - { - tx = 17 - w; - ty = 18 - font.FONT_HEIGHT; - } - - GlStateManager.translate(x + tx, y + ty, 0); - GlStateManager.scale(s, s, 1F); - - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - GlStateManager.disableBlend(); - - font.drawString(text, 0, 0, 16777215, true); - - GlStateManager.enableLighting(); - GlStateManager.enableDepth(); - GlStateManager.enableBlend(); - - GlStateManager.popMatrix(); - } - - itemRender.renderItemOverlayIntoGUI(font, stack, x, y, ""); - } catch(Exception e) - { - BetterQuesting.logger.warn("Unabled to render item " + stack, e); - } - - GlStateManager.disableDepth(); - RenderHelper.disableStandardItemLighting(); - - itemRender.zLevel = preZ; // Just in case - +public class RenderUtils { + public static final String REGEX_NUMBER = "[^\\.0123456789-]"; // I keep screwing this up so now it's reusable + + public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, String text) { + RenderItemStack(mc, stack, x, y, text, Color.WHITE.getRGB()); + } + + public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, String text, Color color) { + RenderItemStack(mc, stack, x, y, text, color.getRGB()); + } + + public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, String text, int color) { + RenderItemStack(mc, stack, x, y, 16F, text, color); + } + + public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, float z, String text, int color) { + if (stack == null || stack.isEmpty()) { + return; + } + + GlStateManager.pushMatrix(); + RenderItem itemRender = mc.getRenderItem(); + float preZ = itemRender.zLevel; + + float r = (float) (color >> 16 & 255) / 255.0F; + float g = (float) (color >> 8 & 255) / 255.0F; + float b = (float) (color & 255) / 255.0F; + GlStateManager.color(r, g, b); + RenderHelper.enableGUIStandardItemLighting(); + GlStateManager.enableRescaleNormal(); + GlStateManager.enableDepth(); + + GlStateManager.translate(0.0F, 0.0F, z); + itemRender.zLevel = -150F; // Counters internal Z depth change so that GL translation makes sense + + FontRenderer font = stack.getItem().getFontRenderer(stack); + if (font == null) { font = mc.fontRenderer; } + + try { + itemRender.renderItemAndEffectIntoGUI(stack, x, y); + + if (stack.getCount() != 1 || text != null) { + GlStateManager.pushMatrix(); + + int w = getStringWidth(text, font); + float tx; + float ty; + float s = 1F; + + if (w > 17) { + s = 17F / w; + tx = 0; + ty = 17 - font.FONT_HEIGHT * s; + } else { + tx = 17 - w; + ty = 18 - font.FONT_HEIGHT; + } + + GlStateManager.translate(x + tx, y + ty, 0); + GlStateManager.scale(s, s, 1F); + + GlStateManager.disableLighting(); + GlStateManager.disableDepth(); + GlStateManager.disableBlend(); + + font.drawString(text, 0, 0, 16777215, true); + + GlStateManager.enableLighting(); + GlStateManager.enableDepth(); + GlStateManager.enableBlend(); + GlStateManager.popMatrix(); - } - - public static void RenderEntity(int posX, int posY, int scale, float rotation, float pitch, Entity entity) - { - RenderEntity(posX, posY, 64F, scale, rotation, pitch, entity); - } - - public static void RenderEntity(float posX, float posY, float posZ, int scale, float rotation, float pitch, Entity entity) - { - try - { - GlStateManager.enableColorMaterial(); - GlStateManager.pushMatrix(); - GlStateManager.enableDepth(); - GlStateManager.translate(posX, posY, posZ); - GlStateManager.scale((float)-scale, (float)scale, (float)scale); // Not entirely sure why mobs are flipped but this is how vanilla GUIs fix it so... - GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(pitch, 1F, 0F, 0F); - GlStateManager.rotate(rotation, 0F, 1F, 0F); - float f3 = entity.rotationYaw; - float f4 = entity.rotationPitch; - float f5 = entity.prevRotationYaw; - float f6 = entity.prevRotationPitch; - entity.rotationYaw = 0; - entity.rotationPitch = 0; - entity.prevRotationYaw = 0; - entity.prevRotationPitch = 0; - EntityLivingBase livingBase = (entity instanceof EntityLivingBase) ? (EntityLivingBase)entity : null; - float f7 = livingBase == null ? 0 : livingBase.renderYawOffset; - float f8 = livingBase == null ? 0 : livingBase.rotationYawHead; - float f9 = livingBase == null ? 0 : livingBase.prevRotationYawHead; - if(livingBase != null) - { - livingBase.renderYawOffset = 0; - livingBase.rotationYawHead = 0; - livingBase.prevRotationYawHead = 0; - } - - RenderHelper.enableStandardItemLighting(); - RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager(); - rendermanager.setPlayerViewY(180.0F); - rendermanager.renderEntity(entity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F, false); - entity.rotationYaw = f3; - entity.rotationPitch = f4; - entity.prevRotationYaw = f5; - entity.prevRotationPitch = f6; - if(livingBase != null) - { - livingBase.renderYawOffset = f7; - livingBase.rotationYawHead = f8; - livingBase.prevRotationYawHead = f9; - } - GlStateManager.disableDepth(); - GlStateManager.popMatrix(); - RenderHelper.disableStandardItemLighting(); - GlStateManager.disableRescaleNormal(); - OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.disableTexture2D(); - OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); - GlStateManager.enableTexture2D(); // Breaks subsequent text rendering if not included - GlStateManager.disableColorMaterial(); - } catch(Exception e) - { - // Hides rendering errors with entities which are common for invalid/technical entities - } + } + + itemRender.renderItemOverlayIntoGUI(font, stack, x, y, ""); + } catch (Exception e) { + BetterQuesting.logger.warn("Unabled to render item " + stack, e); } - - public static void DrawLine(int x1, int y1, int x2, int y2, float width, int color) - { - float r = (float)(color >> 16 & 255) / 255.0F; - float g = (float)(color >> 8 & 255) / 255.0F; - float b = (float)(color & 255) / 255.0F; - GlStateManager.pushMatrix(); - - GlStateManager.disableTexture2D(); - GlStateManager.color(r, g, b, 1F); - GL11.glLineWidth(width); - - GL11.glBegin(GL11.GL_LINES); - GL11.glVertex2f(x1, y1); - GL11.glVertex2f(x2, y2); - GL11.glEnd(); - - GlStateManager.enableTexture2D(); - GlStateManager.color(1F, 1F, 1F, 1F); - - GlStateManager.popMatrix(); - } - - public static void drawSplitString(FontRenderer renderer, String string, int x, int y, int width, int color, boolean shadow) - { - drawSplitString(renderer, string, x, y, width, color, shadow, 0, splitString(string, width, renderer).size() - 1); - } - - public static void drawSplitString(FontRenderer renderer, String string, int x, int y, int width, int color, boolean shadow, int start, int end) - { - drawHighlightedSplitString(renderer, string, x, y, width, color, shadow, start, end, 0, 0, 0); - } - - // TODO: Clean this up. The list of parameters is getting a bit excessive - - public static void drawHighlightedSplitString(FontRenderer renderer, String string, int x, int y, int width, int color, boolean shadow, int highlightColor, int highlightStart, int highlightEnd) - { - drawHighlightedSplitString(renderer, string, x, y, width, color, shadow, 0, splitString(string, width, renderer).size() - 1, highlightColor, highlightStart, highlightEnd); - } - - public static void drawHighlightedSplitString(FontRenderer renderer, String string, int x, int y, int width, int color, boolean shadow, int start, int end, int highlightColor, int highlightStart, int highlightEnd) - { - if(renderer == null || string == null || string.length() <= 0 || start > end) - { - return; - } - - string = string.replaceAll("\r", ""); //Line endings from localizations break things so we remove them - - List list = splitString(string, width, renderer); - List noFormat = splitStringWithoutFormat(string, width, renderer); // Needed for accurate highlight index positions - - if(list.size() != noFormat.size()) - { - //BetterQuesting.logger.error("Line count mismatch (" + list.size() + " != " + noFormat.size() + ") while drawing formatted text!"); - return; - } - - int hlStart = Math.min(highlightStart, highlightEnd); - int hlEnd = Math.max(highlightStart, highlightEnd); - int idxStart = 0; - - for(int i = 0; i < start; i++) - { - if(i >= noFormat.size()) - { - break; - } - - idxStart += noFormat.get(i).length(); - } - - // Text rendering is very vulnerable to colour leaking - GlStateManager.color(1F, 1F, 1F, 1F); - - for(int i = start; i <= end; i++) - { - if(i < 0 || i >= list.size()) - { - continue; - } - - renderer.drawString(list.get(i), x, y + (renderer.FONT_HEIGHT * (i - start)), color, shadow); - - // DEBUG + + GlStateManager.disableDepth(); + RenderHelper.disableStandardItemLighting(); + + itemRender.zLevel = preZ; // Just in case + + GlStateManager.popMatrix(); + } + + public static void RenderEntity(int posX, int posY, int scale, float rotation, float pitch, Entity entity) { + RenderEntity(posX, posY, 64F, scale, rotation, pitch, entity); + } + + public static void RenderEntity(float posX, float posY, float posZ, int scale, float rotation, float pitch, + Entity entity) { + try { + GlStateManager.enableColorMaterial(); + GlStateManager.pushMatrix(); + GlStateManager.enableDepth(); + GlStateManager.translate(posX, posY, posZ); + GlStateManager.scale((float) -scale, (float) scale, + (float) scale); // Not entirely sure why mobs are flipped but this is how vanilla GUIs fix it so... + GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(pitch, 1F, 0F, 0F); + GlStateManager.rotate(rotation, 0F, 1F, 0F); + float f3 = entity.rotationYaw; + float f4 = entity.rotationPitch; + float f5 = entity.prevRotationYaw; + float f6 = entity.prevRotationPitch; + entity.rotationYaw = 0; + entity.rotationPitch = 0; + entity.prevRotationYaw = 0; + entity.prevRotationPitch = 0; + EntityLivingBase livingBase = (entity instanceof EntityLivingBase) ? (EntityLivingBase) entity : null; + float f7 = livingBase == null ? 0 : livingBase.renderYawOffset; + float f8 = livingBase == null ? 0 : livingBase.rotationYawHead; + float f9 = livingBase == null ? 0 : livingBase.prevRotationYawHead; + if (livingBase != null) { + livingBase.renderYawOffset = 0; + livingBase.rotationYawHead = 0; + livingBase.prevRotationYawHead = 0; + } + + RenderHelper.enableStandardItemLighting(); + RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager(); + rendermanager.setPlayerViewY(180.0F); + rendermanager.renderEntity(entity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F, false); + entity.rotationYaw = f3; + entity.rotationPitch = f4; + entity.prevRotationYaw = f5; + entity.prevRotationPitch = f6; + if (livingBase != null) { + livingBase.renderYawOffset = f7; + livingBase.rotationYawHead = f8; + livingBase.prevRotationYawHead = f9; + } + GlStateManager.disableDepth(); + GlStateManager.popMatrix(); + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableRescaleNormal(); + OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.disableTexture2D(); + OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); + GlStateManager.enableTexture2D(); // Breaks subsequent text rendering if not included + GlStateManager.disableColorMaterial(); + } catch (Exception e) { + // Hides rendering errors with entities which are common for invalid/technical entities + } + } + + public static void DrawLine(int x1, int y1, int x2, int y2, float width, int color) { + float r = (float) (color >> 16 & 255) / 255.0F; + float g = (float) (color >> 8 & 255) / 255.0F; + float b = (float) (color & 255) / 255.0F; + GlStateManager.pushMatrix(); + + GlStateManager.disableTexture2D(); + GlStateManager.color(r, g, b, 1F); + GL11.glLineWidth(width); + + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(x1, y1); + GL11.glVertex2f(x2, y2); + GL11.glEnd(); + + GlStateManager.enableTexture2D(); + GlStateManager.color(1F, 1F, 1F, 1F); + + GlStateManager.popMatrix(); + } + + public static void drawSplitString(FontRenderer renderer, String string, int x, int y, int width, int color, + boolean shadow) { + drawSplitString(renderer, string, x, y, width, color, shadow, 0, splitString(string, width, renderer).size() - 1); + } + + public static void drawSplitString(FontRenderer renderer, String string, int x, int y, int width, int color, + boolean shadow, int start, int end) { + drawHighlightedSplitString(renderer, string, x, y, width, color, shadow, start, end, 0, 0, 0); + } + + // TODO: Clean this up. The list of parameters is getting a bit excessive + + public static void drawHighlightedSplitString(FontRenderer renderer, String string, int x, int y, int width, + int color, boolean shadow, int highlightColor, int highlightStart, + int highlightEnd) { + drawHighlightedSplitString(renderer, string, x, y, width, color, shadow, 0, + splitString(string, width, renderer).size() - 1, highlightColor, highlightStart, + highlightEnd); + } + + public static void drawHighlightedSplitString(FontRenderer renderer, String string, int x, int y, int width, + int color, boolean shadow, int start, int end, int highlightColor, + int highlightStart, int highlightEnd) { + if (renderer == null || string == null || string.isEmpty() || start > end) { + return; + } + + string = string.replaceAll("\r", ""); //Line endings from localizations break things so we remove them + + List list = splitString(string, width, renderer); + List noFormat = + splitStringWithoutFormat(string, width, renderer); // Needed for accurate highlight index positions + + if (list.size() != noFormat.size()) { + //BetterQuesting.logger.error("Line count mismatch (" + list.size() + " != " + noFormat.size() + ") while drawing formatted text!"); + return; + } + + int hlStart = Math.min(highlightStart, highlightEnd); + int hlEnd = Math.max(highlightStart, highlightEnd); + int idxStart = 0; + + for (int i = 0; i < start; i++) { + if (i >= noFormat.size()) { + break; + } + + idxStart += noFormat.get(i).length(); + } + + // Text rendering is very vulnerable to colour leaking + GlStateManager.color(1F, 1F, 1F, 1F); + + for (int i = start; i <= end; i++) { + if (i < 0 || i >= list.size()) { + continue; + } + + renderer.drawString(list.get(i), x, y + (renderer.FONT_HEIGHT * (i - start)), color, shadow); + + // DEBUG /*boolean b = (System.currentTimeMillis()/1000)%2 == 0; if(b) @@ -292,579 +275,509 @@ public static void drawHighlightedSplitString(FontRenderer renderer, String stri { renderer.drawString(i + ": " + noFormat.get(i), x, y + (renderer.FONT_HEIGHT * (i - start)), color, shadow); }*/ - - int lineSize = noFormat.get(i).length(); - int idxEnd = idxStart + lineSize; - - int i1 = Math.max(idxStart, hlStart) - idxStart; - int i2 = Math.min(idxEnd, hlEnd) - idxStart; - - if(!(i1 == i2 || i1 < 0 || i2 < 0 || i1 > lineSize || i2 > lineSize)) - { - String lastFormat = FontRenderer.getFormatFromString(list.get(i)); - int x1 = getStringWidth(lastFormat + noFormat.get(i).substring(0, i1), renderer); - int x2 = getStringWidth(lastFormat + noFormat.get(i).substring(0, i2), renderer); - - drawHighlightBox(x + x1, y + (renderer.FONT_HEIGHT * (i - start)), x + x2, y + (renderer.FONT_HEIGHT * (i - start)) + renderer.FONT_HEIGHT, highlightColor); - } - - idxStart = idxEnd; - } - } - - public static void drawHighlightedString(FontRenderer renderer, String string, int x, int y, int color, boolean shadow, int highlightColor, int highlightStart, int highlightEnd) - { - if(renderer == null || string == null || string.length() <= 0) - { - return; - } - - renderer.drawString(string, x, y, color, shadow); - - int hlStart = Math.min(highlightStart, highlightEnd); - int hlEnd = Math.max(highlightStart, highlightEnd); - int size = string.length(); - - int i1 = MathHelper.clamp(hlStart, 0, size); - int i2 = MathHelper.clamp(hlEnd, 0, size); - - if(i1 != i2) - { - int x1 = getStringWidth(string.substring(0, i1), renderer); - int x2 = getStringWidth(string.substring(0, i2), renderer); - - drawHighlightBox(x + x1, y, x + x2, y + renderer.FONT_HEIGHT, highlightColor); - } - } - - public static void drawHighlightBox(IGuiRect rect, IGuiColor color) - { - drawHighlightBox(rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), color.getRGB()); - } - - public static void drawHighlightBox(int left, int top, int right, int bottom, int color) - { - if (left < right) - { - int i = left; - left = right; - right = i; - } - if (top < bottom) - { - int j = top; - top = bottom; - bottom = j; - } + int lineSize = noFormat.get(i).length(); + int idxEnd = idxStart + lineSize; - float f3 = (float)(color >> 24 & 255) / 255.0F; - float f = (float)(color >> 16 & 255) / 255.0F; - float f1 = (float)(color >> 8 & 255) / 255.0F; - float f2 = (float)(color & 255) / 255.0F; - - GlStateManager.pushMatrix(); - - GL11.glDisable(GL11.GL_TEXTURE_2D); - - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder bufferbuilder = tessellator.getBuffer(); - GlStateManager.color(f, f1, f2, f3); - GlStateManager.disableTexture2D(); - GlStateManager.enableColorLogic(); - GlStateManager.colorLogicOp(GlStateManager.LogicOp.OR_REVERSE); - bufferbuilder.begin(7, DefaultVertexFormats.POSITION); - bufferbuilder.pos((double)left, (double)bottom, 0.0D).endVertex(); - bufferbuilder.pos((double)right, (double)bottom, 0.0D).endVertex(); - bufferbuilder.pos((double)right, (double)top, 0.0D).endVertex(); - bufferbuilder.pos((double)left, (double)top, 0.0D).endVertex(); - tessellator.draw(); - GlStateManager.disableColorLogic(); - GlStateManager.enableTexture2D(); - - GL11.glEnable(GL11.GL_TEXTURE_2D); - - GlStateManager.popMatrix(); - } - - public static void drawColoredRect(IGuiRect rect, IGuiColor color) - { - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder vertexbuffer = tessellator.getBuffer(); - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); - color.applyGlColor(); - vertexbuffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION); - vertexbuffer.pos((double)rect.getX(), (double)rect.getY() + rect.getHeight(), 0.0D).endVertex(); - vertexbuffer.pos((double)rect.getX() + rect.getWidth(), (double)rect.getY() + rect.getHeight(), 0.0D).endVertex(); - vertexbuffer.pos((double)rect.getX() + rect.getWidth(), (double)rect.getY(), 0.0D).endVertex(); - vertexbuffer.pos((double)rect.getX(), (double)rect.getY(), 0.0D).endVertex(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); + int i1 = Math.max(idxStart, hlStart) - idxStart; + int i2 = Math.min(idxEnd, hlEnd) - idxStart; + + if (!(i1 == i2 || i1 < 0 || i2 < 0 || i1 > lineSize || i2 > lineSize)) { + String lastFormat = FontRenderer.getFormatFromString(list.get(i)); + int x1 = getStringWidth(lastFormat + noFormat.get(i).substring(0, i1), renderer); + int x2 = getStringWidth(lastFormat + noFormat.get(i).substring(0, i2), renderer); + + drawHighlightBox(x + x1, y + (renderer.FONT_HEIGHT * (i - start)), x + x2, + y + (renderer.FONT_HEIGHT * (i - start)) + renderer.FONT_HEIGHT, highlightColor); + } + + idxStart = idxEnd; } - - private static final IGuiColor STENCIL_COLOR = new GuiColorStatic(0, 0, 0, 255); - private static int stencilDepth = 0; - - public static void startScissor(IGuiRect rect) - { - if(stencilDepth >= 255) - { - throw new IndexOutOfBoundsException("Exceeded the maximum number of nested stencils (255)"); - } - - if(stencilDepth == 0) - { - GL11.glEnable(GL11.GL_STENCIL_TEST); - GL11.glStencilMask(0xFF); - GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); - } - - // Note: This is faster with inverted logic (skips depth tests when writing) - GL11.glStencilFunc(GL11.GL_LESS, stencilDepth, 0xFF); - GL11.glStencilOp(GL11.GL_INCR, GL11.GL_KEEP, GL11.GL_KEEP); - GL11.glStencilMask(0xFF); - - GL11.glColorMask(false, false, false, false); - GL11.glDepthMask(false); - - drawColoredRect(rect, STENCIL_COLOR); - - GL11.glStencilMask(0x00); - GL11.glStencilFunc(GL11.GL_EQUAL, stencilDepth + 1, 0xFF); - - GL11.glColorMask(true, true, true, true); - GL11.glDepthMask(true); - - stencilDepth++; - } - - private static void fillScreen() - { - int w = Minecraft.getMinecraft().displayWidth; - int h = Minecraft.getMinecraft().displayHeight; - - GL11.glPushAttrib(GL11.GL_TEXTURE_BIT | GL11.GL_DEPTH_TEST | GL11.GL_LIGHTING); - - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glDisable(GL11.GL_LIGHTING); - - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - GL11.glOrtho(0, w, h, 0, -1, 1); //or whatever size you want - - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - - drawColoredRect(new GuiRectangle(0, 0, w, h), STENCIL_COLOR); - - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glPopMatrix(); - - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glPopMatrix(); - - GL11.glPopAttrib(); + } + + public static void drawHighlightedString(FontRenderer renderer, String string, int x, int y, int color, + boolean shadow, int highlightColor, int highlightStart, int highlightEnd) { + if (renderer == null || string == null || string.isEmpty()) { + return; } - - /** - * Pops the last scissor off the stack and returns to the last parent scissor or disables it if there are none - */ - public static void endScissor() - { - stencilDepth--; - - if(stencilDepth < 0) - { - throw new IndexOutOfBoundsException("No stencil to end"); - } else if(stencilDepth == 0) - { - GL11.glStencilMask(0xFF); - GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); // Note: Clearing actually requires the mask to be enabled - - GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 0xFF); - GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP); - GL11.glStencilMask(0x00); - - GL11.glDisable(GL11.GL_STENCIL_TEST); - } else - { - GL11.glStencilFunc(GL11.GL_LEQUAL, stencilDepth, 0xFF); - GL11.glStencilOp(GL11.GL_DECR, GL11.GL_KEEP, GL11.GL_KEEP); - GL11.glStencilMask(0xFF); - - GL11.glColorMask(false, false, false, false); - GL11.glDepthMask(false); - - fillScreen(); - - GL11.glColorMask(true, true, true, true); - GL11.glDepthMask(true); - - GL11.glStencilFunc(GL11.GL_EQUAL, stencilDepth, 0xFF); - GL11.glStencilMask(0x00); - } - } - - /** - * Similar to normally splitting a string with the fontRenderer however this variant does - * not attempt to preserve the formatting between lines. This is particularly important when the - * index positions in the text are required to match the original unwrapped text. - */ - public static List splitStringWithoutFormat(String str, int wrapWidth, FontRenderer font) - { - List list = new ArrayList<>(); - - String lastFormat = ""; // Formatting like bold can affect the wrapping width - String temp = str; - - while(true) - { - int i = sizeStringToWidth(lastFormat + temp, wrapWidth, font); // Cut to size WITH formatting - i -= lastFormat.length(); // Remove formatting characters from count - - if(temp.length() <= i) - { - list.add(temp); - break; - } else - { - String s = temp.substring(0, i); - char c0 = temp.charAt(i); - boolean flag = c0 == ' ' || c0 == '\n'; - lastFormat = FontRenderer.getFormatFromString(lastFormat + s); - temp = temp.substring(i + (flag ? 1 : 0)); - // NOTE: The index actually stops just before the space/nl so we don't need to remove it from THIS line. This is why the previous line moves forward by one for the NEXT line - list.add(s + (flag ? "\n" : "")); // Although we need to remove the spaces between each line we have to replace them with invisible new line characters to preserve the index count - - if(temp.length() <= 0 && !flag) - { - break; - } - } - } - - return list; - } - - public static List splitString(String str, int wrapWidth, FontRenderer font) - { - List list = new ArrayList<>(); - - String temp = str; - - while(true) - { - int i = sizeStringToWidth(temp, wrapWidth, font); // Cut to size WITH formatting - - if(temp.length() <= i) - { - list.add(temp); - break; - } else - { - String s = temp.substring(0, i); - char c0 = temp.charAt(i); - boolean flag = c0 == ' ' || c0 == '\n'; - temp = FontRenderer.getFormatFromString(s) + temp.substring(i + (flag ? 1 : 0)); - list.add(s); - - if(temp.length() <= 0 && !flag) - { - break; - } - } - } - - return list; - } - - /** - * Returns the index position under a given set of coordinates in a piece of text - */ - public static int getCursorPos(String text, int x, FontRenderer font) - { - if(text.length() <= 0) - { - return 0; - } - - int i = 0; - - for(; i < text.length(); i++) - { - if(getStringWidth(text.substring(0, i + 1), font) > x) - { - break; - } - } - - if(i - 1 >= 0 && text.charAt(i - 1) == '\n') - { - return i - 1; - } - - return i; - } - - /** - * Returns the index position under a given set of coordinates in a wrapped piece of text - */ - public static int getCursorPos(String text, int x, int y, int width, FontRenderer font) - { - List tLines = RenderUtils.splitStringWithoutFormat(text, width, font); - - if(tLines.size() <= 0) - { - return 0; - } - - int row = MathHelper.clamp(y/font.FONT_HEIGHT, 0, tLines.size() - 1); - String lastFormat = ""; - String line; - int idx = 0; - - for(int i = 0; i < row; i++) - { - line = tLines.get(i); - idx += line.length(); - lastFormat = FontRenderer.getFormatFromString(lastFormat + line); - } - - return idx + getCursorPos(lastFormat + tLines.get(row), x, font) - lastFormat.length(); - } - - private static int sizeStringToWidth(String str, int wrapWidth, FontRenderer font) - { - int i = str.length(); - int j = 0; - int k = 0; - int l = -1; - - for (boolean flag = false; k < i; ++k) - { - char c0 = str.charAt(k); - - switch (c0) - { - case '\n': - --k; - break; - case ' ': - l = k; - default: - j += font.getCharWidth(c0); - - if (flag) - { - ++j; - } - - break; - case '\u00a7': - - if (k < i - 1) - { - ++k; - char c1 = str.charAt(k); - - if (c1 != 'l' && c1 != 'L') - { - if (c1 == 'r' || c1 == 'R' || isFormatColor(c1)) - { - flag = false; - } - } - else - { - flag = true; - } - } - } - if (c0 == '\n') - { - ++k; - l = k; - break; - } + renderer.drawString(string, x, y, color, shadow); + + int hlStart = Math.min(highlightStart, highlightEnd); + int hlEnd = Math.max(highlightStart, highlightEnd); + int size = string.length(); + + int i1 = MathHelper.clamp(hlStart, 0, size); + int i2 = MathHelper.clamp(hlEnd, 0, size); + + if (i1 != i2) { + int x1 = getStringWidth(string.substring(0, i1), renderer); + int x2 = getStringWidth(string.substring(0, i2), renderer); + + drawHighlightBox(x + x1, y, x + x2, y + renderer.FONT_HEIGHT, highlightColor); + } + } + + public static void drawHighlightBox(IGuiRect rect, IGuiColor color) { + drawHighlightBox(rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), + color.getRGB()); + } + + public static void drawHighlightBox(int left, int top, int right, int bottom, int color) { + if (left < right) { + int i = left; + left = right; + right = i; + } + + if (top < bottom) { + int j = top; + top = bottom; + bottom = j; + } + + float f3 = (float) (color >> 24 & 255) / 255.0F; + float f = (float) (color >> 16 & 255) / 255.0F; + float f1 = (float) (color >> 8 & 255) / 255.0F; + float f2 = (float) (color & 255) / 255.0F; + + GlStateManager.pushMatrix(); + + GL11.glDisable(GL11.GL_TEXTURE_2D); + + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder bufferbuilder = tessellator.getBuffer(); + GlStateManager.color(f, f1, f2, f3); + GlStateManager.disableTexture2D(); + GlStateManager.enableColorLogic(); + GlStateManager.colorLogicOp(GlStateManager.LogicOp.OR_REVERSE); + bufferbuilder.begin(7, DefaultVertexFormats.POSITION); + bufferbuilder.pos(left, bottom, 0.0D).endVertex(); + bufferbuilder.pos(right, bottom, 0.0D).endVertex(); + bufferbuilder.pos(right, top, 0.0D).endVertex(); + bufferbuilder.pos(left, top, 0.0D).endVertex(); + tessellator.draw(); + GlStateManager.disableColorLogic(); + GlStateManager.enableTexture2D(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + + GlStateManager.popMatrix(); + } + + public static void drawColoredRect(IGuiRect rect, IGuiColor color) { + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder vertexbuffer = tessellator.getBuffer(); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, + GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, + GlStateManager.DestFactor.ZERO); + color.applyGlColor(); + vertexbuffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION); + vertexbuffer.pos(rect.getX(), (double) rect.getY() + rect.getHeight(), 0.0D).endVertex(); + vertexbuffer.pos((double) rect.getX() + rect.getWidth(), (double) rect.getY() + rect.getHeight(), 0.0D).endVertex(); + vertexbuffer.pos((double) rect.getX() + rect.getWidth(), rect.getY(), 0.0D).endVertex(); + vertexbuffer.pos(rect.getX(), rect.getY(), 0.0D).endVertex(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + private static final IGuiColor STENCIL_COLOR = new GuiColorStatic(0, 0, 0, 255); + private static int stencilDepth = 0; + + public static void startScissor(IGuiRect rect) { + if (stencilDepth >= 255) { + throw new IndexOutOfBoundsException("Exceeded the maximum number of nested stencils (255)"); + } + + if (stencilDepth == 0) { + GL11.glEnable(GL11.GL_STENCIL_TEST); + GL11.glStencilMask(0xFF); + GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); + } + + // Note: This is faster with inverted logic (skips depth tests when writing) + GL11.glStencilFunc(GL11.GL_LESS, stencilDepth, 0xFF); + GL11.glStencilOp(GL11.GL_INCR, GL11.GL_KEEP, GL11.GL_KEEP); + GL11.glStencilMask(0xFF); + + GL11.glColorMask(false, false, false, false); + GL11.glDepthMask(false); + + drawColoredRect(rect, STENCIL_COLOR); + + GL11.glStencilMask(0x00); + GL11.glStencilFunc(GL11.GL_EQUAL, stencilDepth + 1, 0xFF); + + GL11.glColorMask(true, true, true, true); + GL11.glDepthMask(true); + + stencilDepth++; + } + + private static void fillScreen() { + int w = Minecraft.getMinecraft().displayWidth; + int h = Minecraft.getMinecraft().displayHeight; + + GL11.glPushAttrib(GL11.GL_TEXTURE_BIT | GL11.GL_DEPTH_TEST | GL11.GL_LIGHTING); + + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_LIGHTING); + + GL11.glMatrixMode(GL11.GL_PROJECTION); + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + GL11.glOrtho(0, w, h, 0, -1, 1); //or whatever size you want + + GL11.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glPushMatrix(); + GL11.glLoadIdentity(); + + drawColoredRect(new GuiRectangle(0, 0, w, h), STENCIL_COLOR); + + GL11.glMatrixMode(GL11.GL_PROJECTION); + GL11.glPopMatrix(); + + GL11.glMatrixMode(GL11.GL_MODELVIEW); + GL11.glPopMatrix(); + + GL11.glPopAttrib(); + } + + /** + * Pops the last scissor off the stack and returns to the last parent scissor or disables it if there are none + */ + public static void endScissor() { + stencilDepth--; + + if (stencilDepth < 0) { + throw new IndexOutOfBoundsException("No stencil to end"); + } else if (stencilDepth == 0) { + GL11.glStencilMask(0xFF); + GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT); // Note: Clearing actually requires the mask to be enabled + + GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 0xFF); + GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP); + GL11.glStencilMask(0x00); + + GL11.glDisable(GL11.GL_STENCIL_TEST); + } else { + GL11.glStencilFunc(GL11.GL_LEQUAL, stencilDepth, 0xFF); + GL11.glStencilOp(GL11.GL_DECR, GL11.GL_KEEP, GL11.GL_KEEP); + GL11.glStencilMask(0xFF); + + GL11.glColorMask(false, false, false, false); + GL11.glDepthMask(false); + + fillScreen(); + + GL11.glColorMask(true, true, true, true); + GL11.glDepthMask(true); + + GL11.glStencilFunc(GL11.GL_EQUAL, stencilDepth, 0xFF); + GL11.glStencilMask(0x00); + } + } + + /** + * Similar to normally splitting a string with the fontRenderer however this variant does + * not attempt to preserve the formatting between lines. This is particularly important when the + * index positions in the text are required to match the original unwrapped text. + */ + public static List splitStringWithoutFormat(String str, int wrapWidth, FontRenderer font) { + List list = new ArrayList<>(); + + String lastFormat = ""; // Formatting like bold can affect the wrapping width + String temp = str; + + while (true) { + int i = sizeStringToWidth(lastFormat + temp, wrapWidth, font); // Cut to size WITH formatting + i -= lastFormat.length(); // Remove formatting characters from count + + if (temp.length() <= i) { + list.add(temp); + break; + } else { + String s = temp.substring(0, i); + char c0 = temp.charAt(i); + boolean flag = c0 == ' ' || c0 == '\n'; + lastFormat = FontRenderer.getFormatFromString(lastFormat + s); + temp = temp.substring(i + (flag ? 1 : 0)); + // NOTE: The index actually stops just before the space/nl so we don't need to remove it from THIS line. This is why the previous line moves forward by one for the NEXT line + list.add(s + (flag ? "\n" + : "")); // Although we need to remove the spaces between each line we have to replace them with invisible new line characters to preserve the index count + } + } + + return list; + } + + public static List splitString(String str, int wrapWidth, FontRenderer font) { + List list = new ArrayList<>(); + + String temp = str; + + while (true) { + int i = sizeStringToWidth(temp, wrapWidth, font); // Cut to size WITH formatting + + if (temp.length() <= i) { + list.add(temp); + break; + } else { + String s = temp.substring(0, i); + char c0 = temp.charAt(i); + boolean flag = c0 == ' ' || c0 == '\n'; + temp = FontRenderer.getFormatFromString(s) + temp.substring(i + (flag ? 1 : 0)); + list.add(s); + } + } + + return list; + } + + /** + * Returns the index position under a given set of coordinates in a piece of text + */ + public static int getCursorPos(String text, int x, FontRenderer font) { + if (text.isEmpty()) { + return 0; + } + + int i = 0; + + for (; i < text.length(); i++) { + if (getStringWidth(text.substring(0, i + 1), font) > x) { + break; + } + } + + if (i - 1 >= 0 && text.charAt(i - 1) == '\n') { + return i - 1; + } - if (j > wrapWidth) - { - break; + return i; + } + + /** + * Returns the index position under a given set of coordinates in a wrapped piece of text + */ + public static int getCursorPos(String text, int x, int y, int width, FontRenderer font) { + List tLines = RenderUtils.splitStringWithoutFormat(text, width, font); + + if (tLines.isEmpty()) { + return 0; + } + + int row = MathHelper.clamp(y / font.FONT_HEIGHT, 0, tLines.size() - 1); + String lastFormat = ""; + String line; + int idx = 0; + + for (int i = 0; i < row; i++) { + line = tLines.get(i); + idx += line.length(); + lastFormat = FontRenderer.getFormatFromString(lastFormat + line); + } + + return idx + getCursorPos(lastFormat + tLines.get(row), x, font) - lastFormat.length(); + } + + private static int sizeStringToWidth(String str, int wrapWidth, FontRenderer font) { + int i = str.length(); + int j = 0; + int k = 0; + int l = -1; + + for (boolean flag = false; k < i; ++k) { + char c0 = str.charAt(k); + + switch (c0) { + case '\n': + --k; + break; + case ' ': + l = k; + default: + j += font.getCharWidth(c0); + + if (flag) { + ++j; + } + + break; + case '§': + if (k < i - 1) { + ++k; + char c1 = str.charAt(k); + + if (c1 != 'l' && c1 != 'L') { + if (c1 == 'r' || c1 == 'R' || isFormatColor(c1)) { + flag = false; + } + } else { + flag = true; } - } + } + } + + if (c0 == '\n') { + ++k; + l = k; + break; + } + + if (j > wrapWidth) { + break; + } + } - return k != i && l != -1 && l < k ? l : k; + return k != i && l != -1 && l < k ? l : k; + } + + private static boolean isFormatColor(char colorChar) { + return colorChar >= '0' && colorChar <= '9' || colorChar >= 'a' && colorChar <= 'f' || + colorChar >= 'A' && colorChar <= 'F'; + } + + public static float lerpFloat(float f1, float f2, float blend) { + return (f2 * blend) + (f1 * (1F - blend)); + } + + public static double lerpDouble(double d1, double d2, double blend) { + return (d2 * blend) + (d1 * (1D - blend)); + } + + public static int lerpRGB(int c1, int c2, float blend) { + float a1 = c1 >> 24 & 255; + float r1 = c1 >> 16 & 255; + float g1 = c1 >> 8 & 255; + float b1 = c1 & 255; + + float a2 = c2 >> 24 & 255; + float r2 = c2 >> 16 & 255; + float g2 = c2 >> 8 & 255; + float b2 = c2 & 255; + + int a3 = (int) lerpFloat(a1, a2, blend); + int r3 = (int) lerpFloat(r1, r2, blend); + int g3 = (int) lerpFloat(g1, g2, blend); + int b3 = (int) lerpFloat(b1, b2, blend); + + return (a3 << 24) + (r3 << 16) + (g3 << 8) + b3; + } + + public static void drawHoveringText(List textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, + int maxTextWidth, FontRenderer font) { + drawHoveringText(ItemStack.EMPTY, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, font); + } + + /** + * Modified version of Forge's tooltip rendering that doesn't adjust Z depth + */ + public static void drawHoveringText(@Nonnull final ItemStack stack, List textLines, int mouseX, int mouseY, + int screenWidth, int screenHeight, int maxTextWidth, FontRenderer font) { + if (textLines == null || textLines.isEmpty()) { return; } + + RenderTooltipEvent.Pre event = + new RenderTooltipEvent.Pre(stack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, font); + if (MinecraftForge.EVENT_BUS.post(event)) { return; } + + mouseX = event.getX(); + mouseY = event.getY(); + screenWidth = event.getScreenWidth(); + screenHeight = event.getScreenHeight(); + maxTextWidth = event.getMaxWidth(); + font = event.getFontRenderer(); + + GlStateManager.pushMatrix(); + GlStateManager.translate(0F, 0F, 32F); + GlStateManager.disableRescaleNormal(); + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableLighting(); + //GlStateManager.enableDepth(); + GlStateManager.disableDepth(); + int tooltipTextWidth = 0; + + for (String textLine : textLines) { + int textLineWidth = getStringWidth(textLine, font); + + if (textLineWidth > tooltipTextWidth) { + tooltipTextWidth = textLineWidth; + } } - - private static boolean isFormatColor(char colorChar) - { - return colorChar >= '0' && colorChar <= '9' || colorChar >= 'a' && colorChar <= 'f' || colorChar >= 'A' && colorChar <= 'F'; + + boolean needsWrap = false; + + int titleLinesCount = 1; + int tooltipX = mouseX + 12; + + if (tooltipX + tooltipTextWidth + 4 > screenWidth) { + tooltipX = mouseX - 16 - tooltipTextWidth; + + if (tooltipX < 4) // if the tooltip doesn't fit on the screen + { + if (mouseX > screenWidth / 2) { + tooltipTextWidth = mouseX - 12 - 8; + } else { + tooltipTextWidth = screenWidth - 16 - mouseX; + } + needsWrap = true; + } } - - public static float lerpFloat(float f1, float f2, float blend) - { - return (f2 * blend) + (f1 * (1F - blend)); - } - - public static double lerpDouble(double d1, double d2, double blend) - { - return (d2 * blend) + (d1 * (1D - blend)); - } - - public static int lerpRGB(int c1, int c2, float blend) - { - float a1 = c1 >> 24 & 255; - float r1 = c1 >> 16 & 255; - float g1 = c1 >> 8 & 255; - float b1 = c1 & 255; - - float a2 = c2 >> 24 & 255; - float r2 = c2 >> 16 & 255; - float g2 = c2 >> 8 & 255; - float b2 = c2 & 255; - - int a3 = (int)lerpFloat(a1, a2, blend); - int r3 = (int)lerpFloat(r1, r2, blend); - int g3 = (int)lerpFloat(g1, g2, blend); - int b3 = (int)lerpFloat(b1, b2, blend); - - return (a3 << 24) + (r3 << 16) + (g3 << 8) + b3; - } - - public static void drawHoveringText(List textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, int maxTextWidth, FontRenderer font) - { - drawHoveringText(ItemStack.EMPTY, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, font); + + if (maxTextWidth > 0 && tooltipTextWidth > maxTextWidth) { + tooltipTextWidth = maxTextWidth; + needsWrap = true; } - - /** - * Modified version of Forge's tooltip rendering that doesn't adjust Z depth - */ - public static void drawHoveringText(@Nonnull final ItemStack stack, List textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, int maxTextWidth, FontRenderer font) - { - if(textLines == null || textLines.isEmpty()) return; - - RenderTooltipEvent.Pre event = new RenderTooltipEvent.Pre(stack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, font); - if (MinecraftForge.EVENT_BUS.post(event)) return; - - mouseX = event.getX(); - mouseY = event.getY(); - screenWidth = event.getScreenWidth(); - screenHeight = event.getScreenHeight(); - maxTextWidth = event.getMaxWidth(); - font = event.getFontRenderer(); - - GlStateManager.pushMatrix(); - GlStateManager.translate(0F, 0F, 32F); - GlStateManager.disableRescaleNormal(); - RenderHelper.disableStandardItemLighting(); - GlStateManager.disableLighting(); - //GlStateManager.enableDepth(); - GlStateManager.disableDepth(); - int tooltipTextWidth = 0; - - for (String textLine : textLines) - { - int textLineWidth = getStringWidth(textLine, font); - - if (textLineWidth > tooltipTextWidth) - { - tooltipTextWidth = textLineWidth; - } - } - boolean needsWrap = false; + if (needsWrap) { + int wrappedTooltipWidth = 0; + List wrappedTextLines = new ArrayList<>(); - int titleLinesCount = 1; - int tooltipX = mouseX + 12; - - if (tooltipX + tooltipTextWidth + 4 > screenWidth) - { - tooltipX = mouseX - 16 - tooltipTextWidth; - - if (tooltipX < 4) // if the tooltip doesn't fit on the screen - { - if (mouseX > screenWidth / 2) - { - tooltipTextWidth = mouseX - 12 - 8; - } - else - { - tooltipTextWidth = screenWidth - 16 - mouseX; - } - needsWrap = true; - } - } - - if (maxTextWidth > 0 && tooltipTextWidth > maxTextWidth) - { - tooltipTextWidth = maxTextWidth; - needsWrap = true; - } - - if (needsWrap) - { - int wrappedTooltipWidth = 0; - List wrappedTextLines = new ArrayList<>(); - - for (int i = 0; i < textLines.size(); i++) - { - String textLine = textLines.get(i); - List wrappedLine = font.listFormattedStringToWidth(textLine, tooltipTextWidth); - if (i == 0) - { - titleLinesCount = wrappedLine.size(); - } - - for (String line : wrappedLine) - { - int lineWidth = getStringWidth(line, font); - if (lineWidth > wrappedTooltipWidth) - { - wrappedTooltipWidth = lineWidth; - } - wrappedTextLines.add(line); - } - } - - tooltipTextWidth = wrappedTooltipWidth; - textLines = wrappedTextLines; + for (int i = 0; i < textLines.size(); i++) { + String textLine = textLines.get(i); + List wrappedLine = font.listFormattedStringToWidth(textLine, tooltipTextWidth); + if (i == 0) { + titleLinesCount = wrappedLine.size(); + } - if (mouseX > screenWidth / 2) - { - tooltipX = mouseX - 16 - tooltipTextWidth; - } - else - { - tooltipX = mouseX + 12; - } - } + for (String line : wrappedLine) { + int lineWidth = getStringWidth(line, font); + if (lineWidth > wrappedTooltipWidth) { + wrappedTooltipWidth = lineWidth; + } + wrappedTextLines.add(line); + } + } - int tooltipY = mouseY - 12; - int tooltipHeight = 8; + tooltipTextWidth = wrappedTooltipWidth; + textLines = wrappedTextLines; - if (textLines.size() > 1) - { - tooltipHeight += (textLines.size() - 1) * 10; - - if (textLines.size() > titleLinesCount) - { - tooltipHeight += 2; // gap between title lines and next lines - } - } - - if (tooltipY < 4) - { - tooltipY = 4; - } else if (tooltipY + tooltipHeight + 4 > screenHeight) - { - tooltipY = screenHeight - tooltipHeight - 4; - } + if (mouseX > screenWidth / 2) { + tooltipX = mouseX - 16 - tooltipTextWidth; + } else { + tooltipX = mouseX + 12; + } + } + + int tooltipY = mouseY - 12; + int tooltipHeight = 8; + + if (textLines.size() > 1) { + tooltipHeight += (textLines.size() - 1) * 10; + + if (textLines.size() > titleLinesCount) { + tooltipHeight += 2; // gap between title lines and next lines + } + } + + if (tooltipY < 4) { + tooltipY = 4; + } else if (tooltipY + tooltipHeight + 4 > screenHeight) { + tooltipY = screenHeight - tooltipHeight - 4; + } /*int backgroundColor = 0xF0100010; int borderColorStart = 0x505000FF; @@ -887,87 +800,85 @@ public static void drawHoveringText(@Nonnull final ItemStack stack, List GuiUtils.drawGradientRect(0, tooltipX - 3, tooltipY + tooltipHeight + 2, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, borderColorEnd, borderColorEnd); MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostBackground(stack, textLines, tooltipX, tooltipY, font, tooltipTextWidth, tooltipHeight));*/ - PresetTexture.TOOLTIP_BG.getTexture().drawTexture(tooltipX - 4, tooltipY - 4, tooltipTextWidth + 8, tooltipHeight + 8, 0F, 1F); - int tooltipTop = tooltipY; - - GlStateManager.translate(0F, 0F, 0.1F); + PresetTexture.TOOLTIP_BG.getTexture() + .drawTexture(tooltipX - 4, tooltipY - 4, tooltipTextWidth + 8, tooltipHeight + 8, 0F, 1F); + int tooltipTop = tooltipY; - for (int lineNumber = 0; lineNumber < textLines.size(); ++lineNumber) - { - String line = textLines.get(lineNumber); - font.drawStringWithShadow(line, (float)tooltipX, (float)tooltipY, -1); + GlStateManager.translate(0F, 0F, 0.1F); - if (lineNumber + 1 == titleLinesCount) - { - tooltipY += 2; - } + for (int lineNumber = 0; lineNumber < textLines.size(); ++lineNumber) { + String line = textLines.get(lineNumber); + font.drawStringWithShadow(line, (float) tooltipX, (float) tooltipY, -1); - tooltipY += 10; - } + if (lineNumber + 1 == titleLinesCount) { + tooltipY += 2; + } - MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostText(stack, textLines, tooltipX, tooltipTop, font, tooltipTextWidth, tooltipHeight)); + tooltipY += 10; + } - GlStateManager.enableLighting(); - //GlStateManager.disableDepth(); - //GlStateManager.enableDepth(); - RenderHelper.enableStandardItemLighting(); - GlStateManager.enableRescaleNormal(); - GlStateManager.popMatrix(); + MinecraftForge.EVENT_BUS.post( + new RenderTooltipEvent.PostText(stack, textLines, tooltipX, tooltipTop, font, tooltipTextWidth, tooltipHeight)); + + GlStateManager.enableLighting(); + //GlStateManager.disableDepth(); + //GlStateManager.enableDepth(); + RenderHelper.enableStandardItemLighting(); + GlStateManager.enableRescaleNormal(); + GlStateManager.popMatrix(); + } + + /** + * A version of getStringWidth that actually behaves according to the format resetting rules of colour codes. Minecraft's built in one is busted! + */ + public static int getStringWidth(String text, FontRenderer font) { + if (text == null || text.isEmpty()) { + return 0; } - - /** - * A version of getStringWidth that actually behaves according to the format resetting rules of colour codes. Minecraft's built in one is busted! - */ - public static int getStringWidth(String text, FontRenderer font) - { - if (text == null || text.length() == 0) return 0; - - int maxWidth = 0; - int curLineWidth = 0; - boolean bold = false; - - for (int j = 0; j < text.length(); ++j) - { - char c0 = text.charAt(j); - int k = font.getCharWidth(c0); - - if (k < 0 && j < text.length() - 1) // k should only be negative when the section sign has been used! - { - // Move the caret to the formatting character and read from there - ++j; - c0 = text.charAt(j); - - if (c0 != 'l' && c0 != 'L') - { - int ci = "0123456789abcdefklmnor".indexOf(String.valueOf(c0).toLowerCase(Locale.ROOT).charAt(0)); - //if (c0 == 'r' || c0 == 'R') // Minecraft's original implemention. This is broken... - if(ci < 16 || ci == 21) // Reset bolding. Now supporting colour AND reset codes! - { - bold = false; - } - } - else // This is the bold format on. Time to get T H I C C - { - bold = true; - } - - k = 0; // Fix the negative value the section symbol previously set - } - - curLineWidth += k; - if (bold && k > 0) // This is a bolded normal character which is 1px thicker - { - ++curLineWidth; - } - - if(c0 == '\n') // New line. Reset counting width - { - maxWidth = Math.max(maxWidth, curLineWidth); - curLineWidth = 0; - } + int maxWidth = 0; + int curLineWidth = 0; + boolean bold = false; + + for (int j = 0; j < text.length(); ++j) { + char c0 = text.charAt(j); + int k = font.getCharWidth(c0); + + if (k < 0 && j < text.length() - 1) // k should only be negative when the section sign has been used! + { + // Move the caret to the formatting character and read from there + ++j; + c0 = text.charAt(j); + + if (c0 != 'l' && c0 != 'L') { + int ci = "0123456789abcdefklmnor".indexOf(String.valueOf(c0).toLowerCase(Locale.ROOT).charAt(0)); + //if (c0 == 'r' || c0 == 'R') // Minecraft's original implemention. This is broken... + if (ci < 16 || ci == 21) // Reset bolding. Now supporting colour AND reset codes! + { + bold = false; + } + } else // This is the bold format on. Time to get T H I C C + { + bold = true; } - return Math.max(maxWidth, curLineWidth); + k = 0; // Fix the negative value the section symbol previously set + } + + curLineWidth += k; + + if (bold && k > 0) // This is a bolded normal character which is 1px thicker + { + ++curLineWidth; + } + + if (c0 == '\n') // New line. Reset counting width + { + maxWidth = Math.max(maxWidth, curLineWidth); + curLineWidth = 0; + } } + + return Math.max(maxWidth, curLineWidth); + } } diff --git a/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java b/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java index 11f05bfa5..83161feb5 100644 --- a/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java +++ b/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java @@ -10,55 +10,46 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class CapabilityProviderQuestCache implements ICapabilityProvider, ICapabilitySerializable -{ - @CapabilityInject(QuestCache.class) - public static Capability CAP_QUEST_CACHE; - public static final ResourceLocation LOC_QUEST_CACHE = new ResourceLocation("betterquesting", "quest_cache"); - - private final QuestCache cache = new QuestCache(); - - @Override - public NBTTagCompound serializeNBT() - { - return cache.serializeNBT(); - } - - @Override - public void deserializeNBT(NBTTagCompound nbt) - { - cache.deserializeNBT(nbt); - } - - @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) - { - return capability == CAP_QUEST_CACHE; - } - - @Nullable - @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) - { - return capability == CAP_QUEST_CACHE ? CAP_QUEST_CACHE.cast(cache) : null; - } - - public static void register() - { - CapabilityManager.INSTANCE.register(QuestCache.class, new IStorage() - { - @Nullable - @Override - public NBTBase writeNBT(Capability capability, QuestCache instance, EnumFacing side) - { - return instance.serializeNBT(); - } - - @Override - public void readNBT(Capability capability, QuestCache instance, EnumFacing side, NBTBase nbt) - { - if(nbt instanceof NBTTagCompound) instance.deserializeNBT((NBTTagCompound)nbt); - } - }, QuestCache::new); - } +public class CapabilityProviderQuestCache implements ICapabilityProvider, ICapabilitySerializable { + @CapabilityInject(QuestCache.class) + public static Capability CAP_QUEST_CACHE; + public static final ResourceLocation LOC_QUEST_CACHE = new ResourceLocation("betterquesting", "quest_cache"); + + private final QuestCache cache = new QuestCache(); + + @Override + public NBTTagCompound serializeNBT() { + return cache.serializeNBT(); + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + cache.deserializeNBT(nbt); + } + + @Override + public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + return capability == CAP_QUEST_CACHE; + } + + @Nullable + @Override + public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + return capability == CAP_QUEST_CACHE ? CAP_QUEST_CACHE.cast(cache) : null; + } + + public static void register() { + CapabilityManager.INSTANCE.register(QuestCache.class, new IStorage() { + @Nullable + @Override + public NBTBase writeNBT(Capability capability, QuestCache instance, EnumFacing side) { + return instance.serializeNBT(); + } + + @Override + public void readNBT(Capability capability, QuestCache instance, EnumFacing side, NBTBase nbt) { + if (nbt instanceof NBTTagCompound) { instance.deserializeNBT((NBTTagCompound) nbt); } + } + }, QuestCache::new); + } } diff --git a/src/main/java/betterquesting/api2/cache/QuestCache.java b/src/main/java/betterquesting/api2/cache/QuestCache.java index 379dae8ba..9e36effae 100644 --- a/src/main/java/betterquesting/api2/cache/QuestCache.java +++ b/src/main/java/betterquesting/api2/cache/QuestCache.java @@ -19,275 +19,245 @@ import java.util.TreeSet; import java.util.UUID; -public class QuestCache implements INBTSerializable -{ - // Quests that are visible to the player - private final TreeSet visibleQuests = new TreeSet<>(); - - // Quests that are currently being undertaken. NOTE: Quests can be locked but still processing data if configured to do so - private final TreeSet activeQuests = new TreeSet<>(); - - // Quests and their scheduled time of being reset - private final TreeSet resetSchedule = new TreeSet<>((o1, o2) -> o1.questID == o2.questID ? 0 : Long.compare(o1.time, o2.time)); - - // Quests with pending auto claims (usually should be empty unless a condition needs to be met) - private final TreeSet autoClaims = new TreeSet<>(); - - // Quests that need to be sent to the client to update progression (NOT for edits. Handle that elsewhere) - private final TreeSet markedDirty = new TreeSet<>(); - - public synchronized int[] getActiveQuests() - { - // Probably a better way of doing this but this will do for now - int i = 0; - int[] aryAct = new int[activeQuests.size()]; - for(Integer q : activeQuests) aryAct[i++] = q; - return aryAct; - } - - public synchronized int[] getVisibleQuests() - { - // Probably a better way of doing this but this will do for now - int i = 0; - int[] aryVis = new int[visibleQuests.size()]; - for(Integer q : visibleQuests) aryVis[i++] = q; - return aryVis; - } - - public synchronized int[] getPendingAutoClaims() - { - // Probably a better way of doing this but this will do for now - int i = 0; - int[] aryAC = new int[autoClaims.size()]; - for(Integer q : autoClaims) aryAC[i++] = q; - return aryAC; - } - - public synchronized QResetTime[] getScheduledResets() // Already sorted by time - { - return resetSchedule.toArray(new QResetTime[0]); - } - - public synchronized void markQuestDirty(int questID) - { - if(questID < 0) return; - markedDirty.add(questID); - } - - public synchronized void markQuestClean(int questID) - { - if(questID < 0) return; - markedDirty.remove(questID); +public class QuestCache implements INBTSerializable { + // Quests that are visible to the player + private final TreeSet visibleQuests = new TreeSet<>(); + + // Quests that are currently being undertaken. NOTE: Quests can be locked but still processing data if configured to do so + private final TreeSet activeQuests = new TreeSet<>(); + + // Quests and their scheduled time of being reset + private final TreeSet resetSchedule = + new TreeSet<>((o1, o2) -> o1.questID == o2.questID ? 0 : Long.compare(o1.time, o2.time)); + + // Quests with pending auto claims (usually should be empty unless a condition needs to be met) + private final TreeSet autoClaims = new TreeSet<>(); + + // Quests that need to be sent to the client to update progression (NOT for edits. Handle that elsewhere) + private final TreeSet markedDirty = new TreeSet<>(); + + public synchronized int[] getActiveQuests() { + // Probably a better way of doing this but this will do for now + int i = 0; + int[] aryAct = new int[activeQuests.size()]; + for (Integer q : activeQuests) { aryAct[i++] = q; } + return aryAct; + } + + public synchronized int[] getVisibleQuests() { + // Probably a better way of doing this but this will do for now + int i = 0; + int[] aryVis = new int[visibleQuests.size()]; + for (Integer q : visibleQuests) { aryVis[i++] = q; } + return aryVis; + } + + public synchronized int[] getPendingAutoClaims() { + // Probably a better way of doing this but this will do for now + int i = 0; + int[] aryAC = new int[autoClaims.size()]; + for (Integer q : autoClaims) { aryAC[i++] = q; } + return aryAC; + } + + public synchronized QResetTime[] getScheduledResets() // Already sorted by time + { + return resetSchedule.toArray(new QResetTime[0]); + } + + public synchronized void markQuestDirty(int questID) { + if (questID < 0) { return; } + markedDirty.add(questID); + } + + public synchronized void markQuestClean(int questID) { + if (questID < 0) { return; } + markedDirty.remove(questID); + } + + public synchronized void cleanAllQuests() { + markedDirty.clear(); + } + + public int[] getDirtyQuests() { + // Probably a better way of doing this but this will do for now + int i = 0; + int[] aryMD = new int[markedDirty.size()]; + for (Integer q : markedDirty) { aryMD[i++] = q; } + return aryMD; + } + + // TODO: Ensure this is thread safe because we're likely going to run this in the background + // NOTE: Only run this when the quests completion and claim states change. Use markQuestDirty() for progression changes that need syncing + public synchronized void updateCache(EntityPlayer player) { + if (player == null) { return; } + + UUID uuid = QuestingAPI.getQuestingUUID(player); + List> questDB = QuestingAPI.getAPI(ApiReference.QUEST_DB).getEntries(); + + NonNullList tmpVisible = NonNullList.create(); + NonNullList tmpActive = NonNullList.create(); + NonNullList tmpReset = NonNullList.create(); + NonNullList tmpAutoClaim = NonNullList.create(); + + for (DBEntry entry : questDB) { + if (entry.getValue().isUnlocked(uuid) || entry.getValue().isComplete(uuid) || + entry.getValue().getProperty(NativeProps.LOCKED_PROGRESS)) // Unlocked or actively processing progression data + { + int repeat = entry.getValue().getProperty(NativeProps.REPEAT_TIME); + NBTTagCompound ue = entry.getValue().getCompletionInfo(uuid); + + if ((ue == null && entry.getValue().getTasks().size() <= 0) || entry.getValue().canSubmit( + player)) // Can be active without completion in the case of locked progress. Also account for taskless quests + { + tmpActive.add(entry.getID()); + } else if (ue != null) // These conditions only trigger after first completion + { + if (repeat >= 0 && entry.getValue().hasClaimed(uuid)) { + long altTime = ue.getLong("timestamp"); + if (repeat > 1 && !entry.getValue().getProperty(NativeProps.REPEAT_REL)) { altTime -= (altTime % repeat); } + tmpReset.add(new QResetTime(entry.getID(), altTime + (repeat * 50L))); + } + + if (!entry.getValue().hasClaimed(uuid) && entry.getValue().getProperty(NativeProps.AUTO_CLAIM)) { + tmpAutoClaim.add(entry.getID()); + } + } + } + + if (isQuestShown(entry.getValue(), uuid, player)) { + tmpVisible.add(entry.getID()); + } } - - public synchronized void cleanAllQuests() - { - markedDirty.clear(); + + visibleQuests.clear(); + visibleQuests.addAll(tmpVisible); + + activeQuests.clear(); + activeQuests.addAll(tmpActive); + + resetSchedule.clear(); + resetSchedule.addAll(tmpReset); + + autoClaims.clear(); + autoClaims.addAll(tmpAutoClaim); + + if (player instanceof EntityPlayerMP) { NetCacheSync.sendSync((EntityPlayerMP) player); } + } + + @Override + public synchronized NBTTagCompound serializeNBT() { + NBTTagCompound tags = new NBTTagCompound(); + + tags.setIntArray("visibleQuests", getVisibleQuests()); + tags.setIntArray("activeQuests", getActiveQuests()); + tags.setIntArray("autoClaims", getPendingAutoClaims()); + tags.setIntArray("markedDirty", getDirtyQuests()); + + NBTTagList tagSchedule = new NBTTagList(); + for (QResetTime entry : getScheduledResets()) { + NBTTagCompound tagEntry = new NBTTagCompound(); + tagEntry.setInteger("quest", entry.questID); + tagEntry.setLong("time", entry.time); + tagSchedule.appendTag(tagEntry); } - - public int[] getDirtyQuests() - { - // Probably a better way of doing this but this will do for now - int i = 0; - int[] aryMD = new int[markedDirty.size()]; - for(Integer q : markedDirty) aryMD[i++] = q; - return aryMD; + tags.setTag("resetSchedule", tagSchedule); + + return tags; + } + + @Override + public synchronized void deserializeNBT(NBTTagCompound nbt) { + visibleQuests.clear(); + activeQuests.clear(); + resetSchedule.clear(); + autoClaims.clear(); + markedDirty.clear(); + + for (int i : nbt.getIntArray("visibleQuests")) { visibleQuests.add(i); } + for (int i : nbt.getIntArray("activeQuests")) { activeQuests.add(i); } + for (int i : nbt.getIntArray("autoClaims")) { autoClaims.add(i); } + for (int i : nbt.getIntArray("markedDirty")) { markedDirty.add(i); } + + NBTTagList tagList = nbt.getTagList("resetSchedule", 10); + for (int i = 0; i < tagList.tagCount(); i++) { + NBTTagCompound tagEntry = tagList.getCompoundTagAt(i); + if (tagEntry.hasKey("quest", 99)) { + resetSchedule.add(new QResetTime(tagEntry.getInteger("quest"), tagEntry.getLong("time"))); + } } - - // TODO: Ensure this is thread safe because we're likely going to run this in the background - // NOTE: Only run this when the quests completion and claim states change. Use markQuestDirty() for progression changes that need syncing - public synchronized void updateCache(EntityPlayer player) - { - if(player == null) return; - - UUID uuid = QuestingAPI.getQuestingUUID(player); - List> questDB = QuestingAPI.getAPI(ApiReference.QUEST_DB).getEntries(); - - NonNullList tmpVisible = NonNullList.create(); - NonNullList tmpActive = NonNullList.create(); - NonNullList tmpReset = NonNullList.create(); - NonNullList tmpAutoClaim = NonNullList.create(); - - for(DBEntry entry : questDB) - { - if(entry.getValue().isUnlocked(uuid) || entry.getValue().isComplete(uuid) || entry.getValue().getProperty(NativeProps.LOCKED_PROGRESS)) // Unlocked or actively processing progression data - { - int repeat = entry.getValue().getProperty(NativeProps.REPEAT_TIME); - NBTTagCompound ue = entry.getValue().getCompletionInfo(uuid); - - if((ue == null && entry.getValue().getTasks().size() <= 0) || entry.getValue().canSubmit(player)) // Can be active without completion in the case of locked progress. Also account for taskless quests - { - tmpActive.add(entry.getID()); - } else if(ue != null) // These conditions only trigger after first completion - { - if(repeat >= 0 && entry.getValue().hasClaimed(uuid)) - { - long altTime = ue.getLong("timestamp"); - if(repeat > 1 && !entry.getValue().getProperty(NativeProps.REPEAT_REL)) altTime -= (altTime % repeat); - tmpReset.add(new QResetTime(entry.getID(), altTime + (repeat * 50))); - } - - if(!entry.getValue().hasClaimed(uuid) && entry.getValue().getProperty(NativeProps.AUTO_CLAIM)) - { - tmpAutoClaim.add(entry.getID()); - } - } - } - - if(isQuestShown(entry.getValue(), uuid, player)) - { - tmpVisible.add(entry.getID()); - } - } - - visibleQuests.clear(); - visibleQuests.addAll(tmpVisible); - - activeQuests.clear(); - activeQuests.addAll(tmpActive); - - resetSchedule.clear(); - resetSchedule.addAll(tmpReset); - - autoClaims.clear(); - autoClaims.addAll(tmpAutoClaim); - - if(player instanceof EntityPlayerMP) NetCacheSync.sendSync((EntityPlayerMP)player); + } + + public static class QResetTime implements Comparable { + public final int questID; + public final long time; + + private QResetTime(int questID, long time) { + this.questID = questID; + this.time = time; } - + @Override - public synchronized NBTTagCompound serializeNBT() - { - NBTTagCompound tags = new NBTTagCompound(); - - tags.setIntArray("visibleQuests", getVisibleQuests()); - tags.setIntArray("activeQuests", getActiveQuests()); - tags.setIntArray("autoClaims", getPendingAutoClaims()); - tags.setIntArray("markedDirty", getDirtyQuests()); - - NBTTagList tagSchedule = new NBTTagList(); - for(QResetTime entry : getScheduledResets()) - { - NBTTagCompound tagEntry = new NBTTagCompound(); - tagEntry.setInteger("quest", entry.questID); - tagEntry.setLong("time", entry.time); - tagSchedule.appendTag(tagEntry); - } - tags.setTag("resetSchedule", tagSchedule); - - return tags; + public int compareTo(QResetTime o) { + return Long.compare(o.time, time); } - + @Override - public synchronized void deserializeNBT(NBTTagCompound nbt) - { - visibleQuests.clear(); - activeQuests.clear(); - resetSchedule.clear(); - autoClaims.clear(); - markedDirty.clear(); - - for(int i : nbt.getIntArray("visibleQuests")) visibleQuests.add(i); - for(int i : nbt.getIntArray("activeQuests")) activeQuests.add(i); - for(int i : nbt.getIntArray("autoClaims")) autoClaims.add(i); - for(int i : nbt.getIntArray("markedDirty")) markedDirty.add(i); - - NBTTagList tagList = nbt.getTagList("resetSchedule", 10); - for(int i = 0; i < tagList.tagCount(); i++) - { - NBTTagCompound tagEntry = tagList.getCompoundTagAt(i); - if(tagEntry.hasKey("quest", 99)) - { - resetSchedule.add(new QResetTime(tagEntry.getInteger("quest"), tagEntry.getLong("time"))); - } - } + public boolean equals(Object o) { + if (!(o instanceof QResetTime)) { return false; } + return ((QResetTime) o).questID == questID; } - - public class QResetTime implements Comparable - { - public final int questID; - public final long time; - - private QResetTime(int questID, long time) - { - this.questID = questID; - this.time = time; - } - - @Override - public int compareTo(QResetTime o) - { - return Long.compare(o.time, time); - } - - @Override - public boolean equals(Object o) - { - if(!(o instanceof QResetTime)) return false; - return ((QResetTime)o).questID == questID; - } + } + + // TODO: Make this based on a fixed state stored on the quest instead of calculated on demand + // TODO: Also make this thread safe + public static boolean isQuestShown(IQuest quest, UUID uuid, EntityPlayer player) { + if (quest == null || uuid == null) { + return false; } - - // TODO: Make this based on a fixed state stored on the quest instead of calculated on demand - // TODO: Also make this thread safe - public static boolean isQuestShown(IQuest quest, UUID uuid, EntityPlayer player) + + EnumQuestVisibility vis = quest.getProperty(NativeProps.VISIBILITY); + + if (QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(player) || + vis == EnumQuestVisibility.ALWAYS) // Always shown or in edit mode { - if(quest == null || uuid == null) - { - return false; - } - - EnumQuestVisibility vis = quest.getProperty(NativeProps.VISIBILITY); - - if(QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(player) || vis == EnumQuestVisibility.ALWAYS) // Always shown or in edit mode - { - return true; - } else if(vis == EnumQuestVisibility.HIDDEN) - { - return false; - } else if(vis == EnumQuestVisibility.UNLOCKED) - { - return quest.isComplete(uuid) || quest.isUnlocked(uuid); - } else if(vis == EnumQuestVisibility.NORMAL) - { - if(quest.isComplete(uuid) || quest.isUnlocked(uuid)) // Complete or pending - { - return true; - } - - // Previous quest is underway and this one is visible but still locked (foreshadowing) - for(DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) - { - if(!q.getValue().isUnlocked(uuid)) - { - return false; - } - } - - return true; - } else if(vis == EnumQuestVisibility.COMPLETED) - { - return quest.isComplete(uuid); - } else if(vis == EnumQuestVisibility.CHAIN) - { - if(quest.getRequirements().length <= 0) - { - return true; - } - - for(DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) - { - if(q == null) return true; - - if(isQuestShown(q.getValue(), uuid, player)) - { - return true; - } - } - - return false; + return true; + } else if (vis == EnumQuestVisibility.HIDDEN) { + return false; + } else if (vis == EnumQuestVisibility.UNLOCKED) { + return quest.isComplete(uuid) || quest.isUnlocked(uuid); + } else if (vis == EnumQuestVisibility.NORMAL) { + if (quest.isComplete(uuid) || quest.isUnlocked(uuid)) // Complete or pending + { + return true; + } + + // Previous quest is underway and this one is visible but still locked (foreshadowing) + for (DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) { + if (!q.getValue().isUnlocked(uuid)) { + return false; } - + } + + return true; + } else if (vis == EnumQuestVisibility.COMPLETED) { + return quest.isComplete(uuid); + } else if (vis == EnumQuestVisibility.CHAIN) { + if (quest.getRequirements().length == 0) { return true; + } + + for (DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) { + if (q == null) { return true; } + + if (isQuestShown(q.getValue(), uuid, player)) { + return true; + } + } + + return false; } + + return true; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java b/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java index 9324f73a2..10cd5dd3d 100644 --- a/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java +++ b/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java @@ -28,450 +28,393 @@ import java.util.concurrent.CopyOnWriteArrayList; // This will probably be rewritten at a later date once I reimplement Minecraft's inventory controls natively into their own isolated canvas elements -public class GuiContainerCanvas extends GuiContainer implements IScene -{ - private final List guiPanels = new CopyOnWriteArrayList<>(); - private final GuiRectangle rootTransform = new GuiRectangle(0, 0, 0, 0, 0); - private final GuiTransform transform = new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0); - private boolean enabled = true; - private boolean useMargins = true; - private boolean useDefaultBG = false; - private boolean isVolatile = false; - - public final GuiScreen parent; - - private IGuiPanel popup = null; - //private IGuiPanel focused = null; - - public GuiContainerCanvas(GuiScreen parent, Container container) - { - super(container); - this.parent = parent; +public class GuiContainerCanvas extends GuiContainer implements IScene { + private final List guiPanels = new CopyOnWriteArrayList<>(); + private final GuiRectangle rootTransform = new GuiRectangle(0, 0, 0, 0, 0); + private final GuiTransform transform = new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0); + private boolean enabled = true; + private boolean useMargins = true; + private boolean useDefaultBG = false; + private boolean isVolatile = false; + + public final GuiScreen parent; + + private IGuiPanel popup = null; + //private IGuiPanel focused = null; + + public GuiContainerCanvas(GuiScreen parent, Container container) { + super(container); + this.parent = parent; + } + + @Override + public void openPopup(@Nonnull IGuiPanel panel) { + this.popup = panel; + } + + @Override + public void closePopup() { + this.popup = null; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Nonnull + @Override + public List getChildren() { + return this.guiPanels; + } + + public GuiContainerCanvas useMargins(boolean enable) { + this.useMargins = enable; + return this; + } + + public GuiContainerCanvas useDefaultBG(boolean enable) { + this.useDefaultBG = enable; + return this; + } + + public GuiContainerCanvas setVolatile(boolean state) { + this.isVolatile = state; + return this; + } + + /** + * Use initPanel() for embed support + */ + @Override + public final void initGui() { + super.initGui(); + + // Make the container somewhat behave using the root transform bounds + this.guiLeft = 0; + this.guiTop = 0; + this.xSize = width; + this.ySize = height; + + initPanel(); + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + + Keyboard.enableRepeatEvents(false); + } + + @Override + public void initPanel() { + rootTransform.w = this.width; + rootTransform.h = this.height; + transform.setParent(rootTransform); + + if (useMargins) { + int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); + int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); + transform.getPadding().setPadding(marginX, marginY, marginX, marginY); + } else { + transform.getPadding().setPadding(0, 0, 0, 0); } - - @Override - public void openPopup(@Nonnull IGuiPanel panel) - { - this.popup = panel; + + this.guiPanels.clear(); + } + + @Override + public void setEnabled(boolean state) { + // Technically supported if you wanted something like a multiscreen where this isn't actually the root screen + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float partialTick, int mx, int my) { + if (useDefaultBG) { this.drawDefaultBackground(); } + + GlStateManager.pushMatrix(); + GlStateManager.color(1F, 1F, 1F, 1F); + GlStateManager.disableDepth(); + + this.drawPanel(mx, my, partialTick); + + GlStateManager.enableDepth(); + GlStateManager.popMatrix(); + } + + @Override + public void drawScreen(int mx, int my, float partialTick) { + super.drawScreen(mx, my, partialTick); + + List tt = this.getTooltip(mx, my); + if (tt != null && !tt.isEmpty()) { this.drawHoveringText(tt, mx, my); } + } + + /** + * Use panel buttons and the event broadcaster + */ + @Override + @Deprecated + public void actionPerformed(@Nonnull GuiButton button) { } + + // Remembers the last mouse buttons states. Required to fire release events + private final boolean[] mBtnState = new boolean[3]; + + @Override + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + + int i = Mouse.getEventX() * width / mc.displayWidth; + int j = height - Mouse.getEventY() * height / mc.displayHeight - 1; + int k = Mouse.getEventButton(); + int SDX = (int) -Math.signum(Mouse.getEventDWheel()); + boolean flag = Mouse.getEventButtonState(); + + if (k >= 0 && k < 3 && mBtnState[k] != flag) { + if (flag) { + this.onMouseClick(i, j, k); + } else { + this.onMouseRelease(i, j, k); + } + mBtnState[k] = flag; } - - @Override - public void closePopup() - { - this.popup = null; + + if (SDX != 0) { + this.onMouseScroll(i, j, SDX); } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Nonnull - @Override - public List getChildren() - { - return this.guiPanels; + } + + @Override + public void keyTyped(char c, int keyCode) { + if (keyCode == 1) { + if (this.isVolatile || this instanceof IVolatileScreen) { + openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + + QuestTranslation.translate("betterquesting.gui.closing_confirm"), + PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, + QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); + } else { + this.mc.displayGuiScreen(null); + if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + } + + return; } - - public GuiContainerCanvas useMargins(boolean enable) - { - this.useMargins = enable; - return this; + + this.onKeyTyped(c, keyCode); + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + for (IGuiPanel entry : guiPanels) { + if (entry.isEnabled()) { + entry.drawPanel(mx, my, partialTick); + } } - - public GuiContainerCanvas useDefaultBG(boolean enable) - { - this.useDefaultBG = enable; - return this; + + if (popup != null && popup.isEnabled()) { + popup.drawPanel(mx, my, partialTick); } - - public GuiContainerCanvas setVolatile(boolean state) - { - this.isVolatile = state; - return this; + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + boolean used = false; + + if (popup != null && popup.isEnabled()) { + popup.onMouseClick(mx, my, click); + return true;// Regardless of whether this is actually used we prevent other things from being edited } - - /** - * Use initPanel() for embed support - */ - @Override - public final void initGui() - { - super.initGui(); - - // Make the container somewhat behave using the root transform bounds - this.guiLeft = 0; - this.guiTop = 0; - this.xSize = width; - this.ySize = height; - - initPanel(); - } - - @Override - public void onGuiClosed() + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) // TODO: Allow click through even after used. Other panels need it to passively reset things { - super.onGuiClosed(); - - Keyboard.enableRepeatEvents(false); + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseClick(mx, my, click)) { + used = true; + break; + } } - - @Override - public void initPanel() - { - rootTransform.w = this.width; - rootTransform.h = this.height; - transform.setParent(rootTransform); - - if(useMargins) - { - int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); - int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); - transform.getPadding().setPadding(marginX, marginY, marginX, marginY); - } else - { - transform.getPadding().setPadding(0, 0, 0, 0); - } - - this.guiPanels.clear(); - } - - @Override - public void setEnabled(boolean state) - { - // Technically supported if you wanted something like a multiscreen where this isn't actually the root screen - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - protected void drawGuiContainerBackgroundLayer(float partialTick, int mx, int my) - { - if(useDefaultBG) this.drawDefaultBackground(); - - GlStateManager.pushMatrix(); - GlStateManager.color(1F, 1F, 1F, 1F); - GlStateManager.disableDepth(); - - this.drawPanel(mx, my, partialTick); - - GlStateManager.enableDepth(); - GlStateManager.popMatrix(); + + return used; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + boolean used = false; + + if (popup != null && popup.isEnabled()) { + popup.onMouseRelease(mx, my, click); + return true;// Regardless of whether this is actually used we prevent other things from being edited } - - @Override - public void drawScreen(int mx, int my, float partialTick) + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) // TODO: Allow click through even after used. Other panels need it to passively reset things { - super.drawScreen(mx, my, partialTick); - - List tt = this.getTooltip(mx, my); - if(tt != null && tt.size() > 0) this.drawHoveringText(tt, mx, my); + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseRelease(mx, my, click)) { + used = true; + break; + } } - - /** - * Use panel buttons and the event broadcaster - */ - @Override - @Deprecated - public void actionPerformed(GuiButton button) - { - } - - // Remembers the last mouse buttons states. Required to fire release events - private boolean[] mBtnState = new boolean[3]; - - @Override - public void handleMouseInput() throws IOException - { - super.handleMouseInput(); - - int i = Mouse.getEventX() * width / mc.displayWidth; - int j = height - Mouse.getEventY() * height / mc.displayHeight - 1; - int k = Mouse.getEventButton(); - int SDX = (int)-Math.signum(Mouse.getEventDWheel()); - boolean flag = Mouse.getEventButtonState(); - - if(k >= 0 && k < 3 && mBtnState[k] != flag) - { - if(flag) - { - this.onMouseClick(i, j, k); - } else - { - this.onMouseRelease(i, j, k); - } - mBtnState[k] = flag; - } - - if(SDX != 0) - { - this.onMouseScroll(i, j, SDX); - } - } - - @Override - public void keyTyped(char c, int keyCode) - { - if (keyCode == 1) - { - if(this.isVolatile || this instanceof IVolatileScreen) - { - openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); - } else - { - this.mc.displayGuiScreen(null); - if(this.mc.currentScreen == null) this.mc.setIngameFocus(); - } - - return; - } - - this.onKeyTyped(c, keyCode); + + return used; + } + + //@Override + public boolean onMouseScroll(int mx, int my, int scroll) { + boolean used = false; + + if (popup != null && popup.isEnabled()) { + popup.onMouseScroll(mx, my, scroll); + return true;// Regardless of whether this is actually used we prevent other things from being edited } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - for(IGuiPanel entry : guiPanels) - { - if(entry.isEnabled()) - { - entry.drawPanel(mx, my, partialTick); - } - } - - if(popup != null && popup.isEnabled()) - { - popup.drawPanel(mx, my, partialTick); - } - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - boolean used = false; - - if(popup != null && popup.isEnabled()) - { - popup.onMouseClick(mx, my, click); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) // TODO: Allow click through even after used. Other panels need it to passively reset things - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseClick(mx, my, click)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - boolean used = false; - - if(popup != null && popup.isEnabled()) - { - popup.onMouseRelease(mx, my, click); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) // TODO: Allow click through even after used. Other panels need it to passively reset things - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseRelease(mx, my, click)) - { - used = true; - break; - } - } - - return used; - } - - //@Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - boolean used = false; - - if(popup != null && popup.isEnabled()) - { - popup.onMouseScroll(mx, my, scroll); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - boolean used = false; - - if(popup != null) - { - if(popup.isEnabled()) - { - popup.onKeyTyped(c, keycode); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onKeyTyped(c, keycode)) - { - used = true; - break; - } - } - - if(!used && (BQ_Keybindings.openQuests.getKeyCode() == keycode || mc.gameSettings.keyBindInventory.getKeyCode() == keycode)) - { - if(this.isVolatile || this instanceof IVolatileScreen) - { - openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); - } else - { - this.mc.displayGuiScreen(null); - if(this.mc.currentScreen == null) this.mc.setIngameFocus(); - } - } - - return used; - } - - @Override - public List getTooltip(int mx, int my) - { - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - List tt = null; - - if(popup != null && popup.isEnabled()) - { - tt = popup.getTooltip(mx, my); - if(tt != null) return tt; - } - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - if(!entry.isEnabled()) continue; - - tt = entry.getTooltip(mx, my); - if(tt != null && tt.size() > 0) return tt; - } - - if(tt == null) - { - for(Slot slot : this.inventorySlots.inventorySlots) - { - if(slot.isEnabled() && slot.getHasStack() && isPointInRegion(slot.xPos, slot.yPos, 16, 16, mx, my)) - { - tt = slot.getStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED : TooltipFlags.NORMAL); - return tt.size() <= 0 ? null : tt; - } - } - } - - return null; - } - - @Override - public void addPanel(IGuiPanel panel) - { - if(panel == null || guiPanels.contains(panel)) - { - return; - } - - guiPanels.add(panel); - guiPanels.sort(ComparatorGuiDepth.INSTANCE); - panel.getTransform().setParent(getTransform()); - panel.initPanel(); - } - - @Override - public boolean removePanel(IGuiPanel panel) - { - return guiPanels.remove(panel); - } - - @Override - public void resetCanvas() - { - guiPanels.clear(); - } - - @Override - public boolean doesGuiPauseGame() - { - return false; // Halts packet handling if paused + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) { + used = true; + break; + } } - - /** - * Should be using PanelButton instead when using a Canvas - */ - @Override - @Deprecated - public T addButton(T button) - { - return super.addButton(button); - } - - @Override - protected void renderToolTip(ItemStack stack, int x, int y) - { - FontRenderer font = stack.getItem().getFontRenderer(stack); - RenderUtils.drawHoveringText(stack, this.getItemToolTip(stack), x, y, width, height, -1, (font == null ? fontRenderer : font)); + + return used; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + boolean used = false; + + if (popup != null) { + if (popup.isEnabled()) { + popup.onKeyTyped(c, keycode); + return true;// Regardless of whether this is actually used we prevent other things from being edited + } } - - @Override - protected void drawHoveringText(List textLines, int x, int y, FontRenderer font) - { - RenderUtils.drawHoveringText(textLines, x, y, width, height, -1, font); + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onKeyTyped(c, keycode)) { + used = true; + break; + } } - - public void confirmClose(int id) - { - if(id == 0) - { - this.mc.displayGuiScreen(null); - if(this.mc.currentScreen == null) this.mc.setIngameFocus(); + + if (!used && (BQ_Keybindings.openQuests.getKeyCode() == keycode || + mc.gameSettings.keyBindInventory.getKeyCode() == keycode)) { + if (this.isVolatile || this instanceof IVolatileScreen) { + openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + + QuestTranslation.translate("betterquesting.gui.closing_confirm"), + PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, + QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); + } else { + this.mc.displayGuiScreen(null); + if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + } + } + + return used; + } + + @Override + public List getTooltip(int mx, int my) { + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + List tt = null; + + if (popup != null && popup.isEnabled()) { + tt = popup.getTooltip(mx, my); + if (tt != null) { return tt; } + } + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + if (!entry.isEnabled()) { continue; } + + tt = entry.getTooltip(mx, my); + if (tt != null && !tt.isEmpty()) { return tt; } + } + + if (tt == null) { + for (Slot slot : this.inventorySlots.inventorySlots) { + if (slot.isEnabled() && slot.getHasStack() && isPointInRegion(slot.xPos, slot.yPos, 16, 16, mx, my)) { + tt = slot.getStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED + : TooltipFlags.NORMAL); + return tt.isEmpty() ? null : tt; } + } + } + + return null; + } + + @Override + public void addPanel(IGuiPanel panel) { + if (panel == null || guiPanels.contains(panel)) { + return; + } + + guiPanels.add(panel); + guiPanels.sort(ComparatorGuiDepth.INSTANCE); + panel.getTransform().setParent(getTransform()); + panel.initPanel(); + } + + @Override + public boolean removePanel(IGuiPanel panel) { + return guiPanels.remove(panel); + } + + @Override + public void resetCanvas() { + guiPanels.clear(); + } + + @Override + public boolean doesGuiPauseGame() { + return false; // Halts packet handling if paused + } + + /** + * Should be using PanelButton instead when using a Canvas + */ + @Nonnull + @Override + @Deprecated + public T addButton(@Nonnull T button) { + return super.addButton(button); + } + + @Override + protected void renderToolTip(ItemStack stack, int x, int y) { + FontRenderer font = stack.getItem().getFontRenderer(stack); + RenderUtils.drawHoveringText(stack, this.getItemToolTip(stack), x, y, width, height, -1, + (font == null ? fontRenderer : font)); + } + + @Override + protected void drawHoveringText(@Nonnull List textLines, int x, int y, @Nonnull FontRenderer font) { + RenderUtils.drawHoveringText(textLines, x, y, width, height, -1, font); + } + + public void confirmClose(int id) { + if (id == 0) { + this.mc.displayGuiScreen(null); + if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java b/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java index 50ba46193..8a9b56504 100644 --- a/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java +++ b/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java @@ -24,434 +24,377 @@ import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; -public class GuiScreenCanvas extends GuiScreen implements IScene -{ - private final List guiPanels = new CopyOnWriteArrayList<>(); - private final GuiRectangle rootTransform = new GuiRectangle(0, 0, 0, 0, 0); - private final GuiTransform transform = new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0); - private boolean enabled = true; - private boolean useMargins = true; - private boolean useDefaultBG = false; - private boolean isVolatile = false; - - public final GuiScreen parent; - - private IGuiPanel popup = null; - //private IGuiPanel focused = null; - - public GuiScreenCanvas(GuiScreen parent) - { - this.parent = parent; - } - - @Override - public void openPopup(@Nonnull IGuiPanel panel) - { - panel.getTransform().setParent(rootTransform); - popup = panel; - panel.initPanel(); - //forceFocus(panel); +public class GuiScreenCanvas extends GuiScreen implements IScene { + private final List guiPanels = new CopyOnWriteArrayList<>(); + private final GuiRectangle rootTransform = new GuiRectangle(0, 0, 0, 0, 0); + private final GuiTransform transform = new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0); + private boolean enabled = true; + private boolean useMargins = true; + private boolean useDefaultBG = false; + private boolean isVolatile = false; + + public final GuiScreen parent; + + private IGuiPanel popup = null; + //private IGuiPanel focused = null; + + public GuiScreenCanvas(GuiScreen parent) { + this.parent = parent; + } + + @Override + public void openPopup(@Nonnull IGuiPanel panel) { + panel.getTransform().setParent(rootTransform); + popup = panel; + panel.initPanel(); + //forceFocus(panel); + } + + @Override + public void closePopup() { + popup = null; + //resetFocus(); + } + + @Override + public IGuiRect getTransform() { + return this.transform; + } + + @Nonnull + @Override + public List getChildren() { + return this.guiPanels; + } + + public GuiScreenCanvas useMargins(boolean enable) { + this.useMargins = enable; + return this; + } + + public GuiScreenCanvas useDefaultBG(boolean enable) { + this.useDefaultBG = enable; + return this; + } + + public GuiScreenCanvas setVolatile(boolean state) { + this.isVolatile = state; + return this; + } + + /** + * Use initPanel() for embed support + */ + @Override + public final void initGui() { + super.initGui(); + + initPanel(); + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + + Keyboard.enableRepeatEvents(false); + } + + @Override + public void initPanel() { + rootTransform.w = this.width; + rootTransform.h = this.height; + transform.setParent(rootTransform); + + if (useMargins) { + int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); + int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); + transform.getPadding().setPadding(marginX, marginY, marginX, marginY); + } else { + transform.getPadding().setPadding(0, 0, 0, 0); } - - @Override - public void closePopup() - { - popup = null; - //resetFocus(); + + this.guiPanels.clear(); + Arrays.fill(mBtnState, false); // Reset mouse states // TODO: See if I can just make this static across all GUIs + + if (popup != null) { + popup = null; } - - @Override - public IGuiRect getTransform() - { - return this.transform; - } - - @Nonnull - @Override - public List getChildren() - { - return this.guiPanels; + } + + @Override + public void setEnabled(boolean state) { + // Technically supported if you wanted something like a multiscreen where this isn't actually the root screen + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + /** + * Use initPanel() for embed support + */ + @Override + public final void drawScreen(int mx, int my, float partialTick) { + super.drawScreen(mx, my, partialTick); + + if (useDefaultBG) { this.drawDefaultBackground(); } + + GlStateManager.pushMatrix(); + GlStateManager.color(1F, 1F, 1F, 1F); + GlStateManager.disableDepth(); + + this.drawPanel(mx, my, partialTick); + + List tt = getTooltip(mx, my); + + if (tt != null && !tt.isEmpty()) { + this.drawHoveringText(tt, mx, my); } - - public GuiScreenCanvas useMargins(boolean enable) - { - this.useMargins = enable; - return this; + + GlStateManager.enableDepth(); + GlStateManager.popMatrix(); + } + + /** + * Use panel buttons and the event broadcaster + */ + @Override + @Deprecated + public void actionPerformed(@Nonnull GuiButton button) { + } + + // Remembers the last mouse buttons states. Required to fire release events + private final boolean[] mBtnState = new boolean[3]; + + @Override + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + + int i = Mouse.getEventX() * width / mc.displayWidth; + int j = height - Mouse.getEventY() * height / mc.displayHeight - 1; + int k = Mouse.getEventButton(); + int SDX = (int) -Math.signum(Mouse.getEventDWheel()); + boolean flag = Mouse.getEventButtonState(); + + if (k >= 0 && k < 3 && mBtnState[k] != flag) { + if (flag) { + this.onMouseClick(i, j, k); + } else { + this.onMouseRelease(i, j, k); + } + mBtnState[k] = flag; } - - public GuiScreenCanvas useDefaultBG(boolean enable) - { - this.useDefaultBG = enable; - return this; + + if (SDX != 0) { + this.onMouseScroll(i, j, SDX); } - - public GuiScreenCanvas setVolatile(boolean state) - { - this.isVolatile = state; - return this; + } + + @Override + public void keyTyped(char c, int keyCode) { + if (keyCode == 1) { + if (this.isVolatile || this instanceof IVolatileScreen) { + openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + + QuestTranslation.translate("betterquesting.gui.closing_confirm"), + PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, + QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); + } else { + this.mc.displayGuiScreen(null); + if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + } + + return; } - - /** - * Use initPanel() for embed support - */ - @Override - public final void initGui() - { - super.initGui(); - - initPanel(); - } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - - Keyboard.enableRepeatEvents(false); + + this.onKeyTyped(c, keyCode); + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + for (IGuiPanel entry : guiPanels) { + if (entry.isEnabled()) { + entry.drawPanel(mx, my, partialTick); + } } - - @Override - public void initPanel() - { - rootTransform.w = this.width; - rootTransform.h = this.height; - transform.setParent(rootTransform); - - if(useMargins) - { - int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); - int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); - transform.getPadding().setPadding(marginX, marginY, marginX, marginY); - } else - { - transform.getPadding().setPadding(0, 0, 0, 0); - } - - this.guiPanels.clear(); - Arrays.fill(mBtnState, false); // Reset mouse states // TODO: See if I can just make this static across all GUIs - - if(popup != null) - { - popup = null; - } - } - - @Override - public void setEnabled(boolean state) - { - // Technically supported if you wanted something like a multiscreen where this isn't actually the root screen - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - /** - * Use initPanel() for embed support - */ - @Override - public final void drawScreen(int mx, int my, float partialTick) - { - super.drawScreen(mx, my, partialTick); - - if(useDefaultBG) this.drawDefaultBackground(); - - GlStateManager.pushMatrix(); - GlStateManager.color(1F, 1F, 1F, 1F); - GlStateManager.disableDepth(); - - this.drawPanel(mx, my, partialTick); - - List tt = getTooltip(mx, my); - - if(tt != null && tt.size() > 0) - { - this.drawHoveringText(tt, mx, my); - } - - GlStateManager.enableDepth(); - GlStateManager.popMatrix(); - } - - /** - * Use panel buttons and the event broadcaster - */ - @Override - @Deprecated - public void actionPerformed(GuiButton button) - { - } - - // Remembers the last mouse buttons states. Required to fire release events - private boolean[] mBtnState = new boolean[3]; - - @Override - public void handleMouseInput() throws IOException - { - super.handleMouseInput(); - - int i = Mouse.getEventX() * width / mc.displayWidth; - int j = height - Mouse.getEventY() * height / mc.displayHeight - 1; - int k = Mouse.getEventButton(); - int SDX = (int)-Math.signum(Mouse.getEventDWheel()); - boolean flag = Mouse.getEventButtonState(); - - if(k >= 0 && k < 3 && mBtnState[k] != flag) - { - if(flag) - { - this.onMouseClick(i, j, k); - } else - { - this.onMouseRelease(i, j, k); - } - mBtnState[k] = flag; - } - - if(SDX != 0) - { - this.onMouseScroll(i, j, SDX); - } - } - - @Override - public void keyTyped(char c, int keyCode) - { - if (keyCode == 1) - { - if(this.isVolatile || this instanceof IVolatileScreen) - { - openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); - } else - { - this.mc.displayGuiScreen(null); - if(this.mc.currentScreen == null) this.mc.setIngameFocus(); - } - - return; - } - - this.onKeyTyped(c, keyCode); + + if (popup != null && popup.isEnabled()) { + popup.drawPanel(mx, my, partialTick); } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - for(IGuiPanel entry : guiPanels) - { - if(entry.isEnabled()) - { - entry.drawPanel(mx, my, partialTick); - } - } - - if(popup != null && popup.isEnabled()) - { - popup.drawPanel(mx, my, partialTick); - } - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - boolean used = false; - - if(popup != null && popup.isEnabled()) - { - popup.onMouseClick(mx, my, click); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseClick(mx, my, click)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - boolean used = false; - - if(popup != null && popup.isEnabled()) - { - popup.onMouseRelease(mx, my, click); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseRelease(mx, my, click)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - boolean used = false; - - if(popup != null && popup.isEnabled()) - { - popup.onMouseScroll(mx, my, scroll); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - boolean used = false; - - if(popup != null) - { - if(popup.isEnabled()) - { - popup.onKeyTyped(c, keycode); - return true;// Regardless of whether this is actually used we prevent other things from being edited - } - } - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onKeyTyped(c, keycode)) - { - used = true; - break; - } - } - - if(!used && (BQ_Keybindings.openQuests.getKeyCode() == keycode || mc.gameSettings.keyBindInventory.getKeyCode() == keycode)) - { - if(this.isVolatile || this instanceof IVolatileScreen) - { - openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); - } else - { - this.mc.displayGuiScreen(null); - if(this.mc.currentScreen == null) this.mc.setIngameFocus(); - } - } - - return used; - } - - @Override - public List getTooltip(int mx, int my) - { - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - List tt; - - if(popup != null && popup.isEnabled()) - { - tt = popup.getTooltip(mx, my); - if(tt != null) return tt; - } - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - if(!entry.isEnabled()) continue; - - tt = entry.getTooltip(mx, my); - if(tt != null) return tt; - } - - return null; - } - - @Override - public void addPanel(IGuiPanel panel) - { - if(panel == null || guiPanels.contains(panel)) - { - return; - } - - guiPanels.add(panel); - guiPanels.sort(ComparatorGuiDepth.INSTANCE); - panel.getTransform().setParent(getTransform()); - panel.initPanel(); - } - - @Override - public boolean removePanel(IGuiPanel panel) - { - return guiPanels.remove(panel); - } - - @Override - public void resetCanvas() - { - guiPanels.clear(); - } - - @Override - public boolean doesGuiPauseGame() - { - return false; // Halts packet handling if paused + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + boolean used = false; + + if (popup != null && popup.isEnabled()) { + popup.onMouseClick(mx, my, click); + return true;// Regardless of whether this is actually used we prevent other things from being edited } - - @Override - protected void renderToolTip(ItemStack stack, int x, int y) - { - FontRenderer font = stack.getItem().getFontRenderer(stack); - RenderUtils.drawHoveringText(stack, this.getItemToolTip(stack), x, y, width, height, -1, (font == null ? fontRenderer : font)); + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseClick(mx, my, click)) { + used = true; + break; + } } - - @Override - protected void drawHoveringText(List textLines, int x, int y, @Nonnull FontRenderer font) - { - RenderUtils.drawHoveringText(textLines, x, y, width, height, -1, font); + + return used; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + boolean used = false; + + if (popup != null && popup.isEnabled()) { + popup.onMouseRelease(mx, my, click); + return true;// Regardless of whether this is actually used we prevent other things from being edited + } + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseRelease(mx, my, click)) { + used = true; + break; + } + } + + return used; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + boolean used = false; + + if (popup != null && popup.isEnabled()) { + popup.onMouseScroll(mx, my, scroll); + return true;// Regardless of whether this is actually used we prevent other things from being edited + } + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) { + used = true; + break; + } + } + + return used; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + boolean used = false; + + if (popup != null) { + if (popup.isEnabled()) { + popup.onKeyTyped(c, keycode); + return true;// Regardless of whether this is actually used we prevent other things from being edited + } + } + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onKeyTyped(c, keycode)) { + used = true; + break; + } + } + + if (!used && (BQ_Keybindings.openQuests.getKeyCode() == keycode || + mc.gameSettings.keyBindInventory.getKeyCode() == keycode)) { + if (this.isVolatile || this instanceof IVolatileScreen) { + openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + + QuestTranslation.translate("betterquesting.gui.closing_confirm"), + PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, + QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); + } else { + this.mc.displayGuiScreen(null); + if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + } + } + + return used; + } + + @Override + public List getTooltip(int mx, int my) { + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + List tt; + + if (popup != null && popup.isEnabled()) { + tt = popup.getTooltip(mx, my); + if (tt != null) { return tt; } + } + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + if (!entry.isEnabled()) { continue; } + + tt = entry.getTooltip(mx, my); + if (tt != null) { return tt; } } - - private void confirmClose(int id) - { - if(id == 0) - { - this.mc.displayGuiScreen(null); - if(this.mc.currentScreen == null) this.mc.setIngameFocus(); - } + + return null; + } + + @Override + public void addPanel(IGuiPanel panel) { + if (panel == null || guiPanels.contains(panel)) { + return; + } + + guiPanels.add(panel); + guiPanels.sort(ComparatorGuiDepth.INSTANCE); + panel.getTransform().setParent(getTransform()); + panel.initPanel(); + } + + @Override + public boolean removePanel(IGuiPanel panel) { + return guiPanels.remove(panel); + } + + @Override + public void resetCanvas() { + guiPanels.clear(); + } + + @Override + public boolean doesGuiPauseGame() { + return false; // Halts packet handling if paused + } + + @Override + protected void renderToolTip(ItemStack stack, int x, int y) { + FontRenderer font = stack.getItem().getFontRenderer(stack); + RenderUtils.drawHoveringText(stack, this.getItemToolTip(stack), x, y, width, height, -1, + (font == null ? fontRenderer : font)); + } + + @Override + protected void drawHoveringText(@Nonnull List textLines, int x, int y, @Nonnull FontRenderer font) { + RenderUtils.drawHoveringText(textLines, x, y, width, height, -1, font); + } + + private void confirmClose(int id) { + if (id == 0) { + this.mc.displayGuiScreen(null); + if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java b/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java index c91673406..c4145abac 100644 --- a/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java +++ b/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java @@ -13,46 +13,49 @@ import betterquesting.api2.client.gui.themes.presets.PresetTexture; import net.minecraft.client.gui.GuiScreen; -public class GuiScreenTest extends GuiScreenCanvas -{ - public GuiScreenTest(GuiScreen parent) - { - super(parent); - } - - @Override - public void initPanel() - { - super.initPanel(); - - CanvasTextured cvt1 = new CanvasTextured(new GuiTransform(), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvt1); - - PanelHBarFill phf = new PanelHBarFill(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(72, 16, 72, -32), 0)); - phf.setFillColor(new GuiColorTransition(new GuiColorStatic(0xFFFF0000), new GuiColorStatic(0xFF00FF00)).setupBlending(true, 0.25F)); - cvt1.addPanel(phf); - - PanelVBarFill pvf = new PanelVBarFill(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(16, 72, -72, 72), 0)); - pvf.setFillColor(new GuiColorTransition(new GuiColorStatic(0xFFFF0000), new GuiColorStatic(0xFF00FF00)).setupBlending(true, 0.25F)); - cvt1.addPanel(pvf); - - IValueIO fillDriver = new ValueFuncIO<>(() -> (int)Math.abs(System.currentTimeMillis()%5000L - 2500L)/2500F); - - GuiColorTransition transColor = new GuiColorTransition(new GuiColorStatic(0xFF00FF00), new GuiColorStatic(0xFFFF0000)).setupBlending(true, 0.25F); - transColor.setBlendDriver(fillDriver); - - phf.setFillColor(transColor); - pvf.setFillColor(transColor); - - phf.setFillDriver(fillDriver); - pvf.setFillDriver(fillDriver); - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - this.drawDefaultBackground(); - - super.drawPanel(mx, my, partialTick); - } +public class GuiScreenTest extends GuiScreenCanvas { + public GuiScreenTest(GuiScreen parent) { + super(parent); + } + + @Override + public void initPanel() { + super.initPanel(); + + CanvasTextured cvt1 = new CanvasTextured(new GuiTransform(), PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvt1); + + PanelHBarFill phf = new PanelHBarFill(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(72, 16, 72, -32), 0)); + phf.setFillColor( + new GuiColorTransition(new GuiColorStatic(0xFFFF0000), new GuiColorStatic(0xFF00FF00)).setupBlending(true, + 0.25F)); + cvt1.addPanel(phf); + + PanelVBarFill pvf = new PanelVBarFill(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(16, 72, -72, 72), 0)); + pvf.setFillColor( + new GuiColorTransition(new GuiColorStatic(0xFFFF0000), new GuiColorStatic(0xFF00FF00)).setupBlending(true, + 0.25F)); + cvt1.addPanel(pvf); + + IValueIO fillDriver = + new ValueFuncIO<>(() -> (int) Math.abs(System.currentTimeMillis() % 5000L - 2500L) / 2500F); + + GuiColorTransition transColor = + new GuiColorTransition(new GuiColorStatic(0xFF00FF00), new GuiColorStatic(0xFFFF0000)).setupBlending(true, + 0.25F); + transColor.setBlendDriver(fillDriver); + + phf.setFillColor(transColor); + pvf.setFillColor(transColor); + + phf.setFillDriver(fillDriver); + pvf.setFillDriver(fillDriver); + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + this.drawDefaultBackground(); + + super.drawPanel(mx, my, partialTick); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/client/gui/IScene.java b/src/main/java/betterquesting/api2/client/gui/IScene.java index 528ad1e92..c80c649f1 100644 --- a/src/main/java/betterquesting/api2/client/gui/IScene.java +++ b/src/main/java/betterquesting/api2/client/gui/IScene.java @@ -7,16 +7,16 @@ // The root canvas in charge of extra top level functions. Should idealy be attached to a GuiScreen but left open for other embedded use cases // Inner panels can make use of the fact that this is an IGuiCanvas to search through the whole heirachy of panel content on screen -public interface IScene extends IGuiCanvas -{ - // Unadjusted canvas representing the entire screen's bounds - //IGuiCanvas getRootCanvas(); - - // TODO: Force isolate all UI interaction to this panel until manually unfocused. NOTE: Escape key will always unfocus to prevent softlocking - //void forceFocus(@Nonnull IGuiPanel panel); - //void resetFocus(); - - // Opens a top level canvas off the root canvas - void openPopup(@Nonnull IGuiPanel panel); - void closePopup(); +public interface IScene extends IGuiCanvas { + // Unadjusted canvas representing the entire screen's bounds + //IGuiCanvas getRootCanvas(); + + // TODO: Force isolate all UI interaction to this panel until manually unfocused. NOTE: Escape key will always unfocus to prevent softlocking + //void forceFocus(@Nonnull IGuiPanel panel); + //void resetFocus(); + + // Opens a top level canvas off the root canvas + void openPopup(@Nonnull IGuiPanel panel); + + void closePopup(); } diff --git a/src/main/java/betterquesting/api2/client/gui/SceneController.java b/src/main/java/betterquesting/api2/client/gui/SceneController.java index 5ce728c79..83c9d23d6 100644 --- a/src/main/java/betterquesting/api2/client/gui/SceneController.java +++ b/src/main/java/betterquesting/api2/client/gui/SceneController.java @@ -9,31 +9,26 @@ import javax.annotation.Nullable; @EventBusSubscriber -public class SceneController -{ - private static IScene curScene = null; - - @Nullable - public static IScene getActiveScene() - { - return curScene; - } - - public static void setActiveScene(@Nullable IScene scene) - { - curScene = scene; - } - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public static void onGuiOpened(GuiOpenEvent event) - { - if(event.getGui() instanceof IScene) - { - // TODO: Review the following - // Does this need to be cleared if the GUI isn't compatible? - // Would this interfere with an overlay canvas? - curScene = (IScene)event.getGui(); - } +public class SceneController { + private static IScene curScene = null; + + @Nullable + public static IScene getActiveScene() { + return curScene; + } + + public static void setActiveScene(@Nullable IScene scene) { + curScene = scene; + } + + @SubscribeEvent + @SideOnly(Side.CLIENT) + public static void onGuiOpened(GuiOpenEvent event) { + if (event.getGui() instanceof IScene) { + // TODO: Review the following + // Does this need to be cleared if the GUI isn't compatible? + // Would this interfere with an overlay canvas? + curScene = (IScene) event.getGui(); } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/IFieldFilter.java b/src/main/java/betterquesting/api2/client/gui/controls/IFieldFilter.java index 4465b063f..3313c5b63 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/IFieldFilter.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/IFieldFilter.java @@ -1,8 +1,9 @@ package betterquesting.api2.client.gui.controls; -public interface IFieldFilter -{ - boolean isValid(String input); - String filterText(String input); - T parseValue(String input); +public interface IFieldFilter { + boolean isValid(String input); + + String filterText(String input); + + T parseValue(String input); } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/IPanelButton.java b/src/main/java/betterquesting/api2/client/gui/controls/IPanelButton.java index 9fb5c3b32..3684aef43 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/IPanelButton.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/IPanelButton.java @@ -2,12 +2,12 @@ import betterquesting.api2.client.gui.panels.IGuiPanel; -public interface IPanelButton extends IGuiPanel -{ - int getButtonID(); - - boolean isActive(); - void setActive(boolean state); - - void onButtonClick(); +public interface IPanelButton extends IGuiPanel { + int getButtonID(); + + boolean isActive(); + + void setActive(boolean state); + + void onButtonClick(); } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/IValueIO.java b/src/main/java/betterquesting/api2/client/gui/controls/IValueIO.java index 1d5ab71ce..45fe68f5b 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/IValueIO.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/IValueIO.java @@ -1,12 +1,13 @@ package betterquesting.api2.client.gui.controls; -public interface IValueIO -{ - T readValue(); - void writeValue(T value); - - // These are necessary for things like interpolating values that need to be jumped to a specific value (such as reloading an exising GUI) - // Just redirect these to the useual read and write methods if you don't need them. - T readValueRaw(); - void writeValueRaw(T value); +public interface IValueIO { + T readValue(); + + void writeValue(T value); + + // These are necessary for things like interpolating values that need to be jumped to a specific value (such as reloading an exising GUI) + // Just redirect these to the useual read and write methods if you don't need them. + T readValueRaw(); + + void writeValueRaw(T value); } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java index d43f694e3..23c725df9 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java @@ -23,281 +23,250 @@ import java.util.List; import java.util.function.Consumer; -public class PanelButton implements IPanelButton, IGuiPanel, INBTSaveLoad -{ - private final IGuiRect transform; - private boolean enabled = true; - - private final IGuiTexture[] texStates = new IGuiTexture[3]; - private IGuiColor[] colStates = new IGuiColor[]{new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 255, 255, 255), new GuiColorStatic(16777120)}; - private IGuiTexture texIcon = null; - private IGuiColor colIcon = null; - private int icoPadding = 0; - private List tooltip = null; - private boolean txtShadow = true; - private String btnText; - private int textAlign = 1; - private boolean isActive = true; - private final int btnID; - - private boolean pendingRelease = false; - - private Consumer clickAction = null; - - public PanelButton(IGuiRect rect, int id, String txt) - { - this.transform = rect; - this.btnText = txt; - this.btnID = id; - - this.setTextures(PresetTexture.BTN_NORMAL_0.getTexture(), PresetTexture.BTN_NORMAL_1.getTexture(), PresetTexture.BTN_NORMAL_2.getTexture()); - this.setTextHighlight(PresetColor.BTN_DISABLED.getColor(), PresetColor.BTN_IDLE.getColor(), PresetColor.BTN_HOVER.getColor()); - } - - public PanelButton setClickAction(Consumer action) - { - this.clickAction = action; - return this; +public class PanelButton implements IPanelButton, IGuiPanel, INBTSaveLoad { + private final IGuiRect transform; + private boolean enabled = true; + + private final IGuiTexture[] texStates = new IGuiTexture[3]; + private final IGuiColor[] colStates = + new IGuiColor[] { new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 255, 255, 255), + new GuiColorStatic(16777120) }; + private IGuiTexture texIcon = null; + private IGuiColor colIcon = null; + private int icoPadding = 0; + private List tooltip = null; + private boolean txtShadow = true; + private String btnText; + private int textAlign = 1; + private boolean isActive = true; + private final int btnID; + + private boolean pendingRelease = false; + + private Consumer clickAction = null; + + public PanelButton(IGuiRect rect, int id, String txt) { + this.transform = rect; + this.btnText = txt; + this.btnID = id; + + this.setTextures(PresetTexture.BTN_NORMAL_0.getTexture(), PresetTexture.BTN_NORMAL_1.getTexture(), + PresetTexture.BTN_NORMAL_2.getTexture()); + this.setTextHighlight(PresetColor.BTN_DISABLED.getColor(), PresetColor.BTN_IDLE.getColor(), + PresetColor.BTN_HOVER.getColor()); + } + + public PanelButton setClickAction(Consumer action) { + this.clickAction = action; + return this; + } + + public PanelButton setTextHighlight(IGuiColor disabled, IGuiColor idle, IGuiColor hover) { + this.colStates[0] = disabled; + this.colStates[1] = idle; + this.colStates[2] = hover; + return this; + } + + public PanelButton setTextShadow(boolean enabled) { + this.txtShadow = enabled; + return this; + } + + public PanelButton setTextAlignment(int align) { + this.textAlign = MathHelper.clamp(align, 0, 2); + return this; + } + + public PanelButton setTextures(IGuiTexture disabled, IGuiTexture idle, IGuiTexture hover) { + this.texStates[0] = disabled; + this.texStates[1] = idle; + this.texStates[2] = hover; + return this; + } + + public PanelButton setIcon(IGuiTexture icon) { + return this.setIcon(icon, 0); + } + + public PanelButton setIcon(IGuiTexture icon, int padding) { + return setIcon(icon, null, padding); + } + + public PanelButton setIcon(IGuiTexture icon, IGuiColor color, int padding) { + this.texIcon = icon; + this.colIcon = color; + this.icoPadding = padding * 2; + return this; + } + + public PanelButton setTooltip(List tooltip) { + this.tooltip = tooltip; + return this; + } + + public void setText(String text) { + this.btnText = text; + } + + public String getText() { + return this.btnText; + } + + @Override + public int getButtonID() { + return this.btnID; + } + + @Override + public boolean isActive() { + return this.isActive; + } + + @Override + public void setActive(boolean state) { + this.isActive = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void initPanel() { + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + IGuiRect bounds = this.getTransform(); + GlStateManager.pushMatrix(); + GlStateManager.color(1F, 1F, 1F, 1F); + int curState = !isActive() ? 0 : (bounds.contains(mx, my) ? 2 : 1); + + if (curState == 2 && pendingRelease && Mouse.isButtonDown(0)) { + curState = 0; } - - public PanelButton setTextHighlight(IGuiColor disabled, IGuiColor idle, IGuiColor hover) - { - this.colStates[0] = disabled; - this.colStates[1] = idle; - this.colStates[2] = hover; - return this; - } - - public PanelButton setTextShadow(boolean enabled) - { - this.txtShadow = enabled; - return this; - } - - public PanelButton setTextAlignment(int align) + + IGuiTexture t = texStates[curState]; + + if (t != null) // Support for text or icon only buttons in one or more states. { - this.textAlign = MathHelper.clamp(align, 0, 2); - return this; + t.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); } - - public PanelButton setTextures(IGuiTexture disabled, IGuiTexture idle, IGuiTexture hover) - { - this.texStates[0] = disabled; - this.texStates[1] = idle; - this.texStates[2] = hover; - return this; - } - - public PanelButton setIcon(IGuiTexture icon) - { - return this.setIcon(icon, 0); - } - - public PanelButton setIcon(IGuiTexture icon, int padding) - { - return setIcon(icon, null, padding); - } - - public PanelButton setIcon(IGuiTexture icon, IGuiColor color, int padding) - { - this.texIcon = icon; - this.colIcon = color; - this.icoPadding = padding * 2; - return this; - } - - public PanelButton setTooltip(List tooltip) - { - this.tooltip = tooltip; - return this; - } - - public void setText(String text) - { - this.btnText = text; - } - - public String getText() - { - return this.btnText; - } - - @Override - public int getButtonID() - { - return this.btnID; - } - - @Override - public boolean isActive() - { - return this.isActive; - } - - @Override - public void setActive(boolean state) - { - this.isActive = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void initPanel() - { - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - IGuiRect bounds = this.getTransform(); - GlStateManager.pushMatrix(); - GlStateManager.color(1F, 1F, 1F, 1F); - int curState = !isActive()? 0 : (bounds.contains(mx, my)? 2 : 1); - - if(curState == 2 && pendingRelease && Mouse.isButtonDown(0)) - { - curState = 0; - } - - IGuiTexture t = texStates[curState]; - - if(t != null) // Support for text or icon only buttons in one or more states. - { - t.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); - } - - if(texIcon != null) - { - int isz = Math.min(bounds.getHeight() - icoPadding, bounds.getWidth()- icoPadding); - - if(isz > 0) - { - if(colIcon != null) - { - texIcon.drawTexture(bounds.getX() + (bounds.getWidth() / 2) - (isz / 2), bounds.getY() + (bounds.getHeight() / 2) - (isz / 2), isz, isz, 0F, partialTick, colIcon); - } else - { - texIcon.drawTexture(bounds.getX() + (bounds.getWidth() / 2) - (isz / 2), bounds.getY() + (bounds.getHeight() / 2) - (isz / 2), isz, isz, 0F, partialTick); - } - } - } - - if(btnText != null && btnText.length() > 0) - { - drawCenteredString(Minecraft.getMinecraft().fontRenderer, btnText, bounds.getX(), bounds.getY() + bounds.getHeight()/2 - 4, bounds.getWidth(), colStates[curState].getRGB(), txtShadow, textAlign); - } - - GlStateManager.popMatrix(); - } - - private static void drawCenteredString(FontRenderer font, String text, int x, int y, int width, int color, boolean shadow, int align) - { - switch(align) - { - case 0: - { - font.drawString(text, x + 4, y, color, shadow); - break; - } - case 2: - { - font.drawString(text, x + width - RenderUtils.getStringWidth(text, font) / 2F - 4, y, color, shadow); - break; - } - default: - { - font.drawString(text, x + Math.floorDiv(width, 2) - RenderUtils.getStringWidth(text, font) / 2F, y, color, shadow); - } + + if (texIcon != null) { + int isz = Math.min(bounds.getHeight() - icoPadding, bounds.getWidth() - icoPadding); + + if (isz > 0) { + if (colIcon != null) { + texIcon.drawTexture(bounds.getX() + (bounds.getWidth() / 2) - (isz / 2), + bounds.getY() + (bounds.getHeight() / 2) - (isz / 2), isz, isz, 0F, partialTick, colIcon); + } else { + texIcon.drawTexture(bounds.getX() + (bounds.getWidth() / 2) - (isz / 2), + bounds.getY() + (bounds.getHeight() / 2) - (isz / 2), isz, isz, 0F, partialTick); } + } } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - boolean contains = this.getTransform().contains(mx, my); - pendingRelease = isActive() && click == 0 && contains; - - return (click == 0 || click == 1) && contains; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - if(!pendingRelease) - { - return false; - } - - pendingRelease = false; - - IGuiRect bounds = this.getTransform(); - boolean clicked = isActive() && click == 0 && bounds.contains(mx, my) && !PEventBroadcaster.INSTANCE.postEvent(new PEventButton(this)); - - if(clicked) - { - Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F)); - onButtonClick(); - } - - return clicked; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - if(this.getTransform().contains(mx, my)) - { - return tooltip; - } - - return null; - } - - @Override - public void onButtonClick() - { - if(clickAction != null) clickAction.accept(this); + + if (btnText != null && !btnText.isEmpty()) { + drawCenteredString(Minecraft.getMinecraft().fontRenderer, btnText, bounds.getX(), + bounds.getY() + bounds.getHeight() / 2 - 4, bounds.getWidth(), colStates[curState].getRGB(), + txtShadow, textAlign); } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) - { - // TODO: Fix me - return nbt; + + GlStateManager.popMatrix(); + } + + private static void drawCenteredString(FontRenderer font, String text, int x, int y, int width, int color, + boolean shadow, int align) { + switch (align) { + case 0: { + font.drawString(text, x + 4, y, color, shadow); + break; + } + case 2: { + font.drawString(text, x + width - RenderUtils.getStringWidth(text, font) / 2F - 4, y, color, shadow); + break; + } + default: { + font.drawString(text, x + Math.floorDiv(width, 2) - RenderUtils.getStringWidth(text, font) / 2F, y, color, + shadow); + } } - - @Override - public void readFromNBT(NBTTagCompound nbt) - { - + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + boolean contains = this.getTransform().contains(mx, my); + pendingRelease = isActive() && click == 0 && contains; + + return (click == 0 || click == 1) && contains; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + if (!pendingRelease) { + return false; } + + pendingRelease = false; + + IGuiRect bounds = this.getTransform(); + boolean clicked = isActive() && click == 0 && bounds.contains(mx, my) && + !PEventBroadcaster.INSTANCE.postEvent(new PEventButton(this)); + + if (clicked) { + Minecraft.getMinecraft().getSoundHandler() + .playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + onButtonClick(); + } + + return clicked; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + if (this.getTransform().contains(mx, my)) { + return tooltip; + } + + return null; + } + + @Override + public void onButtonClick() { + if (clickAction != null) { clickAction.accept(this); } + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + // TODO: Fix me + return nbt; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java index e274561f0..1255c18b9 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java @@ -30,180 +30,171 @@ import java.util.List; import java.util.UUID; -public class PanelButtonQuest extends PanelButtonStorage> -{ - public final GuiRectangle rect; - public final EntityPlayer player; - - public PanelButtonQuest(GuiRectangle rect, int id, String txt, DBEntry value) - { - super(rect, id, txt, value); - this.rect = rect; - - player = Minecraft.getMinecraft().player; - EnumQuestState qState = value == null ? EnumQuestState.LOCKED : value.getValue().getState(QuestingAPI.getQuestingUUID(player)); - IGuiTexture txFrame = null; - IGuiColor txIconCol = null; - boolean main = value == null ? false : value.getValue().getProperty(NativeProps.MAIN); - boolean lock = false; - - switch(qState) - { - case LOCKED: - txFrame = main ? PresetTexture.QUEST_MAIN_0.getTexture() : PresetTexture.QUEST_NORM_0.getTexture(); - txIconCol = PresetColor.QUEST_ICON_LOCKED.getColor(); - lock = true; - break; - case UNLOCKED: - txFrame = main ? PresetTexture.QUEST_MAIN_1.getTexture() : PresetTexture.QUEST_NORM_1.getTexture(); - txIconCol = PresetColor.QUEST_ICON_UNLOCKED.getColor(); - break; - case UNCLAIMED: - txFrame = main ? PresetTexture.QUEST_MAIN_2.getTexture() : PresetTexture.QUEST_NORM_2.getTexture(); - txIconCol = PresetColor.QUEST_ICON_PENDING.getColor(); - break; - case COMPLETED: - txFrame = main ? PresetTexture.QUEST_MAIN_3.getTexture() : PresetTexture.QUEST_NORM_3.getTexture(); - txIconCol = PresetColor.QUEST_ICON_COMPLETE.getColor(); - break; - } - - IGuiTexture btnTx = new GuiTextureColored(txFrame, txIconCol); - setTextures(btnTx, btnTx, btnTx); - setIcon(new OreDictTexture(1F, value == null ? new BigItemStack(Items.NETHER_STAR) : value.getValue().getProperty(NativeProps.ICON), false, true), 4); - //setTooltip(value == null ? Collections.emptyList() : getQuestTooltip(value.getValue(), player, value.getID())); - setActive(QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(player) || !lock); +public class PanelButtonQuest extends PanelButtonStorage> { + public final GuiRectangle rect; + public final EntityPlayer player; + + public PanelButtonQuest(GuiRectangle rect, int id, String txt, DBEntry value) { + super(rect, id, txt, value); + this.rect = rect; + + player = Minecraft.getMinecraft().player; + EnumQuestState qState = + value == null ? EnumQuestState.LOCKED : value.getValue().getState(QuestingAPI.getQuestingUUID(player)); + IGuiTexture txFrame = null; + IGuiColor txIconCol = null; + boolean main = value != null && value.getValue().getProperty(NativeProps.MAIN); + boolean lock = false; + + switch (qState) { + case LOCKED: + txFrame = main ? PresetTexture.QUEST_MAIN_0.getTexture() : PresetTexture.QUEST_NORM_0.getTexture(); + txIconCol = PresetColor.QUEST_ICON_LOCKED.getColor(); + lock = true; + break; + case UNLOCKED: + txFrame = main ? PresetTexture.QUEST_MAIN_1.getTexture() : PresetTexture.QUEST_NORM_1.getTexture(); + txIconCol = PresetColor.QUEST_ICON_UNLOCKED.getColor(); + break; + case UNCLAIMED: + txFrame = main ? PresetTexture.QUEST_MAIN_2.getTexture() : PresetTexture.QUEST_NORM_2.getTexture(); + txIconCol = PresetColor.QUEST_ICON_PENDING.getColor(); + break; + case COMPLETED: + txFrame = main ? PresetTexture.QUEST_MAIN_3.getTexture() : PresetTexture.QUEST_NORM_3.getTexture(); + txIconCol = PresetColor.QUEST_ICON_COMPLETE.getColor(); + break; } - - @Override - public List getTooltip(int mx, int my) - { - if(!this.getTransform().contains(mx, my)) return null; - - DBEntry value = this.getStoredValue(); - return value == null ? Collections.emptyList() : getQuestTooltip(value.getValue(), player, value.getID()); + + IGuiTexture btnTx = new GuiTextureColored(txFrame, txIconCol); + setTextures(btnTx, btnTx, btnTx); + setIcon(new OreDictTexture(1F, value == null ? new BigItemStack(Items.NETHER_STAR) + : value.getValue().getProperty(NativeProps.ICON), false, true), 4); + //setTooltip(value == null ? Collections.emptyList() : getQuestTooltip(value.getValue(), player, value.getID())); + setActive(QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(player) || !lock); + } + + @Override + public List getTooltip(int mx, int my) { + if (!this.getTransform().contains(mx, my)) { return null; } + + DBEntry value = this.getStoredValue(); + return value == null ? Collections.emptyList() : getQuestTooltip(value.getValue(), player, value.getID()); + } + + private List getQuestTooltip(IQuest quest, EntityPlayer player, int qID) { + List tooltip = getStandardTooltip(quest, player, qID); + + if (Minecraft.getMinecraft().gameSettings.advancedItemTooltips && + QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) { + tooltip.add(""); + tooltip.addAll(this.getAdvancedTooltip(quest, player, qID)); } - - private List getQuestTooltip(IQuest quest, EntityPlayer player, int qID) - { - List tooltip = getStandardTooltip(quest, player, qID); - - if(Minecraft.getMinecraft().gameSettings.advancedItemTooltips && QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) - { - tooltip.add(""); - tooltip.addAll(this.getAdvancedTooltip(quest, player, qID)); - } - - return tooltip; + + return tooltip; + } + + private List getStandardTooltip(IQuest quest, EntityPlayer player, int qID) { + List list = new ArrayList<>(); + + list.add(QuestTranslation.translate(quest.getProperty(NativeProps.NAME)) + + (!Minecraft.getMinecraft().gameSettings.advancedItemTooltips ? "" : (" #" + qID))); + + UUID playerID = QuestingAPI.getQuestingUUID(player); + + if (quest.isComplete(playerID)) { + list.add(TextFormatting.GREEN + QuestTranslation.translate("betterquesting.tooltip.complete")); + + if (!quest.hasClaimed(playerID)) { + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.rewards_pending")); + } else if (quest.getProperty(NativeProps.REPEAT_TIME) > 0) { + long time = getRepeatSeconds(quest, player); + DecimalFormat df = new DecimalFormat("00"); + String timeTxt = ""; + + if (time >= 3600) { + timeTxt += (time / 3600) + "h " + df.format((time % 3600) / 60) + "m "; + } else if (time >= 60) { + timeTxt += (time / 60) + "m "; + } + + timeTxt += df.format(time % 60) + "s"; + + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.repeat", timeTxt)); + } + } else if (!quest.isUnlocked(playerID)) { + list.add(TextFormatting.RED + "" + TextFormatting.UNDERLINE + + QuestTranslation.translate("betterquesting.tooltip.requires") + " (" + + quest.getProperty(NativeProps.LOGIC_QUEST).toString().toUpperCase() + ")"); + + // TODO: Make this lookup unnecessary + for (DBEntry req : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) { + if (!req.getValue().isComplete(playerID)) { + list.add( + TextFormatting.RED + "- " + QuestTranslation.translate(req.getValue().getProperty(NativeProps.NAME))); + } + } + } else { + int n = 0; + + for (DBEntry task : quest.getTasks().getEntries()) { + if (task.getValue().isComplete(playerID)) { + n++; + } + } + + list.add(TextFormatting.GRAY + + QuestTranslation.translate("betterquesting.tooltip.tasks_complete", n, quest.getTasks().size())); } - - private List getStandardTooltip(IQuest quest, EntityPlayer player, int qID) - { - List list = new ArrayList<>(); - - list.add(QuestTranslation.translate(quest.getProperty(NativeProps.NAME)) + (!Minecraft.getMinecraft().gameSettings.advancedItemTooltips ? "" : (" #" + qID))); - - UUID playerID = QuestingAPI.getQuestingUUID(player); - - if(quest.isComplete(playerID)) - { - list.add(TextFormatting.GREEN + QuestTranslation.translate("betterquesting.tooltip.complete")); - - if(!quest.hasClaimed(playerID)) - { - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.rewards_pending")); - } else if(quest.getProperty(NativeProps.REPEAT_TIME) > 0) - { - long time = getRepeatSeconds(quest, player); - DecimalFormat df = new DecimalFormat("00"); - String timeTxt = ""; - - if(time >= 3600) - { - timeTxt += (time/3600) + "h " + df.format((time%3600)/60) + "m "; - } else if(time >= 60) - { - timeTxt += (time/60) + "m "; - } - - timeTxt += df.format(time%60) + "s"; - - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.repeat", timeTxt)); - } - } else if(!quest.isUnlocked(playerID)) - { - list.add(TextFormatting.RED + "" + TextFormatting.UNDERLINE + QuestTranslation.translate("betterquesting.tooltip.requires") + " (" + quest.getProperty(NativeProps.LOGIC_QUEST).toString().toUpperCase() + ")"); - - // TODO: Make this lookup unnecessary - for(DBEntry req : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) - { - if(!req.getValue().isComplete(playerID)) - { - list.add(TextFormatting.RED + "- " + QuestTranslation.translate(req.getValue().getProperty(NativeProps.NAME))); - } - } - } else - { - int n = 0; - - for(DBEntry task : quest.getTasks().getEntries()) - { - if(task.getValue().isComplete(playerID)) - { - n++; - } - } - - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.tasks_complete", n, quest.getTasks().size())); - } - - return list; + + return list; + } + + private List getAdvancedTooltip(IQuest quest, EntityPlayer player, int qID) { + List list = new ArrayList<>(); + + list.add(TextFormatting.GRAY + + QuestTranslation.translate("betterquesting.tooltip.global_quest", quest.getProperty(NativeProps.GLOBAL))); + if (quest.getProperty(NativeProps.GLOBAL)) { + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_share", + quest.getProperty(NativeProps.GLOBAL_SHARE))); } - - private List getAdvancedTooltip(IQuest quest, EntityPlayer player, int qID) - { - List list = new ArrayList<>(); - - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_quest", quest.getProperty(NativeProps.GLOBAL))); - if(quest.getProperty(NativeProps.GLOBAL)) - { - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_share", quest.getProperty(NativeProps.GLOBAL_SHARE))); - } - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.quest_logic", quest.getProperty(NativeProps.LOGIC_QUEST).toString().toUpperCase())); - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.simultaneous", quest.getProperty(NativeProps.SIMULTANEOUS))); - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.auto_claim", quest.getProperty(NativeProps.AUTO_CLAIM))); - if(quest.getProperty(NativeProps.REPEAT_TIME).intValue() >= 0) - { - long time = quest.getProperty(NativeProps.REPEAT_TIME)/20; - DecimalFormat df = new DecimalFormat("00"); - String timeTxt = ""; - - if(time >= 3600) - { - timeTxt += (time/3600) + "h " + df.format((time%3600)/60) + "m "; - } else if(time >= 60) - { - timeTxt += (time/60) + "m "; - } - - timeTxt += df.format(time%60) + "s"; - - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.repeat", timeTxt)); - } else - { - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.repeat", false)); - } - - return list; + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.quest_logic", + quest.getProperty(NativeProps.LOGIC_QUEST).toString() + .toUpperCase())); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.simultaneous", + quest.getProperty(NativeProps.SIMULTANEOUS))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.auto_claim", + quest.getProperty(NativeProps.AUTO_CLAIM))); + if (quest.getProperty(NativeProps.REPEAT_TIME) >= 0) { + long time = quest.getProperty(NativeProps.REPEAT_TIME) / 20; + DecimalFormat df = new DecimalFormat("00"); + String timeTxt = ""; + + if (time >= 3600) { + timeTxt += (time / 3600) + "h " + df.format((time % 3600) / 60) + "m "; + } else if (time >= 60) { + timeTxt += (time / 60) + "m "; + } + + timeTxt += df.format(time % 60) + "s"; + + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.repeat", timeTxt)); + } else { + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.repeat", false)); } - - private long getRepeatSeconds(IQuest quest, EntityPlayer player) - { - if(quest.getProperty(NativeProps.REPEAT_TIME) < 0) return -1; - - NBTTagCompound ue = quest.getCompletionInfo(QuestingAPI.getQuestingUUID(player)); - if(ue == null) return 0; - - return ((quest.getProperty(NativeProps.REPEAT_TIME) * 50L) - (System.currentTimeMillis() - ue.getLong("timestamp"))) / 1000L; - } + + return list; + } + + private long getRepeatSeconds(IQuest quest, EntityPlayer player) { + if (quest.getProperty(NativeProps.REPEAT_TIME) < 0) { return -1; } + + NBTTagCompound ue = quest.getCompletionInfo(QuestingAPI.getQuestingUUID(player)); + if (ue == null) { return 0; } + + return + ((quest.getProperty(NativeProps.REPEAT_TIME) * 50L) - (System.currentTimeMillis() - ue.getLong("timestamp"))) / + 1000L; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java index ef74206bd..07615c48f 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java @@ -3,42 +3,35 @@ import betterquesting.api.misc.ICallback; import betterquesting.api2.client.gui.misc.IGuiRect; -public class PanelButtonStorage extends PanelButton -{ - private T stored = null; - private ICallback callback = null; - - public PanelButtonStorage(IGuiRect rect, int id, String txt, T value) - { - super(rect, id, txt); - this.setStoredValue(value); - } - - public PanelButtonStorage setStoredValue(T value) - { - this.stored = value; - return this; - } - - public T getStoredValue() - { - return stored; - } - - public PanelButtonStorage setCallback(ICallback callback) - { - this.callback = callback; - return this; - } - - public ICallback getCallback() - { - return this.callback; - } - - @Override - public void onButtonClick() - { - if(callback != null) this.callback.setValue(this.getStoredValue()); - } +public class PanelButtonStorage extends PanelButton { + private T stored = null; + private ICallback callback = null; + + public PanelButtonStorage(IGuiRect rect, int id, String txt, T value) { + super(rect, id, txt); + this.setStoredValue(value); + } + + public PanelButtonStorage setStoredValue(T value) { + this.stored = value; + return this; + } + + public T getStoredValue() { + return stored; + } + + public PanelButtonStorage setCallback(ICallback callback) { + this.callback = callback; + return this; + } + + public ICallback getCallback() { + return this.callback; + } + + @Override + public void onButtonClick() { + if (callback != null) { this.callback.setValue(this.getStoredValue()); } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java index abed1f86d..ae2d2ad32 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java @@ -17,837 +17,705 @@ import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.math.MathHelper; import org.lwjgl.input.Mouse; + import java.util.List; -public class PanelTextField implements IGuiPanel -{ - private final IGuiRect transform; - private boolean enabled = true; - - private IGuiTexture[] texState = new IGuiTexture[3]; - private IGuiColor[] colStates = new IGuiColor[3]; - private IGuiColor colHighlight; - private IGuiColor colWatermark; - - private boolean lockFocus = false; - private boolean isFocused = false; - private boolean isActive = true; - private boolean canWrap = false; - private int maxLength = 32; - - private String text; - private String watermark = ""; - - private int selectStart = 0; - private int selectEnd = 0; // WARNING: Selection end can be before selection start! - private boolean dragging = false; - private GuiRectangle cursorLine = new GuiRectangle(4, 4, 1, 8); - - // Yep... we're supporting this without a scrolling canvas (we don't need the zooming and mouse dragging but the scrolling bounds change much more often) - private IValueIO scrollX; - private IValueIO scrollY; - private int scrollWidth = 0; - private int scrollHeight = 0; - - private final IFieldFilter filter; - private ICallback callback; - - public PanelTextField(IGuiRect rect, String text, IFieldFilter filter) - { - this.transform = rect; - cursorLine.setParent(this.transform); - this.filter = filter; - - this.setTextures(PresetTexture.TEXT_BOX_0.getTexture(), PresetTexture.TEXT_BOX_1.getTexture(), PresetTexture.TEXT_BOX_2.getTexture()); - this.setMainColors(PresetColor.TEXT_AUX_0.getColor(), PresetColor.TEXT_AUX_0.getColor(), PresetColor.TEXT_AUX_0.getColor()); - this.setAuxColors(PresetColor.TEXT_WATERMARK.getColor(), PresetColor.TEXT_HIGHLIGHT.getColor()); - - // Dummy value drivers - - scrollX = new FloatSimpleIO(); - scrollY = new FloatSimpleIO(); - - this.setText(text); - } - - public PanelTextField setCallback(ICallback callback) - { - this.callback = callback; - return this; +public class PanelTextField implements IGuiPanel { + private final IGuiRect transform; + private boolean enabled = true; + + private final IGuiTexture[] texState = new IGuiTexture[3]; + private final IGuiColor[] colStates = new IGuiColor[3]; + private IGuiColor colHighlight; + private IGuiColor colWatermark; + + private boolean lockFocus = false; + private boolean isFocused = false; + private boolean isActive = true; + private boolean canWrap = false; + private int maxLength = 32; + + private String text; + private String watermark = ""; + + private int selectStart = 0; + private int selectEnd = 0; // WARNING: Selection end can be before selection start! + private boolean dragging = false; + private final GuiRectangle cursorLine = new GuiRectangle(4, 4, 1, 8); + + // Yep... we're supporting this without a scrolling canvas (we don't need the zooming and mouse dragging but the scrolling bounds change much more often) + private IValueIO scrollX; + private IValueIO scrollY; + private int scrollWidth = 0; + private int scrollHeight = 0; + + private final IFieldFilter filter; + private ICallback callback; + + public PanelTextField(IGuiRect rect, String text, IFieldFilter filter) { + this.transform = rect; + cursorLine.setParent(this.transform); + this.filter = filter; + + this.setTextures(PresetTexture.TEXT_BOX_0.getTexture(), PresetTexture.TEXT_BOX_1.getTexture(), + PresetTexture.TEXT_BOX_2.getTexture()); + this.setMainColors(PresetColor.TEXT_AUX_0.getColor(), PresetColor.TEXT_AUX_0.getColor(), + PresetColor.TEXT_AUX_0.getColor()); + this.setAuxColors(PresetColor.TEXT_WATERMARK.getColor(), PresetColor.TEXT_HIGHLIGHT.getColor()); + + // Dummy value drivers + + scrollX = new FloatSimpleIO(); + scrollY = new FloatSimpleIO(); + + this.setText(text); + } + + public PanelTextField setCallback(ICallback callback) { + this.callback = callback; + return this; + } + + public PanelTextField setTextures(IGuiTexture disabled, IGuiTexture idle, IGuiTexture focused) { + this.texState[0] = disabled; + this.texState[1] = idle; + this.texState[2] = focused; + return this; + } + + public PanelTextField setMainColors(IGuiColor disabled, IGuiColor idle, IGuiColor focused) { + this.colStates[0] = disabled; + this.colStates[1] = idle; + this.colStates[2] = focused; + return this; + } + + public PanelTextField setAuxColors(IGuiColor watermark, IGuiColor highlight) { + this.colWatermark = watermark; + this.colHighlight = highlight; + return this; + } + + public PanelTextField setMaxLength(int size) { + this.maxLength = size; + return this; + } + + /** + * Enables text wrapping for multi-line editing + */ + public PanelTextField enableWrapping(boolean state) { + this.canWrap = state; + updateScrollBounds(); + return this; + } + + public void lockFocus(boolean state) { + this.lockFocus = state; + + if (state) { + this.isFocused = true; } - - public PanelTextField setTextures(IGuiTexture disabled, IGuiTexture idle, IGuiTexture focused) - { - this.texState[0] = disabled; - this.texState[1] = idle; - this.texState[2] = focused; - return this; + } + + public PanelTextField setScrollDriverX(IValueIO driver) { + this.scrollX = driver; + return this; + } + + public PanelTextField setScrollDriverY(IValueIO driver) { + this.scrollY = driver; + return this; + } + + public int getScrollX() { + if (scrollWidth <= 0) { + return 0; } - - public PanelTextField setMainColors(IGuiColor disabled, IGuiColor idle, IGuiColor focused) - { - this.colStates[0] = disabled; - this.colStates[1] = idle; - this.colStates[2] = focused; - return this; + + return (int) (scrollWidth * scrollX.readValue()); + } + + public int getScrollY() { + if (scrollHeight <= 0) { + return 0; } - - public PanelTextField setAuxColors(IGuiColor watermark, IGuiColor highlight) - { - this.colWatermark = watermark; - this.colHighlight = highlight; - return this; + + return (int) (scrollHeight * scrollY.readValue()); + } + + public void setScrollX(int value) { + if (scrollWidth <= 0) { + scrollX.writeValue(0F); + return; } - - public PanelTextField setMaxLength(int size) - { - this.maxLength = size; - return this; + + scrollX.writeValue(MathHelper.clamp(value, 0, scrollWidth) / (float) scrollWidth); + } + + public void setScrollY(int value) { + if (scrollHeight <= 0) { + scrollY.writeValue(0F); + return; } - - /** - * Enables text wrapping for multi-line editing - */ - public PanelTextField enableWrapping(boolean state) - { - this.canWrap = state; - updateScrollBounds(); - return this; + + scrollY.writeValue(MathHelper.clamp(value, 0, scrollHeight) / (float) scrollHeight); + } + + public void setActive(boolean state) { + this.isActive = state; + } + + public boolean isActive() { + return this.isActive; + } + + public boolean isFocused() { + return this.isFocused; + } + + public PanelTextField setWatermark(String text) { + this.watermark = text; + return this; + } + + public void setText(String text) { + this.text = filter.filterText(text); + updateScrollBounds(); + setCursorPosition(0); + } + + public String getRawText() { + return this.text; + } + + public T getValue() { + return this.filter.parseValue(getRawText()); + } + + public String getSelectedText() { + int l = Math.min(selectStart, selectEnd); + int r = Math.max(selectStart, selectEnd); + return text.substring(l, r); + } + + /** + * Writes text to the current cursor position replacing any current selection + */ + public void writeText(String in) { + StringBuilder out = new StringBuilder(); + int l = Math.min(selectStart, selectEnd); + int r = Math.max(selectStart, selectEnd); + int space = this.maxLength - text.length() - (l - r); + + if (!text.isEmpty()) { + out.append(text, 0, l); } - - public void lockFocus(boolean state) + + int used; + + if (space < 0) // Can happen if someone instantiates the field with more characters than it normally allows { - this.lockFocus = state; - - if(state) - { - this.isFocused = true; - } - } - - public PanelTextField setScrollDriverX(IValueIO driver) + used = 0; + } else if (space < in.length()) // Written string won fit { - this.scrollX = driver; - return this; + out.append(in, 0, space); // Cut to size + used = space; // Mark all space as used + } else { + out.append(in); + used = in.length(); } - - public PanelTextField setScrollDriverY(IValueIO driver) - { - this.scrollY = driver; - return this; + + if (!text.isEmpty() && r < text.length()) { + out.append(text, r, text.length()); } - - public int getScrollX() + + //if(filter.isValid(text)) { - if(scrollWidth <= 0) - { - return 0; - } - - return (int)(scrollWidth * scrollX.readValue()); + this.text = filter.filterText(out.toString()); + updateScrollBounds(); + moveCursorBy(l - selectEnd + used); + + // Broadcast changes + if (callback != null) { + callback.setValue(filter.parseValue(this.text)); + } } - - public int getScrollY() - { - if(scrollHeight <= 0) - { - return 0; + } + + /** + * Deletes the given number of whole words from the current cursor's position, unless there is currently a selection, in + * which case the selection is deleted instead. + */ + public void deleteWords(int num) { + if (!this.text.isEmpty()) { + if (this.selectEnd != this.selectStart) { + this.writeText(""); + } else { + this.deleteFromCursor(this.getNthWordFromCursor(num) - this.selectStart); + } + } + } + + /** + * Deletes the given number of characters from the current cursor's position, unless there is currently a selection, + * in which case the selection is deleted instead. + */ + public void deleteFromCursor(int num) { + if (!this.text.isEmpty()) { + if (this.selectEnd != this.selectStart) { + this.writeText(""); + } else { + boolean flag = num < 0; + int i = flag ? this.selectStart + num : this.selectStart; + int j = flag ? this.selectStart : this.selectStart + num; + String s = ""; + + if (i >= 0) { + s = this.text.substring(0, i); } - - return (int)(scrollHeight * scrollY.readValue()); - } - - public void setScrollX(int value) - { - if(scrollWidth <= 0) - { - scrollX.writeValue(0F); - return; + + if (j < this.text.length()) { + s = s + this.text.substring(j); } - - scrollX.writeValue(MathHelper.clamp(value, 0, scrollWidth) / (float)scrollWidth); - } - - public void setScrollY(int value) - { - if(scrollHeight <= 0) + + //if(filter.isValid(s)) { - scrollY.writeValue(0F); - return; + this.text = filter.filterText(s); + + updateScrollBounds(); + + if (flag) { + this.moveCursorBy(num); + } + + // Broadcast changes + if (callback != null) { + callback.setValue(filter.parseValue(this.text)); + } } - - scrollY.writeValue(MathHelper.clamp(value, 0, scrollHeight) / (float)scrollHeight); - } - - public void setActive(boolean state) - { - this.isActive = state; - } - - public boolean isActive() - { - return this.isActive; - } - - public boolean isFocused() - { - return this.isFocused; - } - - public PanelTextField setWatermark(String text) - { - this.watermark = text; - return this; - } - - public void setText(String text) - { - this.text = filter.filterText(text); - updateScrollBounds(); - setCursorPosition(0); - } - - public String getRawText() - { - return this.text; - } - - public T getValue() - { - return this.filter.parseValue(getRawText()); - } - - public String getSelectedText() - { - int l = Math.min(selectStart, selectEnd); - int r = Math.max(selectStart, selectEnd); - return text.substring(l, r); + } } - - /** - * Writes text to the current cursor position replacing any current selection - */ - public void writeText(String in) - { - StringBuilder out = new StringBuilder(); - int l = Math.min(selectStart, selectEnd); - int r = Math.max(selectStart, selectEnd); - int space = this.maxLength - text.length() - (l - r); - - if(!text.isEmpty()) - { - out.append(text, 0, l); - } - - int used; - - if(space < 0) // Can happen if someone instantiates the field with more characters than it normally allows - { - used = 0; - } else if(space < in.length()) // Written string won fit - { - out.append(in, 0, space); // Cut to size - used = space; // Mark all space as used - } else - { - out.append(in); - used = in.length(); - } - - if(!text.isEmpty() && r < text.length()) - { - out.append(text, r, text.length()); - } - - //if(filter.isValid(text)) - { - this.text = filter.filterText(out.toString()); - updateScrollBounds(); - moveCursorBy(l - selectEnd + used); - - // Broadcast changes - if(callback != null) - { - callback.setValue(filter.parseValue(this.text)); - } + } + + /** + * Gets the starting index of the word at the specified number of words away from the cursor position. + */ + public int getNthWordFromCursor(int numWords) { + return this.getNthWordFromPos(numWords, this.selectStart); + } + + /** + * Gets the starting index of the word at a distance of the specified number of words away from the given position. + */ + public int getNthWordFromPos(int n, int pos) { + return this.getNthWordFromPosWS(n, pos, true); + } + + /** + * Like getNthWordFromPos (which wraps this), but adds option for skipping consecutive spaces + */ + public int getNthWordFromPosWS(int n, int pos, boolean skipWs) { + int i = pos; + boolean flag = n < 0; + int j = Math.abs(n); + + for (int k = 0; k < j; ++k) { + if (!flag) { + int l = this.text.length(); + i = this.text.indexOf(32, i); + + if (i == -1) { + i = l; + } else { + while (skipWs && i < l && this.text.charAt(i) == ' ') { + ++i; + } } - } - - /** - * Deletes the given number of whole words from the current cursor's position, unless there is currently a selection, in - * which case the selection is deleted instead. - */ - public void deleteWords(int num) - { - if (!this.text.isEmpty()) - { - if (this.selectEnd != this.selectStart) - { - this.writeText(""); - } - else - { - this.deleteFromCursor(this.getNthWordFromCursor(num) - this.selectStart); - } + } else { + while (skipWs && i > 0 && this.text.charAt(i - 1) == ' ') { + --i; } - } - /** - * Deletes the given number of characters from the current cursor's position, unless there is currently a selection, - * in which case the selection is deleted instead. - */ - public void deleteFromCursor(int num) - { - if (!this.text.isEmpty()) - { - if (this.selectEnd != this.selectStart) - { - this.writeText(""); - } - else - { - boolean flag = num < 0; - int i = flag ? this.selectStart + num : this.selectStart; - int j = flag ? this.selectStart : this.selectStart + num; - String s = ""; - - if (i >= 0) - { - s = this.text.substring(0, i); - } - - if (j < this.text.length()) - { - s = s + this.text.substring(j); - } - - //if(filter.isValid(s)) - { - this.text = filter.filterText(s); - - updateScrollBounds(); - - if (flag) - { - this.moveCursorBy(num); - } - - // Broadcast changes - if(callback != null) - { - callback.setValue(filter.parseValue(this.text)); - } - } - } + while (i > 0 && this.text.charAt(i - 1) != ' ') { + --i; } + } } - /** - * Gets the starting index of the word at the specified number of words away from the cursor position. - */ - public int getNthWordFromCursor(int numWords) - { - return this.getNthWordFromPos(numWords, this.selectStart); - } + return i; + } - /** - * Gets the starting index of the word at a distance of the specified number of words away from the given position. - */ - public int getNthWordFromPos(int n, int pos) - { - return this.getNthWordFromPosWS(n, pos, true); - } + /** + * Moves the text cursor by a specified number of characters and clears the selection + */ + public void moveCursorBy(int num) { + this.setCursorPosition(this.selectEnd + num); + } - /** - * Like getNthWordFromPos (which wraps this), but adds option for skipping consecutive spaces - */ - public int getNthWordFromPosWS(int n, int pos, boolean skipWs) - { - int i = pos; - boolean flag = n < 0; - int j = Math.abs(n); + /** + * Sets the current position of the cursor. + */ + public void setCursorPosition(int pos) { + this.selectStart = pos; + int i = this.text.length(); + this.selectStart = MathHelper.clamp(this.selectStart, 0, i); + this.setSelectionPos(this.selectStart); + } - for (int k = 0; k < j; ++k) - { - if (!flag) - { - int l = this.text.length(); - i = this.text.indexOf(32, i); - - if (i == -1) - { - i = l; - } - else - { - while (skipWs && i < l && this.text.charAt(i) == ' ') - { - ++i; - } - } - } - else - { - while (skipWs && i > 0 && this.text.charAt(i - 1) == ' ') - { - --i; - } - - while (i > 0 && this.text.charAt(i - 1) != ' ') - { - --i; - } - } - } + /** + * Call this method from your GuiScreen to process the keys into the textbox + */ + @Override + public boolean onKeyTyped(char typedChar, int keyCode) { + if (!this.isFocused) { + return false; + } else if (GuiScreen.isKeyComboCtrlA(keyCode)) { + this.setCursorPosition(text.length()); + this.setSelectionPos(0); + return true; + } else if (GuiScreen.isKeyComboCtrlC(keyCode)) { + GuiScreen.setClipboardString(this.getSelectedText()); + return true; + } else if (GuiScreen.isKeyComboCtrlV(keyCode)) { + if (this.isActive) { + this.writeText(GuiScreen.getClipboardString()); + } - return i; - } + return true; + } else if (GuiScreen.isKeyComboCtrlX(keyCode)) { + GuiScreen.setClipboardString(this.getSelectedText()); - /** - * Moves the text cursor by a specified number of characters and clears the selection - */ - public void moveCursorBy(int num) - { - this.setCursorPosition(this.selectEnd + num); - } + if (this.isActive) { + this.writeText(""); + } - /** - * Sets the current position of the cursor. - */ - public void setCursorPosition(int pos) - { - this.selectStart = pos; - int i = this.text.length(); - this.selectStart = MathHelper.clamp(this.selectStart, 0, i); - this.setSelectionPos(this.selectStart); - } + return true; + } else { + switch (keyCode) { + case 14: // Backspace + { + if (GuiScreen.isCtrlKeyDown()) { + if (this.isActive) { + this.deleteWords(-1); + } + } else if (this.isActive) { + this.deleteFromCursor(-1); + } - /** - * Call this method from your GuiScreen to process the keys into the textbox - */ - @Override - public boolean onKeyTyped(char typedChar, int keyCode) - { - if (!this.isFocused) - { - return false; + return true; } - else if (GuiScreen.isKeyComboCtrlA(keyCode)) + case 28: // Enter { - this.setCursorPosition(text.length()); - this.setSelectionPos(0); - return true; + if (canWrap) { + this.writeText("\n"); + } + + return true; } - else if (GuiScreen.isKeyComboCtrlC(keyCode)) + case 199: // Home { - GuiScreen.setClipboardString(this.getSelectedText()); - return true; + if (GuiScreen.isShiftKeyDown()) { + this.setSelectionPos(0); + } else { + this.setCursorPosition(0); + } + + return true; } - else if (GuiScreen.isKeyComboCtrlV(keyCode)) + case 203: // Left arrow { - if (this.isActive) - { - this.writeText(GuiScreen.getClipboardString()); + if (GuiScreen.isShiftKeyDown()) { + if (GuiScreen.isCtrlKeyDown()) { + this.setSelectionPos(this.getNthWordFromPos(-1, selectEnd)); + } else { + this.setSelectionPos(selectEnd - 1); } + } else if (GuiScreen.isCtrlKeyDown()) { + this.setCursorPosition(this.getNthWordFromCursor(-1)); + } else { + this.moveCursorBy(-1); + } - return true; + return true; } - else if (GuiScreen.isKeyComboCtrlX(keyCode)) + case 205: // Right arrow { - GuiScreen.setClipboardString(this.getSelectedText()); - - if (this.isActive) - { - this.writeText(""); + if (GuiScreen.isShiftKeyDown()) { + if (GuiScreen.isCtrlKeyDown()) { + this.setSelectionPos(this.getNthWordFromPos(1, selectEnd)); + } else { + this.setSelectionPos(selectEnd + 1); } + } else if (GuiScreen.isCtrlKeyDown()) { + this.setCursorPosition(this.getNthWordFromCursor(1)); + } else { + this.moveCursorBy(1); + } - return true; + return true; } - else + case 207: // End { - switch (keyCode) - { - case 14: // Backspace - { - if(GuiScreen.isCtrlKeyDown()) - { - if(this.isActive) - { - this.deleteWords(-1); - } - } else if(this.isActive) - { - this.deleteFromCursor(-1); - } - - return true; - } - case 28: // Enter - { - if(canWrap) - { - this.writeText("\n"); - } - - return true; - } - case 199: // Home - { - if(GuiScreen.isShiftKeyDown()) - { - this.setSelectionPos(0); - } else - { - this.setCursorPosition(0); - } - - return true; - } - case 203: // Left arrow - { - if(GuiScreen.isShiftKeyDown()) - { - if(GuiScreen.isCtrlKeyDown()) - { - this.setSelectionPos(this.getNthWordFromPos(-1, selectEnd)); - } else - { - this.setSelectionPos(selectEnd - 1); - } - } else if(GuiScreen.isCtrlKeyDown()) - { - this.setCursorPosition(this.getNthWordFromCursor(-1)); - } else - { - this.moveCursorBy(-1); - } - - return true; - } - case 205: // Right arrow - { - if(GuiScreen.isShiftKeyDown()) - { - if(GuiScreen.isCtrlKeyDown()) - { - this.setSelectionPos(this.getNthWordFromPos(1, selectEnd)); - } else - { - this.setSelectionPos(selectEnd + 1); - } - } else if(GuiScreen.isCtrlKeyDown()) - { - this.setCursorPosition(this.getNthWordFromCursor(1)); - } else - { - this.moveCursorBy(1); - } - - return true; - } - case 207: // End - { - if(GuiScreen.isShiftKeyDown()) - { - this.setSelectionPos(this.text.length()); - } else - { - this.setCursorPosition(text.length()); - } - - return true; - } - case 200: // Up arrow - { - // TODO: Move cursor up one line - return true; - } - case 208: // Down arrow - { - // TODO: Move cursor down one line - return true; - } - case 211: // Delete - { - if(GuiScreen.isCtrlKeyDown()) - { - if(this.isActive) - { - this.deleteWords(1); - } - } else if(this.isActive) - { - this.deleteFromCursor(1); - } - - return true; - } - default: - { - if(ChatAllowedCharacters.isAllowedCharacter(typedChar)) - { - if(this.isActive) - { - this.writeText(Character.toString(typedChar)); - } - - return true; - } else - { - return false; // We're not using this key. Other controls/menus are free to use it - } - } - } + if (GuiScreen.isShiftKeyDown()) { + this.setSelectionPos(this.text.length()); + } else { + this.setCursorPosition(text.length()); + } + + return true; } - } - - /** - * Sets the position of the selection anchor (the selection anchor and the cursor position mark the edges of the - * selection). If the anchor is set beyond the bounds of the current text, it will be put back inside. - */ - public void setSelectionPos(int position) - { - int i = this.text.length(); - - if(position > i) + case 200: // Up arrow { - position = i; + // TODO: Move cursor up one line + return true; } - - if(position < 0) + case 208: // Down arrow { - position = 0; + // TODO: Move cursor down one line + return true; } - - if(selectEnd != position) + case 211: // Delete { - this.selectEnd = position; - - FontRenderer font = Minecraft.getMinecraft().fontRenderer; - - if(canWrap) - { - List lines = RenderUtils.splitStringWithoutFormat(text, getTransform().getWidth() - 8, font); - String lastFormat = ""; - int idx = 0; - int y = 0; - int x = 0; - - for(; y < lines.size(); y++) - { - String s = lines.get(y); - - if(selectEnd >= idx && selectEnd < idx + s.length() + (y == lines.size() - 1 ? 1 : 0)) - { - x = RenderUtils.getStringWidth(lastFormat + s.substring(0, selectEnd - idx), font); - break; - } - - idx += s.length(); - lastFormat = FontRenderer.getFormatFromString(lastFormat + s); - } - - y *= font.FONT_HEIGHT; - int sy = getScrollY(); - - if(y < sy) - { - setScrollY(y); - } else if(y > sy + (transform.getHeight() - 8) - font.FONT_HEIGHT) - { - setScrollY(y - (transform.getHeight() - 8) + font.FONT_HEIGHT); - } - - cursorLine.x = x + 4; - cursorLine.y = y + 4; - cursorLine.w = 1; - cursorLine.h = font.FONT_HEIGHT; - } else - { - int x = RenderUtils.getStringWidth(text.substring(0, selectEnd), font); - int sx = getScrollX(); - - if(x < sx) - { - setScrollX(x); - } else if(x > sx + (transform.getWidth() - 8)) - { - setScrollX(x - (transform.getWidth() - 8)); - } - - cursorLine.x = x + 4; - cursorLine.y = 4; - cursorLine.w = 1; - cursorLine.h = font.FONT_HEIGHT; + if (GuiScreen.isCtrlKeyDown()) { + if (this.isActive) { + this.deleteWords(1); } + } else if (this.isActive) { + this.deleteFromCursor(1); + } + + return true; } - } - - public void updateScrollBounds() - { - FontRenderer font = Minecraft.getMinecraft().fontRenderer; - - int prevX = getScrollX(); - int prevY = getScrollY(); - - if(!canWrap) - { - scrollHeight = 0; - scrollWidth = Math.max(0, RenderUtils.getStringWidth(text, font) - (transform.getWidth() - 8)); - } else - { - scrollWidth = 0; - scrollHeight = Math.max(0, (RenderUtils.splitString(text, transform.getWidth() - 8, font).size() * font.FONT_HEIGHT) - (transform.getHeight() - 8)); + default: { + if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) { + if (this.isActive) { + this.writeText(Character.toString(typedChar)); + } + + return true; + } else { + return false; // We're not using this key. Other controls/menus are free to use it + } } - - setScrollX(prevX); - setScrollY(prevY); - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void initPanel() - { - + } } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; + } + + /** + * Sets the position of the selection anchor (the selection anchor and the cursor position mark the edges of the + * selection). If the anchor is set beyond the bounds of the current text, it will be put back inside. + */ + public void setSelectionPos(int position) { + int i = this.text.length(); + + if (position > i) { + position = i; } - - @Override - public boolean isEnabled() - { - return this.enabled; + + if (position < 0) { + position = 0; } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(isActive && dragging && Mouse.isButtonDown(0)) - { - if(canWrap) - { - setSelectionPos(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), my - (transform.getY() + 4) + getScrollY(), transform.getWidth() - 8, Minecraft.getMinecraft().fontRenderer)); - } else - { - setSelectionPos(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), Minecraft.getMinecraft().fontRenderer)); - } - } else if(dragging) - { - dragging = false; - } - - IGuiRect bounds = this.getTransform(); - int state = !this.isActive() ? 0 : (isFocused ? 2 : 1); - Minecraft mc = Minecraft.getMinecraft(); - IGuiTexture t = texState[state]; - GlStateManager.pushMatrix(); - - if(t != null) // Full screen text editors probably don't need the backgrounds - { - t.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + + if (selectEnd != position) { + this.selectEnd = position; + + FontRenderer font = Minecraft.getMinecraft().fontRenderer; + + if (canWrap) { + List lines = RenderUtils.splitStringWithoutFormat(text, getTransform().getWidth() - 8, font); + String lastFormat = ""; + int idx = 0; + int y = 0; + int x = 0; + + for (; y < lines.size(); y++) { + String s = lines.get(y); + + if (selectEnd >= idx && selectEnd < idx + s.length() + (y == lines.size() - 1 ? 1 : 0)) { + x = RenderUtils.getStringWidth(lastFormat + s.substring(0, selectEnd - idx), font); + break; + } + + idx += s.length(); + lastFormat = FontRenderer.getFormatFromString(lastFormat + s); } - - RenderUtils.startScissor(bounds); - GlStateManager.translate(-getScrollX(), -getScrollY(), 0); - - if(text.length() <= 0) - { - if(!isFocused) - { - mc.fontRenderer.drawString(watermark, bounds.getX() + 4, bounds.getY() + 4, colWatermark.getRGB(), false); - } - } else - { - IGuiColor c = colStates[state]; - - if(!canWrap) - { - RenderUtils.drawHighlightedString(mc.fontRenderer, text, bounds.getX() + 4, bounds.getY() + 4, c.getRGB(), false, colHighlight.getRGB(), selectStart, selectEnd); - } else - { - RenderUtils.drawHighlightedSplitString(mc.fontRenderer, text, bounds.getX() + 4, bounds.getY() + 4, bounds.getWidth() - 8, c.getRGB(), false, colHighlight.getRGB(), selectStart, selectEnd); - } + + y *= font.FONT_HEIGHT; + int sy = getScrollY(); + + if (y < sy) { + setScrollY(y); + } else if (y > sy + (transform.getHeight() - 8) - font.FONT_HEIGHT) { + setScrollY(y - (transform.getHeight() - 8) + font.FONT_HEIGHT); } - - if(isFocused && selectStart == selectEnd && (System.currentTimeMillis()/500L)%2 == 0) - { - RenderUtils.drawHighlightBox(cursorLine, colHighlight); + + cursorLine.x = x + 4; + cursorLine.y = y + 4; + } else { + int x = RenderUtils.getStringWidth(text.substring(0, selectEnd), font); + int sx = getScrollX(); + + if (x < sx) { + setScrollX(x); + } else if (x > sx + (transform.getWidth() - 8)) { + setScrollX(x - (transform.getWidth() - 8)); } - - RenderUtils.endScissor(); - GlStateManager.popMatrix(); + + cursorLine.x = x + 4; + cursorLine.y = 4; + } + cursorLine.w = 1; + cursorLine.h = font.FONT_HEIGHT; } - - @Override - public boolean onMouseClick(int mx, int my, int button) - { - if(transform.contains(mx, my)) - { - if(!this.isFocused) - { - this.isFocused = true; - updateScrollBounds(); // Just in case - } - - if(canWrap) - { - setCursorPosition(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), my - (transform.getY() + 4) + getScrollY(), transform.getWidth() - 8, Minecraft.getMinecraft().fontRenderer)); - } else - { - setCursorPosition(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), Minecraft.getMinecraft().fontRenderer)); - } - dragging = true; - - //return true; - } else if(this.isFocused && !lockFocus) - { - this.isFocused = false; - this.text = filter.parseValue(this.text).toString(); - //setCursorPosition(0); - } - - return false; + } + + public void updateScrollBounds() { + FontRenderer font = Minecraft.getMinecraft().fontRenderer; + + int prevX = getScrollX(); + int prevY = getScrollY(); + + if (!canWrap) { + scrollHeight = 0; + scrollWidth = Math.max(0, RenderUtils.getStringWidth(text, font) - (transform.getWidth() - 8)); + } else { + scrollWidth = 0; + scrollHeight = Math.max(0, (RenderUtils.splitString(text, transform.getWidth() - 8, font).size() * + font.FONT_HEIGHT) - (transform.getHeight() - 8)); } - - @Override - public boolean onMouseRelease(int mx, int my, int button) - { - return isFocused && dragging; + + setScrollX(prevX); + setScrollY(prevY); + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void initPanel() { + + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (isActive && dragging && Mouse.isButtonDown(0)) { + if (canWrap) { + setSelectionPos(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), + my - (transform.getY() + 4) + getScrollY(), transform.getWidth() - 8, + Minecraft.getMinecraft().fontRenderer)); + } else { + setSelectionPos(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), + Minecraft.getMinecraft().fontRenderer)); + } + } else if (dragging) { + dragging = false; } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) + + IGuiRect bounds = this.getTransform(); + int state = !this.isActive() ? 0 : (isFocused ? 2 : 1); + Minecraft mc = Minecraft.getMinecraft(); + IGuiTexture t = texState[state]; + GlStateManager.pushMatrix(); + + if (t != null) // Full screen text editors probably don't need the backgrounds { - if(!isFocused || !transform.contains(mx, my)) - { - return false; - } - - if(canWrap) - { - setScrollY(getScrollY() + (scroll * 4)); - return true; - } /*else + t.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + } + + RenderUtils.startScissor(bounds); + GlStateManager.translate(-getScrollX(), -getScrollY(), 0); + + if (text.isEmpty()) { + if (!isFocused) { + mc.fontRenderer.drawString(watermark, bounds.getX() + 4, bounds.getY() + 4, colWatermark.getRGB(), false); + } + } else { + IGuiColor c = colStates[state]; + + if (!canWrap) { + RenderUtils.drawHighlightedString(mc.fontRenderer, text, bounds.getX() + 4, bounds.getY() + 4, c.getRGB(), + false, colHighlight.getRGB(), selectStart, selectEnd); + } else { + RenderUtils.drawHighlightedSplitString(mc.fontRenderer, text, bounds.getX() + 4, bounds.getY() + 4, + bounds.getWidth() - 8, c.getRGB(), false, colHighlight.getRGB(), + selectStart, selectEnd); + } + } + + if (isFocused && selectStart == selectEnd && (System.currentTimeMillis() / 500L) % 2 == 0) { + RenderUtils.drawHighlightBox(cursorLine, colHighlight); + } + + RenderUtils.endScissor(); + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int button) { + if (transform.contains(mx, my)) { + if (!this.isFocused) { + this.isFocused = true; + updateScrollBounds(); // Just in case + } + + if (canWrap) { + setCursorPosition(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), + my - (transform.getY() + 4) + getScrollY(), transform.getWidth() - 8, + Minecraft.getMinecraft().fontRenderer)); + } else { + setCursorPosition(RenderUtils.getCursorPos(text, mx - (transform.getX() + 4) + getScrollX(), + Minecraft.getMinecraft().fontRenderer)); + } + dragging = true; + + //return true; + } else if (this.isFocused && !lockFocus) { + this.isFocused = false; + this.text = filter.parseValue(this.text).toString(); + //setCursorPosition(0); + } + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int button) { + return isFocused && dragging; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + if (!isFocused || !transform.contains(mx, my)) { + return false; + } + + if (canWrap) { + setScrollY(getScrollY() + (scroll * 4)); + return true; + } /*else { // This is kinda annoying in lists //setScrollX(getScrollX() + (scroll * 12)); }*/ - - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } + + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackMulti.java b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackMulti.java index ec919cdc1..29f3d324d 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackMulti.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackMulti.java @@ -2,21 +2,17 @@ import betterquesting.api.misc.ICallback; -public class CallbackMulti implements ICallback -{ - private final ICallback[] callbacks; - - public CallbackMulti(ICallback... callbacks) - { - this.callbacks = callbacks; - } - - @Override - public void setValue(T value) - { - for(ICallback c : callbacks) - { - c.setValue(value); - } +public class CallbackMulti implements ICallback { + private final ICallback[] callbacks; + + public CallbackMulti(ICallback... callbacks) { + this.callbacks = callbacks; + } + + @Override + public void setValue(T value) { + for (ICallback c : callbacks) { + c.setValue(value); } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java index 92e2e88b4..0c1c14519 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java @@ -3,114 +3,97 @@ import betterquesting.api.misc.ICallback; import net.minecraft.nbt.*; -public class CallbackNBTPrimitive implements ICallback -{ - private final NBTBase tag; - private final String sKey; - private final int iKey; - private final int tagID; - - public CallbackNBTPrimitive(NBTTagCompound tag, String key, Class c) - { - this.tag = tag; - this.sKey = key; - this.iKey = -1; - this.tagID = getTagID(c); - } - - public CallbackNBTPrimitive(NBTTagList tag, int key, Class c) - { - this.tag = tag; - this.sKey = null; - this.iKey = key; - this.tagID = getTagID(c); - } - - @Override - public void setValue(T value) - { - if(tag.getId() == 10) - { - setCompoundTag((NBTTagCompound)tag, value); - } else - { - setListTag((NBTTagList)tag, value); - } +public class CallbackNBTPrimitive implements ICallback { + private final NBTBase tag; + private final String sKey; + private final int iKey; + private final int tagID; + + public CallbackNBTPrimitive(NBTTagCompound tag, String key, Class c) { + this.tag = tag; + this.sKey = key; + this.iKey = -1; + this.tagID = getTagID(c); + } + + public CallbackNBTPrimitive(NBTTagList tag, int key, Class c) { + this.tag = tag; + this.sKey = null; + this.iKey = key; + this.tagID = getTagID(c); + } + + @Override + public void setValue(T value) { + if (tag.getId() == 10) { + setCompoundTag((NBTTagCompound) tag, value); + } else { + setListTag((NBTTagList) tag, value); } - - private void setCompoundTag(NBTTagCompound compound, T value) - { - switch(tagID) - { - case 1: - compound.setByte(sKey, value.byteValue()); - break; - case 2: - compound.setShort(sKey, value.shortValue()); - break; - case 3: - compound.setInteger(sKey, value.intValue()); - break; - case 4: - compound.setLong(sKey, value.longValue()); - break; - case 5: - compound.setFloat(sKey, value.floatValue()); - break; - case 6: - compound.setDouble(sKey, value.doubleValue()); - break; - } + } + + private void setCompoundTag(NBTTagCompound compound, T value) { + switch (tagID) { + case 1: + compound.setByte(sKey, value.byteValue()); + break; + case 2: + compound.setShort(sKey, value.shortValue()); + break; + case 3: + compound.setInteger(sKey, value.intValue()); + break; + case 4: + compound.setLong(sKey, value.longValue()); + break; + case 5: + compound.setFloat(sKey, value.floatValue()); + break; + case 6: + compound.setDouble(sKey, value.doubleValue()); + break; } - - private void setListTag(NBTTagList list, T value) - { - switch(tagID) - { - case 1: - list.set(iKey, new NBTTagByte(value.byteValue())); - break; - case 2: - list.set(iKey, new NBTTagShort(value.shortValue())); - break; - case 3: - list.set(iKey, new NBTTagInt(value.intValue())); - break; - case 4: - list.set(iKey, new NBTTagLong(value.longValue())); - break; - case 5: - list.set(iKey, new NBTTagFloat(value.floatValue())); - break; - case 6: - list.set(iKey, new NBTTagDouble(value.doubleValue())); - break; - } + } + + private void setListTag(NBTTagList list, T value) { + switch (tagID) { + case 1: + list.set(iKey, new NBTTagByte(value.byteValue())); + break; + case 2: + list.set(iKey, new NBTTagShort(value.shortValue())); + break; + case 3: + list.set(iKey, new NBTTagInt(value.intValue())); + break; + case 4: + list.set(iKey, new NBTTagLong(value.longValue())); + break; + case 5: + list.set(iKey, new NBTTagFloat(value.floatValue())); + break; + case 6: + list.set(iKey, new NBTTagDouble(value.doubleValue())); + break; } - - private int getTagID(Class c) - { - // There's gotta be a better way of doing this right? - if(c == Byte.class) - { - return 1; - } else if(c == Short.class) - { - return 2; - } else if(c == Integer.class) - { - return 3; - } else if(c == Long.class) - { - return 4; - } else if(c == Float.class) - { - return 5; - } else if(c == Double.class) - { - return 6; - } - - return 0; // WTF? + } + + private int getTagID(Class c) { + // There's gotta be a better way of doing this right? + if (c == Byte.class) { + return 1; + } else if (c == Short.class) { + return 2; + } else if (c == Integer.class) { + return 3; + } else if (c == Long.class) { + return 4; + } else if (c == Float.class) { + return 5; + } else if (c == Double.class) { + return 6; } + + return 0; // WTF? + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java index e4c3dffc6..1293007c8 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java @@ -6,35 +6,29 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; -public class CallbackNBTTagString implements ICallback -{ - private final NBTBase tag; - private final String sKey; - private final int iKey; - - public CallbackNBTTagString(NBTTagCompound tag, String key) - { - this.tag = tag; - this.sKey = key; - this.iKey = -1; - } - - public CallbackNBTTagString(NBTTagList tag, int key) - { - this.tag = tag; - this.sKey = null; - this.iKey = key; - } - - @Override - public void setValue(String value) - { - if(tag.getId() == 10) - { - ((NBTTagCompound)tag).setString(sKey, value); - } else - { - ((NBTTagList)tag).set(iKey, new NBTTagString(value)); - } +public class CallbackNBTTagString implements ICallback { + private final NBTBase tag; + private final String sKey; + private final int iKey; + + public CallbackNBTTagString(NBTTagCompound tag, String key) { + this.tag = tag; + this.sKey = key; + this.iKey = -1; + } + + public CallbackNBTTagString(NBTTagList tag, int key) { + this.tag = tag; + this.sKey = null; + this.iKey = key; + } + + @Override + public void setValue(String value) { + if (tag.getId() == 10) { + ((NBTTagCompound) tag).setString(sKey, value); + } else { + ((NBTTagList) tag).set(iKey, new NBTTagString(value)); } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterNumber.java b/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterNumber.java index 75e8a1c6e..a28ab0949 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterNumber.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterNumber.java @@ -3,112 +3,84 @@ import betterquesting.api2.client.gui.controls.IFieldFilter; // Generic number filter -public abstract class FieldFilterNumber implements IFieldFilter -{ - public static final FieldFilterNumber DOUBLE = new FieldFilterNumber(true) - { - @Override - public Double parseValue(String input) - { - try - { - return Double.parseDouble(input); - } catch(Exception e) - { - return 0D; - } - } - }; - public static final FieldFilterNumber FLOAT = new FieldFilterNumber(true) - { - @Override - public Float parseValue(String input) - { - try - { - return Float.parseFloat(input); - } catch(Exception e) - { - return 0F; - } - } - }; - - public static final FieldFilterNumber LONG = new FieldFilterNumber(false) - { - @Override - public Long parseValue(String input) - { - try - { - return Long.parseLong(input); - } catch(Exception e) - { - return 0L; - } - } - }; - public static final FieldFilterNumber INT = new FieldFilterNumber(false) - { - @Override - public Integer parseValue(String input) - { - try - { - return Integer.parseInt(input); - } catch(Exception e) - { - return 0; - } - } - }; - public static final FieldFilterNumber SHORT = new FieldFilterNumber(false) - { - @Override - public Short parseValue(String input) - { - try - { - return Short.parseShort(input); - } catch(Exception e) - { - return 0; - } - } - }; - public static final FieldFilterNumber BYTE = new FieldFilterNumber(false) - { - @Override - public Byte parseValue(String input) - { - try - { - return Byte.parseByte(input); - } catch(Exception e) - { - return 0; - } - } - }; - - // === CLASS START === - - private final boolean floating; - - public FieldFilterNumber(boolean floating) - { - this.floating = floating; +public abstract class FieldFilterNumber implements IFieldFilter { + public static final FieldFilterNumber DOUBLE = new FieldFilterNumber(true) { + @Override + public Double parseValue(String input) { + try { + return Double.parseDouble(input); + } catch (Exception e) { + return 0D; + } + } + }; + public static final FieldFilterNumber FLOAT = new FieldFilterNumber(true) { + @Override + public Float parseValue(String input) { + try { + return Float.parseFloat(input); + } catch (Exception e) { + return 0F; + } } - + }; + + public static final FieldFilterNumber LONG = new FieldFilterNumber(false) { @Override - public boolean isValid(String input) - { - return floating ? !input.matches("[^.0123456789-]") : !input.matches("[^0123456789-]"); + public Long parseValue(String input) { + try { + return Long.parseLong(input); + } catch (Exception e) { + return 0L; + } } - + }; + public static final FieldFilterNumber INT = new FieldFilterNumber(false) { @Override - public String filterText(String input) - { - return floating ? input.replaceAll("[^.0123456789-]", "") : input.replaceAll("[^0123456789-]", ""); + public Integer parseValue(String input) { + try { + return Integer.parseInt(input); + } catch (Exception e) { + return 0; + } } + }; + public static final FieldFilterNumber SHORT = new FieldFilterNumber(false) { + @Override + public Short parseValue(String input) { + try { + return Short.parseShort(input); + } catch (Exception e) { + return 0; + } + } + }; + public static final FieldFilterNumber BYTE = new FieldFilterNumber(false) { + @Override + public Byte parseValue(String input) { + try { + return Byte.parseByte(input); + } catch (Exception e) { + return 0; + } + } + }; + + // === CLASS START === + + private final boolean floating; + + public FieldFilterNumber(boolean floating) { + this.floating = floating; + } + + @Override + public boolean isValid(String input) { + return floating ? !input.matches("[^.0123456789-]") : !input.matches("[^0123456789-]"); + } + + @Override + public String filterText(String input) { + return floating ? input.replaceAll("[^.0123456789-]", "") : input.replaceAll("[^0123456789-]", ""); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterString.java b/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterString.java index 7d301af8c..42d9f9444 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterString.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/filters/FieldFilterString.java @@ -2,42 +2,35 @@ import betterquesting.api2.client.gui.controls.IFieldFilter; -public class FieldFilterString implements IFieldFilter -{ - public static final FieldFilterString INSTANCE = new FieldFilterString(null); - - private final String regex; - - public FieldFilterString(String regex) - { - this.regex = null; - } - - @Override - public boolean isValid(String input) - { - if(regex != null) - { - return input.matches(regex); - } - - return true; - } - - @Override - public String filterText(String input) - { - if(regex != null) - { - return input.replaceAll(regex, ""); - } - - return input; +public class FieldFilterString implements IFieldFilter { + public static final FieldFilterString INSTANCE = new FieldFilterString(null); + + private final String regex; + + public FieldFilterString(String regex) { + this.regex = null; + } + + @Override + public boolean isValid(String input) { + if (regex != null) { + return input.matches(regex); } - - @Override - public String parseValue(String input) - { - return input; + + return true; + } + + @Override + public String filterText(String input) { + if (regex != null) { + return input.replaceAll(regex, ""); } + + return input; + } + + @Override + public String parseValue(String input) { + return input; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java b/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java index 61a4944e0..f04170f20 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java @@ -4,83 +4,74 @@ import betterquesting.api2.client.gui.controls.IValueIO; import net.minecraft.util.math.MathHelper; -public class FloatSimpleIO implements IValueIO -{ - private boolean lerp = false; - private float lerpSpd = 0.02F; - - private boolean clamp = true; - private final float min; - private final float max; - - protected float v; // Target value - protected float s; // Start value - private long t; // Start time - - public FloatSimpleIO() - { - this(0F, 0F, 1F); - } - - public FloatSimpleIO(float startVal, float min, float max) - { - this.v = startVal; - this.s = startVal; - this.min = min; - this.max = max; - this.t = System.currentTimeMillis(); // Added precaution for lerp math - } - - public FloatSimpleIO setClamp(boolean enable) - { - this.clamp = enable; - return this; - } - - public FloatSimpleIO setLerp(boolean enable, float speed) - { - this.lerp = enable; - this.lerpSpd = speed; - return this; - } - - @Override - public Float readValue() - { - if(lerp && s != v) - { - if(Math.abs(s - v) < 0.001F) - { - s = v; - return v; - } - - long d = System.currentTimeMillis() - t; - s = RenderUtils.lerpFloat(s, v, (float)MathHelper.clamp(d * (double)lerpSpd, 0D, 1D)); - if(d > 0) t = System.currentTimeMillis(); // Required if read out more than once in 1ms - return s; - } - +public class FloatSimpleIO implements IValueIO { + private boolean lerp = false; + private float lerpSpd = 0.02F; + + private boolean clamp = true; + private final float min; + private final float max; + + protected float v; // Target value + protected float s; // Start value + private long t; // Start time + + public FloatSimpleIO() { + this(0F, 0F, 1F); + } + + public FloatSimpleIO(float startVal, float min, float max) { + this.v = startVal; + this.s = startVal; + this.min = min; + this.max = max; + this.t = System.currentTimeMillis(); // Added precaution for lerp math + } + + public FloatSimpleIO setClamp(boolean enable) { + this.clamp = enable; + return this; + } + + public FloatSimpleIO setLerp(boolean enable, float speed) { + this.lerp = enable; + this.lerpSpd = speed; + return this; + } + + @Override + public Float readValue() { + if (lerp && s != v) { + if (Math.abs(s - v) < 0.001F) { + s = v; return v; + } + + long d = System.currentTimeMillis() - t; + s = RenderUtils.lerpFloat(s, v, (float) MathHelper.clamp(d * (double) lerpSpd, 0D, 1D)); + if (d > 0) { + t = System.currentTimeMillis(); // Required if read out more than once in 1ms + } + return s; } - - @Override - public void writeValue(Float value) - { - if(s == v) t = System.currentTimeMillis(); - this.v = clamp ? MathHelper.clamp(value, min, max) : value; - } - - @Override - public Float readValueRaw() - { - return this.v; - } - - @Override - public void writeValueRaw(Float value) - { - this.v = clamp ? MathHelper.clamp(value, min, max) : value; - this.s = v; - } + + return v; + } + + @Override + public void writeValue(Float value) { + if (s == v) { t = System.currentTimeMillis(); } + this.v = clamp ? MathHelper.clamp(value, min, max) : value; + } + + @Override + public Float readValueRaw() { + return this.v; + } + + @Override + public void writeValueRaw(Float value) { + this.v = clamp ? MathHelper.clamp(value, min, max) : value; + this.s = v; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java b/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java index 00740c829..91d2678d8 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java @@ -1,40 +1,35 @@ package betterquesting.api2.client.gui.controls.io; import betterquesting.api2.client.gui.controls.IValueIO; +import betterquesting.core.BetterQuesting; import java.util.concurrent.Callable; -public class ValueFuncIO implements IValueIO -{ - private final Callable v; - - public ValueFuncIO(Callable value) - { - this.v = value; - } - - @Override - public T readValue() - { - try - { - return v.call(); - } catch(Exception e) - { - e.printStackTrace(); - return null; - } - } - - @Override - public void writeValue(T value){} - - @Override - public T readValueRaw() - { - return readValue(); +public class ValueFuncIO implements IValueIO { + private final Callable v; + + public ValueFuncIO(Callable value) { + this.v = value; + } + + @Override + public T readValue() { + try { + return v.call(); + } catch (Exception e) { + BetterQuesting.logger.warn(e); + return null; } - - @Override - public void writeValueRaw(T value){} + } + + @Override + public void writeValue(T value) { } + + @Override + public T readValueRaw() { + return readValue(); + } + + @Override + public void writeValueRaw(T value) { } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/CommonPanelEvents.java b/src/main/java/betterquesting/api2/client/gui/events/CommonPanelEvents.java index 6b6e9d92b..83b968948 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/CommonPanelEvents.java +++ b/src/main/java/betterquesting/api2/client/gui/events/CommonPanelEvents.java @@ -8,12 +8,10 @@ import net.minecraftforge.fml.relauncher.SideOnly; @EventBusSubscriber -public class CommonPanelEvents -{ - @SubscribeEvent - @SideOnly(Side.CLIENT) - public static void OnQuestCompleted(QuestEvent event) - { - PEventBroadcaster.INSTANCE.postEvent(new PEventQuest(event.getQuestIDs())); - } +public class CommonPanelEvents { + @SubscribeEvent + @SideOnly(Side.CLIENT) + public static void OnQuestCompleted(QuestEvent event) { + PEventBroadcaster.INSTANCE.postEvent(new PEventQuest(event.getQuestIDs())); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/IPEventListener.java b/src/main/java/betterquesting/api2/client/gui/events/IPEventListener.java index 375d09129..c5dfe334e 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/IPEventListener.java +++ b/src/main/java/betterquesting/api2/client/gui/events/IPEventListener.java @@ -1,7 +1,6 @@ package betterquesting.api2.client.gui.events; @Deprecated // Just use lambdas FFS -public interface IPEventListener -{ - void onPanelEvent(PanelEvent event); +public interface IPEventListener { + void onPanelEvent(PanelEvent event); } diff --git a/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java b/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java index c76ce5447..b9a9b936b 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java +++ b/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java @@ -12,61 +12,52 @@ Provides a means of broadcasting various things to and around the currently open GUI. Useful if your panel/canvas is contained within a screen you're not in control of but still needs to respond to events */ -public class PEventBroadcaster -{ - public static PEventBroadcaster INSTANCE = new PEventBroadcaster(); - - private final HashMap, PEventEntry> entryList = new HashMap<>(); - - @Deprecated - public void register(@Nonnull IPEventListener l, @Nonnull Class type) - { - register((Consumer)l::onPanelEvent, type); - } - - public void register(@Nonnull Consumer consumer, @Nonnull Class type) - { - PEventEntry pe = entryList.computeIfAbsent(type, PEventEntry::new); - pe.registerListener(consumer); - } - - public void register(@Nonnull Consumer consumer, @Nonnull Iterable> type) - { - type.forEach((c) -> { - PEventEntry pe = entryList.computeIfAbsent(c, PEventEntry::new); - pe.registerListener(consumer); - }); - } - - @Deprecated - public void unregister(IPEventListener l) - { - unregister((Consumer)l::onPanelEvent); - } - - public void unregister(@Nonnull Consumer consumer) - { - entryList.values().forEach((value) -> value.unregisterListener(consumer)); +public class PEventBroadcaster { + public static final PEventBroadcaster INSTANCE = new PEventBroadcaster(); + + private final HashMap, PEventEntry> entryList = new HashMap<>(); + + @Deprecated + public void register(@Nonnull IPEventListener l, @Nonnull Class type) { + register((Consumer) l::onPanelEvent, type); + } + + public void register(@Nonnull Consumer consumer, @Nonnull Class type) { + PEventEntry pe = entryList.computeIfAbsent(type, PEventEntry::new); + pe.registerListener(consumer); + } + + public void register(@Nonnull Consumer consumer, @Nonnull Iterable> type) { + type.forEach((c) -> { + PEventEntry pe = entryList.computeIfAbsent(c, PEventEntry::new); + pe.registerListener(consumer); + }); + } + + @Deprecated + public void unregister(IPEventListener l) { + unregister((Consumer) l::onPanelEvent); + } + + public void unregister(@Nonnull Consumer consumer) { + entryList.values().forEach((value) -> value.unregisterListener(consumer)); + } + + public boolean postEvent(@Nonnull PanelEvent event) { + // We cycle over all entries incase we need to fire events for parent class types + for (Entry, PEventEntry> e : entryList.entrySet()) { + if (!e.getKey().isAssignableFrom(event.getClass())) { continue; } + e.getValue().fire(event); } - - public boolean postEvent(@Nonnull PanelEvent event) - { - // We cycle over all entries incase we need to fire events for parent class types - for(Entry, PEventEntry> e : entryList.entrySet()) - { - if(!e.getKey().isAssignableFrom(event.getClass())) continue; - e.getValue().fire(event); - } - - return event.canCancel() && event.isCancelled(); - } - - /** - * Clears event listeners whenever a new GUI loads. If you must have cross GUI communication either handle this yourself or re-register the relevant listeners. - */ - @SubscribeEvent - public void onGuiOpened(GuiOpenEvent event) - { - entryList.clear(); - } + + return event.canCancel() && event.isCancelled(); + } + + /** + * Clears event listeners whenever a new GUI loads. If you must have cross GUI communication either handle this yourself or re-register the relevant listeners. + */ + @SubscribeEvent + public void onGuiOpened(GuiOpenEvent event) { + entryList.clear(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java b/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java index e1f46b09e..cdd764367 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java +++ b/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java @@ -5,30 +5,25 @@ import java.util.List; import java.util.function.Consumer; -public class PEventEntry -{ - private final List> listeners = new ArrayList<>(); - private final Class cType; - - public PEventEntry(Class type) - { - this.cType = type; - } - - public void registerListener(@Nonnull Consumer consumer) - { - if(listeners.contains(consumer)) return; - listeners.add(consumer); - } - - public void unregisterListener(@Nonnull Consumer consumer) - { - listeners.remove(consumer); - } - - public void fire(@Nonnull PanelEvent event) - { - if(!cType.isAssignableFrom(event.getClass())) return; - listeners.forEach((l) -> l.accept(event)); - } +public class PEventEntry { + private final List> listeners = new ArrayList<>(); + private final Class cType; + + public PEventEntry(Class type) { + this.cType = type; + } + + public void registerListener(@Nonnull Consumer consumer) { + if (listeners.contains(consumer)) { return; } + listeners.add(consumer); + } + + public void unregisterListener(@Nonnull Consumer consumer) { + listeners.remove(consumer); + } + + public void fire(@Nonnull PanelEvent event) { + if (!cType.isAssignableFrom(event.getClass())) { return; } + listeners.forEach((l) -> l.accept(event)); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java b/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java index 7a55f8cdc..263f2578a 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java +++ b/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java @@ -1,23 +1,19 @@ package betterquesting.api2.client.gui.events; -public abstract class PanelEvent -{ - private boolean cancelled = false; - - public abstract boolean canCancel(); - - public boolean isCancelled() - { - return this.cancelled; - } - - public void setCancelled(boolean state) - { - if(!this.canCancel()) - { - throw new IllegalStateException("Attempted to cancel a non cancellable panel event"); - } - - this.cancelled = state; - } +public abstract class PanelEvent { + private boolean cancelled = false; + + public abstract boolean canCancel(); + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean state) { + if (!this.canCancel()) { + throw new IllegalStateException("Attempted to cancel a non cancellable panel event"); + } + + this.cancelled = state; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java b/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java index 41a921e13..973e07dab 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java +++ b/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java @@ -4,23 +4,19 @@ import betterquesting.api2.client.gui.events.PanelEvent; // You don't really need to use this for every button on a GUI. Only the ones you wish to expose for expansions -public class PEventButton extends PanelEvent -{ - private final IPanelButton btn; - - public PEventButton(IPanelButton btn) - { - this.btn = btn; - } - - public IPanelButton getButton() - { - return this.btn; - } - - @Override - public boolean canCancel() - { - return true; - } +public class PEventButton extends PanelEvent { + private final IPanelButton btn; + + public PEventButton(IPanelButton btn) { + this.btn = btn; + } + + public IPanelButton getButton() { + return this.btn; + } + + @Override + public boolean canCancel() { + return true; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java b/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java index ddd6c11df..7f08f940b 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java +++ b/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java @@ -8,28 +8,23 @@ import java.util.TreeSet; // Use whenever one or more parties change -public class PEventParty extends PanelEvent -{ - private final Set partyIDs; - - public PEventParty(int partyID) - { - this.partyIDs = Collections.singleton(partyID); - } - - public PEventParty(Collection partyIDs) - { - this.partyIDs = Collections.unmodifiableSet(new TreeSet<>(partyIDs)); - } - - public Set getPartyIDs() - { - return this.partyIDs; - } - - @Override - public boolean canCancel() - { - return false; - } +public class PEventParty extends PanelEvent { + private final Set partyIDs; + + public PEventParty(int partyID) { + this.partyIDs = Collections.singleton(partyID); + } + + public PEventParty(Collection partyIDs) { + this.partyIDs = Collections.unmodifiableSet(new TreeSet<>(partyIDs)); + } + + public Set getPartyIDs() { + return this.partyIDs; + } + + @Override + public boolean canCancel() { + return false; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java b/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java index b4afbfec5..8e9efd326 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java +++ b/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java @@ -8,28 +8,23 @@ import java.util.TreeSet; // Use whenever one or more quests change -public class PEventQuest extends PanelEvent -{ - private final Set questIDs; - - public PEventQuest(int questID) - { - this.questIDs = Collections.singleton(questID); - } - - public PEventQuest(Collection questIDs) - { - this.questIDs = Collections.unmodifiableSet(new TreeSet<>(questIDs)); - } - - public Set getQuestID() - { - return this.questIDs; - } - - @Override - public boolean canCancel() - { - return false; - } +public class PEventQuest extends PanelEvent { + private final Set questIDs; + + public PEventQuest(int questID) { + this.questIDs = Collections.singleton(questID); + } + + public PEventQuest(Collection questIDs) { + this.questIDs = Collections.unmodifiableSet(new TreeSet<>(questIDs)); + } + + public Set getQuestID() { + return this.questIDs; + } + + @Override + public boolean canCancel() { + return false; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java b/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java index 0ec7b1819..6897d79f6 100644 --- a/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java +++ b/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java @@ -4,32 +4,28 @@ import java.util.List; // Could probably be more refined and fleshed out in functionality at a later date but for now this is just to decouple it from the GUIs -public class HelpRegistry -{ - public static final HelpRegistry INSTANCE = new HelpRegistry(); - - private final List topicList = new ArrayList<>(); - - public HelpRegistry() - { - registerTopic(new HelpTopic("betterquesting.btn.help1", "betterquesting.help.page1")); - registerTopic(new HelpTopic("betterquesting.btn.help2", "betterquesting.help.page2")); - registerTopic(new HelpTopic("betterquesting.btn.help3", "betterquesting.help.page3")); - registerTopic(new HelpTopic("betterquesting.btn.help4", "betterquesting.help.page4")); - registerTopic(new HelpTopic("betterquesting.btn.help5", "betterquesting.help.page5")); - registerTopic(new HelpTopic("betterquesting.btn.help6", "betterquesting.help.page6")); - registerTopic(new HelpTopic("betterquesting.btn.help7", "betterquesting.help.page7")); - registerTopic(new HelpTopic("betterquesting.btn.help8", "betterquesting.help.page8")); - } - - public boolean registerTopic(HelpTopic topic) - { - if(topicList.contains(topic)) return false; - return topicList.add(topic); - } - - public HelpTopic[] getTopics() - { - return topicList.toArray(new HelpTopic[0]); - } +public class HelpRegistry { + public static final HelpRegistry INSTANCE = new HelpRegistry(); + + private final List topicList = new ArrayList<>(); + + public HelpRegistry() { + registerTopic(new HelpTopic("betterquesting.btn.help1", "betterquesting.help.page1")); + registerTopic(new HelpTopic("betterquesting.btn.help2", "betterquesting.help.page2")); + registerTopic(new HelpTopic("betterquesting.btn.help3", "betterquesting.help.page3")); + registerTopic(new HelpTopic("betterquesting.btn.help4", "betterquesting.help.page4")); + registerTopic(new HelpTopic("betterquesting.btn.help5", "betterquesting.help.page5")); + registerTopic(new HelpTopic("betterquesting.btn.help6", "betterquesting.help.page6")); + registerTopic(new HelpTopic("betterquesting.btn.help7", "betterquesting.help.page7")); + registerTopic(new HelpTopic("betterquesting.btn.help8", "betterquesting.help.page8")); + } + + public boolean registerTopic(HelpTopic topic) { + if (topicList.contains(topic)) { return false; } + return topicList.add(topic); + } + + public HelpTopic[] getTopics() { + return topicList.toArray(new HelpTopic[0]); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java b/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java index a70301e5e..b32559e6a 100644 --- a/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java +++ b/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java @@ -4,34 +4,29 @@ import javax.annotation.Nonnull; -public class HelpTopic -{ - private final String title; - private final String description; - - public HelpTopic(@Nonnull String title, @Nonnull String description) - { - this.title = title; - this.description = description; - } - - public String getTitle() - { - return QuestTranslation.translate(title); - } - - public String getDescription() - { - return QuestTranslation.translate(description); - } - - @Override - public boolean equals(Object o) - { - if(!(o instanceof HelpTopic)) return false; - - HelpTopic ht = (HelpTopic)o; - - return ht.title.equals(this.title) && ht.description.equals(this.description); - } +public class HelpTopic { + private final String title; + private final String description; + + public HelpTopic(@Nonnull String title, @Nonnull String description) { + this.title = title; + this.description = description; + } + + public String getTitle() { + return QuestTranslation.translate(title); + } + + public String getDescription() { + return QuestTranslation.translate(description); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof HelpTopic)) { return false; } + + HelpTopic ht = (HelpTopic) o; + + return ht.title.equals(this.title) && ht.description.equals(this.description); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/ComparatorGuiDepth.java b/src/main/java/betterquesting/api2/client/gui/misc/ComparatorGuiDepth.java index d32f2c49d..076fb8334 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/ComparatorGuiDepth.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/ComparatorGuiDepth.java @@ -1,15 +1,14 @@ package betterquesting.api2.client.gui.misc; -import java.util.Comparator; import betterquesting.api2.client.gui.panels.IGuiPanel; -public class ComparatorGuiDepth implements Comparator -{ - public static ComparatorGuiDepth INSTANCE = new ComparatorGuiDepth(); - - @Override - public int compare(IGuiPanel o1, IGuiPanel o2) - { - return o1.getTransform().compareTo(o2.getTransform()); - } +import java.util.Comparator; + +public class ComparatorGuiDepth implements Comparator { + public static final ComparatorGuiDepth INSTANCE = new ComparatorGuiDepth(); + + @Override + public int compare(IGuiPanel o1, IGuiPanel o2) { + return o1.getTransform().compareTo(o2.getTransform()); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java index d4e232380..51434f615 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java @@ -1,101 +1,91 @@ package betterquesting.api2.client.gui.misc; -import java.nio.FloatBuffer; import org.lwjgl.util.vector.ReadableVector4f; import org.lwjgl.util.vector.Vector; import org.lwjgl.util.vector.Vector4f; +import java.nio.FloatBuffer; + /** * Provides pre-made anchor points for GUIs with functions to quickly create new ones */ -public class GuiAlign -{ - public static final ReadableVector4f FULL_BOX = new ImmutableVec4f(0F, 0F, 1F, 1F); - - public static final ReadableVector4f TOP_LEFT = new ImmutableVec4f(0F, 0F, 0F, 0F); - public static final ReadableVector4f TOP_CENTER = new ImmutableVec4f(0.5F, 0F, 0.5F, 0F); - public static final ReadableVector4f TOP_RIGHT = new ImmutableVec4f(1F, 0F, 1F, 0F); - public static final ReadableVector4f TOP_EDGE = new ImmutableVec4f(0F, 0F, 1F, 0F); - - public static final ReadableVector4f MID_LEFT = new ImmutableVec4f(0F, 0.5F, 0F, 0.5F); - public static final ReadableVector4f MID_CENTER = new ImmutableVec4f(0.5F, 0.5F, 0.5F, 0.5F); - public static final ReadableVector4f MID_RIGHT = new ImmutableVec4f(1F, 0.5F, 1F, 0.5F); - - public static final ReadableVector4f BOTTOM_LEFT = new ImmutableVec4f(0F, 1F, 0F, 1F); - public static final ReadableVector4f BOTTOM_CENTER = new ImmutableVec4f(0.5F, 1F, 0.5F, 1F); - public static final ReadableVector4f BOTTOM_RIGHT = new ImmutableVec4f(1F, 1F, 1F, 1F); - public static final ReadableVector4f BOTTOM_EDGE = new ImmutableVec4f(0F, 1F, 1F, 1F); - - public static final ReadableVector4f HALF_LEFT = new ImmutableVec4f(0F, 0F, 0.5F, 1F); - public static final ReadableVector4f HALF_RIGHT = new ImmutableVec4f(0.5F, 0F, 1F, 1F); - public static final ReadableVector4f HALF_TOP = new ImmutableVec4f(0F, 0F, 1F, 0.5F); - public static final ReadableVector4f HALF_BOTTOM = new ImmutableVec4f(0F, 0.5F, 1F, 1F); - - public static final ReadableVector4f LEFT_EDGE = new ImmutableVec4f(0F, 0F, 0F, 1F); - public static final ReadableVector4f RIGHT_EDGE = new ImmutableVec4f(1F, 0F, 1F, 1F); - - /** - * Takes two readable Vector4f points and merges them in a single Vector4f anchor region - */ - public static Vector4f quickAnchor(ReadableVector4f v1, ReadableVector4f v2) - { - float x1 = Math.min(v1.getX(), v2.getX()); - float y1 = Math.min(v1.getY(), v2.getY()); - float x2 = Math.max(v1.getZ(), v2.getZ()); - float y2 = Math.max(v1.getW(), v2.getW()); - - return new Vector4f(x1, y1, x2, y2); - } - - private static class ImmutableVec4f implements ReadableVector4f - { - private final ReadableVector4f v4f; - - public ImmutableVec4f(float x, float y, float z, float w) - { - this.v4f = new Vector4f(x, y, z, w); - } - - @Override - public float getZ() - { - return v4f.getZ(); - } - - @Override - public float getX() - { - return v4f.getX(); - } - - @Override - public float getY() - { - return v4f.getY(); - } - - @Override - public float length() - { - return v4f.length(); - } - - @Override - public float lengthSquared() - { - return v4f.lengthSquared(); - } - - @Override - public Vector store(FloatBuffer buf) - { - return v4f.store(buf); - } - - @Override - public float getW() - { - return v4f.getW(); - } - } +public class GuiAlign { + public static final ReadableVector4f FULL_BOX = new ImmutableVec4f(0F, 0F, 1F, 1F); + + public static final ReadableVector4f TOP_LEFT = new ImmutableVec4f(0F, 0F, 0F, 0F); + public static final ReadableVector4f TOP_CENTER = new ImmutableVec4f(0.5F, 0F, 0.5F, 0F); + public static final ReadableVector4f TOP_RIGHT = new ImmutableVec4f(1F, 0F, 1F, 0F); + public static final ReadableVector4f TOP_EDGE = new ImmutableVec4f(0F, 0F, 1F, 0F); + + public static final ReadableVector4f MID_LEFT = new ImmutableVec4f(0F, 0.5F, 0F, 0.5F); + public static final ReadableVector4f MID_CENTER = new ImmutableVec4f(0.5F, 0.5F, 0.5F, 0.5F); + public static final ReadableVector4f MID_RIGHT = new ImmutableVec4f(1F, 0.5F, 1F, 0.5F); + + public static final ReadableVector4f BOTTOM_LEFT = new ImmutableVec4f(0F, 1F, 0F, 1F); + public static final ReadableVector4f BOTTOM_CENTER = new ImmutableVec4f(0.5F, 1F, 0.5F, 1F); + public static final ReadableVector4f BOTTOM_RIGHT = new ImmutableVec4f(1F, 1F, 1F, 1F); + public static final ReadableVector4f BOTTOM_EDGE = new ImmutableVec4f(0F, 1F, 1F, 1F); + + public static final ReadableVector4f HALF_LEFT = new ImmutableVec4f(0F, 0F, 0.5F, 1F); + public static final ReadableVector4f HALF_RIGHT = new ImmutableVec4f(0.5F, 0F, 1F, 1F); + public static final ReadableVector4f HALF_TOP = new ImmutableVec4f(0F, 0F, 1F, 0.5F); + public static final ReadableVector4f HALF_BOTTOM = new ImmutableVec4f(0F, 0.5F, 1F, 1F); + + public static final ReadableVector4f LEFT_EDGE = new ImmutableVec4f(0F, 0F, 0F, 1F); + public static final ReadableVector4f RIGHT_EDGE = new ImmutableVec4f(1F, 0F, 1F, 1F); + + /** + * Takes two readable Vector4f points and merges them in a single Vector4f anchor region + */ + public static Vector4f quickAnchor(ReadableVector4f v1, ReadableVector4f v2) { + float x1 = Math.min(v1.getX(), v2.getX()); + float y1 = Math.min(v1.getY(), v2.getY()); + float x2 = Math.max(v1.getZ(), v2.getZ()); + float y2 = Math.max(v1.getW(), v2.getW()); + + return new Vector4f(x1, y1, x2, y2); + } + + private static class ImmutableVec4f implements ReadableVector4f { + private final ReadableVector4f v4f; + + public ImmutableVec4f(float x, float y, float z, float w) { + this.v4f = new Vector4f(x, y, z, w); + } + + @Override + public float getZ() { + return v4f.getZ(); + } + + @Override + public float getX() { + return v4f.getX(); + } + + @Override + public float getY() { + return v4f.getY(); + } + + @Override + public float length() { + return v4f.length(); + } + + @Override + public float lengthSquared() { + return v4f.lengthSquared(); + } + + @Override + public Vector store(FloatBuffer buf) { + return v4f.store(buf); + } + + @Override + public float getW() { + return v4f.getW(); + } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java index c0ce84378..41975a9c2 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java @@ -1,58 +1,48 @@ package betterquesting.api2.client.gui.misc; -public class GuiPadding -{ - public int l, t, r, b = 0; - - public GuiPadding() - { - this(0, 0, 0, 0); - } - - public GuiPadding(int left, int top, int right, int bottom) - { - this.setPadding(left, top, right, bottom); - } - - public GuiPadding copy() - { - return new GuiPadding(l, t, r, b); - } - - public GuiPadding setPadding(int left, int top, int right, int bottom) - { - this.l = left; - this.t = top; - - this.r = right; - this.b = bottom; - - return this; - } - - public int getLeft() - { - return l; - } - - public int getTop() - { - return t; - } - - public int getRight() - { - return r; - } - - public int getBottom() - { - return b; - } - - @Override - public String toString() - { - return getClass().getName() + "[left=" + l + ",top=" + t + ",right=" + r + ",bottom=" + b + "]"; - } +public class GuiPadding { + public int l, t, r, b = 0; + + public GuiPadding() { + this(0, 0, 0, 0); + } + + public GuiPadding(int left, int top, int right, int bottom) { + this.setPadding(left, top, right, bottom); + } + + public GuiPadding copy() { + return new GuiPadding(l, t, r, b); + } + + public GuiPadding setPadding(int left, int top, int right, int bottom) { + this.l = left; + this.t = top; + + this.r = right; + this.b = bottom; + + return this; + } + + public int getLeft() { + return l; + } + + public int getTop() { + return t; + } + + public int getRight() { + return r; + } + + public int getBottom() { + return b; + } + + @Override + public String toString() { + return getClass().getName() + "[left=" + l + ",top=" + t + ",right=" + r + ",bottom=" + b + "]"; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java index d41f27a4d..19c2371e4 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java @@ -4,109 +4,101 @@ import javax.annotation.Nonnull; -public class GuiRectLerp implements IGuiRect -{ - private IGuiRect startRect; - private IGuiRect targetRect; - private long duration = 200L; - private long et; - - private final ProxyRect pxRect; - - public GuiRectLerp(@Nonnull IGuiRect start) - { - this.startRect = start; - this.targetRect = start; - this.pxRect = new ProxyRect(start); - this.et = System.currentTimeMillis(); - } - - public void lerpTo(@Nonnull IGuiRect target, long time) - { - if(time <= 0) return; - - this.targetRect = target; - this.duration = time; - this.et = System.currentTimeMillis(); - this.pxRect.changeReference(target); - } - - public void snapTo(@Nonnull IGuiRect target) - { - this.startRect = target; - this.targetRect = target; - this.et = System.currentTimeMillis(); - this.pxRect.changeReference(target); - } - - // Allows other transforms to snap to new destinations even if the targetRect variable changes instance - public IGuiRect getProxyRect() - { - return pxRect; - } - - public boolean isIdle() - { - if(startRect == targetRect) return true; - if(System.currentTimeMillis() - et >= duration) - { - this.startRect = this.targetRect; - return true; - } - return false; - } - - @Override - public int getX() - { - return isIdle() ? targetRect.getX() : (int)Math.round(RenderUtils.lerpDouble((double)startRect.getX(), (double)targetRect.getX(), (System.currentTimeMillis() - et) / (double)duration)); - } - - @Override - public int getY() - { - return isIdle() ? targetRect.getY() : (int)Math.round(RenderUtils.lerpDouble((double)startRect.getY(), (double)targetRect.getY(), (System.currentTimeMillis() - et) / (double)duration)); - } - - @Override - public int getWidth() - { - return isIdle() ? targetRect.getWidth() : (int)Math.round(RenderUtils.lerpDouble((double)startRect.getWidth(), (double)targetRect.getWidth(), (System.currentTimeMillis() - et) / (double)duration)); - } - - @Override - public int getHeight() - { - return isIdle() ? targetRect.getHeight() :(int)Math.round(RenderUtils.lerpDouble((double)startRect.getHeight(), (double)targetRect.getHeight(), (System.currentTimeMillis() - et) / (double)duration)); - } - - @Override - public int getDepth() - { - return targetRect.getDepth(); - } - - @Override - public IGuiRect getParent() - { - return targetRect.getParent(); - } - - @Override - public void setParent(IGuiRect rect) - { - targetRect.setParent(rect); - } - - @Override - public boolean contains(int x, int y) - { - return targetRect.contains(x, y); - } - - @Override - public int compareTo(@Nonnull IGuiRect o) - { - return targetRect.compareTo(o); +public class GuiRectLerp implements IGuiRect { + private IGuiRect startRect; + private IGuiRect targetRect; + private long duration = 200L; + private long et; + + private final ProxyRect pxRect; + + public GuiRectLerp(@Nonnull IGuiRect start) { + this.startRect = start; + this.targetRect = start; + this.pxRect = new ProxyRect(start); + this.et = System.currentTimeMillis(); + } + + public void lerpTo(@Nonnull IGuiRect target, long time) { + if (time <= 0) { return; } + + this.targetRect = target; + this.duration = time; + this.et = System.currentTimeMillis(); + this.pxRect.changeReference(target); + } + + public void snapTo(@Nonnull IGuiRect target) { + this.startRect = target; + this.targetRect = target; + this.et = System.currentTimeMillis(); + this.pxRect.changeReference(target); + } + + // Allows other transforms to snap to new destinations even if the targetRect variable changes instance + public IGuiRect getProxyRect() { + return pxRect; + } + + public boolean isIdle() { + if (startRect == targetRect) { return true; } + if (System.currentTimeMillis() - et >= duration) { + this.startRect = this.targetRect; + return true; } + return false; + } + + @Override + public int getX() { + return isIdle() ? targetRect.getX() : (int) Math.round( + RenderUtils.lerpDouble(startRect.getX(), targetRect.getX(), + (System.currentTimeMillis() - et) / (double) duration)); + } + + @Override + public int getY() { + return isIdle() ? targetRect.getY() : (int) Math.round( + RenderUtils.lerpDouble(startRect.getY(), targetRect.getY(), + (System.currentTimeMillis() - et) / (double) duration)); + } + + @Override + public int getWidth() { + return isIdle() ? targetRect.getWidth() : (int) Math.round( + RenderUtils.lerpDouble(startRect.getWidth(), targetRect.getWidth(), + (System.currentTimeMillis() - et) / (double) duration)); + } + + @Override + public int getHeight() { + return isIdle() ? targetRect.getHeight() : (int) Math.round( + RenderUtils.lerpDouble(startRect.getHeight(), targetRect.getHeight(), + (System.currentTimeMillis() - et) / (double) duration)); + } + + @Override + public int getDepth() { + return targetRect.getDepth(); + } + + @Override + public IGuiRect getParent() { + return targetRect.getParent(); + } + + @Override + public void setParent(IGuiRect rect) { + targetRect.setParent(rect); + } + + @Override + public boolean contains(int x, int y) { + return targetRect.contains(x, y); + } + + @Override + public int compareTo(@Nonnull IGuiRect o) { + return targetRect.compareTo(o); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java index e8f84f029..6cd26cb18 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java @@ -2,82 +2,74 @@ import javax.annotation.Nonnull; -public class GuiRectangle implements IGuiRect -{ - public int x, y, w, h, d; - private IGuiRect parent = null; - - public GuiRectangle(int x, int y, int w, int h) - { - this(x, y, w, h, 0); - } - - public GuiRectangle(int x, int y, int w, int h, int d) - { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - this.d = d; - } - - // Mainly to convert a GuiTransform to a fixed size version - public GuiRectangle(IGuiRect rect) - { - this(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(), rect.getDepth()); - } +public class GuiRectangle implements IGuiRect { + public int x; + public int y; + public int w; + public int h; + public final int d; + private IGuiRect parent = null; - @Override - public int getX() - { - return x + (parent == null? 0 : parent.getX()); - } + public GuiRectangle(int x, int y, int w, int h) { + this(x, y, w, h, 0); + } - @Override - public int getY() - { - return y + (parent == null? 0 : parent.getY()); - } + public GuiRectangle(int x, int y, int w, int h, int d) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + this.d = d; + } - @Override - public int getWidth() - { - return w; - } + // Mainly to convert a GuiTransform to a fixed size version + public GuiRectangle(IGuiRect rect) { + this(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(), rect.getDepth()); + } - @Override - public int getHeight() - { - return h; - } - - @Override - public int getDepth() - { - return d; - } - - @Override - public IGuiRect getParent() - { - return this.parent; - } - - @Override - public void setParent(IGuiRect rect) - { - this.parent = rect; - } - - @Override - public boolean contains(int x, int y) - { - int x1 = this.getX(); - int x2 = x1 + this.getWidth(); - int y1 = this.getY(); - int y2 = y1 + this.getHeight(); - return x >= x1 && x < x2 && y >= y1 && y < y2; - } + @Override + public int getX() { + return x + (parent == null ? 0 : parent.getX()); + } + + @Override + public int getY() { + return y + (parent == null ? 0 : parent.getY()); + } + + @Override + public int getWidth() { + return w; + } + + @Override + public int getHeight() { + return h; + } + + @Override + public int getDepth() { + return d; + } + + @Override + public IGuiRect getParent() { + return this.parent; + } + + @Override + public void setParent(IGuiRect rect) { + this.parent = rect; + } + + @Override + public boolean contains(int x, int y) { + int x1 = this.getX(); + int x2 = x1 + this.getWidth(); + int y1 = this.getY(); + int y2 = y1 + this.getHeight(); + return x >= x1 && x < x2 && y >= y1 && y < y2; + } /*@Override public void translate(int dx, int dy) @@ -85,10 +77,9 @@ public void translate(int dx, int dy) this.x += dx; this.y += dy; }*/ - - @Override - public int compareTo(@Nonnull IGuiRect o) - { - return (int)Math.signum(o.getDepth() - d); - } + + @Override + public int compareTo(@Nonnull IGuiRect o) { + return (int) Math.signum(o.getDepth() - d); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java index 6b9907486..a811bd0fe 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java @@ -3,129 +3,112 @@ import org.lwjgl.util.vector.ReadableVector4f; import org.lwjgl.util.vector.Vector4f; -public final class GuiTransform implements IGuiRect -{ - private IGuiRect parent; - private final Vector4f anchor; // TODO: Change to one that accounts for min-max dimensions - private final GuiPadding padding; - private int drawOrder; - - public GuiTransform() - { - this(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0); - } - - public GuiTransform(ReadableVector4f anchor) - { - this(anchor, new GuiPadding(0, 0, 0, 0), 0); - } - - public GuiTransform(ReadableVector4f anchor, int xOff, int yOff, int width, int height, int order) - { - this(new Vector4f(anchor.getX(), anchor.getY(), anchor.getX(), anchor.getY()), new GuiPadding(xOff, yOff, -xOff - width, -yOff - height), order); - } - - public GuiTransform(ReadableVector4f anchor, GuiPadding padding, int depth) - { - this(new Vector4f(anchor), padding, depth); - } - - public GuiTransform(Vector4f anchor, GuiPadding padding, int depth) - { - this.anchor = anchor; - this.padding = padding; - this.drawOrder = depth; - - float l = Math.min(anchor.x, anchor.z); - float r = Math.max(anchor.x, anchor.z); - float t = Math.min(anchor.y, anchor.w); - float b = Math.max(anchor.y, anchor.w); - - this.anchor.x = l; - this.anchor.y = t; - this.anchor.z = r; - this.anchor.w = b; - } - - public GuiTransform copy() - { - GuiTransform trans = new GuiTransform(new Vector4f(anchor), padding.copy(), drawOrder); - trans.setParent(this.parent); - return trans; - } - - public GuiPadding getPadding() - { - return this.padding; - } - - public Vector4f getAnchor() - { - return this.anchor; - } - - public void setDrawDepth(int order) - { - this.drawOrder = order; - } - - @Override - public int getX() - { - int i = parent == null ? 0 : (parent.getX() + (int)Math.ceil(parent.getWidth() * this.anchor.x)); - return i + padding.getLeft(); - } - - @Override - public int getY() - { - int i = parent == null ? 0 : (parent.getY() + (int)Math.ceil(parent.getHeight() * this.anchor.y)); - return i + padding.getTop(); - } - - @Override - public int getWidth() - { - int i = parent == null ? 0 : (int)Math.ceil(parent.getWidth() * (this.anchor.z - this.anchor.x)); - return i - (padding.getRight() + padding.getLeft()); - } - - @Override - public int getHeight() - { - int i = parent == null ? 0 : (int)Math.ceil(parent.getHeight() * (this.anchor.w - this.anchor.y)); - return i - (padding.getBottom() + padding.getTop()); - } - - @Override - public int getDepth() - { - return this.drawOrder; - } - - @Override - public IGuiRect getParent() - { - return parent; - } - - @Override - public void setParent(IGuiRect rect) - { - this.parent = rect; - } - - @Override - public boolean contains(int x3, int y3) - { - int x1 = getX(); - int y1 = getY(); - int w = getWidth(); - int h = getHeight(); - int x2 = x1 + w; - int y2 = y1 + h; - return x3 >= x1 && x3 < x2 && y3 >= y1 && y3 < y2; - } +public final class GuiTransform implements IGuiRect { + private IGuiRect parent; + private final Vector4f anchor; // TODO: Change to one that accounts for min-max dimensions + private final GuiPadding padding; + private int drawOrder; + + public GuiTransform() { + this(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0); + } + + public GuiTransform(ReadableVector4f anchor) { + this(anchor, new GuiPadding(0, 0, 0, 0), 0); + } + + public GuiTransform(ReadableVector4f anchor, int xOff, int yOff, int width, int height, int order) { + this(new Vector4f(anchor.getX(), anchor.getY(), anchor.getX(), anchor.getY()), + new GuiPadding(xOff, yOff, -xOff - width, -yOff - height), order); + } + + public GuiTransform(ReadableVector4f anchor, GuiPadding padding, int depth) { + this(new Vector4f(anchor), padding, depth); + } + + public GuiTransform(Vector4f anchor, GuiPadding padding, int depth) { + this.anchor = anchor; + this.padding = padding; + this.drawOrder = depth; + + float l = Math.min(anchor.x, anchor.z); + float r = Math.max(anchor.x, anchor.z); + float t = Math.min(anchor.y, anchor.w); + float b = Math.max(anchor.y, anchor.w); + + this.anchor.x = l; + this.anchor.y = t; + this.anchor.z = r; + this.anchor.w = b; + } + + public GuiTransform copy() { + GuiTransform trans = new GuiTransform(new Vector4f(anchor), padding.copy(), drawOrder); + trans.setParent(this.parent); + return trans; + } + + public GuiPadding getPadding() { + return this.padding; + } + + public Vector4f getAnchor() { + return this.anchor; + } + + public void setDrawDepth(int order) { + this.drawOrder = order; + } + + @Override + public int getX() { + int i = parent == null ? 0 : (parent.getX() + (int) Math.ceil(parent.getWidth() * this.anchor.x)); + return i + padding.getLeft(); + } + + @Override + public int getY() { + int i = parent == null ? 0 : (parent.getY() + (int) Math.ceil(parent.getHeight() * this.anchor.y)); + return i + padding.getTop(); + } + + @Override + public int getWidth() { + int i = parent == null ? 0 : (int) Math.ceil(parent.getWidth() * (this.anchor.z - this.anchor.x)); + return i - (padding.getRight() + padding.getLeft()); + } + + @Override + public int getHeight() { + int i = parent == null ? 0 : (int) Math.ceil(parent.getHeight() * (this.anchor.w - this.anchor.y)); + return i - (padding.getBottom() + padding.getTop()); + } + + @Override + public int getDepth() { + return this.drawOrder; + } + + @Override + public IGuiRect getParent() { + return parent; + } + + @Override + public void setParent(IGuiRect rect) { + this.parent = rect; + } + + @Override + public boolean contains(int x3, int y3) { + int x1 = getX(); + int y1 = getY(); + int w = getWidth(); + int h = getHeight(); + int x2 = x1 + w; + int y2 = y1 + h; + return x3 >= x1 && x3 < x2 && y3 >= y1 && y3 < y2; + } /*@Override public void translate(int x, int y) @@ -133,9 +116,8 @@ public void translate(int x, int y) this.padding.setPadding(padding.getLeft() + x, padding.getTop() + y, padding.getRight() - x, padding.getBottom() - y); }*/ - @Override - public int compareTo(IGuiRect o) - { - return (int)Math.signum(o.getDepth() - drawOrder); - } + @Override + public int compareTo(IGuiRect o) { + return (int) Math.signum(o.getDepth() - drawOrder); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/IGuiRect.java b/src/main/java/betterquesting/api2/client/gui/misc/IGuiRect.java index 2696b4b60..af62a29cb 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/IGuiRect.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/IGuiRect.java @@ -1,15 +1,19 @@ package betterquesting.api2.client.gui.misc; -public interface IGuiRect extends Comparable -{ - int getX(); - int getY(); - int getWidth(); - int getHeight(); - int getDepth(); - - IGuiRect getParent(); - void setParent(IGuiRect rect); - - boolean contains(int x, int y); +public interface IGuiRect extends Comparable { + int getX(); + + int getY(); + + int getWidth(); + + int getHeight(); + + int getDepth(); + + IGuiRect getParent(); + + void setParent(IGuiRect rect); + + boolean contains(int x, int y); } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java b/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java index 23d12e641..94c3055d8 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java @@ -3,71 +3,59 @@ import javax.annotation.Nonnull; // Used as a means to hotswap a rect without disturbing the parenting heirachy -public class ProxyRect implements IGuiRect -{ - private IGuiRect ref; - - public ProxyRect(IGuiRect refRect) - { - this.ref = refRect; - } - - public void changeReference(IGuiRect refRect) - { - this.ref = refRect; - } - - @Override - public int getX() - { - return ref != null ? ref.getX() : 0; - } - - @Override - public int getY() - { - return ref != null ? ref.getY() : 0; - } - - @Override - public int getWidth() - { - return ref != null ? ref.getWidth() : 0; - } - - @Override - public int getHeight() - { - return ref != null ? ref.getHeight() : 0; - } - - @Override - public int getDepth() - { - return ref != null ? ref.getDepth() : 0; - } - - @Override - public IGuiRect getParent() - { - return ref != null ? ref.getParent() : null; - } - - @Override - public void setParent(IGuiRect rect) - { - if(ref != null) ref.setParent(rect); - } - - @Override - public boolean contains(int x, int y) - { - return ref != null && ref.contains(x, y); - } - - @Override - public int compareTo(@Nonnull IGuiRect o) - { - return ref != null ? ref.compareTo(o) : 0; - } +public class ProxyRect implements IGuiRect { + private IGuiRect ref; + + public ProxyRect(IGuiRect refRect) { + this.ref = refRect; + } + + public void changeReference(IGuiRect refRect) { + this.ref = refRect; + } + + @Override + public int getX() { + return ref != null ? ref.getX() : 0; + } + + @Override + public int getY() { + return ref != null ? ref.getY() : 0; + } + + @Override + public int getWidth() { + return ref != null ? ref.getWidth() : 0; + } + + @Override + public int getHeight() { + return ref != null ? ref.getHeight() : 0; + } + + @Override + public int getDepth() { + return ref != null ? ref.getDepth() : 0; + } + + @Override + public IGuiRect getParent() { + return ref != null ? ref.getParent() : null; + } + + @Override + public void setParent(IGuiRect rect) { + if (ref != null) { ref.setParent(rect); } + } + + @Override + public boolean contains(int x, int y) { + return ref != null && ref.contains(x, y); + } + + @Override + public int compareTo(@Nonnull IGuiRect o) { + return ref != null ? ref.compareTo(o) : 0; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java b/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java index 7d7a7df6f..804aebd5e 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java @@ -8,193 +8,163 @@ import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; -public class CanvasEmpty implements IGuiCanvas -{ - private final List guiPanels = new CopyOnWriteArrayList<>(); - private final IGuiRect transform; - private boolean enabled = true; - - public CanvasEmpty(IGuiRect rect) - { - this.transform = rect; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Nonnull - @Override - public List getChildren() - { - return this.guiPanels; +public class CanvasEmpty implements IGuiCanvas { + private final List guiPanels = new CopyOnWriteArrayList<>(); + private final IGuiRect transform; + private boolean enabled = true; + + public CanvasEmpty(IGuiRect rect) { + this.transform = rect; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Nonnull + @Override + public List getChildren() { + return this.guiPanels; + } + + @Override + public void initPanel() { + this.guiPanels.clear(); + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + for (IGuiPanel entry : guiPanels) { + if (entry.isEnabled()) { + entry.drawPanel(mx, my, partialTick); + } + } + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseClick(mx, my, click)) { + used = true; + break; + } } - - @Override - public void initPanel() - { - this.guiPanels.clear(); - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - for(IGuiPanel entry : guiPanels) - { - if(entry.isEnabled()) - { - entry.drawPanel(mx, my, partialTick); - } - } - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseClick(mx, my, click)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseRelease(mx, my, click)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onKeyTyped(c, keycode)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public List getTooltip(int mx, int my) - { - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - List tt; - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(!entry.isEnabled()) - { - continue; - } - - tt = entry.getTooltip(mx, my); - - if(tt != null) - { - return tt; - } - } - - return null; - } - - @Override - public void addPanel(IGuiPanel panel) - { - if(panel == null || guiPanels.contains(panel)) - { - return; - } - - guiPanels.add(panel); - guiPanels.sort(ComparatorGuiDepth.INSTANCE); - panel.getTransform().setParent(getTransform()); - panel.initPanel(); - } - - @Override - public boolean removePanel(IGuiPanel panel) - { - return guiPanels.remove(panel); - } - - @Override - public void resetCanvas() - { - guiPanels.clear(); - } + + return used; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseRelease(mx, my, click)) { + used = true; + break; + } + } + + return used; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) { + used = true; + break; + } + } + + return used; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onKeyTyped(c, keycode)) { + used = true; + break; + } + } + + return used; + } + + @Override + public List getTooltip(int mx, int my) { + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + List tt; + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (!entry.isEnabled()) { + continue; + } + + tt = entry.getTooltip(mx, my); + + if (tt != null) { + return tt; + } + } + + return null; + } + + @Override + public void addPanel(IGuiPanel panel) { + if (panel == null || guiPanels.contains(panel)) { + return; + } + + guiPanels.add(panel); + guiPanels.sort(ComparatorGuiDepth.INSTANCE); + panel.getTransform().setParent(getTransform()); + panel.initPanel(); + } + + @Override + public boolean removePanel(IGuiPanel panel) { + return guiPanels.remove(panel); + } + + @Override + public void resetCanvas() { + guiPanels.clear(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java b/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java index 15598d786..b4e2ce8d3 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java @@ -14,235 +14,200 @@ import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; -public class CanvasResizeable implements IGuiCanvas -{ - private final List guiPanels = new CopyOnWriteArrayList<>(); - - private IGuiTexture bgTexture; - private final GuiRectLerp rectLerp; - private boolean enabled = true; - private final boolean crop; - - public CanvasResizeable(IGuiRect rect, IGuiTexture texture) - { - this(rect, texture, true); - } - - public CanvasResizeable(IGuiRect rect, IGuiTexture texture, boolean crop) - { - this.bgTexture = texture; - this.rectLerp = new GuiRectLerp(rect); - this.crop = crop; - } - - public void changeBG(@Nullable IGuiTexture texture) - { - this.bgTexture = texture; +public class CanvasResizeable implements IGuiCanvas { + private final List guiPanels = new CopyOnWriteArrayList<>(); + + private IGuiTexture bgTexture; + private final GuiRectLerp rectLerp; + private boolean enabled = true; + private final boolean crop; + + public CanvasResizeable(IGuiRect rect, IGuiTexture texture) { + this(rect, texture, true); + } + + public CanvasResizeable(IGuiRect rect, IGuiTexture texture, boolean crop) { + this.bgTexture = texture; + this.rectLerp = new GuiRectLerp(rect); + this.crop = crop; + } + + public void changeBG(@Nullable IGuiTexture texture) { + this.bgTexture = texture; + } + + @Override + public IGuiRect getTransform() { + return crop ? rectLerp.getProxyRect() : rectLerp; + } + + public GuiRectLerp getRectLerp() { + return this.rectLerp; + } + + @Nonnull + @Override + public List getChildren() { + return this.guiPanels; + } + + @Override + public void initPanel() { + this.guiPanels.clear(); + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + public void lerpToRect(@Nonnull IGuiRect rect, long time, boolean inheritParent) { + if (inheritParent) { rect.setParent(rectLerp.getParent()); } + rectLerp.lerpTo(rect, time); + } + + public void snapToRect(@Nonnull IGuiRect rect, boolean inheritParent) { + if (inheritParent) { rect.setParent(rectLerp.getParent()); } + rectLerp.snapTo(rect); + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (crop) { RenderUtils.startScissor(rectLerp); } + + if (bgTexture != null) { + IGuiRect bounds = rectLerp; + GlStateManager.pushMatrix(); + GlStateManager.color(1F, 1F, 1F, 1F); + bgTexture.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + GlStateManager.popMatrix(); } - - @Override - public IGuiRect getTransform() - { - return crop ? rectLerp.getProxyRect() : rectLerp; - } - - public GuiRectLerp getRectLerp() - { - return this.rectLerp; + + for (IGuiPanel entry : guiPanels) { + if (entry.isEnabled()) { entry.drawPanel(mx, my, partialTick); } } - - @Nonnull - @Override - public List getChildren() - { - return this.guiPanels; + + if (crop) { RenderUtils.endScissor(); } + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseClick(mx, my, click)) { + used = true; + break; + } } - - @Override - public void initPanel() - { - this.guiPanels.clear(); - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - public void lerpToRect(@Nonnull IGuiRect rect, long time, boolean inheritParent) - { - if(inheritParent) rect.setParent(rectLerp.getParent()); - rectLerp.lerpTo(rect, time); + + return used || (bgTexture != null && rectLerp.contains(mx, my)); + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseRelease(mx, my, click)) { + used = true; + break; + } } - - public void snapToRect(@Nonnull IGuiRect rect, boolean inheritParent) - { - if(inheritParent) rect.setParent(rectLerp.getParent()); - rectLerp.snapTo(rect); + + return used || (bgTexture != null && rectLerp.contains(mx, my)); + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) { + used = true; + break; + } + } + + return used || (bgTexture != null && rectLerp.contains(mx, my)); + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onKeyTyped(c, keycode)) { + used = true; + break; + } + } + + return used; + } + + @Override + public List getTooltip(int mx, int my) { + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + List tt; + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (!entry.isEnabled()) { + continue; + } + + tt = entry.getTooltip(mx, my); + + if (tt != null) { + return tt; + } } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(crop) RenderUtils.startScissor(rectLerp); - - if(bgTexture != null) - { - IGuiRect bounds = rectLerp; - GlStateManager.pushMatrix(); - GlStateManager.color(1F, 1F, 1F, 1F); - bgTexture.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); - GlStateManager.popMatrix(); - } - - for(IGuiPanel entry : guiPanels) - { - if(entry.isEnabled()) entry.drawPanel(mx, my, partialTick); - } - - if(crop) RenderUtils.endScissor(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseClick(mx, my, click)) - { - used = true; - break; - } - } - - return used || (bgTexture != null && rectLerp.contains(mx, my)); - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseRelease(mx, my, click)) - { - used = true; - break; - } - } - - return used || (bgTexture != null && rectLerp.contains(mx, my)); - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseScroll(mx, my, scroll)) - { - used = true; - break; - } - } - - return used || (bgTexture != null && rectLerp.contains(mx, my)); - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onKeyTyped(c, keycode)) - { - used = true; - break; - } - } - - return used; - } - - @Override - public List getTooltip(int mx, int my) - { - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - List tt; - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(!entry.isEnabled()) - { - continue; - } - - tt = entry.getTooltip(mx, my); - - if(tt != null) - { - return tt; - } - } - - return (bgTexture != null && rectLerp.contains(mx, my)) ? Collections.emptyList() : null; - } - - @Override - public void addPanel(IGuiPanel panel) - { - if(panel == null || guiPanels.contains(panel)) - { - return; - } - - guiPanels.add(panel); - guiPanels.sort(ComparatorGuiDepth.INSTANCE); - panel.getTransform().setParent(getTransform()); - panel.initPanel(); - } - - @Override - public boolean removePanel(IGuiPanel panel) - { - return guiPanels.remove(panel); - } - - @Override - public void resetCanvas() - { - guiPanels.clear(); - } + + return (bgTexture != null && rectLerp.contains(mx, my)) ? Collections.emptyList() : null; + } + + @Override + public void addPanel(IGuiPanel panel) { + if (panel == null || guiPanels.contains(panel)) { + return; + } + + guiPanels.add(panel); + guiPanels.sort(ComparatorGuiDepth.INSTANCE); + panel.getTransform().setParent(getTransform()); + panel.initPanel(); + } + + @Override + public boolean removePanel(IGuiPanel panel) { + return guiPanels.remove(panel); + } + + @Override + public void resetCanvas() { + guiPanels.clear(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java b/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java index 369abcdab..e9ff388c6 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java @@ -6,34 +6,29 @@ import javax.annotation.Nullable; -public class CanvasTextured extends CanvasEmpty -{ - private IGuiTexture bgTexture; - - public CanvasTextured(IGuiRect rect, IGuiTexture texture) - { - super(rect); - - this.bgTexture = texture; - } - - public void changeBG(@Nullable IGuiTexture texture) - { - this.bgTexture = texture; +public class CanvasTextured extends CanvasEmpty { + private IGuiTexture bgTexture; + + public CanvasTextured(IGuiRect rect, IGuiTexture texture) { + super(rect); + + this.bgTexture = texture; + } + + public void changeBG(@Nullable IGuiTexture texture) { + this.bgTexture = texture; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (bgTexture != null) { + IGuiRect bounds = this.getTransform(); + GlStateManager.pushMatrix(); + GlStateManager.color(1F, 1F, 1F, 1F); + bgTexture.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + GlStateManager.popMatrix(); } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(bgTexture != null) - { - IGuiRect bounds = this.getTransform(); - GlStateManager.pushMatrix(); - GlStateManager.color(1F, 1F, 1F, 1F); - bgTexture.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); - GlStateManager.popMatrix(); - } - - super.drawPanel(mx, my, partialTick); - } + + super.drawPanel(mx, my, partialTick); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/IGuiCanvas.java b/src/main/java/betterquesting/api2/client/gui/panels/IGuiCanvas.java index f5fedbd8d..7acd66440 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/IGuiCanvas.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/IGuiCanvas.java @@ -3,16 +3,16 @@ import javax.annotation.Nonnull; import java.util.List; -public interface IGuiCanvas extends IGuiPanel -{ - void addPanel(IGuiPanel panel); - boolean removePanel(IGuiPanel panel); - - @Nonnull - List getChildren(); - - /** - * Removes all children and resets the canvas to its initial blank state - */ - void resetCanvas(); +public interface IGuiCanvas extends IGuiPanel { + void addPanel(IGuiPanel panel); + + boolean removePanel(IGuiPanel panel); + + @Nonnull + List getChildren(); + + /** + * Removes all children and resets the canvas to its initial blank state + */ + void resetCanvas(); } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/client/gui/panels/IGuiPanel.java b/src/main/java/betterquesting/api2/client/gui/panels/IGuiPanel.java index 09a3bea81..5f840a4a2 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/IGuiPanel.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/IGuiPanel.java @@ -1,21 +1,27 @@ package betterquesting.api2.client.gui.panels; -import java.util.List; import betterquesting.api2.client.gui.misc.IGuiRect; -public interface IGuiPanel -{ - IGuiRect getTransform(); - - void initPanel(); - void setEnabled(boolean state); - boolean isEnabled(); - void drawPanel(int mx, int my, float partialTick); - - boolean onMouseClick(int mx, int my, int button); - boolean onMouseRelease(int mx, int my, int button); - boolean onMouseScroll(int mx, int my, int scroll); - boolean onKeyTyped(char c, int keycode); - - List getTooltip(int mx, int my); +import java.util.List; + +public interface IGuiPanel { + IGuiRect getTransform(); + + void initPanel(); + + void setEnabled(boolean state); + + boolean isEnabled(); + + void drawPanel(int mx, int my, float partialTick); + + boolean onMouseClick(int mx, int my, int button); + + boolean onMouseRelease(int mx, int my, int button); + + boolean onMouseScroll(int mx, int my, int scroll); + + boolean onKeyTyped(char c, int keycode); + + List getTooltip(int mx, int my); } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/IBarFill.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/IBarFill.java index 0cd1ea9a6..750be6fc1 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/IBarFill.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/IBarFill.java @@ -5,10 +5,12 @@ import betterquesting.api2.client.gui.resources.colors.IGuiColor; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; -public interface IBarFill extends IGuiPanel -{ - IBarFill setFillDriver(IValueIO driver); - IBarFill setFlipped(boolean flipped); - IBarFill setFillColor(IGuiColor color); // Setup the transitional colour manually if necessary - IBarFill setBarTexture(IGuiTexture back, IGuiTexture front); +public interface IBarFill extends IGuiPanel { + IBarFill setFillDriver(IValueIO driver); + + IBarFill setFlipped(boolean flipped); + + IBarFill setFillColor(IGuiColor color); // Setup the transitional colour manually if necessary + + IBarFill setBarTexture(IGuiTexture back, IGuiTexture front); } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/IScrollBar.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/IScrollBar.java index 4e380ad2d..5e97ac19a 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/IScrollBar.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/IScrollBar.java @@ -4,12 +4,15 @@ import betterquesting.api2.client.gui.panels.IGuiPanel; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; -public interface IScrollBar extends IValueIO, IGuiPanel -{ - void setActive(boolean state); - boolean isActive(); - - IScrollBar setHandleSize(int size, int inset); - IScrollBar setBarTexture(IGuiTexture background, IGuiTexture handleDisabled, IGuiTexture handleIdle, IGuiTexture handleHover); - IScrollBar setScrollSpeed(float spd); +public interface IScrollBar extends IValueIO, IGuiPanel { + void setActive(boolean state); + + boolean isActive(); + + IScrollBar setHandleSize(int size, int inset); + + IScrollBar setBarTexture(IGuiTexture background, IGuiTexture handleDisabled, IGuiTexture handleIdle, + IGuiTexture handleHover); + + IScrollBar setScrollSpeed(float spd); } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java index 168b9fe23..4b27affde 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java @@ -13,137 +13,120 @@ import java.util.List; -public class PanelHBarFill implements IBarFill -{ - private final IGuiRect transform; - private boolean enabled = true; - - private IGuiTexture texBack; - private IGuiTexture texFill; - private IValueIO fillDriver; - private boolean flipBar = false; - private IGuiColor color = new GuiColorStatic(0xFFFFFFFF); - - public PanelHBarFill(IGuiRect rect) - { - this.texBack = PresetTexture.METER_H_0.getTexture(); - this.texFill = PresetTexture.METER_H_1.getTexture(); - - this.transform = rect; - } - - @Override - public PanelHBarFill setFillDriver(IValueIO driver) - { - this.fillDriver = driver; - return this; - } - - @Override - public PanelHBarFill setFlipped(boolean flipped) - { - this.flipBar = flipped; - return this; - } - - @Override - public PanelHBarFill setFillColor(IGuiColor color) - { - this.color = color; - return this; - } - - @Override - public PanelHBarFill setBarTexture(IGuiTexture back, IGuiTexture front) - { - this.texBack = back; - this.texFill = front; - return this; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - IGuiRect bounds = this.getTransform(); - GlStateManager.pushMatrix(); - - GlStateManager.color(1F, 1F, 1F, 1F); - - if(texBack != null) - { - texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); - } - - float f = MathHelper.clamp(fillDriver.readValue(), 0F, 1F); - - if(this.flipBar) - { - RenderUtils.startScissor(new GuiRectangle(bounds.getX() + (int)(bounds.getWidth() - (bounds.getWidth() * f)), bounds.getY(), (int)(bounds.getWidth() * f), bounds.getHeight(), 0)); - } else - { - RenderUtils.startScissor(new GuiRectangle(bounds.getX(), bounds.getY(), (int)(bounds.getWidth() * f), bounds.getHeight(), 0)); - } - - if(texFill != null) - { - texFill.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick, color); - } - - RenderUtils.endScissor(); - - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } +public class PanelHBarFill implements IBarFill { + private final IGuiRect transform; + private boolean enabled = true; + + private IGuiTexture texBack; + private IGuiTexture texFill; + private IValueIO fillDriver; + private boolean flipBar = false; + private IGuiColor color = new GuiColorStatic(0xFFFFFFFF); + + public PanelHBarFill(IGuiRect rect) { + this.texBack = PresetTexture.METER_H_0.getTexture(); + this.texFill = PresetTexture.METER_H_1.getTexture(); + + this.transform = rect; + } + + @Override + public PanelHBarFill setFillDriver(IValueIO driver) { + this.fillDriver = driver; + return this; + } + + @Override + public PanelHBarFill setFlipped(boolean flipped) { + this.flipBar = flipped; + return this; + } + + @Override + public PanelHBarFill setFillColor(IGuiColor color) { + this.color = color; + return this; + } + + @Override + public PanelHBarFill setBarTexture(IGuiTexture back, IGuiTexture front) { + this.texBack = back; + this.texFill = front; + return this; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + IGuiRect bounds = this.getTransform(); + GlStateManager.pushMatrix(); + + GlStateManager.color(1F, 1F, 1F, 1F); + + if (texBack != null) { + texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + } + + float f = MathHelper.clamp(fillDriver.readValue(), 0F, 1F); + + if (this.flipBar) { + RenderUtils.startScissor( + new GuiRectangle(bounds.getX() + (int) (bounds.getWidth() - (bounds.getWidth() * f)), bounds.getY(), + (int) (bounds.getWidth() * f), bounds.getHeight(), 0)); + } else { + RenderUtils.startScissor( + new GuiRectangle(bounds.getX(), bounds.getY(), (int) (bounds.getWidth() * f), bounds.getHeight(), 0)); + } + + if (texFill != null) { + texFill.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick, color); + } + + RenderUtils.endScissor(); + + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java index a07093cc5..4bdaa2036 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java @@ -9,200 +9,173 @@ import java.util.List; -public class PanelHScrollBar implements IScrollBar -{ - private final IGuiRect transform; - private boolean enabled = true; - private boolean active = true; - - private IGuiTexture texBack; - private IGuiTexture[] texHandleState = new IGuiTexture[3]; - - private float scroll = 0F; - private float speed = 0.1F; - private int hSize = 16; - private int inset = 0; - private boolean isDragging = false; - - public PanelHScrollBar(IGuiRect rect) - { - this.transform = rect; - this.setBarTexture(PresetTexture.SCROLL_H_BG.getTexture(), PresetTexture.SCROLL_H_0.getTexture(), PresetTexture.SCROLL_H_1.getTexture(), PresetTexture.SCROLL_H_2.getTexture()); - } - - @Override - public PanelHScrollBar setHandleSize(int size, int inset) - { - this.hSize = size; - this.inset = inset; - return this; - } - - @Override - public PanelHScrollBar setBarTexture(IGuiTexture back, IGuiTexture handleDisabled, IGuiTexture handleIdle, IGuiTexture handleHover) - { - this.texBack = back; - this.texHandleState[0] = handleDisabled; - this.texHandleState[1] = handleIdle; - this.texHandleState[2] = handleHover; - return this; - } - - @Override - public PanelHScrollBar setScrollSpeed(float f) - { - this.speed = f; - return this; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public void setActive(boolean state) - { - this.active = state; - } - - @Override - public boolean isActive() - { - return this.active; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - IGuiRect bounds = this.getTransform(); - - if(active && isDragging && (Mouse.isButtonDown(0) || Mouse.isButtonDown(2))) - { - float cx = (float)(mx - (bounds.getX() + hSize/2)) / (float)(bounds.getWidth() - hSize); - this.writeValue(cx); - } else if(isDragging) - { - this.isDragging = false; - } - - GlStateManager.pushMatrix(); - GlStateManager.color(1F, 1F, 1F, 1F); - - if(texBack != null) - { - texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); - } - - int sx = MathHelper.floor((bounds.getWidth() - hSize - (inset*2)) * scroll); - int state = !active ? 0 : (isDragging || bounds.contains(mx, my) ? 2 : 1); - IGuiTexture tex = texHandleState[state]; - - if(tex != null) - { - tex.drawTexture(bounds.getX() + sx + inset, bounds.getY() + inset, hSize, bounds.getHeight() - (inset * 2), 0F, partialTick); - } - - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - IGuiRect bounds = this.getTransform(); - - if(!active || !bounds.contains(mx, my)) - { - return false; - } - - if(click == 0 || click == 2) - { - isDragging = true; - return true; - } - - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int sdx) - { - IGuiRect bounds = this.getTransform(); - if(!active || sdx == 0 || !bounds.contains(mx, my)) - { - return false; - } - - float dx = sdx * speed; - - if((dx < 0 && scroll <= 0F) || (dx > 0 && scroll >= 1)) - { - return false; - } else - { - this.writeValue(dx + scroll); - return true; - } - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } - - @Override - public Float readValue() - { - return this.scroll; - } - - @Override - public void writeValue(Float value) - { - this.scroll = MathHelper.clamp(value, 0F, 1F); - } - - @Override - public Float readValueRaw() - { - return readValue(); +public class PanelHScrollBar implements IScrollBar { + private final IGuiRect transform; + private boolean enabled = true; + private boolean active = true; + + private IGuiTexture texBack; + private final IGuiTexture[] texHandleState = new IGuiTexture[3]; + + private float scroll = 0F; + private float speed = 0.1F; + private int hSize = 16; + private int inset = 0; + private boolean isDragging = false; + + public PanelHScrollBar(IGuiRect rect) { + this.transform = rect; + this.setBarTexture(PresetTexture.SCROLL_H_BG.getTexture(), PresetTexture.SCROLL_H_0.getTexture(), + PresetTexture.SCROLL_H_1.getTexture(), PresetTexture.SCROLL_H_2.getTexture()); + } + + @Override + public PanelHScrollBar setHandleSize(int size, int inset) { + this.hSize = size; + this.inset = inset; + return this; + } + + @Override + public PanelHScrollBar setBarTexture(IGuiTexture back, IGuiTexture handleDisabled, IGuiTexture handleIdle, + IGuiTexture handleHover) { + this.texBack = back; + this.texHandleState[0] = handleDisabled; + this.texHandleState[1] = handleIdle; + this.texHandleState[2] = handleHover; + return this; + } + + @Override + public PanelHScrollBar setScrollSpeed(float f) { + this.speed = f; + return this; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void setActive(boolean state) { + this.active = state; + } + + @Override + public boolean isActive() { + return this.active; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + IGuiRect bounds = this.getTransform(); + + if (active && isDragging && (Mouse.isButtonDown(0) || Mouse.isButtonDown(2))) { + float cx = (float) (mx - (bounds.getX() + hSize / 2)) / (float) (bounds.getWidth() - hSize); + this.writeValue(cx); + } else if (isDragging) { + this.isDragging = false; + } + + GlStateManager.pushMatrix(); + GlStateManager.color(1F, 1F, 1F, 1F); + + if (texBack != null) { + texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + } + + int sx = MathHelper.floor((bounds.getWidth() - hSize - (inset * 2)) * scroll); + int state = !active ? 0 : (isDragging || bounds.contains(mx, my) ? 2 : 1); + IGuiTexture tex = texHandleState[state]; + + if (tex != null) { + tex.drawTexture(bounds.getX() + sx + inset, bounds.getY() + inset, hSize, bounds.getHeight() - (inset * 2), 0F, + partialTick); + } + + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + IGuiRect bounds = this.getTransform(); + + if (!active || !bounds.contains(mx, my)) { + return false; } - - @Override - public void writeValueRaw(Float value) - { - this.scroll = value; + + if (click == 0 || click == 2) { + isDragging = true; + return true; + } + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int sdx) { + IGuiRect bounds = this.getTransform(); + if (!active || sdx == 0 || !bounds.contains(mx, my)) { + return false; } + + float dx = sdx * speed; + + if ((dx < 0 && scroll <= 0F) || (dx > 0 && scroll >= 1)) { + return false; + } else { + this.writeValue(dx + scroll); + return true; + } + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public Float readValue() { + return this.scroll; + } + + @Override + public void writeValue(Float value) { + this.scroll = MathHelper.clamp(value, 0F, 1F); + } + + @Override + public Float readValueRaw() { + return readValue(); + } + + @Override + public void writeValueRaw(Float value) { + this.scroll = value; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java index 6daa1f2fd..15c5b1952 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java @@ -12,137 +12,120 @@ import java.util.List; -public class PanelVBarFill implements IBarFill -{ - private final IGuiRect transform; - private boolean enabled = true; - - private IGuiTexture texBack; - private IGuiTexture texFill; - private IValueIO fillDriver; - private boolean flipBar = false; - private IGuiColor color; - - public PanelVBarFill(IGuiRect rect) - { - this.texBack = PresetTexture.METER_V_0.getTexture(); - this.texFill = PresetTexture.METER_V_1.getTexture(); - - this.transform = rect; - } - - @Override - public PanelVBarFill setFillDriver(IValueIO driver) - { - this.fillDriver = driver; - return this; - } - - @Override - public PanelVBarFill setFlipped(boolean flipped) - { - this.flipBar = flipped; - return this; - } - - @Override - public PanelVBarFill setFillColor(IGuiColor color) - { - this.color = color; - return this; - } - - @Override - public PanelVBarFill setBarTexture(IGuiTexture back, IGuiTexture front) - { - this.texBack = back; - this.texFill = front; - return this; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - IGuiRect bounds = this.getTransform(); - GlStateManager.pushMatrix(); - - GlStateManager.color(1F, 1F, 1F, 1F); - - if(texBack != null) - { - texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); - } - - float f = MathHelper.clamp(fillDriver.readValue(), 0F, 1F); - - if(this.flipBar) - { - RenderUtils.startScissor(new GuiRectangle(bounds.getX(), bounds.getY(), bounds.getWidth(), (int)(bounds.getHeight() * f), 0)); - } else - { - RenderUtils.startScissor(new GuiRectangle(bounds.getX(), bounds.getY() + (int)(bounds.getHeight() - (bounds.getHeight() * f)), bounds.getWidth(), (int)(bounds.getHeight() * f), 0)); - } - - if(texFill != null) - { - texFill.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick, color); - } - - RenderUtils.endScissor(); - - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } +public class PanelVBarFill implements IBarFill { + private final IGuiRect transform; + private boolean enabled = true; + + private IGuiTexture texBack; + private IGuiTexture texFill; + private IValueIO fillDriver; + private boolean flipBar = false; + private IGuiColor color; + + public PanelVBarFill(IGuiRect rect) { + this.texBack = PresetTexture.METER_V_0.getTexture(); + this.texFill = PresetTexture.METER_V_1.getTexture(); + + this.transform = rect; + } + + @Override + public PanelVBarFill setFillDriver(IValueIO driver) { + this.fillDriver = driver; + return this; + } + + @Override + public PanelVBarFill setFlipped(boolean flipped) { + this.flipBar = flipped; + return this; + } + + @Override + public PanelVBarFill setFillColor(IGuiColor color) { + this.color = color; + return this; + } + + @Override + public PanelVBarFill setBarTexture(IGuiTexture back, IGuiTexture front) { + this.texBack = back; + this.texFill = front; + return this; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + IGuiRect bounds = this.getTransform(); + GlStateManager.pushMatrix(); + + GlStateManager.color(1F, 1F, 1F, 1F); + + if (texBack != null) { + texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + } + + float f = MathHelper.clamp(fillDriver.readValue(), 0F, 1F); + + if (this.flipBar) { + RenderUtils.startScissor( + new GuiRectangle(bounds.getX(), bounds.getY(), bounds.getWidth(), (int) (bounds.getHeight() * f), 0)); + } else { + RenderUtils.startScissor( + new GuiRectangle(bounds.getX(), bounds.getY() + (int) (bounds.getHeight() - (bounds.getHeight() * f)), + bounds.getWidth(), (int) (bounds.getHeight() * f), 0)); + } + + if (texFill != null) { + texFill.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick, color); + } + + RenderUtils.endScissor(); + + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java index d9035f085..f7b2c6b6b 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java @@ -9,198 +9,171 @@ import java.util.List; -public class PanelVScrollBar implements IScrollBar -{ - private final IGuiRect transform; - private boolean enabled = true; - private boolean active = true; - - private IGuiTexture texBack; - private IGuiTexture[] texHandleState = new IGuiTexture[3]; - - private float scroll = 0F; - private float speed = 0.1F; - private int hSize = 16; - private int inset = 0; - private boolean isDragging = false; - - public PanelVScrollBar(IGuiRect rect) - { - this.transform = rect; - this.setBarTexture(PresetTexture.SCROLL_V_BG.getTexture(), PresetTexture.SCROLL_V_0.getTexture(), PresetTexture.SCROLL_V_1.getTexture(), PresetTexture.SCROLL_V_2.getTexture()); - } - - @Override - public PanelVScrollBar setHandleSize(int size, int inset) - { - this.hSize = size; - this.inset = inset; - return this; - } - - @Override - public PanelVScrollBar setBarTexture(IGuiTexture back, IGuiTexture handleDisabled, IGuiTexture handleIdle, IGuiTexture handleHover) - { - this.texBack = back; - this.texHandleState[0] = handleDisabled; - this.texHandleState[1] = handleIdle; - this.texHandleState[2] = handleHover; - return this; - } - - public PanelVScrollBar setScrollSpeed(float f) - { - this.speed = f; - return this; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public void setActive(boolean state) - { - this.active = state; - } - - @Override - public boolean isActive() - { - return this.active; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - IGuiRect bounds = this.getTransform(); - - if(active && isDragging && (Mouse.isButtonDown(0) || Mouse.isButtonDown(2))) - { - float cy = (float)(my - (bounds.getY() + hSize/2)) / (float)(bounds.getHeight() - hSize); - this.writeValue(cy); - } else if(isDragging) - { - this.isDragging = false; - } - - GlStateManager.pushMatrix(); - GlStateManager.color(1F, 1F, 1F, 1F); - - if(texBack != null) - { - texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); - } - - int sy = MathHelper.floor((bounds.getHeight() - hSize - (inset*2)) * scroll); - int state = !active ? 0 : (isDragging || bounds.contains(mx, my) ? 2 : 1); - IGuiTexture tex = texHandleState[state]; - - if(tex != null) - { - tex.drawTexture(bounds.getX() + inset, bounds.getY() + sy + inset, bounds.getWidth() - (inset * 2), hSize, 0F, partialTick); - } - - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - IGuiRect bounds = this.getTransform(); - if(!active || !bounds.contains(mx, my)) - { - return false; - } - - if(click == 0 || click == 2) - { - isDragging = true; - return true; - } - - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int sdx) - { - IGuiRect bounds = this.getTransform(); - if(!active || sdx == 0 || !bounds.contains(mx, my)) - { - return false; - } - - float dy = sdx * speed; - - if((dy < 0F && scroll <= 0F) || (dy > 0F && scroll >= 1F)) - { - return false; - } else - { - this.writeValue(dy + scroll); - return true; - } - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } - - @Override - public Float readValue() - { - return this.scroll; - } - - @Override - public void writeValue(Float value) - { - this.scroll = MathHelper.clamp(value, 0F, 1F); - } - - @Override - public Float readValueRaw() - { - return readValue(); +public class PanelVScrollBar implements IScrollBar { + private final IGuiRect transform; + private boolean enabled = true; + private boolean active = true; + + private IGuiTexture texBack; + private final IGuiTexture[] texHandleState = new IGuiTexture[3]; + + private float scroll = 0F; + private float speed = 0.1F; + private int hSize = 16; + private int inset = 0; + private boolean isDragging = false; + + public PanelVScrollBar(IGuiRect rect) { + this.transform = rect; + this.setBarTexture(PresetTexture.SCROLL_V_BG.getTexture(), PresetTexture.SCROLL_V_0.getTexture(), + PresetTexture.SCROLL_V_1.getTexture(), PresetTexture.SCROLL_V_2.getTexture()); + } + + @Override + public PanelVScrollBar setHandleSize(int size, int inset) { + this.hSize = size; + this.inset = inset; + return this; + } + + @Override + public PanelVScrollBar setBarTexture(IGuiTexture back, IGuiTexture handleDisabled, IGuiTexture handleIdle, + IGuiTexture handleHover) { + this.texBack = back; + this.texHandleState[0] = handleDisabled; + this.texHandleState[1] = handleIdle; + this.texHandleState[2] = handleHover; + return this; + } + + public PanelVScrollBar setScrollSpeed(float f) { + this.speed = f; + return this; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void setActive(boolean state) { + this.active = state; + } + + @Override + public boolean isActive() { + return this.active; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + IGuiRect bounds = this.getTransform(); + + if (active && isDragging && (Mouse.isButtonDown(0) || Mouse.isButtonDown(2))) { + float cy = (float) (my - (bounds.getY() + hSize / 2)) / (float) (bounds.getHeight() - hSize); + this.writeValue(cy); + } else if (isDragging) { + this.isDragging = false; } - - @Override - public void writeValueRaw(Float value) - { - this.scroll = value; + + GlStateManager.pushMatrix(); + GlStateManager.color(1F, 1F, 1F, 1F); + + if (texBack != null) { + texBack.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); + } + + int sy = MathHelper.floor((bounds.getHeight() - hSize - (inset * 2)) * scroll); + int state = !active ? 0 : (isDragging || bounds.contains(mx, my) ? 2 : 1); + IGuiTexture tex = texHandleState[state]; + + if (tex != null) { + tex.drawTexture(bounds.getX() + inset, bounds.getY() + sy + inset, bounds.getWidth() - (inset * 2), hSize, 0F, + partialTick); } + + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + IGuiRect bounds = this.getTransform(); + if (!active || !bounds.contains(mx, my)) { + return false; + } + + if (click == 0 || click == 2) { + isDragging = true; + return true; + } + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int sdx) { + IGuiRect bounds = this.getTransform(); + if (!active || sdx == 0 || !bounds.contains(mx, my)) { + return false; + } + + float dy = sdx * speed; + + if ((dy < 0F && scroll <= 0F) || (dy > 0F && scroll >= 1F)) { + return false; + } else { + this.writeValue(dy + scroll); + return true; + } + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public Float readValue() { + return this.scroll; + } + + @Override + public void writeValue(Float value) { + this.scroll = MathHelper.clamp(value, 0F, 1F); + } + + @Override + public Float readValueRaw() { + return readValue(); + } + + @Override + public void writeValueRaw(Float value) { + this.scroll = value; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java index 3b4639172..6fa604582 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java @@ -12,133 +12,118 @@ import java.util.List; -public class PanelEntityPreview implements IGuiPanel -{ - private final IGuiRect transform; - private boolean enabled = true; - - public Entity entity; - - private final IValueIO basePitch; - private final IValueIO baseYaw; - private IValueIO pitchDriver; - private IValueIO yawDriver; - - private float zDepth = 100F; - - public PanelEntityPreview(IGuiRect rect, Entity entity) - { - this.transform = rect; - this.entity = entity; - - this.basePitch = new ValueFuncIO<>(() -> 15F); - this.pitchDriver = basePitch; - - this.baseYaw = new ValueFuncIO<>(() -> -30F); - this.yawDriver = baseYaw; - } - - public PanelEntityPreview setRotationFixed(float pitch, float yaw) - { - this.pitchDriver = basePitch; - this.yawDriver = baseYaw; - basePitch.writeValue(pitch); - baseYaw.writeValue(yaw); - return this; - } - - public PanelEntityPreview setRotationDriven(IValueIO pitch, IValueIO yaw) - { - this.pitchDriver = pitch == null? basePitch : pitch; - this.yawDriver = yaw == null? baseYaw : yaw; - return this; - } - - public PanelEntityPreview setDepth(float z) - { - this.zDepth = z; - return this; - } - - public void setEntity(Entity entity) - { - this.entity = entity; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(entity == null) - { - return; - } - - IGuiRect bounds = this.getTransform(); - GlStateManager.pushMatrix(); - RenderUtils.startScissor(new GuiRectangle(bounds)); - - GlStateManager.color(1F, 1F, 1F, 1F); - - int sizeX = bounds.getWidth(); - int sizeY = bounds.getHeight(); - float scale = Math.min((sizeY/2F)/entity.height, (sizeX/2F)/entity.width); - - RenderUtils.RenderEntity(bounds.getX() + sizeX/2, bounds.getY() + sizeY/2 + MathHelper.ceil(entity.height * scale / 2F), (int)scale, yawDriver.readValue(), pitchDriver.readValue(), entity); - - RenderUtils.endScissor(); - GlStateManager.popMatrix(); +public class PanelEntityPreview implements IGuiPanel { + private final IGuiRect transform; + private boolean enabled = true; + + public Entity entity; + + private final IValueIO basePitch; + private final IValueIO baseYaw; + private IValueIO pitchDriver; + private IValueIO yawDriver; + + private float zDepth = 100F; + + public PanelEntityPreview(IGuiRect rect, Entity entity) { + this.transform = rect; + this.entity = entity; + + this.basePitch = new ValueFuncIO<>(() -> 15F); + this.pitchDriver = basePitch; + + this.baseYaw = new ValueFuncIO<>(() -> -30F); + this.yawDriver = baseYaw; + } + + public PanelEntityPreview setRotationFixed(float pitch, float yaw) { + this.pitchDriver = basePitch; + this.yawDriver = baseYaw; + basePitch.writeValue(pitch); + baseYaw.writeValue(yaw); + return this; + } + + public PanelEntityPreview setRotationDriven(IValueIO pitch, IValueIO yaw) { + this.pitchDriver = pitch == null ? basePitch : pitch; + this.yawDriver = yaw == null ? baseYaw : yaw; + return this; + } + + public PanelEntityPreview setDepth(float z) { + this.zDepth = z; + return this; + } + + public void setEntity(Entity entity) { + this.entity = entity; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (entity == null) { + return; } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } + + IGuiRect bounds = this.getTransform(); + GlStateManager.pushMatrix(); + RenderUtils.startScissor(new GuiRectangle(bounds)); + + GlStateManager.color(1F, 1F, 1F, 1F); + + int sizeX = bounds.getWidth(); + int sizeY = bounds.getHeight(); + float scale = Math.min((sizeY / 2F) / entity.height, (sizeX / 2F) / entity.width); + + RenderUtils.RenderEntity(bounds.getX() + sizeX / 2, + bounds.getY() + sizeY / 2 + MathHelper.ceil(entity.height * scale / 2F), (int) scale, + yawDriver.readValue(), pitchDriver.readValue(), entity); + + RenderUtils.endScissor(); + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java index 8b39508c2..ca375ff70 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java @@ -14,43 +14,40 @@ import java.util.ArrayList; import java.util.List; -public class PanelFluidSlot extends PanelButtonStorage -{ - private final boolean showCount; - - public PanelFluidSlot(IGuiRect rect, int id, FluidStack value) - { - this(rect, id, value, false); - } - - public PanelFluidSlot(IGuiRect rect, int id, FluidStack value, boolean showCount) - { - super(rect, id, "", value); - this.showCount = showCount; - - this.setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), new GuiPadding(1, 1, 1, 1)))); - this.setStoredValue(value); // Need to run this again because of the instatiation order of showCount - - } - - @Override - public PanelFluidSlot setStoredValue(FluidStack value) - { - super.setStoredValue(value); - - if(value != null) - { - this.setIcon(new FluidTexture(value, showCount, true), 1); - List tooltip = new ArrayList<>(); - tooltip.add(value.getLocalizedName()); - tooltip.add(TextFormatting.GRAY.toString() + value.amount + "mB"); - this.setTooltip(tooltip); - } else - { - this.setIcon(null); - this.setTooltip(null); - } - - return this; +public class PanelFluidSlot extends PanelButtonStorage { + private final boolean showCount; + + public PanelFluidSlot(IGuiRect rect, int id, FluidStack value) { + this(rect, id, value, false); + } + + public PanelFluidSlot(IGuiRect rect, int id, FluidStack value, boolean showCount) { + super(rect, id, "", value); + this.showCount = showCount; + + this.setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), + new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), + new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), + new GuiPadding(1, 1, 1, 1)))); + this.setStoredValue(value); // Need to run this again because of the instatiation order of showCount + + } + + @Override + public PanelFluidSlot setStoredValue(FluidStack value) { + super.setStoredValue(value); + + if (value != null) { + this.setIcon(new FluidTexture(value, showCount, true), 1); + List tooltip = new ArrayList<>(); + tooltip.add(value.getLocalizedName()); + tooltip.add(TextFormatting.GRAY.toString() + value.amount + "mB"); + this.setTooltip(tooltip); + } else { + this.setIcon(null); + this.setTooltip(null); } + + return this; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java index 35822db39..d50b33ad7 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java @@ -11,113 +11,96 @@ /** * Sets up a panel with texture and tooltip options. Useful for simple images or even labelling an invisible region with a tooltip */ -public class PanelGeneric implements IGuiPanel -{ - private final IGuiRect transform; - private boolean enabled = true; - - private IGuiTexture texture; - private IGuiColor color; - - private List tooltip = null; - - public PanelGeneric(IGuiRect rect, IGuiTexture texture) - { - this(rect, texture, null); - } - - public PanelGeneric(IGuiRect rect, IGuiTexture texture, IGuiColor color) - { - this.transform = rect; - this.texture = texture; - this.color = color; - } - - public void setTooltip(List tooltip) - { - this.tooltip = tooltip; - } - - public void setTexture(IGuiTexture texture, IGuiColor color) - { - this.texture = texture; - this.color = color; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(texture != null) - { - GlStateManager.pushMatrix(); - - if(color != null) - { - texture.drawTexture(transform.getX(), transform.getY(), transform.getWidth(), transform.getHeight(), 0F, partialTick, color); - } else - { - texture.drawTexture(transform.getX(), transform.getY(), transform.getWidth(), transform.getHeight(), 0F, partialTick); - } - - GlStateManager.popMatrix(); - } - } - - @Override - public boolean onMouseClick(int mx, int my, int button) - { - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int button) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; +public class PanelGeneric implements IGuiPanel { + private final IGuiRect transform; + private boolean enabled = true; + + private IGuiTexture texture; + private IGuiColor color; + + private List tooltip = null; + + public PanelGeneric(IGuiRect rect, IGuiTexture texture) { + this(rect, texture, null); + } + + public PanelGeneric(IGuiRect rect, IGuiTexture texture, IGuiColor color) { + this.transform = rect; + this.texture = texture; + this.color = color; + } + + public void setTooltip(List tooltip) { + this.tooltip = tooltip; + } + + public void setTexture(IGuiTexture texture, IGuiColor color) { + this.texture = texture; + this.color = color; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (texture != null) { + GlStateManager.pushMatrix(); + + if (color != null) { + texture.drawTexture(transform.getX(), transform.getY(), transform.getWidth(), transform.getHeight(), 0F, + partialTick, color); + } else { + texture.drawTexture(transform.getX(), transform.getY(), transform.getWidth(), transform.getHeight(), 0F, + partialTick); + } + + GlStateManager.popMatrix(); } - - @Override - public List getTooltip(int mx, int my) - { - if(transform.contains(mx, my)) - { - return tooltip; - } - - return null; + } + + @Override + public boolean onMouseClick(int mx, int my, int button) { + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int button) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + if (transform.contains(mx, my)) { + return tooltip; } + + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java index 6e07c53f1..9527d4ef5 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java @@ -20,122 +20,117 @@ import java.util.ArrayList; import java.util.List; -public class PanelItemSlot extends PanelButtonStorage -{ - private final boolean showCount; - private final boolean oreDict; - - private final List oreVariants = new ArrayList<>(); - - public PanelItemSlot(IGuiRect rect, int id, BigItemStack value) - { - this(rect, id, value, false, false); - } - - public PanelItemSlot(IGuiRect rect, int id, BigItemStack value, boolean showCount) - { - this(rect, id, value, showCount, false); +public class PanelItemSlot extends PanelButtonStorage { + private final boolean showCount; + private final boolean oreDict; + + private final List oreVariants = new ArrayList<>(); + + public PanelItemSlot(IGuiRect rect, int id, BigItemStack value) { + this(rect, id, value, false, false); + } + + public PanelItemSlot(IGuiRect rect, int id, BigItemStack value, boolean showCount) { + this(rect, id, value, showCount, false); + } + + public PanelItemSlot(IGuiRect rect, int id, BigItemStack value, boolean showCount, boolean oreDict) { + super(rect, id, "", value); + this.showCount = showCount; + this.oreDict = oreDict; + + this.setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), + new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), + new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), + new GuiPadding(1, 1, 1, 1)))); + this.setStoredValue(value); // Need to run this again because of the instatiation order of showCount + } + + @Override + public PanelItemSlot setStoredValue(BigItemStack value) { + super.setStoredValue(value); + + if (value != null) { + Minecraft mc = Minecraft.getMinecraft(); + this.setIcon( + oreDict || value.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE ? new OreDictTexture(1F, + value, + showCount, + true) + : new ItemTexture(value, + showCount, + true), 1); + this.setTooltip(value.getBaseStack().getTooltip(mc.player, + mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED + : TooltipFlags.NORMAL)); + } else { + this.setIcon(null); + this.setTooltip(null); } - - public PanelItemSlot(IGuiRect rect, int id, BigItemStack value, boolean showCount, boolean oreDict) - { - super(rect, id, "", value); - this.showCount = showCount; - this.oreDict = oreDict; - - this.setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), new GuiPadding(1, 1, 1, 1)))); - this.setStoredValue(value); // Need to run this again because of the instatiation order of showCount + + updateOreStacks(); + + return this; + } + + @Override + public List getTooltip(int mx, int my) { + if (getStoredValue() != null && getTransform().contains(mx, my)) { + BigItemStack ttStack = getStoredValue(); + + if (oreDict && !oreVariants.isEmpty()) { + ttStack = oreVariants.get((int) (System.currentTimeMillis() / 1000D) % oreVariants.size()); + } + + Minecraft mc = Minecraft.getMinecraft(); + return ttStack.getBaseStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED + : TooltipFlags.NORMAL); } - - @Override - public PanelItemSlot setStoredValue(BigItemStack value) + + return null; + } + + private void updateOreStacks() { + if (oreVariants == null) // Pre-instantiation check. Crashes otherwise >_> { - super.setStoredValue(value); - - if(value != null) - { - Minecraft mc = Minecraft.getMinecraft(); - this.setIcon(oreDict || value.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE ? new OreDictTexture(1F, value, showCount, true) : new ItemTexture(value, showCount, true), 1); - this.setTooltip(value.getBaseStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED : TooltipFlags.NORMAL)); - } else - { - this.setIcon(null); - this.setTooltip(null); - } - - updateOreStacks(); - - return this; + return; } - - @Override - public List getTooltip(int mx, int my) - { - if(getStoredValue() != null && getTransform().contains(mx, my)) - { - BigItemStack ttStack = getStoredValue(); - - if(oreDict && oreVariants.size() > 0) - { - ttStack = oreVariants.get((int)(System.currentTimeMillis()/1000D)%oreVariants.size()); - } - - Minecraft mc = Minecraft.getMinecraft(); - return ttStack.getBaseStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED : TooltipFlags.NORMAL); - } - - return null; + + oreVariants.clear(); + + BigItemStack stack = getStoredValue(); + if (stack == null) { return; } + + if (!stack.hasOreDict()) { + if (stack.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE) { + NonNullList subItems = NonNullList.create(); + stack.getBaseStack().getItem().getSubItems(CreativeTabs.SEARCH, subItems); + subItems.forEach((is) -> { + BigItemStack bis = new BigItemStack(is); + bis.stackSize = stack.stackSize; + oreVariants.add(bis); + }); + } else { + oreVariants.add(stack); + } + return; } - - private void updateOreStacks() - { - if(oreVariants == null) // Pre-instantiation check. Crashes otherwise >_> - { - return; - } - - oreVariants.clear(); - - BigItemStack stack = getStoredValue(); - if(stack == null) return; - - if(!stack.hasOreDict()) - { - if(stack.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE) - { - NonNullList subItems = NonNullList.create(); - stack.getBaseStack().getItem().getSubItems(CreativeTabs.SEARCH, subItems); - subItems.forEach((is) -> { - BigItemStack bis = new BigItemStack(is); - bis.stackSize = stack.stackSize; - oreVariants.add(bis); - }); - } else - { - oreVariants.add(stack); - } - return; - } - - for(ItemStack iStack : stack.getOreIngredient().getMatchingStacks()) - { - if(iStack.getItemDamage() == OreDictionary.WILDCARD_VALUE) - { - NonNullList subItems = NonNullList.create(); - iStack.getItem().getSubItems(CreativeTabs.SEARCH, subItems); - - for(ItemStack sStack : subItems) - { - BigItemStack bStack = new BigItemStack(sStack); - bStack.stackSize = stack.stackSize; - oreVariants.add(bStack); - } - } else - { - BigItemStack bStack = new BigItemStack(iStack); - bStack.stackSize = stack.stackSize; - oreVariants.add(bStack); - } + + for (ItemStack iStack : stack.getOreIngredient().getMatchingStacks()) { + if (iStack.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + NonNullList subItems = NonNullList.create(); + iStack.getItem().getSubItems(CreativeTabs.SEARCH, subItems); + + for (ItemStack sStack : subItems) { + BigItemStack bStack = new BigItemStack(sStack); + bStack.stackSize = stack.stackSize; + oreVariants.add(bStack); } + } else { + BigItemStack bStack = new BigItemStack(iStack); + bStack.stackSize = stack.stackSize; + oreVariants.add(bStack); + } } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java index 87df84825..a0edf1bd6 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java @@ -1,96 +1,85 @@ package betterquesting.api2.client.gui.panels.content; -import java.util.List; - -import betterquesting.api2.client.gui.misc.*; -import betterquesting.api2.client.gui.resources.colors.IGuiColor; -import net.minecraft.client.renderer.GlStateManager; +import betterquesting.api2.client.gui.misc.GuiRectangle; +import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.panels.IGuiPanel; +import betterquesting.api2.client.gui.resources.colors.IGuiColor; import betterquesting.api2.client.gui.resources.lines.IGuiLine; +import net.minecraft.client.renderer.GlStateManager; + +import java.util.List; + +public class PanelLine implements IGuiPanel { + /** + * Bounds aren't used in the drawing of the line, merely for determining draw order + */ + private final IGuiRect bounds; + private final IGuiLine line; + private final IGuiRect start; + private final IGuiRect end; + private final IGuiColor color; + private final int width; + + private boolean enabled = true; + + public PanelLine(IGuiRect start, IGuiRect end, IGuiLine line, int width, IGuiColor color, int drawOrder) { + this.start = start; + this.end = end; + this.line = line; + this.width = width; + this.color = color; + this.bounds = new GuiRectangle(0, 0, 0, 0, drawOrder); + this.bounds.setParent(start); + } + + @Override + public IGuiRect getTransform() { + return bounds; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + GlStateManager.pushMatrix(); + line.drawLine(start, end, width, color, partialTick); + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int button) { + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int button) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } -public class PanelLine implements IGuiPanel -{ - /** - * Bounds aren't used in the drawing of the line, merely for determining draw order - */ - private final IGuiRect bounds; - private final IGuiLine line; - private final IGuiRect start; - private final IGuiRect end; - private final IGuiColor color; - private final int width; - - private boolean enabled = true; - - public PanelLine(IGuiRect start, IGuiRect end, IGuiLine line, int width, IGuiColor color, int drawOrder) - { - this.start = start; - this.end = end; - this.line = line; - this.width = width; - this.color = color; - this.bounds = new GuiRectangle(0, 0, 0, 0, drawOrder); - this.bounds.setParent(start); - } - - @Override - public IGuiRect getTransform() - { - return bounds; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - GlStateManager.pushMatrix(); - line.drawLine(start, end, width, color, partialTick); - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int button) - { - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int button) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } + @Override + public List getTooltip(int mx, int my) { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java index 10faa782b..f3d6755bf 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java @@ -16,134 +16,117 @@ import java.util.List; import java.util.UUID; -public class PanelPlayerPortrait implements IGuiPanel -{ - private final IGuiRect transform; - private boolean enabled = true; - - private final AbstractClientPlayer player; - - private final IValueIO basePitch; - private final IValueIO baseYaw; - private IValueIO pitchDriver; - private IValueIO yawDriver; - - private float zDepth = 100F; - - public PanelPlayerPortrait(IGuiRect rect, UUID playerID, String username) - { - this(rect, new EntityPlayerPreview(Minecraft.getMinecraft().world, new GameProfile(playerID, username))); - } - - public PanelPlayerPortrait(IGuiRect rect, AbstractClientPlayer player) - { - this.transform = rect; - this.player = new EntityPlayerPreview(player.world, player.getGameProfile()); - this.player.limbSwing = 0F; - this.player.limbSwingAmount = 0F; - this.player.rotationYawHead = 0F; - - ResourceLocation resource = this.player.getLocationSkin(); - - if(Minecraft.getMinecraft().getTextureManager().getTexture(resource) == null) - { - AbstractClientPlayer.getDownloadImageSkin(resource, player.getGameProfile().getName()); - } - - this.basePitch = new ValueFuncIO<>(() -> 15F); - this.pitchDriver = basePitch; - - this.baseYaw = new ValueFuncIO<>(() -> -30F); - this.yawDriver = baseYaw; - } - - public PanelPlayerPortrait setRotationFixed(float pitch, float yaw) - { - this.pitchDriver = basePitch; - this.yawDriver = baseYaw; - basePitch.writeValue(pitch); - baseYaw.writeValue(yaw); - return this; - } - - public PanelPlayerPortrait setRotationDriven(IValueIO pitch, IValueIO yaw) - { - this.pitchDriver = pitch == null? basePitch : pitch; - this.yawDriver = yaw == null? baseYaw : yaw; - return this; - } - - public PanelPlayerPortrait setDepth(float z) - { - this.zDepth = z; - return this; - } - - @Override - public void initPanel() - { - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - IGuiRect bounds = this.getTransform(); - GlStateManager.pushMatrix(); - RenderUtils.startScissor(new GuiRectangle(bounds)); - - GlStateManager.color(1F, 1F, 1F, 1F); - int scale = Math.min(bounds.getWidth(), bounds.getHeight()); - RenderUtils.RenderEntity(bounds.getX() + bounds.getWidth()/2, bounds.getY() + bounds.getHeight()/2 + (int)(scale*1.5F), zDepth, scale, yawDriver.readValue(), pitchDriver.readValue(), player); - - RenderUtils.endScissor(); - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } +public class PanelPlayerPortrait implements IGuiPanel { + private final IGuiRect transform; + private boolean enabled = true; + + private final AbstractClientPlayer player; + + private final IValueIO basePitch; + private final IValueIO baseYaw; + private IValueIO pitchDriver; + private IValueIO yawDriver; + + private float zDepth = 100F; + + public PanelPlayerPortrait(IGuiRect rect, UUID playerID, String username) { + this(rect, new EntityPlayerPreview(Minecraft.getMinecraft().world, new GameProfile(playerID, username))); + } + + public PanelPlayerPortrait(IGuiRect rect, AbstractClientPlayer player) { + this.transform = rect; + this.player = new EntityPlayerPreview(player.world, player.getGameProfile()); + this.player.limbSwing = 0F; + this.player.limbSwingAmount = 0F; + this.player.rotationYawHead = 0F; + + ResourceLocation resource = this.player.getLocationSkin(); + + Minecraft.getMinecraft().getTextureManager().getTexture(resource); + + this.basePitch = new ValueFuncIO<>(() -> 15F); + this.pitchDriver = basePitch; + + this.baseYaw = new ValueFuncIO<>(() -> -30F); + this.yawDriver = baseYaw; + } + + public PanelPlayerPortrait setRotationFixed(float pitch, float yaw) { + this.pitchDriver = basePitch; + this.yawDriver = baseYaw; + basePitch.writeValue(pitch); + baseYaw.writeValue(yaw); + return this; + } + + public PanelPlayerPortrait setRotationDriven(IValueIO pitch, IValueIO yaw) { + this.pitchDriver = pitch == null ? basePitch : pitch; + this.yawDriver = yaw == null ? baseYaw : yaw; + return this; + } + + public PanelPlayerPortrait setDepth(float z) { + this.zDepth = z; + return this; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + IGuiRect bounds = this.getTransform(); + GlStateManager.pushMatrix(); + RenderUtils.startScissor(new GuiRectangle(bounds)); + + GlStateManager.color(1F, 1F, 1F, 1F); + int scale = Math.min(bounds.getWidth(), bounds.getHeight()); + RenderUtils.RenderEntity(bounds.getX() + bounds.getWidth() / 2f, + bounds.getY() + bounds.getHeight() / 2f + (int) (scale * 1.5F), zDepth, scale, + yawDriver.readValue(), pitchDriver.readValue(), player); + + RenderUtils.endScissor(); + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java index dce3d8ebc..7e8c6af2d 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java @@ -15,255 +15,223 @@ import java.util.Collections; import java.util.List; -public class PanelTextBox implements IGuiPanel -{ - private final GuiRectText transform; - private final GuiRectangle refRect = new GuiRectangle(0, 0, 0, 0, 0); - private boolean enabled = true; - - private String text = ""; - private boolean shadow = false; - private IGuiColor color = new GuiColorStatic(255, 255, 255, 255); - private final boolean autoFit; - private int align = 0; - private int fontScale = 12; - - private int lines = 1; // Cached number of lines - private final float relScale = 12F; - - public PanelTextBox(IGuiRect rect, String text) - { - this(rect, text, false); - } - - public PanelTextBox(IGuiRect rect, String text, boolean autoFit) - { - this.transform = new GuiRectText(rect, autoFit); - this.setText(text); - this.autoFit = autoFit; - } - - public PanelTextBox setText(String text) - { - this.text = text; - - refreshText(); - - return this; - } - - public PanelTextBox setColor(IGuiColor color) - { - this.color = color; - return this; - } - - public PanelTextBox setAlignment(int align) - { - this.align = MathHelper.clamp(align, 0, 2); - return this; - } - - public PanelTextBox setFontSize(int size) - { - this.fontScale = size; - return this; +public class PanelTextBox implements IGuiPanel { + private final GuiRectText transform; + private final GuiRectangle refRect = new GuiRectangle(0, 0, 0, 0, 0); + private boolean enabled = true; + + private String text = ""; + private boolean shadow = false; + private IGuiColor color = new GuiColorStatic(255, 255, 255, 255); + private final boolean autoFit; + private int align = 0; + private int fontScale = 12; + + private int lines = 1; // Cached number of lines + private final float relScale = 12F; + + public PanelTextBox(IGuiRect rect, String text) { + this(rect, text, false); + } + + public PanelTextBox(IGuiRect rect, String text, boolean autoFit) { + this.transform = new GuiRectText(rect, autoFit); + this.setText(text); + this.autoFit = autoFit; + } + + public PanelTextBox setText(String text) { + this.text = text; + + refreshText(); + + return this; + } + + public PanelTextBox setColor(IGuiColor color) { + this.color = color; + return this; + } + + public PanelTextBox setAlignment(int align) { + this.align = MathHelper.clamp(align, 0, 2); + return this; + } + + public PanelTextBox setFontSize(int size) { + this.fontScale = size; + return this; + } + + public PanelTextBox enableShadow(boolean enable) { + this.shadow = enable; + return this; + } + + private void refreshText() { + IGuiRect bounds = this.getTransform(); + FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + float scale = fontScale / relScale; + + if (!autoFit) { + lines = (int) Math.floor(bounds.getHeight() / (fr.FONT_HEIGHT * scale)) - 1; + return; + } + + int w = (int) Math.floor(bounds.getWidth() / scale); + List sl = w > 8 ? fr.listFormattedStringToWidth(text, w) : Collections.emptyList(); + lines = sl.size() - 1; + + this.transform.h = (int) Math.floor(fr.FONT_HEIGHT * sl.size() * scale); + + refRect.x = bounds.getX(); + refRect.y = bounds.getY(); + refRect.w = bounds.getWidth(); + refRect.h = bounds.getHeight(); + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void initPanel() { + refreshText(); + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (!isRectEqual(refRect, getTransform())) { + refreshText(); // Makes this panel work with resizable canvases without having to update every frame + } + if (lines < 0) { return; } + + IGuiRect bounds = this.getTransform(); + FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + //FontRenderer fr = BqFontRenderer.FONT_UNICODE; + //FontRenderer fr = BqFontRenderer.FONT_STANDARD; + + double s = fontScale / relScale; + int bw = (int) Math.ceil(bounds.getWidth() / s); + double w = Math.min(bw, RenderUtils.getStringWidth(text, fr) * s); + + if (bw <= 0) { return; } + + GlStateManager.pushMatrix(); + GlStateManager.translate(bounds.getX(), bounds.getY(), 1); + if (align == 1) { GlStateManager.translate(bounds.getWidth() / 2D - w / 2D, 0D, 0D); } + if (align == 2) { GlStateManager.translate(bounds.getWidth() - w, 0D, 0D); } + GlStateManager.scale(s, s, 1D); + + if (align == 2) { + RenderUtils.drawSplitString(fr, text, 0, 0, bw, color.getRGB(), shadow, 0, lines); + } else if (align == 1) { + RenderUtils.drawSplitString(fr, text, 0, 0, bw, color.getRGB(), shadow, 0, lines); + } else { + RenderUtils.drawSplitString(fr, text, 0, 0, bw, color.getRGB(), shadow, 0, lines); + } + + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return false; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + private static class GuiRectText implements IGuiRect { + private final IGuiRect proxy; + private final boolean useH; + private int h; + + public GuiRectText(IGuiRect proxy, boolean useH) { + this.proxy = proxy; + this.useH = useH; } - - public PanelTextBox enableShadow(boolean enable) - { - this.shadow = enable; - return this; - } - - private void refreshText() - { - IGuiRect bounds = this.getTransform(); - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - float scale = fontScale / relScale; - - if(!autoFit) - { - lines = (int)Math.floor(bounds.getHeight() / (fr.FONT_HEIGHT * scale)) - 1; - return; - } - - int w = (int)Math.floor(bounds.getWidth() / scale); - List sl = w > 8 ? fr.listFormattedStringToWidth(text, w) : Collections.emptyList(); - lines = sl.size() - 1; - - this.transform.h = (int)Math.floor(fr.FONT_HEIGHT * sl.size() * scale); - - refRect.x = bounds.getX(); - refRect.y = bounds.getY(); - refRect.w = bounds.getWidth(); - refRect.h = bounds.getHeight(); + + @Override + public int getX() { + return proxy.getX(); } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void initPanel() - { - refreshText(); - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(!isRectEqual(refRect, getTransform())) refreshText(); // Makes this panel work with resizable canvases without having to update every frame - if(lines < 0) return; - - IGuiRect bounds = this.getTransform(); - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - //FontRenderer fr = BqFontRenderer.FONT_UNICODE; - //FontRenderer fr = BqFontRenderer.FONT_STANDARD; - - double s = fontScale / relScale; - int bw = (int)Math.ceil(bounds.getWidth() / s); - double w = Math.min(bw, RenderUtils.getStringWidth(text, fr) * s); - - if(bw <= 0) return; - - GlStateManager.pushMatrix(); - GlStateManager.translate(bounds.getX(), bounds.getY(), 1); - if(align == 1) GlStateManager.translate(bounds.getWidth() / 2D - w / 2D, 0D, 0D); - if(align == 2) GlStateManager.translate(bounds.getWidth() - w, 0D, 0D); - GlStateManager.scale(s, s, 1D); - - if(align == 2) - { - RenderUtils.drawSplitString(fr, text, 0, 0, bw, color.getRGB(), shadow, 0, lines); - } else if(align == 1) - { - RenderUtils.drawSplitString(fr, text, 0, 0, bw, color.getRGB(), shadow, 0, lines); - } else - { - RenderUtils.drawSplitString(fr, text, 0, 0, bw, color.getRGB(), shadow, 0, lines); - } - - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } - - private static class GuiRectText implements IGuiRect - { - private final IGuiRect proxy; - private final boolean useH; - private int h; - - public GuiRectText(IGuiRect proxy, boolean useH) - { - this.proxy = proxy; - this.useH = useH; - } - - @Override - public int getX() - { - return proxy.getX(); - } - - @Override - public int getY() - { - return proxy.getY(); - } - - @Override - public int getWidth() - { - return proxy.getWidth(); - } - - @Override - public int getHeight() - { - return useH ? h : proxy.getHeight(); - } - - @Override - public int getDepth() - { - return proxy.getDepth(); - } - - @Override - public IGuiRect getParent() - { - return proxy.getParent(); - } - - @Override - public void setParent(IGuiRect rect) - { - proxy.setParent(rect); - } - - @Override - public boolean contains(int x, int y) - { - int x1 = this.getX(); - int x2 = x1 + this.getWidth(); - int y1 = this.getY(); - int y2 = y1 + this.getHeight(); - return x >= x1 && x < x2 && y >= y1 && y < y2; - } - - @Override - public int compareTo(@Nonnull IGuiRect o) - { - return proxy.compareTo(o); - } - } - - private boolean isRectEqual(IGuiRect r1, IGuiRect r2) - { - return r1.getX() == r2.getX() && r1.getY() == r2.getY() && r1.getWidth() == r2.getWidth() && r1.getHeight() == r2.getHeight(); + + @Override + public int getY() { + return proxy.getY(); + } + + @Override + public int getWidth() { + return proxy.getWidth(); } + + @Override + public int getHeight() { + return useH ? h : proxy.getHeight(); + } + + @Override + public int getDepth() { + return proxy.getDepth(); + } + + @Override + public IGuiRect getParent() { + return proxy.getParent(); + } + + @Override + public void setParent(IGuiRect rect) { + proxy.setParent(rect); + } + + @Override + public boolean contains(int x, int y) { + int x1 = this.getX(); + int x2 = x1 + this.getWidth(); + int y1 = this.getY(); + int y2 = y1 + this.getHeight(); + return x >= x1 && x < x2 && y >= y1 && y < y2; + } + + @Override + public int compareTo(@Nonnull IGuiRect o) { + return proxy.compareTo(o); + } + } + + private boolean isRectEqual(IGuiRect r1, IGuiRect r2) { + return r1.getX() == r2.getX() && r1.getY() == r2.getY() && r1.getWidth() == r2.getWidth() && + r1.getHeight() == r2.getHeight(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java index 5e594c182..b1055d575 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java @@ -4,207 +4,178 @@ import betterquesting.api2.client.gui.misc.GuiRectangle; import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.panels.IGuiPanel; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; -public class CanvasCullingManager -{ - private final List dynamicPanels = new ArrayList<>(); // Panels not regioned (likely moving or important) - - private final Map panelRegions = new HashMap<>(); // Panels separated into regional blocks - - private final List cachedPanels = new CopyOnWriteArrayList<>(); // The last updated list of visible panels - - private final int gridSize; - - public CanvasCullingManager() - { - this(128); - } - - public CanvasCullingManager(int gridSize) - { - this.gridSize = gridSize; - } - - public void reset() - { - dynamicPanels.clear(); - panelRegions.clear(); - cachedPanels.clear(); +public class CanvasCullingManager { + private final List dynamicPanels = new ArrayList<>(); // Panels not regioned (likely moving or important) + + private final Map panelRegions = new HashMap<>(); // Panels separated into regional blocks + + private final List cachedPanels = new CopyOnWriteArrayList<>(); // The last updated list of visible panels + + private final int gridSize; + + public CanvasCullingManager() { + this(128); + } + + public CanvasCullingManager(int gridSize) { + this.gridSize = gridSize; + } + + public void reset() { + dynamicPanels.clear(); + panelRegions.clear(); + cachedPanels.clear(); + } + + public void addPanel(IGuiPanel panel, boolean useBlocks) { + if (!useBlocks) { + if (!dynamicPanels.contains(panel)) { + dynamicPanels.add(panel); + cachedPanels.add(panel); + } + } else { + int x = panel.getTransform().getX(); + int y = panel.getTransform().getY(); + x = (x - ((x % gridSize) + gridSize) % gridSize) / gridSize; + y = (y - ((y % gridSize) + gridSize) % gridSize) / gridSize; + + RegionInfo cbl = panelRegions.get(x + "," + y); + + if (cbl != null) { + if (!cbl.panels.contains(panel)) { + cbl.panels.add(panel); + + int minX = Math.min(cbl.rect.x, panel.getTransform().getX()); + int minY = Math.min(cbl.rect.y, panel.getTransform().getY()); + int maxX = Math.max(cbl.rect.x + cbl.rect.w, panel.getTransform().getX() + panel.getTransform().getWidth()); + int maxY = Math.max(cbl.rect.y + cbl.rect.h, panel.getTransform().getY() + panel.getTransform().getHeight()); + + cbl.rect.x = minX; + cbl.rect.y = minY; + cbl.rect.w = maxX - minX; + cbl.rect.h = maxY - minY; + + if (cbl.enabled) { + cachedPanels.add(panel); + cachedPanels.sort(ComparatorGuiDepth.INSTANCE); + } + } + + } else { + cbl = new RegionInfo(x, y, gridSize); + + int minX = Math.min(cbl.rect.x, panel.getTransform().getX()); + int minY = Math.min(cbl.rect.y, panel.getTransform().getY()); + int maxX = Math.max(cbl.rect.x + cbl.rect.w, panel.getTransform().getX() + panel.getTransform().getWidth()); + int maxY = Math.max(cbl.rect.y + cbl.rect.h, panel.getTransform().getY() + panel.getTransform().getHeight()); + + cbl.rect.x = minX; + cbl.rect.y = minY; + cbl.rect.w = maxX - minX; + cbl.rect.h = maxY - minY; + + cbl.panels.add(panel); + panelRegions.put(x + "," + y, cbl); + } } - - public void addPanel(IGuiPanel panel, boolean useBlocks) - { - if(!useBlocks) - { - if(!dynamicPanels.contains(panel)) - { - dynamicPanels.add(panel); - cachedPanels.add(panel); - } - } else - { - int x = panel.getTransform().getX(); - int y = panel.getTransform().getY(); - x = (x - ((x % gridSize) + gridSize) % gridSize) / gridSize; - y = (y - ((y % gridSize) + gridSize) % gridSize) / gridSize; - - RegionInfo cbl = panelRegions.get(x + "," + y); - - if(cbl != null) - { - if(!cbl.panels.contains(panel)) - { - cbl.panels.add(panel); - - int minX = Math.min(cbl.rect.x, panel.getTransform().getX()); - int minY = Math.min(cbl.rect.y, panel.getTransform().getY()); - int maxX = Math.max(cbl.rect.x + cbl.rect.w, panel.getTransform().getX() + panel.getTransform().getWidth()); - int maxY = Math.max(cbl.rect.y + cbl.rect.h, panel.getTransform().getY() + panel.getTransform().getHeight()); - - cbl.rect.x = minX; - cbl.rect.y = minY; - cbl.rect.w = maxX - minX; - cbl.rect.h = maxY - minY; - - if(cbl.enabled) - { - cachedPanels.add(panel); - cachedPanels.sort(ComparatorGuiDepth.INSTANCE); - } - } - - } else - { - cbl = new RegionInfo(x, y, gridSize); - - int minX = Math.min(cbl.rect.x, panel.getTransform().getX()); - int minY = Math.min(cbl.rect.y, panel.getTransform().getY()); - int maxX = Math.max(cbl.rect.x + cbl.rect.w, panel.getTransform().getX() + panel.getTransform().getWidth()); - int maxY = Math.max(cbl.rect.y + cbl.rect.h, panel.getTransform().getY() + panel.getTransform().getHeight()); - - cbl.rect.x = minX; - cbl.rect.y = minY; - cbl.rect.w = maxX - minX; - cbl.rect.h = maxY - minY; - - cbl.panels.add(panel); - panelRegions.put(x + "," + y, cbl); - } + } + + public void removePanel(IGuiPanel panel) { + if (!dynamicPanels.remove(panel)) { + for (RegionInfo cbl : panelRegions.values()) { + if (cbl.panels.remove(panel)) { + cbl.refreshBounds(); + cachedPanels.remove(panel); + break; } + } + } else { + cachedPanels.remove(panel); } - - public void removePanel(IGuiPanel panel) - { - if(!dynamicPanels.remove(panel)) - { - for(RegionInfo cbl : panelRegions.values()) - { - if(cbl.panels.remove(panel)) - { - cbl.refreshBounds(); - cachedPanels.remove(panel); - break; - } - } - } else - { - cachedPanels.remove(panel); + } + + public List getVisiblePanels() { + return cachedPanels; + } + + public void updateVisiblePanels(IGuiRect region) { + boolean changed = false; + + for (RegionInfo cb : panelRegions.values()) { + boolean prevState = cb.enabled; + cb.enabled = overlapCheck(cb.rect, region); + + if (prevState != cb.enabled) { + if (cb.enabled) { + cachedPanels.addAll(cb.panels); + } else { + cachedPanels.removeAll(cb.panels); } + + changed = true; + } } - - public List getVisiblePanels() - { - return cachedPanels; + + if (changed) { + cachedPanels.sort(ComparatorGuiDepth.INSTANCE); } - - public void updateVisiblePanels(IGuiRect region) + } + + // TODO: Move this to a utility class + private static boolean overlapCheck(IGuiRect rect1, IGuiRect rect2) { + if (rect1.getX() + rect1.getWidth() < rect2.getX() || + rect1.getX() > rect2.getX() + rect2.getWidth()) // Rectangle outside width bounds { - boolean changed = false; - - for(RegionInfo cb : panelRegions.values()) - { - boolean prevState = cb.enabled; - cb.enabled = overlapCheck(cb.rect, region); - - if(prevState != cb.enabled) - { - if(cb.enabled) - { - cachedPanels.addAll(cb.panels); - } else - { - cachedPanels.removeAll(cb.panels); - } - - changed = true; - } - } - - if(changed) - { - cachedPanels.sort(ComparatorGuiDepth.INSTANCE); - } + return false; + } else { + return rect1.getY() + rect1.getHeight() >= rect2.getY() && rect1.getY() <= rect2.getY() + rect2.getHeight(); } - - // TODO: Move this to a utility class - private static boolean overlapCheck(IGuiRect rect1, IGuiRect rect2) - { - if(rect1.getX() + rect1.getWidth() < rect2.getX() || rect1.getX() > rect2.getX() + rect2.getWidth()) // Rectangle outside width bounds - { - return false; - } else - { - return rect1.getY() + rect1.getHeight() >= rect2.getY() && rect1.getY() <= rect2.getY() + rect2.getHeight(); - } + } + + private static class RegionInfo { + private final List panels = new ArrayList<>(); + + private boolean enabled = false; // Starts disabled so that the cache can be populated on initial checks + private final GuiRectangle rect; + // Needs to be updated with the min-max bounds (doesn't actually conform to any grid) + + private RegionInfo(int blockX, int blockY, int gridSize) { + this.rect = new GuiRectangle(blockX * gridSize, blockY * gridSize, gridSize, gridSize); } - - private static class RegionInfo - { - private final List panels = new ArrayList<>(); - - private boolean enabled = false; // Starts disabled so that the cache can be populated on initial checks - private final GuiRectangle rect; // Needs to be updated with the min-max bounds (doesn't actually conform to any grid) - - private RegionInfo(int blockX, int blockY, int gridSize) - { - this.rect = new GuiRectangle(blockX * gridSize, blockY * gridSize, gridSize, gridSize); - } - - private void refreshBounds() - { - boolean set = false; - int minX = 0; - int minY = 0; - int maxX = 0; - int maxY = 0; - - for(IGuiPanel pan : panels) - { - if(!set) - { - set = true; - minX = pan.getTransform().getX(); - minY = pan.getTransform().getY(); - maxX = minX + pan.getTransform().getWidth(); - maxY = minY + pan.getTransform().getHeight(); - } else - { - minX = Math.min(minX, pan.getTransform().getX()); - minY = Math.min(minY, pan.getTransform().getY()); - maxX = Math.max(maxX, pan.getTransform().getX() + pan.getTransform().getWidth()); - maxY = Math.max(maxY, pan.getTransform().getY() + pan.getTransform().getHeight()); - } - } - - rect.x = minX; - rect.y = minY; - rect.w = maxX - minX; - rect.h = maxY - minY; + + private void refreshBounds() { + boolean set = false; + int minX = 0; + int minY = 0; + int maxX = 0; + int maxY = 0; + + for (IGuiPanel pan : panels) { + if (!set) { + set = true; + minX = pan.getTransform().getX(); + minY = pan.getTransform().getY(); + maxX = minX + pan.getTransform().getWidth(); + maxY = minY + pan.getTransform().getHeight(); + } else { + minX = Math.min(minX, pan.getTransform().getX()); + minY = Math.min(minY, pan.getTransform().getY()); + maxX = Math.max(maxX, pan.getTransform().getX() + pan.getTransform().getWidth()); + maxY = Math.max(maxY, pan.getTransform().getY() + pan.getTransform().getHeight()); } + } + + rect.x = minX; + rect.y = minY; + rect.w = maxX - minX; + rect.h = maxY - minY; } + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java index 48d5bbb67..bf2a005f8 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java @@ -6,49 +6,46 @@ import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.fml.common.registry.ForgeRegistries; -import java.util.*; - -public class CanvasEntityDatabase extends CanvasSearch -{ - private final int btnId; - - public CanvasEntityDatabase(IGuiRect rect, int buttonId) - { - super(rect); - this.btnId = buttonId; - } - - @Override - protected Iterator getIterator() - { - List list = new ArrayList<>(ForgeRegistries.ENTITIES.getValuesCollection()); - list.sort((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); - return list.iterator(); - } - - @Override - protected void queryMatches(EntityEntry ee, String query, final ArrayDeque results) - { - if(ee == null || ee.getRegistryName() == null) return; - - String qlc = query.toLowerCase(); - - if(ee.getRegistryName().toString().toLowerCase().contains(qlc) || ee.getName().toLowerCase().contains(qlc)) - { - results.add(ee); - } +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class CanvasEntityDatabase extends CanvasSearch { + private final int btnId; + + public CanvasEntityDatabase(IGuiRect rect, int buttonId) { + super(rect); + this.btnId = buttonId; + } + + @Override + protected Iterator getIterator() { + List list = new ArrayList<>(ForgeRegistries.ENTITIES.getValuesCollection()); + list.sort((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); + return list.iterator(); + } + + @Override + protected void queryMatches(EntityEntry ee, String query, final ArrayDeque results) { + if (ee == null || ee.getRegistryName() == null) { return; } + + String qlc = query.toLowerCase(); + + if (ee.getRegistryName().toString().toLowerCase().contains(qlc) || ee.getName().toLowerCase().contains(qlc)) { + results.add(ee); } - - @Override - protected boolean addResult(EntityEntry ee, int index, int cachedWidth) - { - if(ee == null) - { - return false; - } - - this.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), btnId, ee.getName(), ee)); - - return true; + } + + @Override + protected boolean addResult(EntityEntry ee, int index, int cachedWidth) { + if (ee == null) { + return false; } + + this.addPanel( + new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), btnId, ee.getName(), ee)); + + return true; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java index aa4ccc4ef..6d689451c 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java @@ -7,72 +7,54 @@ import java.util.*; @SuppressWarnings("WeakerAccess") -public abstract class CanvasFileDirectory extends CanvasSearch -{ - private static final FileSort sorter = new FileSort(); - private final FileFilter filter; - private File curDir; - - public CanvasFileDirectory(IGuiRect rect, File dirStart, FileFilter filter) - { - super(rect); - this.filter = filter; - this.curDir = dirStart; - - if(curDir != null && !curDir.isDirectory()) curDir = curDir.getParentFile(); - } - - public void setCurDirectory(File file) - { - curDir = file; - this.refreshSearch(); - this.scrollY.writeValue(0F); - } - - @Override - protected Iterator getIterator() - { - File[] files; - if(curDir == null) - { - files = File.listRoots(); - } else - { - files = !curDir.isDirectory() ? new File[0] : curDir.listFiles(filter); - } - if(files == null) files = new File[0]; - List fList = Arrays.asList(files); - fList.sort(sorter); - return fList.iterator(); +public abstract class CanvasFileDirectory extends CanvasSearch { + private static final FileSort sorter = new FileSort(); + private final FileFilter filter; + private File curDir; + + public CanvasFileDirectory(IGuiRect rect, File dirStart, FileFilter filter) { + super(rect); + this.filter = filter; + this.curDir = dirStart; + + if (curDir != null && !curDir.isDirectory()) { curDir = curDir.getParentFile(); } + } + + public void setCurDirectory(File file) { + curDir = file; + this.refreshSearch(); + this.scrollY.writeValue(0F); + } + + @Override + protected Iterator getIterator() { + File[] files; + if (curDir == null) { + files = File.listRoots(); + } else { + files = !curDir.isDirectory() ? new File[0] : curDir.listFiles(filter); } - + if (files == null) { files = new File[0]; } + List fList = Arrays.asList(files); + fList.sort(sorter); + return fList.iterator(); + } + + @Override + protected void queryMatches(File value, String query, ArrayDeque results) { + if (value.getName().toLowerCase().contains(query.toLowerCase())) { results.add(value); } + } + + private static class FileSort implements Comparator { @Override - protected void queryMatches(File value, String query, ArrayDeque results) - { - if(value.getName().toLowerCase().contains(query.toLowerCase())) results.add(value); - } - - private static class FileSort implements Comparator - { - @Override - public int compare(File f1, File f2) - { - if(f1 == null || f2 == null) - { - return 0; - } else if(f1.isDirectory() == f2.isDirectory()) - { - return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase()); - } else - { - return f1.isDirectory() ? -1 : 1; - } - } - - @Override - public boolean equals(Object obj) - { - return obj == this; - } + public int compare(File f1, File f2) { + if (f1 == null || f2 == null) { + return 0; + } else if (f1.isDirectory() == f2.isDirectory()) { + return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase()); + } else { + return f1.isDirectory() ? -1 : 1; + } } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java index e84804fda..af3b8ebab 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java @@ -11,58 +11,51 @@ import java.util.ArrayDeque; import java.util.Iterator; -public class CanvasFluidDatabase extends CanvasSearch -{ - private final int btnId; - - public CanvasFluidDatabase(IGuiRect rect, int buttonId) - { - super(rect); - - this.btnId = buttonId; - } - - @Override - protected Iterator getIterator() - { - return FluidRegistry.getRegisteredFluids().values().iterator(); +public class CanvasFluidDatabase extends CanvasSearch { + private final int btnId; + + public CanvasFluidDatabase(IGuiRect rect, int buttonId) { + super(rect); + + this.btnId = buttonId; + } + + @Override + protected Iterator getIterator() { + return FluidRegistry.getRegisteredFluids().values().iterator(); + } + + @Override + protected void queryMatches(Fluid fluid, String query, final ArrayDeque results) { + if (fluid == null || fluid.getName() == null) { + return; } - - @Override - protected void queryMatches(Fluid fluid, String query, final ArrayDeque results) - { - if(fluid == null || fluid.getName() == null) - { - return; - } - - try - { - FluidStack stack = new FluidStack(fluid, 1000); - if(fluid.getUnlocalizedName().toLowerCase().contains(query) || fluid.getLocalizedName(stack).toLowerCase().contains(query) || fluid.getName().toLowerCase().contains(query)) - { - results.add(stack); - } - } catch(Exception e) - { - BetterQuesting.logger.error("An error occured while searching fluid \"" + fluid.getName() + "\" (" + fluid.getClass().getName() + ")", e); - } + try { + FluidStack stack = new FluidStack(fluid, 1000); + + if (fluid.getUnlocalizedName().toLowerCase().contains(query) || + fluid.getLocalizedName(stack).toLowerCase().contains(query) || + fluid.getName().toLowerCase().contains(query)) { + results.add(stack); + } + } catch (Exception e) { + BetterQuesting.logger.error( + "An error occured while searching fluid \"" + fluid.getName() + "\" (" + fluid.getClass().getName() + ")", e); } - - @Override - protected boolean addResult(FluidStack stack, int index, int cachedWidth) - { - if(stack == null) - { - return false; - } - - int x = (index % (cachedWidth / 18)) * 18; - int y = (index / (cachedWidth / 18)) * 18; - - this.addPanel(new PanelFluidSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, stack)); - - return true; + } + + @Override + protected boolean addResult(FluidStack stack, int index, int cachedWidth) { + if (stack == null) { + return false; } + + int x = (index % (cachedWidth / 18)) * 18; + int y = (index / (cachedWidth / 18)) * 18; + + this.addPanel(new PanelFluidSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, stack)); + + return true; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java index 1872079c2..c0845ec87 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java @@ -8,125 +8,108 @@ import betterquesting.api2.client.gui.panels.IGuiCanvas; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; -public class CanvasHoverTray extends CanvasResizeable -{ - private boolean manualOpen = false; - - private final IGuiRect rectClosed; - private final IGuiRect rectOpen; - - // Note: You can still attach things to the base canvas instead of these if they don't need to move/switch - private final IGuiCanvas cvOpen; - private final IGuiCanvas cvClosed; - - private Runnable actionOpen; - private Runnable actionClose; - - public CanvasHoverTray(IGuiRect rectClosed, IGuiRect rectOpen, IGuiTexture texture) - { - super(rectClosed, texture); - - this.rectClosed = rectClosed; - this.rectOpen = rectOpen; - - GuiTransform trans = new GuiTransform(GuiAlign.FULL_BOX); - trans.setParent(this.getRectLerp()); - cvOpen = new CanvasEmpty(trans); - cvClosed = new CanvasEmpty(trans); - } - - public IGuiCanvas getCanvasOpen() - { - return cvOpen; - } - - public IGuiCanvas getCanvasClosed() - { - return cvClosed; - } - - public boolean isTrayOpen() - { - return cvOpen.isEnabled(); - } - - public CanvasHoverTray setManualOpen(boolean state) - { - this.manualOpen = state; - return this; - } - - public CanvasHoverTray setCloseAction(Runnable action) - { - this.actionClose = action; - return this; - } - - public CanvasHoverTray setOpenAction(Runnable action) - { - this.actionOpen = action; - return this; - } - - public void setTrayState(boolean open, long time) - { - if(!open && isTrayOpen()) - { - this.lerpToRect(rectClosed, time, true); - cvOpen.setEnabled(false); - cvClosed.setEnabled(true); - if(actionClose != null) actionClose.run(); - } else if(open && !isTrayOpen()) - { - this.lerpToRect(rectOpen, time, true); - cvOpen.setEnabled(true); - cvClosed.setEnabled(false); - if(actionOpen != null) actionOpen.run(); - } - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(!manualOpen) - { - if(isTrayOpen() && !rectOpen.contains(mx, my)) - { - setTrayState(false, 200); - } else if(!isTrayOpen() && rectClosed.contains(mx, my)) - { - setTrayState(true, 200); - } - } - - super.drawPanel(mx, my, partialTick); - } - - @Override - public void resetCanvas() - { - super.resetCanvas(); - - cvOpen.resetCanvas(); - cvClosed.resetCanvas(); - - this.addPanel(cvOpen); - this.addPanel(cvClosed); - cvOpen.setEnabled(false); - cvClosed.setEnabled(true); +public class CanvasHoverTray extends CanvasResizeable { + private boolean manualOpen = false; + + private final IGuiRect rectClosed; + private final IGuiRect rectOpen; + + // Note: You can still attach things to the base canvas instead of these if they don't need to move/switch + private final IGuiCanvas cvOpen; + private final IGuiCanvas cvClosed; + + private Runnable actionOpen; + private Runnable actionClose; + + public CanvasHoverTray(IGuiRect rectClosed, IGuiRect rectOpen, IGuiTexture texture) { + super(rectClosed, texture); + + this.rectClosed = rectClosed; + this.rectOpen = rectOpen; + + GuiTransform trans = new GuiTransform(GuiAlign.FULL_BOX); + trans.setParent(this.getRectLerp()); + cvOpen = new CanvasEmpty(trans); + cvClosed = new CanvasEmpty(trans); + } + + public IGuiCanvas getCanvasOpen() { + return cvOpen; + } + + public IGuiCanvas getCanvasClosed() { + return cvClosed; + } + + public boolean isTrayOpen() { + return cvOpen.isEnabled(); + } + + public CanvasHoverTray setManualOpen(boolean state) { + this.manualOpen = state; + return this; + } + + public CanvasHoverTray setCloseAction(Runnable action) { + this.actionClose = action; + return this; + } + + public CanvasHoverTray setOpenAction(Runnable action) { + this.actionOpen = action; + return this; + } + + public void setTrayState(boolean open, long time) { + if (!open && isTrayOpen()) { + this.lerpToRect(rectClosed, time, true); + cvOpen.setEnabled(false); + cvClosed.setEnabled(true); + if (actionClose != null) { actionClose.run(); } + } else if (open && !isTrayOpen()) { + this.lerpToRect(rectOpen, time, true); + cvOpen.setEnabled(true); + cvClosed.setEnabled(false); + if (actionOpen != null) { actionOpen.run(); } } - - @Override - public void initPanel() - { - super.initPanel(); - - this.addPanel(cvOpen); - this.addPanel(cvClosed); - cvOpen.setEnabled(false); - cvClosed.setEnabled(true); - - // May cause some issues elsewhere but for now this is fine - rectOpen.setParent(rectClosed.getParent()); + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (!manualOpen) { + if (isTrayOpen() && !rectOpen.contains(mx, my)) { + setTrayState(false, 200); + } else if (!isTrayOpen() && rectClosed.contains(mx, my)) { + setTrayState(true, 200); + } } + + super.drawPanel(mx, my, partialTick); + } + + @Override + public void resetCanvas() { + super.resetCanvas(); + + cvOpen.resetCanvas(); + cvClosed.resetCanvas(); + + this.addPanel(cvOpen); + this.addPanel(cvClosed); + cvOpen.setEnabled(false); + cvClosed.setEnabled(true); + } + + @Override + public void initPanel() { + super.initPanel(); + + this.addPanel(cvOpen); + this.addPanel(cvClosed); + cvOpen.setEnabled(false); + cvClosed.setEnabled(true); + + // May cause some issues elsewhere but for now this is fine + rectOpen.setParent(rectClosed.getParent()); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java index 451f688c0..90ba02518 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java @@ -17,92 +17,82 @@ import java.util.ArrayDeque; import java.util.Iterator; -public class CanvasItemDatabase extends CanvasSearch -{ - private final int btnId; - - public CanvasItemDatabase(IGuiRect rect, int buttonId) - { - super(rect); - - this.btnId = buttonId; - } - - @Override - protected Iterator getIterator() - { - return Item.REGISTRY.iterator(); +public class CanvasItemDatabase extends CanvasSearch { + private final int btnId; + + public CanvasItemDatabase(IGuiRect rect, int buttonId) { + super(rect); + + this.btnId = buttonId; + } + + @Override + protected Iterator getIterator() { + return Item.REGISTRY.iterator(); + } + + @Override + protected void queryMatches(Item item, String query, final ArrayDeque results) { + if (item == null || item.getRegistryName() == null) { + return; + } else if (item == Items.AIR) { + results.add(ItemStack.EMPTY); + return; } - - @Override - protected void queryMatches(Item item, String query, final ArrayDeque results) - { - if(item == null || item.getRegistryName() == null) - { - return; - } else if(item == Items.AIR) - { - results.add(ItemStack.EMPTY); - return; - } - - try - { - NonNullList subList = NonNullList.create(); - - item.getSubItems(CreativeTabs.SEARCH, subList); - - if(subList.isEmpty()) - { - subList.add(item.getDefaultInstance()); + + try { + NonNullList subList = NonNullList.create(); + + item.getSubItems(CreativeTabs.SEARCH, subList); + + if (subList.isEmpty()) { + subList.add(item.getDefaultInstance()); + } + + if (item.getTranslationKey().toLowerCase().contains(query) || + QuestTranslation.translate(item.getTranslationKey()).toLowerCase().contains(query) || + item.getRegistryName().toString().toLowerCase().contains(query)) { + results.addAll(subList); + } else { + for (ItemStack subItem : subList) { + try { + if (subItem.getTranslationKey().toLowerCase().contains(query) || + subItem.getDisplayName().toLowerCase().contains(query)) { + results.add(subItem); + continue; } - - if(item.getTranslationKey().toLowerCase().contains(query) || QuestTranslation.translate(item.getTranslationKey()).toLowerCase().contains(query) || item.getRegistryName().toString().toLowerCase().contains(query)) - { - results.addAll(subList); - } else - { - for(ItemStack subItem : subList) - { - try - { - if(subItem.getTranslationKey().toLowerCase().contains(query) || subItem.getDisplayName().toLowerCase().contains(query)) - { - results.add(subItem); - continue; - } - - int[] oids = OreDictionary.getOreIDs(subItem); - for(int oid : oids) - { - if(OreDictionary.getOreName(oid).toLowerCase().contains(query)) - { - results.add(subItem); - break; - } - } - } catch(Exception e) - { - BetterQuesting.logger.error("An error occured while searching itemstack " + subItem.toString() + " from item \"" + item.getRegistryName() + "\" (" + item.getClass().getName() + ").\nNBT: " + subItem.writeToNBT(new NBTTagCompound()), e); - } - } + + int[] oids = OreDictionary.getOreIDs(subItem); + for (int oid : oids) { + if (OreDictionary.getOreName(oid).toLowerCase().contains(query)) { + results.add(subItem); + break; + } } - } catch(Exception e) - { - BetterQuesting.logger.error("An error occured while searching item \"" + item.getRegistryName() + "\" (" + item.getClass().getName() + ")", e); + } catch (Exception e) { + BetterQuesting.logger.error( + "An error occured while searching itemstack " + subItem.toString() + " from item \"" + + item.getRegistryName() + "\" (" + item.getClass().getName() + ").\nNBT: " + + subItem.writeToNBT(new NBTTagCompound()), e); + } } + } + } catch (Exception e) { + BetterQuesting.logger.error( + "An error occured while searching item \"" + item.getRegistryName() + "\" (" + item.getClass().getName() + + ")", e); } - - @Override - public boolean addResult(ItemStack stack, int index, int cachedWidth) - { - if(stack == null) return false; - - int x = (index % (cachedWidth / 18)) * 18; - int y = (index / (cachedWidth / 18)) * 18; - - this.addPanel(new PanelItemSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, new BigItemStack(stack))); - - return true; - } + } + + @Override + public boolean addResult(ItemStack stack, int index, int cachedWidth) { + if (stack == null) { return false; } + + int x = (index % (cachedWidth / 18)) * 18; + int y = (index / (cachedWidth / 18)) * 18; + + this.addPanel(new PanelItemSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, new BigItemStack(stack))); + + return true; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestDatabase.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestDatabase.java index 36213ba2e..61251fc5f 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestDatabase.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestDatabase.java @@ -11,25 +11,22 @@ import java.util.Iterator; @SuppressWarnings("WeakerAccess") -public abstract class CanvasQuestDatabase extends CanvasSearch, DBEntry> -{ - public CanvasQuestDatabase(IGuiRect rect) - { - super(rect); - } - - @Override - protected Iterator> getIterator() - { - return QuestDatabase.INSTANCE.getEntries().iterator(); - } - - @Override - protected void queryMatches(DBEntry entry, String query, final ArrayDeque> results) - { - if(("" + entry.getID()).contains(query) || entry.getValue().getProperty(NativeProps.NAME).toLowerCase().contains(query) || QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)).toLowerCase().contains(query)) - { - results.add(entry); - } +public abstract class CanvasQuestDatabase extends CanvasSearch, DBEntry> { + public CanvasQuestDatabase(IGuiRect rect) { + super(rect); + } + + @Override + protected Iterator> getIterator() { + return QuestDatabase.INSTANCE.getEntries().iterator(); + } + + @Override + protected void queryMatches(DBEntry entry, String query, final ArrayDeque> results) { + if (("" + entry.getID()).contains(query) || + entry.getValue().getProperty(NativeProps.NAME).toLowerCase().contains(query) || + QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)).toLowerCase().contains(query)) { + results.add(entry); } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java index 9f000bc5a..d2a0efc1f 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java @@ -30,180 +30,171 @@ /** * My class for lazy quest line setup on a scrolling canvas */ -public class CanvasQuestLine extends CanvasScrolling -{ - private final List btnList = new ArrayList<>(); - - private final int buttonId; - private IQuestLine lastQL; - - public CanvasQuestLine(IGuiRect rect, int buttonId) - { - super(rect); - this.setupAdvanceScroll(true, true, 24); - this.enableBlocking(false); - this.buttonId = buttonId; - } - - public Collection getQuestButtons() - { - return Collections.unmodifiableCollection(this.btnList); - } - - public PanelButtonQuest getButtonAt(int mx, int my) - { - float zs = zoomScale.readValue(); - int tx = getTransform().getX(); - int ty = getTransform().getY(); - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - for(PanelButtonQuest btn : btnList) - { - if(btn.rect.contains(smx, smy)) return btn; - } - - return null; +public class CanvasQuestLine extends CanvasScrolling { + private final List btnList = new ArrayList<>(); + + private final int buttonId; + private IQuestLine lastQL; + + public CanvasQuestLine(IGuiRect rect, int buttonId) { + super(rect); + this.setupAdvanceScroll(true, true, 24); + this.enableBlocking(false); + this.buttonId = buttonId; + } + + public Collection getQuestButtons() { + return Collections.unmodifiableCollection(this.btnList); + } + + public PanelButtonQuest getButtonAt(int mx, int my) { + float zs = zoomScale.readValue(); + int tx = getTransform().getX(); + int ty = getTransform().getY(); + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + for (PanelButtonQuest btn : btnList) { + if (btn.rect.contains(smx, smy)) { return btn; } } - - public IQuestLine getQuestLine() - { - return lastQL; + + return null; + } + + public IQuestLine getQuestLine() { + return lastQL; + } + + public void refreshQuestLine() { + setQuestLine(lastQL); + } + + /** + * Loads in quests and connecting lines + * + * @param line The quest line to load + */ + public void setQuestLine(IQuestLine line) { + // Rest contents + this.resetCanvas(); + this.btnList.clear(); + lastQL = line; + + if (line == null) { return; } + + EntityPlayer player = Minecraft.getMinecraft().player; + UUID pid = QuestingAPI.getQuestingUUID(player); + + String bgString = line.getProperty(NativeProps.BG_IMAGE); + + if (!StringUtils.isNullOrEmpty(bgString)) { + int bgSize = line.getProperty(NativeProps.BG_SIZE); + this.addPanel(new PanelGeneric(new GuiRectangle(0, 0, bgSize, bgSize, 1), + new SimpleTexture(new ResourceLocation(bgString), + new GuiRectangle(0, 0, 256, 256)))); } - - public void refreshQuestLine() - { - setQuestLine(lastQL); + + HashMap questBtns = new HashMap<>(); + + for (DBEntry qle : line.getEntries()) { + IQuest quest = QuestingAPI.getAPI(ApiReference.QUEST_DB).getValue(qle.getID()); + + if (!QuestCache.isQuestShown(quest, pid, player)) { continue; } + + GuiRectangle rect = + new GuiRectangle(qle.getValue().getPosX(), qle.getValue().getPosY(), qle.getValue().getSizeX(), + qle.getValue().getSizeY()); + PanelButtonQuest paBtn = new PanelButtonQuest(rect, buttonId, "", new DBEntry<>(qle.getID(), quest)); + + this.addPanel(paBtn); + this.btnList.add(paBtn); + questBtns.put(qle.getID(), paBtn); } - - /** - * Loads in quests and connecting lines - * @param line The quest line to load - */ - public void setQuestLine(IQuestLine line) - { - // Rest contents - this.resetCanvas(); - this.btnList.clear(); - lastQL = line; - - if(line == null) return; - - EntityPlayer player = Minecraft.getMinecraft().player; - UUID pid = QuestingAPI.getQuestingUUID(player); - - String bgString = line.getProperty(NativeProps.BG_IMAGE); - - if(!StringUtils.isNullOrEmpty(bgString)) - { - int bgSize = line.getProperty(NativeProps.BG_SIZE); - this.addPanel(new PanelGeneric(new GuiRectangle(0, 0, bgSize, bgSize, 1), new SimpleTexture(new ResourceLocation(bgString), new GuiRectangle(0, 0, 256, 256)))); - } - - HashMap questBtns = new HashMap<>(); - - for(DBEntry qle : line.getEntries()) - { - IQuest quest = QuestingAPI.getAPI(ApiReference.QUEST_DB).getValue(qle.getID()); - - if(!QuestCache.isQuestShown(quest, pid, player)) continue; - - GuiRectangle rect = new GuiRectangle(qle.getValue().getPosX(), qle.getValue().getPosY(), qle.getValue().getSizeX(), qle.getValue().getSizeY()); - PanelButtonQuest paBtn = new PanelButtonQuest(rect, buttonId, "", new DBEntry<>(qle.getID(), quest)); - - this.addPanel(paBtn); - this.btnList.add(paBtn); - questBtns.put(qle.getID(), paBtn); - } - - for(Entry entry : questBtns.entrySet()) - { - DBEntry quest = entry.getValue().getStoredValue(); - - List> reqList = QuestingAPI.getAPI(ApiReference.QUEST_DB).bulkLookup(quest.getValue().getRequirements()); - - if(reqList.size() <= 0) continue; - - boolean main = quest.getValue().getProperty(NativeProps.MAIN); - EnumQuestState qState = quest.getValue().getState(pid); - IGuiLine lineRender = null; - IGuiColor txLineCol = null; - - switch(qState) - { - case LOCKED: - lineRender = PresetLine.QUEST_LOCKED.getLine(); - txLineCol = PresetColor.QUEST_LINE_LOCKED.getColor(); - break; - case UNLOCKED: - lineRender = PresetLine.QUEST_UNLOCKED.getLine(); - txLineCol = PresetColor.QUEST_LINE_UNLOCKED.getColor(); - break; - case UNCLAIMED: - lineRender = PresetLine.QUEST_PENDING.getLine(); - txLineCol = PresetColor.QUEST_LINE_PENDING.getColor(); - break; - case COMPLETED: - lineRender = PresetLine.QUEST_COMPLETE.getLine(); - txLineCol = PresetColor.QUEST_LINE_COMPLETE.getColor(); - break; - } - - for(DBEntry req : reqList) - { - PanelButtonQuest parBtn = questBtns.get(req.getID()); - - if(parBtn != null) - { - PanelLine prLine = new PanelLine(parBtn.getTransform(), entry.getValue().getTransform(), lineRender, main? 8 : 4, txLineCol, 1); - this.addPanel(prLine); - } - } + + for (Entry entry : questBtns.entrySet()) { + DBEntry quest = entry.getValue().getStoredValue(); + + List> reqList = + QuestingAPI.getAPI(ApiReference.QUEST_DB).bulkLookup(quest.getValue().getRequirements()); + + if (reqList.isEmpty()) { continue; } + + boolean main = quest.getValue().getProperty(NativeProps.MAIN); + EnumQuestState qState = quest.getValue().getState(pid); + IGuiLine lineRender = null; + IGuiColor txLineCol = null; + + switch (qState) { + case LOCKED: + lineRender = PresetLine.QUEST_LOCKED.getLine(); + txLineCol = PresetColor.QUEST_LINE_LOCKED.getColor(); + break; + case UNLOCKED: + lineRender = PresetLine.QUEST_UNLOCKED.getLine(); + txLineCol = PresetColor.QUEST_LINE_UNLOCKED.getColor(); + break; + case UNCLAIMED: + lineRender = PresetLine.QUEST_PENDING.getLine(); + txLineCol = PresetColor.QUEST_LINE_PENDING.getColor(); + break; + case COMPLETED: + lineRender = PresetLine.QUEST_COMPLETE.getLine(); + txLineCol = PresetColor.QUEST_LINE_COMPLETE.getColor(); + break; + } + + for (DBEntry req : reqList) { + PanelButtonQuest parBtn = questBtns.get(req.getID()); + + if (parBtn != null) { + PanelLine prLine = + new PanelLine(parBtn.getTransform(), entry.getValue().getTransform(), lineRender, main ? 8 : 4, txLineCol, + 1); + this.addPanel(prLine); } - - fitToWindow(); + } } - - public void fitToWindow() - { - // Used later to center focus the quest line within the window - boolean flag = false; - int minX = 0; - int minY = 0; - int maxX = 0; - int maxY = 0; - - for(PanelButtonQuest btn : btnList) - { - GuiRectangle rect = btn.rect; - - if(!flag) - { - minX = rect.getX(); - minY = rect.getY(); - maxX = minX + rect.getWidth(); - maxY = minY + rect.getHeight(); - flag = true; - } else - { - minX = Math.min(minX, rect.getX()); - minY = Math.min(minY, rect.getY()); - maxX = Math.max(maxX, rect.getX() + rect.getWidth()); - maxY = Math.max(maxY, rect.getY() + rect.getHeight()); - } - } - - minX -= margin; - minY -= margin; - maxX += margin; - maxY += margin; - - this.setZoom(Math.min(getTransform().getWidth()/(float)(maxX - minX), getTransform().getHeight()/(float)(maxY - minY))); - this.refreshScrollBounds(); - - IGuiRect bounds = getScrollBounds(); - this.setScrollX(bounds.getX() + bounds.getWidth()/2); - this.setScrollY(bounds.getY() + bounds.getHeight()/2); - this.updatePanelScroll(); + + fitToWindow(); + } + + public void fitToWindow() { + // Used later to center focus the quest line within the window + boolean flag = false; + int minX = 0; + int minY = 0; + int maxX = 0; + int maxY = 0; + + for (PanelButtonQuest btn : btnList) { + GuiRectangle rect = btn.rect; + + if (!flag) { + minX = rect.getX(); + minY = rect.getY(); + maxX = minX + rect.getWidth(); + maxY = minY + rect.getHeight(); + flag = true; + } else { + minX = Math.min(minX, rect.getX()); + minY = Math.min(minY, rect.getY()); + maxX = Math.max(maxX, rect.getX() + rect.getWidth()); + maxY = Math.max(maxY, rect.getY() + rect.getHeight()); + } } + + minX -= margin; + minY -= margin; + maxX += margin; + maxY += margin; + + this.setZoom(Math.min(getTransform().getWidth() / (float) (maxX - minX), + getTransform().getHeight() / (float) (maxY - minY))); + this.refreshScrollBounds(); + + IGuiRect bounds = getScrollBounds(); + this.setScrollX(bounds.getX() + bounds.getWidth() / 2); + this.setScrollY(bounds.getY() + bounds.getHeight() / 2); + this.updatePanelScroll(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java index f809a8581..bfcabc156 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java @@ -16,577 +16,517 @@ import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; -public class CanvasScrolling implements IGuiCanvas -{ - private final List guiPanels = new CopyOnWriteArrayList<>(); - private final IGuiRect transform; - private boolean enabled = true; - - // Scrolling bounds - protected final GuiRectangle scrollBounds = new GuiRectangle(0, 0, 0, 0); - private final GuiRectangle scrollWindow = new GuiRectangle(0, 0 ,0, 0); - protected boolean extendedScroll = false; - protected boolean zoomMode = false; - protected int margin = 0; - // Scroll and zoom drivers - protected IValueIO scrollX; - protected IValueIO scrollY; - protected IValueIO zoomScale; - - private boolean isDragging = false; // Mouse buttons held for dragging - private boolean hasDragged = false; // Dragging used. Don't fire onMouseRelease - protected int scrollSpeed = 12; - - // Starting drag scroll values - private float dragSX = 0; - private float dragSY = 0; - // Starting drag mouse positions - private int dragMX = 0; - private int dragMY = 0; - // Last known scroll position (unscaled) - protected float lsz = 1F; - protected int lsx = 0; - protected int lsy = 0; - - // Enables the auto-disabling panels outside the cropped region. Useful for very large lists - private boolean useBlocking = true; - private final CanvasCullingManager cullingManager = new CanvasCullingManager(); - private final GuiRectangle refRect = new GuiRectangle(0, 0, 0, 0); - - public CanvasScrolling(IGuiRect rect) - { - this.transform = rect; - - // Dummy value drivers - - scrollX = new FloatSimpleIO().setLerp(true, 0.02F); - scrollY = new FloatSimpleIO().setLerp(true, 0.02F); - zoomScale = new FloatSimpleIO(1F, 0.2F, 2F).setLerp(true, 0.02F); - } - - public CanvasScrolling setScrollDriverX(IValueIO driver) - { - this.scrollX = driver; - return this; - } - - public CanvasScrolling setScrollDriverY(IValueIO driver) - { - this.scrollY = driver; - return this; - } - - public CanvasScrolling setZoomDriver(IValueIO driver) - { - this.zoomScale = driver; - return this; - } - - public CanvasScrolling setScrollSpeed(int dx) - { - this.scrollSpeed = dx; - return this; - } - - public CanvasScrolling setupAdvanceScroll(boolean scrollToZoom, boolean extendedScroll, int scrollMargin) - { - this.zoomMode = scrollToZoom; - this.extendedScroll = extendedScroll; - this.margin = scrollMargin; - return this; - } - - public CanvasScrolling enableBlocking(boolean state) - { - this.useBlocking = state; - return this; - } - - public IGuiRect getScrollBounds() - { - return this.scrollBounds; - } - - public int getScrollX() - { - return Math.round(scrollBounds.getX() + scrollBounds.getWidth() * scrollX.readValue()); - } - - public int getScrollY() - { - return Math.round(scrollBounds.getY() + scrollBounds.getHeight() * scrollY.readValue()); - } - - public float getZoom() - { - return zoomScale.readValue(); - } - - public void setScrollX(int sx) - { - if(scrollBounds.getWidth() <= 0) return; - scrollX.writeValueRaw((sx - scrollBounds.getX()) / (float)scrollBounds.getWidth()); - lsx = this.getScrollX(); - } - - public void setScrollY(int sy) - { - if(scrollBounds.getHeight() <= 0) return; - scrollY.writeValueRaw((sy - scrollBounds.getY()) / (float)scrollBounds.getHeight()); - lsy = this.getScrollY(); - } - - public void setZoom(float z) - { - zoomScale.writeValueRaw(z); - lsz = zoomScale.readValue(); - this.refreshScrollBounds(); - } - - @Override - public void initPanel() - { - this.guiPanels.clear(); - this.cullingManager.reset(); - } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Nonnull - @Override - public List getChildren() +public class CanvasScrolling implements IGuiCanvas { + private final List guiPanels = new CopyOnWriteArrayList<>(); + private final IGuiRect transform; + private boolean enabled = true; + + // Scrolling bounds + protected final GuiRectangle scrollBounds = new GuiRectangle(0, 0, 0, 0); + private final GuiRectangle scrollWindow = new GuiRectangle(0, 0, 0, 0); + protected boolean extendedScroll = false; + protected boolean zoomMode = false; + protected int margin = 0; + // Scroll and zoom drivers + protected IValueIO scrollX; + protected IValueIO scrollY; + protected IValueIO zoomScale; + + private boolean isDragging = false; // Mouse buttons held for dragging + private boolean hasDragged = false; // Dragging used. Don't fire onMouseRelease + protected int scrollSpeed = 12; + + // Starting drag scroll values + private float dragSX = 0; + private float dragSY = 0; + // Starting drag mouse positions + private int dragMX = 0; + private int dragMY = 0; + // Last known scroll position (unscaled) + protected float lsz = 1F; + protected int lsx = 0; + protected int lsy = 0; + + // Enables the auto-disabling panels outside the cropped region. Useful for very large lists + private boolean useBlocking = true; + private final CanvasCullingManager cullingManager = new CanvasCullingManager(); + private final GuiRectangle refRect = new GuiRectangle(0, 0, 0, 0); + + public CanvasScrolling(IGuiRect rect) { + this.transform = rect; + + // Dummy value drivers + + scrollX = new FloatSimpleIO().setLerp(true, 0.02F); + scrollY = new FloatSimpleIO().setLerp(true, 0.02F); + zoomScale = new FloatSimpleIO(1F, 0.2F, 2F).setLerp(true, 0.02F); + } + + public CanvasScrolling setScrollDriverX(IValueIO driver) { + this.scrollX = driver; + return this; + } + + public CanvasScrolling setScrollDriverY(IValueIO driver) { + this.scrollY = driver; + return this; + } + + public CanvasScrolling setZoomDriver(IValueIO driver) { + this.zoomScale = driver; + return this; + } + + public CanvasScrolling setScrollSpeed(int dx) { + this.scrollSpeed = dx; + return this; + } + + public CanvasScrolling setupAdvanceScroll(boolean scrollToZoom, boolean extendedScroll, int scrollMargin) { + this.zoomMode = scrollToZoom; + this.extendedScroll = extendedScroll; + this.margin = scrollMargin; + return this; + } + + public CanvasScrolling enableBlocking(boolean state) { + this.useBlocking = state; + return this; + } + + public IGuiRect getScrollBounds() { + return this.scrollBounds; + } + + public int getScrollX() { + return Math.round(scrollBounds.getX() + scrollBounds.getWidth() * scrollX.readValue()); + } + + public int getScrollY() { + return Math.round(scrollBounds.getY() + scrollBounds.getHeight() * scrollY.readValue()); + } + + public float getZoom() { + return zoomScale.readValue(); + } + + public void setScrollX(int sx) { + if (scrollBounds.getWidth() <= 0) { return; } + scrollX.writeValueRaw((sx - scrollBounds.getX()) / (float) scrollBounds.getWidth()); + lsx = this.getScrollX(); + } + + public void setScrollY(int sy) { + if (scrollBounds.getHeight() <= 0) { return; } + scrollY.writeValueRaw((sy - scrollBounds.getY()) / (float) scrollBounds.getHeight()); + lsy = this.getScrollY(); + } + + public void setZoom(float z) { + zoomScale.writeValueRaw(z); + lsz = zoomScale.readValue(); + this.refreshScrollBounds(); + } + + @Override + public void initPanel() { + this.guiPanels.clear(); + this.cullingManager.reset(); + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Nonnull + @Override + public List getChildren() { + return this.guiPanels; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (!isRectEqual(refRect, transform)) { refreshScrollBounds(); } + + float zs = zoomScale.readValue(); + + int tx = transform.getX(); + int ty = transform.getY(); + + if (isDragging && (Mouse.isButtonDown(0) || + Mouse.isButtonDown(2))) // Extra fallback incase something used the usual release event { - return this.guiPanels; + int dx = (int) ((dragMX - mx) / zs); + int dy = (int) ((dragMY - my) / zs); + + if (scrollBounds.getWidth() > 0) { + float dsx = dx / (float) scrollBounds.getWidth() + dragSX; + scrollX.writeValue(dsx); + + if (!hasDragged && Math.abs(dragSX - scrollX.readValue()) > 0.05F) { + hasDragged = true; + } + } + + if (scrollBounds.getHeight() > 0) { + float dsy = dy / (float) scrollBounds.getHeight() + dragSY; + scrollY.writeValue(dsy); + + if (!hasDragged && Math.abs(dragSY - scrollY.readValue()) > 0.05F) { + hasDragged = true; + } + } + } else if (isDragging || hasDragged) { + isDragging = false; + hasDragged = false; + } + + if (lsz != zs) { + float change = zs / + lsz; // This could probably crash if someone allowed the zoom driver to go to zero. Not really my fault to be fair + + int csx = getScrollX(); + int csy = getScrollY(); + float swcx = scrollWindow.w / 2F; + float swcy = scrollWindow.h / 2F; + swcx -= swcx / change; + swcy -= swcy / change; + + this.refreshScrollBounds(); // NOTE: This runs updatePanelPcroll() too. Hence why the math above is done first before the scroll bounds are changed + + if (scrollBounds.getWidth() > 0) { + scrollX.writeValue(((csx + swcx) - scrollBounds.getX()) / (float) scrollBounds.getWidth()); + } + if (scrollBounds.getHeight() > 0) { + scrollY.writeValue(((csy + swcy) - scrollBounds.getY()) / (float) scrollBounds.getHeight()); + } + lsx = getScrollX(); + lsy = getScrollY(); + lsz = zs; + } else if (lsx != getScrollX() || lsy != getScrollY()) // We can skip this if the above case ran + { + this.updatePanelScroll(); + } + + GlStateManager.pushMatrix(); + + RenderUtils.startScissor(transform); + + GlStateManager.translate(tx - lsx * zs, ty - lsy * zs, 0F); + GlStateManager.scale(zs, zs, zs); + + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + for (IGuiPanel panel : getVisiblePanels()) { + if (panel.isEnabled()) { + panel.drawPanel(smx, smy, partialTick); + } + } + + RenderUtils.endScissor(); + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (!transform.contains(mx, my)) { + return false; + } + + float zs = zoomScale.readValue(); + int tx = transform.getX(); + int ty = transform.getY(); + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseClick(smx, smy, click)) { + used = true; + break; + } + } + + if (!used && (click == 0 || click == 2)) { + dragSX = scrollX.readValue(); + dragSY = scrollY.readValue(); + dragMX = mx; + dragMY = my; + isDragging = true; + return true; + } + + return used; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + boolean used = false; + + if (!hasDragged) { + if (!transform.contains(mx, my)) { return false; } + + float zs = zoomScale.readValue(); + int tx = transform.getX(); + int ty = transform.getY(); + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + if (pnIter.previous().onMouseRelease(smx, smy, click)) { + used = true; + break; + } + } + } + + if (isDragging) { + if (!Mouse.isButtonDown(0) && !Mouse.isButtonDown(2)) { isDragging = false; } + return true; + } + + return used; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + if (scroll == 0 || !transform.contains(mx, my)) { return false; } + + float zs = zoomScale.readValue(); + int tx = transform.getX(); + int ty = transform.getY(); + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onMouseScroll(smx, smy, scroll)) { + used = true; + break; + } + } + + if (!used) { + if (zoomMode) { + float dy = -scroll * 0.05F; + float cs = zoomScale.readValueRaw(); + + zoomScale.writeValue(cs + dy); + used = true; + } else if (scrollBounds.getHeight() > 0) // V scroll + { + float dy = (scroll * scrollSpeed) / (float) scrollBounds.getHeight(); + float cs = scrollY.readValue(); + + if (!((dy < 0F && cs <= 0F) || (dy > 0F && cs >= 1F))) { + scrollY.writeValue(cs + dy); + this.updatePanelScroll(); + used = true; + } + } else if (scrollBounds.getWidth() > 0) // H scroll + { + float dy = (scroll * scrollSpeed) / (float) scrollBounds.getWidth(); + float cs = scrollX.readValue(); + + if (!((dy < 0F && cs <= 0F) || (dy > 0F && cs >= 1F))) { + scrollX.writeValue(cs + dy); + this.updatePanelScroll(); + used = true; + } + } + } + + return used; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + boolean used = false; + + ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (entry.isEnabled() && entry.onKeyTyped(c, keycode)) { + used = true; + break; + } } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(!isRectEqual(refRect, transform)) refreshScrollBounds(); - - float zs = zoomScale.readValue(); - - int tx = transform.getX(); - int ty = transform.getY(); - - if(isDragging && (Mouse.isButtonDown(0) || Mouse.isButtonDown(2))) // Extra fallback incase something used the usual release event - { - int dx = (int)((dragMX - mx) / zs); - int dy = (int)((dragMY - my) / zs); - - if(scrollBounds.getWidth() > 0) - { - float dsx = dx / (float)scrollBounds.getWidth() + dragSX; - scrollX.writeValue(dsx); - - if(!hasDragged && Math.abs(dragSX - scrollX.readValue()) > 0.05F) - { - hasDragged = true; - } - } - - if(scrollBounds.getHeight() > 0) - { - float dsy = dy / (float)scrollBounds.getHeight() + dragSY; - scrollY.writeValue(dsy); - - if(!hasDragged && Math.abs(dragSY - scrollY.readValue()) > 0.05F) - { - hasDragged = true; - } - } - } else if(isDragging || hasDragged) - { - isDragging = false; - hasDragged = false; - } - - if(lsz != zs) - { - float change = zs / lsz; // This could probably crash if someone allowed the zoom driver to go to zero. Not really my fault to be fair - - int csx = getScrollX(); - int csy = getScrollY(); - float swcx = scrollWindow.w/2F; - float swcy = scrollWindow.h/2F; - swcx -= swcx / change; - swcy -= swcy / change; - - this.refreshScrollBounds(); // NOTE: This runs updatePanelPcroll() too. Hence why the math above is done first before the scroll bounds are changed - - if(scrollBounds.getWidth() > 0) scrollX.writeValue(((csx + swcx) - scrollBounds.getX()) / (float)scrollBounds.getWidth()); - if(scrollBounds.getHeight() > 0) scrollY.writeValue(((csy + swcy) - scrollBounds.getY()) / (float)scrollBounds.getHeight()); - lsx = getScrollX(); - lsy = getScrollY(); - lsz = zs; - } else if(lsx != getScrollX() || lsy != getScrollY()) // We can skip this if the above case ran - { - this.updatePanelScroll(); - } - - GlStateManager.pushMatrix(); - - RenderUtils.startScissor(transform); - - GlStateManager.translate(tx - lsx * zs, ty - lsy * zs, 0F); - GlStateManager.scale(zs, zs, zs); - - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - for(IGuiPanel panel : getVisiblePanels()) - { - if(panel.isEnabled()) - { - panel.drawPanel(smx, smy, partialTick); - } - } - - RenderUtils.endScissor(); - GlStateManager.popMatrix(); - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(!transform.contains(mx, my)) - { - return false; - } - - float zs = zoomScale.readValue(); - int tx = transform.getX(); - int ty = transform.getY(); - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseClick(smx, smy, click)) - { - used = true; - break; - } - } - - if(!used && (click == 0 || click == 2)) - { - dragSX = scrollX.readValue(); - dragSY = scrollY.readValue(); - dragMX = mx; - dragMY = my; - isDragging = true; - return true; - } - - return used; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - boolean used = false; - - if(!hasDragged) - { - if(!transform.contains(mx, my)) return false; - - float zs = zoomScale.readValue(); - int tx = transform.getX(); - int ty = transform.getY(); - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - if(pnIter.previous().onMouseRelease(smx, smy, click)) - { - used = true; - break; - } - } - } - - if(isDragging) - { - if(!Mouse.isButtonDown(0) && !Mouse.isButtonDown(2)) isDragging = false; - return true; - } - - return used; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - if(scroll == 0 || !transform.contains(mx, my)) return false; - - float zs = zoomScale.readValue(); - int tx = transform.getX(); - int ty = transform.getY(); - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onMouseScroll(smx, smy, scroll)) - { - used = true; - break; - } - } - - if(!used) - { - if(zoomMode) - { - float dy = -scroll * 0.05F; - float cs = zoomScale.readValueRaw(); - - zoomScale.writeValue(cs + dy); - used = true; - } else if(scrollBounds.getHeight() > 0) // V scroll - { - float dy = (scroll * scrollSpeed) / (float)scrollBounds.getHeight(); - float cs = scrollY.readValue(); - - if(!((dy < 0F && cs <= 0F) || (dy > 0F && cs >= 1F))) - { - scrollY.writeValue(cs + dy); - this.updatePanelScroll(); - used = true; - } - } else if(scrollBounds.getWidth() > 0) // H scroll - { - float dy = (scroll * scrollSpeed) / (float)scrollBounds.getWidth(); - float cs = scrollX.readValue(); - - if(!((dy < 0F && cs <= 0F) || (dy > 0F && cs >= 1F))) - { - scrollX.writeValue(cs + dy); - this.updatePanelScroll(); - used = true; - } - } - } - - return used; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - boolean used = false; - - ListIterator pnIter = guiPanels.listIterator(guiPanels.size()); - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(entry.isEnabled() && entry.onKeyTyped(c, keycode)) - { - used = true; - break; - } - } /*if(!used && c == 'c') { setScrollX(0); setScrollY(0); }*/ - - return used; - } - - @Override - public List getTooltip(int mx, int my) - { - if(!transform.contains(mx, my) || isDragging) return null; - - float zs = zoomScale.readValue(); - int tx = transform.getX(); - int ty = transform.getY(); - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - List tmpList = getVisiblePanels(); - ListIterator pnIter = tmpList.listIterator(tmpList.size()); - List tt; - - while(pnIter.hasPrevious()) - { - IGuiPanel entry = pnIter.previous(); - - if(!entry.isEnabled()) - { - continue; - } - - tt = entry.getTooltip(smx, smy); - - if(tt != null && tt.size() > 0) - { - return tt; - } - } - - return null; - } - - @Override - public void addPanel(IGuiPanel panel) - { - addCulledPanel(panel, true); - } - - public void addCulledPanel(IGuiPanel panel, boolean useCulling) - { - if(panel == null || guiPanels.contains(panel)) return; - - guiPanels.add(panel); - guiPanels.sort(ComparatorGuiDepth.INSTANCE); - - cullingManager.addPanel(panel, useCulling); - - panel.initPanel(); - - this.refreshScrollBounds(); - } - - @Override - public boolean removePanel(IGuiPanel panel) - { - boolean b = guiPanels.remove(panel); - - if(b) - { - cullingManager.removePanel(panel); - this.refreshScrollBounds(); - } - - return b; - } - - public void refreshScrollBounds() - { - boolean first = true; - int left = 0; - int right = 0; - int top = 0; - int bottom = 0; - - float zs = zoomScale.readValue(); - - for(IGuiPanel panel : guiPanels) - { - if(first) - { - left = panel.getTransform().getX(); - top = panel.getTransform().getY(); - right = panel.getTransform().getX() + panel.getTransform().getWidth(); - bottom = panel.getTransform().getY() + panel.getTransform().getHeight(); - first = false; - } else - { - left = Math.min(left, panel.getTransform().getX()); - top = Math.min(top, panel.getTransform().getY()); - right = Math.max(right, panel.getTransform().getX() + panel.getTransform().getWidth()); - bottom = Math.max(bottom, panel.getTransform().getY() + panel.getTransform().getHeight()); - } - } - - left -= margin; - right += margin; - top -= margin; - bottom += margin; - - right -= (int)Math.ceil(this.getTransform().getWidth() / zs); - bottom -= (int)Math.ceil(this.getTransform().getHeight() / zs); - - if(extendedScroll) - { - scrollBounds.x = Math.min(left, right); - scrollBounds.y = Math.min(top, bottom); - scrollBounds.w = Math.max(left, right) - scrollBounds.x; - scrollBounds.h = Math.max(top, bottom) - scrollBounds.y; - } else - { - scrollBounds.x = left; - scrollBounds.y = top; - scrollBounds.w = Math.max(0, right - left); - scrollBounds.h = Math.max(0, bottom - top); - } - - updatePanelScroll(); - - refRect.x = transform.getX(); - refRect.y = transform.getY(); - refRect.w = transform.getWidth(); - refRect.h = transform.getHeight(); - } - - public void updatePanelScroll() - { - lsx = this.getScrollX(); - lsy = this.getScrollY(); - - float zs = zoomScale.readValue(); - - scrollWindow.x = lsx; - scrollWindow.y = lsy; - scrollWindow.w = (int)Math.ceil(transform.getWidth() / zs); - scrollWindow.h = (int)Math.ceil(transform.getHeight() / zs); - - cullingManager.updateVisiblePanels(scrollWindow); - } - - @Override - public void resetCanvas() - { - guiPanels.clear(); - cullingManager.reset(); - refreshScrollBounds(); - } - - private List getVisiblePanels() - { - return useBlocking ? cullingManager.getVisiblePanels() : guiPanels; - } - - private boolean isRectEqual(IGuiRect r1, IGuiRect r2) - { - return r1.getX() == r2.getX() && r1.getY() == r2.getY() && r1.getWidth() == r2.getWidth() && r1.getHeight() == r2.getHeight(); + + return used; + } + + @Override + public List getTooltip(int mx, int my) { + if (!transform.contains(mx, my) || isDragging) { return null; } + + float zs = zoomScale.readValue(); + int tx = transform.getX(); + int ty = transform.getY(); + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + List tmpList = getVisiblePanels(); + ListIterator pnIter = tmpList.listIterator(tmpList.size()); + List tt; + + while (pnIter.hasPrevious()) { + IGuiPanel entry = pnIter.previous(); + + if (!entry.isEnabled()) { + continue; + } + + tt = entry.getTooltip(smx, smy); + + if (tt != null && !tt.isEmpty()) { + return tt; + } + } + + return null; + } + + @Override + public void addPanel(IGuiPanel panel) { + addCulledPanel(panel, true); + } + + public void addCulledPanel(IGuiPanel panel, boolean useCulling) { + if (panel == null || guiPanels.contains(panel)) { return; } + + guiPanels.add(panel); + guiPanels.sort(ComparatorGuiDepth.INSTANCE); + + cullingManager.addPanel(panel, useCulling); + + panel.initPanel(); + + this.refreshScrollBounds(); + } + + @Override + public boolean removePanel(IGuiPanel panel) { + boolean b = guiPanels.remove(panel); + + if (b) { + cullingManager.removePanel(panel); + this.refreshScrollBounds(); } + + return b; + } + + public void refreshScrollBounds() { + boolean first = true; + int left = 0; + int right = 0; + int top = 0; + int bottom = 0; + + float zs = zoomScale.readValue(); + + for (IGuiPanel panel : guiPanels) { + if (first) { + left = panel.getTransform().getX(); + top = panel.getTransform().getY(); + right = panel.getTransform().getX() + panel.getTransform().getWidth(); + bottom = panel.getTransform().getY() + panel.getTransform().getHeight(); + first = false; + } else { + left = Math.min(left, panel.getTransform().getX()); + top = Math.min(top, panel.getTransform().getY()); + right = Math.max(right, panel.getTransform().getX() + panel.getTransform().getWidth()); + bottom = Math.max(bottom, panel.getTransform().getY() + panel.getTransform().getHeight()); + } + } + + left -= margin; + right += margin; + top -= margin; + bottom += margin; + + right -= (int) Math.ceil(this.getTransform().getWidth() / zs); + bottom -= (int) Math.ceil(this.getTransform().getHeight() / zs); + + if (extendedScroll) { + scrollBounds.x = Math.min(left, right); + scrollBounds.y = Math.min(top, bottom); + scrollBounds.w = Math.max(left, right) - scrollBounds.x; + scrollBounds.h = Math.max(top, bottom) - scrollBounds.y; + } else { + scrollBounds.x = left; + scrollBounds.y = top; + scrollBounds.w = Math.max(0, right - left); + scrollBounds.h = Math.max(0, bottom - top); + } + + updatePanelScroll(); + + refRect.x = transform.getX(); + refRect.y = transform.getY(); + refRect.w = transform.getWidth(); + refRect.h = transform.getHeight(); + } + + public void updatePanelScroll() { + lsx = this.getScrollX(); + lsy = this.getScrollY(); + + float zs = zoomScale.readValue(); + + scrollWindow.x = lsx; + scrollWindow.y = lsy; + scrollWindow.w = (int) Math.ceil(transform.getWidth() / zs); + scrollWindow.h = (int) Math.ceil(transform.getHeight() / zs); + + cullingManager.updateVisiblePanels(scrollWindow); + } + + @Override + public void resetCanvas() { + guiPanels.clear(); + cullingManager.reset(); + refreshScrollBounds(); + } + + private List getVisiblePanels() { + return useBlocking ? cullingManager.getVisiblePanels() : guiPanels; + } + + private boolean isRectEqual(IGuiRect r1, IGuiRect r2) { + return r1.getX() == r2.getX() && r1.getY() == r2.getY() && r1.getWidth() == r2.getWidth() && + r1.getHeight() == r2.getHeight(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java index aa76a980f..307f79043 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java @@ -6,106 +6,93 @@ import java.util.*; import java.util.concurrent.TimeUnit; -public abstract class CanvasSearch extends CanvasScrolling -{ - private String searchTerm = ""; - private Iterator searching = null; - private final Stopwatch searchTime = Stopwatch.createStarted(); - private int resultWidth = 256; // Used for organising ongoing search results even if the size changes midway - private int searchIdx = 0; // Where are we in the ongoing search? - private final ArrayDeque pendingResults = new ArrayDeque<>(); - private final List savedResults = new ArrayList<>(); - - public CanvasSearch(IGuiRect rect) - { - super(rect); - } - - public void setSearchFilter(String text) - { - this.searchTerm = text.toLowerCase(); - refreshSearch(); - } - - @Override - public void initPanel() - { - super.initPanel(); - refreshSearch(); - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - updateSearch(); - updateResults(); - - super.drawPanel(mx, my, partialTick); - } - - public void refreshSearch() - { - this.resetCanvas(); - this.searchIdx = 0; - this.searching = getIterator(); - this.resultWidth = this.getTransform().getWidth(); - this.pendingResults.clear(); - this.savedResults.clear(); +public abstract class CanvasSearch extends CanvasScrolling { + private String searchTerm = ""; + private Iterator searching = null; + private final Stopwatch searchTime = Stopwatch.createStarted(); + private int resultWidth = 256; // Used for organising ongoing search results even if the size changes midway + private int searchIdx = 0; // Where are we in the ongoing search? + private final ArrayDeque pendingResults = new ArrayDeque<>(); + private final List savedResults = new ArrayList<>(); + + public CanvasSearch(IGuiRect rect) { + super(rect); + } + + public void setSearchFilter(String text) { + this.searchTerm = text.toLowerCase(); + refreshSearch(); + } + + @Override + public void initPanel() { + super.initPanel(); + refreshSearch(); + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + updateSearch(); + updateResults(); + + super.drawPanel(mx, my, partialTick); + } + + public void refreshSearch() { + this.resetCanvas(); + this.searchIdx = 0; + this.searching = getIterator(); + this.resultWidth = this.getTransform().getWidth(); + this.pendingResults.clear(); + this.savedResults.clear(); + } + + private void updateSearch() { + if (searching == null) { + return; + } else if (!searching.hasNext()) { + searching = null; + return; } - - private void updateSearch() - { - if(searching == null) - { - return; - } else if(!searching.hasNext()) - { - searching = null; - return; - } - - searchTime.reset().start(); - - ArrayDeque tmp = new ArrayDeque<>(); - while(searching.hasNext() && searchTime.elapsed(TimeUnit.MILLISECONDS) < 10) - { - E entry = searching.next(); - - if(entry != null) - { - queryMatches(entry, searchTerm, tmp); - } - } - - pendingResults.addAll(tmp); - savedResults.addAll(tmp); - - searchTime.stop(); + + searchTime.reset().start(); + + ArrayDeque tmp = new ArrayDeque<>(); + while (searching.hasNext() && searchTime.elapsed(TimeUnit.MILLISECONDS) < 10) { + E entry = searching.next(); + + if (entry != null) { + queryMatches(entry, searchTerm, tmp); + } } - - private void updateResults() - { - if(pendingResults.isEmpty()) - { - return; - } - - searchTime.reset().start(); - - while(!pendingResults.isEmpty() && searchTime.elapsed(TimeUnit.MILLISECONDS) < 100) - { - if(addResult(pendingResults.poll(), searchIdx, resultWidth)) searchIdx++; - } - - searchTime.stop(); + + pendingResults.addAll(tmp); + savedResults.addAll(tmp); + + searchTime.stop(); + } + + private void updateResults() { + if (pendingResults.isEmpty()) { + return; } - - public List getResults() - { - return Collections.unmodifiableList(savedResults); + + searchTime.reset().start(); + + while (!pendingResults.isEmpty() && searchTime.elapsed(TimeUnit.MILLISECONDS) < 100) { + if (addResult(pendingResults.poll(), searchIdx, resultWidth)) { searchIdx++; } } - - protected abstract Iterator getIterator(); - protected abstract void queryMatches(E value, String query, final ArrayDeque results); - protected abstract boolean addResult(T entry, int index, int cachedWidth); + + searchTime.stop(); + } + + public List getResults() { + return Collections.unmodifiableList(savedResults); + } + + protected abstract Iterator getIterator(); + + protected abstract void queryMatches(E value, String query, final ArrayDeque results); + + protected abstract boolean addResult(T entry, int index, int cachedWidth); } diff --git a/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java b/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java index eb7373320..fb22f141c 100644 --- a/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java +++ b/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java @@ -6,10 +6,10 @@ import betterquesting.api2.client.gui.misc.GuiPadding; import betterquesting.api2.client.gui.misc.GuiTransform; import betterquesting.api2.client.gui.panels.CanvasEmpty; +import betterquesting.api2.client.gui.panels.CanvasResizeable; import betterquesting.api2.client.gui.panels.CanvasTextured; import betterquesting.api2.client.gui.panels.content.PanelGeneric; import betterquesting.api2.client.gui.panels.content.PanelTextBox; -import betterquesting.api2.client.gui.panels.CanvasResizeable; import betterquesting.api2.client.gui.resources.colors.GuiColorStatic; import betterquesting.api2.client.gui.resources.textures.ColorTexture; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; @@ -20,96 +20,94 @@ import javax.annotation.Nullable; import java.util.function.Consumer; -public class PopChoice extends CanvasEmpty -{ - private final String message; - private final IGuiTexture icon; - private final Consumer callback; - private final String[] options; - - public PopChoice(@Nonnull String message, @Nonnull Consumer callback, @Nonnull String... options) - { - this(message, null, callback, options); - } - - public PopChoice(@Nonnull String message, @Nullable IGuiTexture icon, @Nonnull Consumer callback, @Nonnull String... options) - { - super(new GuiTransform(GuiAlign.FULL_BOX)); - this.message = message; - this.icon = icon; - this.callback = callback; - this.options = options; - } - - @Override - public void initPanel() - { - super.initPanel(); - - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), new ColorTexture(new GuiColorStatic(0x80000000)))); - - CanvasResizeable cvBox = new CanvasResizeable(new GuiTransform(new Vector4f(0.5F, 0.45F, 0.5F, 0.45F)), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBox); - cvBox.lerpToRect(new GuiTransform(new Vector4f(0.2F, 0.3F, 0.8F, 0.6F)), 200L, true); - - if(icon != null) - { - CanvasTextured icoFrame = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0.3F, 0.5F, 0.3F), -16, -40, 32, 32, 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(icoFrame); - - icoFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), icon)); - } - - cvBox.addPanel(new PanelTextBox(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), message).setAlignment(1)); - - final int maxW = 3; - for(int i = 0; i < options.length; i++) - { - final int index = i; - int rowY = i / maxW; - int rowX = i % maxW; - int rowW = Math.min(3, options.length - (rowY * maxW)) * 112 - 16; - - PanelButton btn = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0.6F, 0.5F, 0.6F), -rowW / 2 + rowX * 112, 8 + 24 * rowY, 96, 16, 0), -1, options[i]); - btn.setClickAction((b) -> { - callback.accept(index); - if(SceneController.getActiveScene() != null) SceneController.getActiveScene().closePopup(); - }); - this.addPanel(btn); - } - } - - // == TRAP ALL UI USAGE UNTIL CLOSED === - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - super.onMouseClick(mx, my, click); - - return true; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - super.onMouseRelease(mx, my, click); - - return true; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - super.onMouseScroll(mx, my, scroll); - - return true; +public class PopChoice extends CanvasEmpty { + private final String message; + private final IGuiTexture icon; + private final Consumer callback; + private final String[] options; + + public PopChoice(@Nonnull String message, @Nonnull Consumer callback, @Nonnull String... options) { + this(message, null, callback, options); + } + + public PopChoice(@Nonnull String message, @Nullable IGuiTexture icon, @Nonnull Consumer callback, + @Nonnull String... options) { + super(new GuiTransform(GuiAlign.FULL_BOX)); + this.message = message; + this.icon = icon; + this.callback = callback; + this.options = options; + } + + @Override + public void initPanel() { + super.initPanel(); + + this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), + new ColorTexture(new GuiColorStatic(0x80000000)))); + + CanvasResizeable cvBox = new CanvasResizeable(new GuiTransform(new Vector4f(0.5F, 0.45F, 0.5F, 0.45F)), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBox); + cvBox.lerpToRect(new GuiTransform(new Vector4f(0.2F, 0.3F, 0.8F, 0.6F)), 200L, true); + + if (icon != null) { + CanvasTextured icoFrame = + new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0.3F, 0.5F, 0.3F), -16, -40, 32, 32, 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(icoFrame); + + icoFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), icon)); } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - super.onKeyTyped(c, keycode); - - return true; + + cvBox.addPanel( + new PanelTextBox(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), message).setAlignment(1)); + + final int maxW = 3; + for (int i = 0; i < options.length; i++) { + final int index = i; + int rowY = i / maxW; + int rowX = i % maxW; + int rowW = Math.min(3, options.length - (rowY * maxW)) * 112 - 16; + + PanelButton btn = new PanelButton( + new GuiTransform(new Vector4f(0.5F, 0.6F, 0.5F, 0.6F), -rowW / 2 + rowX * 112, 8 + 24 * rowY, 96, 16, 0), -1, + options[i]); + btn.setClickAction((b) -> { + callback.accept(index); + if (SceneController.getActiveScene() != null) { SceneController.getActiveScene().closePopup(); } + }); + this.addPanel(btn); } + } + + // == TRAP ALL UI USAGE UNTIL CLOSED === + + @Override + public boolean onMouseClick(int mx, int my, int click) { + super.onMouseClick(mx, my, click); + + return true; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + super.onMouseRelease(mx, my, click); + + return true; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + super.onMouseScroll(mx, my, scroll); + + return true; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + super.onKeyTyped(c, keycode); + + return true; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java b/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java index 36ef66a0b..a92fce28c 100644 --- a/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java +++ b/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java @@ -7,9 +7,9 @@ import betterquesting.api2.client.gui.misc.GuiTransform; import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.panels.CanvasEmpty; +import betterquesting.api2.client.gui.panels.CanvasResizeable; import betterquesting.api2.client.gui.panels.bars.PanelVScrollBar; import betterquesting.api2.client.gui.panels.content.PanelGeneric; -import betterquesting.api2.client.gui.panels.CanvasResizeable; import betterquesting.api2.client.gui.panels.lists.CanvasScrolling; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; import betterquesting.api2.client.gui.themes.presets.PresetTexture; @@ -20,150 +20,131 @@ import java.util.ArrayList; import java.util.List; -public class PopContextMenu extends CanvasEmpty -{ - private final ContextCategory catRoot = new ContextCategory(null, "root"); - private final GuiRectangle rect; - private final boolean autoClose; - - public PopContextMenu(GuiRectangle rect, boolean autoClose) - { - super(rect); - this.rect = rect; - this.autoClose = autoClose; - } - - public ContextCategory getRootCategory() - { - return this.catRoot; - } - - public void addButton(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) - { - catRoot.addButton(text, icon, action); - } - - public ContextCategory addCateogry(@Nonnull String text) +public class PopContextMenu extends CanvasEmpty { + private final ContextCategory catRoot = new ContextCategory(null, "root"); + private final GuiRectangle rect; + private final boolean autoClose; + + public PopContextMenu(GuiRectangle rect, boolean autoClose) { + super(rect); + this.rect = rect; + this.autoClose = autoClose; + } + + public ContextCategory getRootCategory() { + return this.catRoot; + } + + public void addButton(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) { + catRoot.addButton(text, icon, action); + } + + public ContextCategory addCateogry(@Nonnull String text) { + return catRoot.addCateogry(text); + } + + public void openCategory(@Nonnull ContextCategory category) { + this.resetCanvas(); + + int listH = Math.min(category.entries.size() * 16, rect.getHeight()); + + if (getTransform().getParent() != null) // Auto adjust if hanging off screen { - return catRoot.addCateogry(text); + IGuiRect par = getTransform().getParent(); + rect.x += Math.min(0, (par.getX() + par.getWidth()) - (rect.getX() + rect.getWidth())); + rect.y += Math.min(0, (par.getY() + par.getHeight()) - (rect.getY() + listH)); } - - public void openCategory(@Nonnull ContextCategory category) - { - this.resetCanvas(); - - int listH = Math.min(category.entries.size() * 16, rect.getHeight()); - - if(getTransform().getParent() != null) // Auto adjust if hanging off screen - { - IGuiRect par = getTransform().getParent(); - rect.x += Math.min(0, (par.getX() + par.getWidth()) - (rect.getX() + rect.getWidth())); - rect.y += Math.min(0, (par.getY() + par.getHeight()) - (rect.getY() + listH)); + + CanvasResizeable cvBG = + new CanvasResizeable(new GuiRectangle(0, 0, 0, 0, 0), PresetTexture.PANEL_INNER.getTexture()); + this.addPanel(cvBG); + cvBG.lerpToRect(new GuiRectangle(0, 0, rect.w - 8, listH, 0), 100, true); + + CanvasScrolling cvScroll = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX)); + cvBG.addPanel(cvScroll); + + PanelVScrollBar scrollBar = new PanelVScrollBar(new GuiRectangle(rect.w - 8, 0, 8, listH, 0)); + this.addPanel(scrollBar); + cvScroll.setScrollDriverY(scrollBar); + + for (int i = 0; i < category.entries.size(); i++) { + ContextEntry entry = category.entries.get(i); + if (entry.icon != null) { + cvScroll.addPanel(new PanelGeneric(new GuiRectangle(0, i * 16, 16, 16, 0), entry.icon)); + PanelButton eBtn = new PanelButton(new GuiRectangle(16, i * 16, rect.w - 24, 16, 0), -1, + QuestTranslation.translate(entry.text)); + if (entry.action != null) { + eBtn.setClickAction((b) -> entry.action.run()); + } else { + eBtn.setActive(false); } - - CanvasResizeable cvBG = new CanvasResizeable(new GuiRectangle(0, 0, 0, 0, 0), PresetTexture.PANEL_INNER.getTexture()); - this.addPanel(cvBG); - cvBG.lerpToRect(new GuiRectangle(0, 0, rect.w - 8, listH, 0), 100, true); - - CanvasScrolling cvScroll = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX)); - cvBG.addPanel(cvScroll); - - PanelVScrollBar scrollBar = new PanelVScrollBar(new GuiRectangle(rect.w - 8, 0, 8, listH, 0)); - this.addPanel(scrollBar); - cvScroll.setScrollDriverY(scrollBar); - - for(int i = 0; i < category.entries.size(); i++) - { - ContextEntry entry = category.entries.get(i); - if(entry.icon != null) - { - cvScroll.addPanel(new PanelGeneric(new GuiRectangle(0, i * 16, 16, 16, 0), entry.icon)); - PanelButton eBtn = new PanelButton(new GuiRectangle(16, i * 16, rect.w - 24, 16, 0), -1, QuestTranslation.translate(entry.text)); - if(entry.action != null) - { - eBtn.setClickAction((b) -> entry.action.run()); - } else - { - eBtn.setActive(false); - } - cvScroll.addPanel(eBtn); - } else - { - PanelButton eBtn = new PanelButton(new GuiRectangle(0, i * 16, rect.w - 8, 16, 0), -1, QuestTranslation.translate(entry.text)); - if(entry.action != null) - { - eBtn.setClickAction((b) -> entry.action.run()); - } else - { - eBtn.setActive(false); - } - cvScroll.addPanel(eBtn); - } + cvScroll.addPanel(eBtn); + } else { + PanelButton eBtn = + new PanelButton(new GuiRectangle(0, i * 16, rect.w - 8, 16, 0), -1, QuestTranslation.translate(entry.text)); + if (entry.action != null) { + eBtn.setClickAction((b) -> entry.action.run()); + } else { + eBtn.setActive(false); } - - scrollBar.setEnabled(cvScroll.getScrollBounds().getHeight() > 0); + cvScroll.addPanel(eBtn); + } } - - @Override - public void initPanel() - { - super.initPanel(); - - openCategory(catRoot); + + scrollBar.setEnabled(cvScroll.getScrollBounds().getHeight() > 0); + } + + @Override + public void initPanel() { + super.initPanel(); + + openCategory(catRoot); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + boolean used = super.onMouseClick(mx, my, click); + + if (autoClose && !used && !rect.contains(mx, my) && SceneController.getActiveScene() != null) { + SceneController.getActiveScene().closePopup(); + return true; } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - boolean used = super.onMouseClick(mx, my, click); - - if(autoClose && !used && !rect.contains(mx, my) && SceneController.getActiveScene() != null) - { - SceneController.getActiveScene().closePopup(); - return true; - } - - return used; + + return used; + } + + public class ContextCategory { + private final String name; + private final ContextCategory parent; + private final List entries = new ArrayList<>(); + + private ContextCategory(@Nullable ContextCategory parent, @Nonnull String name) { + this.parent = parent; + this.name = name; + + if (this.parent != null) { addButton("<", null, () -> openCategory(this.parent)); } } - - public class ContextCategory - { - private final String name; - private final ContextCategory parent; - private final List entries = new ArrayList<>(); - - private ContextCategory(@Nullable ContextCategory parent, @Nonnull String name) - { - this.parent = parent; - this.name = name; - - if(this.parent != null) addButton("<", null, () -> openCategory(this.parent)); - } - - public void addButton(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) - { - entries.add(new ContextEntry(text, icon, action)); - } - - public ContextCategory addCateogry(@Nonnull String text) - { - ContextCategory cat = new ContextCategory(this, text); - addButton(QuestTranslation.translate(text) + " >", null, () -> openCategory(cat)); - return cat; - } + + public void addButton(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) { + entries.add(new ContextEntry(text, icon, action)); } - - public class ContextEntry - { - private final String text; - private final IGuiTexture icon; - private final Runnable action; - - public ContextEntry(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) - { - this.text = text; - this.icon = icon; - this.action = action; - } + + public ContextCategory addCateogry(@Nonnull String text) { + ContextCategory cat = new ContextCategory(this, text); + addButton(QuestTranslation.translate(text) + " >", null, () -> openCategory(cat)); + return cat; + } + } + + public static class ContextEntry { + private final String text; + private final IGuiTexture icon; + private final Runnable action; + + public ContextEntry(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) { + this.text = text; + this.icon = icon; + this.action = action; } + } } diff --git a/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java b/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java index cb5f489bb..929067f5a 100644 --- a/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java +++ b/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java @@ -19,80 +19,77 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class PopMessage extends CanvasEmpty -{ - private final String message; - private final IGuiTexture icon; - - public PopMessage(@Nonnull String message) - { - this(message, null); - } - - public PopMessage(@Nonnull String message, @Nullable IGuiTexture icon) - { - super(new GuiTransform(GuiAlign.FULL_BOX)); - this.message = message; - this.icon = icon; - } - - @Override - public void initPanel() - { - super.initPanel(); - - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), new ColorTexture(new GuiColorStatic(0x80000000)))); - - CanvasTextured cvBox = new CanvasTextured(new GuiTransform(new Vector4f(0.2F, 0.3F, 0.8F, 0.6F)), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBox); - - if(icon != null) - { - CanvasTextured icoFrame = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0.3F, 0.5F, 0.3F), -16, -40, 32, 32, 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(icoFrame); - - icoFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), icon)); - } - - cvBox.addPanel(new PanelTextBox(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), message).setAlignment(1)); - PanelButton btn = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0.6F, 0.5F, 0.6F), -48, 8, 96, 16, 0), -1, QuestTranslation.translate("gui.back")); - btn.setClickAction((b) -> { - if(SceneController.getActiveScene() != null) SceneController.getActiveScene().closePopup(); - }); - this.addPanel(btn); - } - - // == TRAP ALL UI USAGE UNTIL CLOSED === - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - super.onMouseClick(mx, my, click); - - return true; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - super.onMouseRelease(mx, my, click); - - return true; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - super.onMouseScroll(mx, my, scroll); - - return true; - } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - super.onKeyTyped(c, keycode); - - return true; +public class PopMessage extends CanvasEmpty { + private final String message; + private final IGuiTexture icon; + + public PopMessage(@Nonnull String message) { + this(message, null); + } + + public PopMessage(@Nonnull String message, @Nullable IGuiTexture icon) { + super(new GuiTransform(GuiAlign.FULL_BOX)); + this.message = message; + this.icon = icon; + } + + @Override + public void initPanel() { + super.initPanel(); + + this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), + new ColorTexture(new GuiColorStatic(0x80000000)))); + + CanvasTextured cvBox = new CanvasTextured(new GuiTransform(new Vector4f(0.2F, 0.3F, 0.8F, 0.6F)), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBox); + + if (icon != null) { + CanvasTextured icoFrame = + new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0.3F, 0.5F, 0.3F), -16, -40, 32, 32, 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(icoFrame); + + icoFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), icon)); } + + cvBox.addPanel( + new PanelTextBox(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), message).setAlignment(1)); + PanelButton btn = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0.6F, 0.5F, 0.6F), -48, 8, 96, 16, 0), -1, + QuestTranslation.translate("gui.back")); + btn.setClickAction((b) -> { + if (SceneController.getActiveScene() != null) { SceneController.getActiveScene().closePopup(); } + }); + this.addPanel(btn); + } + + // == TRAP ALL UI USAGE UNTIL CLOSED === + + @Override + public boolean onMouseClick(int mx, int my, int click) { + super.onMouseClick(mx, my, click); + + return true; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + super.onMouseRelease(mx, my, click); + + return true; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + super.onMouseScroll(mx, my, scroll); + + return true; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + super.onKeyTyped(c, keycode); + + return true; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java index 16d67bf04..35a2a6f06 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java @@ -3,78 +3,69 @@ import betterquesting.api.utils.RenderUtils; import net.minecraft.client.renderer.GlStateManager; -public class GuiColorPulse implements IGuiColor -{ - // Saves me having to run the math function every frame - private final static double RAD = Math.toRadians(360F); - - private final IGuiColor c1; - private final IGuiColor c2; - - private final double period; - private final float phase; - - public GuiColorPulse(int color1, int color2, double period, float phase) - { - this(new GuiColorStatic(color1), new GuiColorStatic(color2), period, phase); - } - - public GuiColorPulse(IGuiColor color1, IGuiColor color2, double period, float phase) - { - this.c1 = color1; - this.c2 = color2; - - this.period = period; - this.phase = phase; - } - - @Override - public int getRGB() - { - // Period in milliseconds - double pms = 1000D * period; - // Current period time - double time = System.currentTimeMillis() % pms; - // Shift current time by phase, wrap value and scale between 0.0 - 1.0 - time = (time + (pms * phase)) % pms / pms; - // Convert time to sine wave between 0.0 and 1.0 - float blend = (float)(Math.cos(time * RAD) / 2D + 0.5D); - // Return interpolated color - return RenderUtils.lerpRGB(c1.getRGB(), c2.getRGB(), blend); - } - - @Override - public float getRed() - { - return (getRGB() >> 16 & 255) / 255F; - } - - @Override - public float getGreen() - { - return (getRGB() >> 8 & 255) / 255F; - } - - @Override - public float getBlue() - { - return (getRGB() & 255) / 255F; - } - - @Override - public float getAlpha() - { - return (getRGB() >> 24 & 255) / 255F; - } - - @Override - public void applyGlColor() - { - int color = getRGB(); - float a = (float)(color >> 24 & 255) / 255F; - float r = (float)(color >> 16 & 255) / 255F; - float g = (float)(color >> 8 & 255) / 255F; - float b = (float)(color & 255) / 255F; - GlStateManager.color(r, g, b, a); - } +public class GuiColorPulse implements IGuiColor { + // Saves me having to run the math function every frame + private final static double RAD = Math.toRadians(360F); + + private final IGuiColor c1; + private final IGuiColor c2; + + private final double period; + private final float phase; + + public GuiColorPulse(int color1, int color2, double period, float phase) { + this(new GuiColorStatic(color1), new GuiColorStatic(color2), period, phase); + } + + public GuiColorPulse(IGuiColor color1, IGuiColor color2, double period, float phase) { + this.c1 = color1; + this.c2 = color2; + + this.period = period; + this.phase = phase; + } + + @Override + public int getRGB() { + // Period in milliseconds + double pms = 1000D * period; + // Current period time + double time = System.currentTimeMillis() % pms; + // Shift current time by phase, wrap value and scale between 0.0 - 1.0 + time = (time + (pms * phase)) % pms / pms; + // Convert time to sine wave between 0.0 and 1.0 + float blend = (float) (Math.cos(time * RAD) / 2D + 0.5D); + // Return interpolated color + return RenderUtils.lerpRGB(c1.getRGB(), c2.getRGB(), blend); + } + + @Override + public float getRed() { + return (getRGB() >> 16 & 255) / 255F; + } + + @Override + public float getGreen() { + return (getRGB() >> 8 & 255) / 255F; + } + + @Override + public float getBlue() { + return (getRGB() & 255) / 255F; + } + + @Override + public float getAlpha() { + return (getRGB() >> 24 & 255) / 255F; + } + + @Override + public void applyGlColor() { + int color = getRGB(); + float a = (float) (color >> 24 & 255) / 255F; + float r = (float) (color >> 16 & 255) / 255F; + float g = (float) (color >> 8 & 255) / 255F; + float b = (float) (color & 255) / 255F; + GlStateManager.color(r, g, b, a); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java index ca012160c..15c158f39 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java @@ -1,60 +1,50 @@ package betterquesting.api2.client.gui.resources.colors; -public class GuiColorSequence implements IGuiColor -{ - private final IGuiColor[] colors; - private final float interval; - - public GuiColorSequence(float interval, IGuiColor... colors) - { - this.colors = colors; - this.interval = interval; - } - - @Override - public int getRGB() - { - return getCurrentColor().getRGB(); - } - - @Override - public float getRed() - { - return getCurrentColor().getRed(); - } - - @Override - public float getGreen() - { - return getCurrentColor().getGreen(); - } - - @Override - public float getBlue() - { - return getCurrentColor().getBlue(); - } - - @Override - public float getAlpha() - { - return getCurrentColor().getAlpha(); - } - - @Override - public void applyGlColor() - { - getCurrentColor().applyGlColor(); - } - - public IGuiColor getCurrentColor() - { - if(colors.length <= 0) return null; - return colors[(int)Math.floor((System.currentTimeMillis()/1000D)%(colors.length * interval) / interval)]; - } - - public IGuiColor[] getAllColors() - { - return this.colors; - } +public class GuiColorSequence implements IGuiColor { + private final IGuiColor[] colors; + private final float interval; + + public GuiColorSequence(float interval, IGuiColor... colors) { + this.colors = colors; + this.interval = interval; + } + + @Override + public int getRGB() { + return getCurrentColor().getRGB(); + } + + @Override + public float getRed() { + return getCurrentColor().getRed(); + } + + @Override + public float getGreen() { + return getCurrentColor().getGreen(); + } + + @Override + public float getBlue() { + return getCurrentColor().getBlue(); + } + + @Override + public float getAlpha() { + return getCurrentColor().getAlpha(); + } + + @Override + public void applyGlColor() { + getCurrentColor().applyGlColor(); + } + + public IGuiColor getCurrentColor() { + if (colors.length == 0) { return null; } + return colors[(int) Math.floor((System.currentTimeMillis() / 1000D) % (colors.length * interval) / interval)]; + } + + public IGuiColor[] getAllColors() { + return this.colors; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java index 923303532..506a4342c 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java @@ -4,63 +4,52 @@ import java.awt.*; -public class GuiColorStatic implements IGuiColor -{ - private final int argb; - - public GuiColorStatic(int color) - { - this.argb = color; - } - - public GuiColorStatic(int red, int green, int blue, int alpha) - { - this.argb = ((alpha & 255) << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255); - } - - public GuiColorStatic(float red, float green, float blue, float alpha) - { - this((int)(red * 255), (int)(green * 255), (int)(blue * 255), (int)(alpha * 255)); - } - - public GuiColorStatic(Color color) - { - this(color.getRGB()); - } - - @Override - public int getRGB() - { - return argb; - } - - @Override - public float getRed() - { - return (argb >> 16 & 255) / 255F; - } - - @Override - public float getGreen() - { - return (argb >> 8 & 255) / 255F; - } - - @Override - public float getBlue() - { - return (argb & 255) / 255F; - } - - @Override - public float getAlpha() - { - return (argb >> 24 & 255) / 255F; - } - - @Override - public void applyGlColor() - { - GlStateManager.color(getRed(), getGreen(), getBlue(), getAlpha()); - } +public class GuiColorStatic implements IGuiColor { + private final int argb; + + public GuiColorStatic(int color) { + this.argb = color; + } + + public GuiColorStatic(int red, int green, int blue, int alpha) { + this.argb = ((alpha & 255) << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255); + } + + public GuiColorStatic(float red, float green, float blue, float alpha) { + this((int) (red * 255), (int) (green * 255), (int) (blue * 255), (int) (alpha * 255)); + } + + public GuiColorStatic(Color color) { + this(color.getRGB()); + } + + @Override + public int getRGB() { + return argb; + } + + @Override + public float getRed() { + return (argb >> 16 & 255) / 255F; + } + + @Override + public float getGreen() { + return (argb >> 8 & 255) / 255F; + } + + @Override + public float getBlue() { + return (argb & 255) / 255F; + } + + @Override + public float getAlpha() { + return (argb >> 24 & 255) / 255F; + } + + @Override + public void applyGlColor() { + GlStateManager.color(getRed(), getGreen(), getBlue(), getAlpha()); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java index ba974f1c4..0892ba8dd 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java @@ -4,85 +4,71 @@ import betterquesting.api2.client.gui.controls.IValueIO; import net.minecraft.client.renderer.GlStateManager; -public class GuiColorTransition implements IGuiColor -{ - private final IGuiColor cNorm; - private final IGuiColor cLow; - - private boolean useLerp = true; - private float threshold = 1F; - private IValueIO driver = null; - - public GuiColorTransition(IGuiColor cNorm, IGuiColor cLow) - { - this.cNorm = cNorm; - this.cLow = cLow; - } - - public GuiColorTransition setupBlending(boolean enable, float threshold) - { - this.useLerp = enable; - this.threshold = threshold; - return this; - } - - public GuiColorTransition setBlendDriver(IValueIO driver) - { - this.driver = driver; - return this; - } - - @Override - public int getRGB() - { - if(driver != null && driver.readValue() < threshold) - { - if(!useLerp) - { - return cLow.getRGB(); - } else - { - return RenderUtils.lerpRGB(cLow.getRGB(), cNorm.getRGB(), driver.readValue() / threshold); - } - } else - { - return cNorm.getRGB(); - } - } - - @Override - public float getRed() - { - return (getRGB() >> 16 & 255) / 255F; - } - - @Override - public float getGreen() - { - return (getRGB() >> 8 & 255) / 255F; - } - - @Override - public float getBlue() - { - return (getRGB() & 255) / 255F; - } - - @Override - public float getAlpha() - { - return (getRGB() >> 24 & 255) / 255F; - } - - @Override - public void applyGlColor() - { - int argb = getRGB(); - float r = (argb >> 16 & 255) / 255F; - float g = (argb >> 8 & 255) / 255F; - float b = (argb & 255) / 255F; - float a = (argb >> 24 & 255) / 255F; - - GlStateManager.color(r, g, b, a); - } +public class GuiColorTransition implements IGuiColor { + private final IGuiColor cNorm; + private final IGuiColor cLow; + + private boolean useLerp = true; + private float threshold = 1F; + private IValueIO driver = null; + + public GuiColorTransition(IGuiColor cNorm, IGuiColor cLow) { + this.cNorm = cNorm; + this.cLow = cLow; + } + + public GuiColorTransition setupBlending(boolean enable, float threshold) { + this.useLerp = enable; + this.threshold = threshold; + return this; + } + + public GuiColorTransition setBlendDriver(IValueIO driver) { + this.driver = driver; + return this; + } + + @Override + public int getRGB() { + if (driver != null && driver.readValue() < threshold) { + if (!useLerp) { + return cLow.getRGB(); + } else { + return RenderUtils.lerpRGB(cLow.getRGB(), cNorm.getRGB(), driver.readValue() / threshold); + } + } else { + return cNorm.getRGB(); + } + } + + @Override + public float getRed() { + return (getRGB() >> 16 & 255) / 255F; + } + + @Override + public float getGreen() { + return (getRGB() >> 8 & 255) / 255F; + } + + @Override + public float getBlue() { + return (getRGB() & 255) / 255F; + } + + @Override + public float getAlpha() { + return (getRGB() >> 24 & 255) / 255F; + } + + @Override + public void applyGlColor() { + int argb = getRGB(); + float r = (argb >> 16 & 255) / 255F; + float g = (argb >> 8 & 255) / 255F; + float b = (argb & 255) / 255F; + float a = (argb >> 24 & 255) / 255F; + + GlStateManager.color(r, g, b, a); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/IGuiColor.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/IGuiColor.java index e90b1d841..d5feb1400 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/IGuiColor.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/IGuiColor.java @@ -1,13 +1,15 @@ package betterquesting.api2.client.gui.resources.colors; -public interface IGuiColor -{ - int getRGB(); - - float getRed(); - float getGreen(); - float getBlue(); - float getAlpha(); - - void applyGlColor(); +public interface IGuiColor { + int getRGB(); + + float getRed(); + + float getGreen(); + + float getBlue(); + + float getAlpha(); + + void applyGlColor(); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java index 13d4164ea..1db11ee67 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java @@ -10,40 +10,38 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactoryColorPulse implements IFactoryData -{ - public static final FactoryColorPulse INSTANCE = new FactoryColorPulse(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "color_pulse"); - - @Override - public GuiColorPulse loadFromData(JsonObject data) - { - float period = JsonHelper.GetNumber(data, "period", 1F).floatValue(); - float phase = JsonHelper.GetNumber(data, "phase", 1F).floatValue(); - IGuiColor color1; - IGuiColor color2; - - JsonObject jo1 = JsonHelper.GetObject(data, "color1"); - color1 = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jo1, "colorType", "null")), jo1); - if(color1 == null) color1 = new GuiColorStatic(0xFFFFFFFF); - - JsonObject jo2 = JsonHelper.GetObject(data, "color2"); - color2 = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jo2, "colorType", "null")), jo2); - if(color2 == null) color2 = new GuiColorStatic(0xFFFFFFFF); - - return new GuiColorPulse(color1, color2, period, phase); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public GuiColorPulse createNew() - { - return new GuiColorPulse(0xFFFFFFFF, 0xFFFFFFFF, 1F, 1F); - } +public class FactoryColorPulse implements IFactoryData { + public static final FactoryColorPulse INSTANCE = new FactoryColorPulse(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "color_pulse"); + + @Override + public GuiColorPulse loadFromData(JsonObject data) { + float period = JsonHelper.GetNumber(data, "period", 1F).floatValue(); + float phase = JsonHelper.GetNumber(data, "phase", 1F).floatValue(); + IGuiColor color1; + IGuiColor color2; + + JsonObject jo1 = JsonHelper.GetObject(data, "color1"); + color1 = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jo1, "colorType", "null")), jo1); + if (color1 == null) { color1 = new GuiColorStatic(0xFFFFFFFF); } + + JsonObject jo2 = JsonHelper.GetObject(data, "color2"); + color2 = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jo2, "colorType", "null")), jo2); + if (color2 == null) { color2 = new GuiColorStatic(0xFFFFFFFF); } + + return new GuiColorPulse(color1, color2, period, phase); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public GuiColorPulse createNew() { + return new GuiColorPulse(0xFFFFFFFF, 0xFFFFFFFF, 1F, 1F); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java index c2f0d605c..71e926b26 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java @@ -15,48 +15,43 @@ import java.util.ArrayList; import java.util.List; -public class FactoryColorSequence implements IFactoryData -{ - public static final FactoryColorSequence INSTANCE = new FactoryColorSequence(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "color_sequence"); - private static final IGuiColor NULL_COL = new GuiColorStatic(0xFFFFFFFF); - - @Override - public GuiColorSequence loadFromData(JsonObject data) - { - List layers = new ArrayList<>(); - - float interval = JsonHelper.GetNumber(data, "interval", 1F).floatValue(); - - JsonArray jAry = JsonHelper.GetArray(data, "colors"); - for(JsonElement je : jAry) - { - if(!je.isJsonObject()) continue; - JsonObject jo = je.getAsJsonObject(); - - try - { - IGuiColor tFact = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jo, "colorType", "null")), jo); - layers.add(tFact); - } catch(Exception ignored) - { - layers.add(NULL_COL); - } - } - - return new GuiColorSequence(interval, layers.toArray(new IGuiColor[0])); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public GuiColorSequence createNew() - { - return new GuiColorSequence(1F); +public class FactoryColorSequence implements IFactoryData { + public static final FactoryColorSequence INSTANCE = new FactoryColorSequence(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "color_sequence"); + private static final IGuiColor NULL_COL = new GuiColorStatic(0xFFFFFFFF); + + @Override + public GuiColorSequence loadFromData(JsonObject data) { + List layers = new ArrayList<>(); + + float interval = JsonHelper.GetNumber(data, "interval", 1F).floatValue(); + + JsonArray jAry = JsonHelper.GetArray(data, "colors"); + for (JsonElement je : jAry) { + if (!je.isJsonObject()) { continue; } + JsonObject jo = je.getAsJsonObject(); + + try { + IGuiColor tFact = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jo, "colorType", "null")), + jo); + layers.add(tFact); + } catch (Exception ignored) { + layers.add(NULL_COL); + } } + + return new GuiColorSequence(interval, layers.toArray(new IGuiColor[0])); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public GuiColorSequence createNew() { + return new GuiColorSequence(1F); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorStatic.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorStatic.java index 4cec94f46..d430b3346 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorStatic.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorStatic.java @@ -7,38 +7,32 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactoryColorStatic implements IFactoryData -{ - public static final FactoryColorStatic INSTANCE = new FactoryColorStatic(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "color_static"); - - @Override - public GuiColorStatic loadFromData(JsonObject data) - { - int color; - - try - { - // Needs to be done through long so that the signed bit isn't dropped - color = (int)Long.parseLong(JsonHelper.GetString(data, "color", "FFFFFFFF"), 16); - } catch(NumberFormatException ignored) - { - color = 0xFFFFFFFF; - } - - return new GuiColorStatic(color); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public GuiColorStatic createNew() - { - return new GuiColorStatic(0xFFFFFFFF); +public class FactoryColorStatic implements IFactoryData { + public static final FactoryColorStatic INSTANCE = new FactoryColorStatic(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "color_static"); + + @Override + public GuiColorStatic loadFromData(JsonObject data) { + int color; + + try { + // Needs to be done through long so that the signed bit isn't dropped + color = (int) Long.parseLong(JsonHelper.GetString(data, "color", "FFFFFFFF"), 16); + } catch (NumberFormatException ignored) { + color = 0xFFFFFFFF; } + + return new GuiColorStatic(color); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public GuiColorStatic createNew() { + return new GuiColorStatic(0xFFFFFFFF); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactoryLineTaxiCab.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactoryLineTaxiCab.java index be7346f19..02d1a4d77 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactoryLineTaxiCab.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactoryLineTaxiCab.java @@ -7,42 +7,36 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactoryLineTaxiCab implements IFactoryData -{ - public static final FactoryLineTaxiCab INSTANCE = new FactoryLineTaxiCab(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "line_manhattan"); - - @Override - public LineTaxiCab loadFromData(JsonObject data) - { - float bias = JsonHelper.GetNumber(data, "bias", 0.5F).floatValue(); - boolean isVertical = JsonHelper.GetBoolean(data, "isVertical", false); - - int stippleScale = JsonHelper.GetNumber(data, "stippleScale", 1).intValue(); - short stippleMask; - - try - { - // Needs to be done through int so that the signed bit isn't dropped - stippleMask = (short)Integer.parseInt(JsonHelper.GetString(data, "stippleMask", "1111111111111111"), 2); - } catch(NumberFormatException ignored) - { - stippleMask = (short)0xFFFF; - } - - return new LineTaxiCab(bias, isVertical, stippleScale, stippleMask); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public LineTaxiCab createNew() - { - return new LineTaxiCab(); +public class FactoryLineTaxiCab implements IFactoryData { + public static final FactoryLineTaxiCab INSTANCE = new FactoryLineTaxiCab(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "line_manhattan"); + + @Override + public LineTaxiCab loadFromData(JsonObject data) { + float bias = JsonHelper.GetNumber(data, "bias", 0.5F).floatValue(); + boolean isVertical = JsonHelper.GetBoolean(data, "isVertical", false); + + int stippleScale = JsonHelper.GetNumber(data, "stippleScale", 1).intValue(); + short stippleMask; + + try { + // Needs to be done through int so that the signed bit isn't dropped + stippleMask = (short) Integer.parseInt(JsonHelper.GetString(data, "stippleMask", "1111111111111111"), 2); + } catch (NumberFormatException ignored) { + stippleMask = (short) 0xFFFF; } + + return new LineTaxiCab(bias, isVertical, stippleScale, stippleMask); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public LineTaxiCab createNew() { + return new LineTaxiCab(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactorySimpleLine.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactorySimpleLine.java index 036ea4dc6..70db44ff0 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactorySimpleLine.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/lines/FactorySimpleLine.java @@ -7,39 +7,33 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactorySimpleLine implements IFactoryData -{ - public static final FactorySimpleLine INSTANCE = new FactorySimpleLine(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "line_simple"); - - @Override - public SimpleLine loadFromData(JsonObject data) - { - int stippleScale = JsonHelper.GetNumber(data, "stippleScale", 1).intValue(); - short stippleMask; - - try - { - // Needs to be done through int so that the signed bit isn't dropped - stippleMask = (short)Integer.parseInt(JsonHelper.GetString(data, "stippleMask", "1111111111111111"), 2); - } catch(NumberFormatException ignored) - { - stippleMask = (short)0xFFFF; - } - - return new SimpleLine(stippleScale, stippleMask); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public SimpleLine createNew() - { - return new SimpleLine(); +public class FactorySimpleLine implements IFactoryData { + public static final FactorySimpleLine INSTANCE = new FactorySimpleLine(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "line_simple"); + + @Override + public SimpleLine loadFromData(JsonObject data) { + int stippleScale = JsonHelper.GetNumber(data, "stippleScale", 1).intValue(); + short stippleMask; + + try { + // Needs to be done through int so that the signed bit isn't dropped + stippleMask = (short) Integer.parseInt(JsonHelper.GetString(data, "stippleMask", "1111111111111111"), 2); + } catch (NumberFormatException ignored) { + stippleMask = (short) 0xFFFF; } + + return new SimpleLine(stippleScale, stippleMask); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public SimpleLine createNew() { + return new SimpleLine(); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java index 9ae519492..5b0b0e3a5 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java @@ -13,49 +13,42 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactoryColorTexture implements IFactoryData -{ - public static final FactoryColorTexture INSTANCE = new FactoryColorTexture(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_color"); - - @Override - public ColorTexture loadFromData(JsonObject data) - { - int[] bounds = new int[]{0,0,0,0}; - JsonArray jAry = JsonHelper.GetArray(data, "padding"); - for(int i = 0; i < jAry.size() && i < bounds.length; i++) - { - if(!(jAry.get(i).isJsonPrimitive())) continue; - try - { - bounds[i] = jAry.get(i).getAsInt(); - } catch(Exception ignored){} - } - - IGuiColor color; - JsonObject jCol = JsonHelper.GetObject(data, "color"); - try - { - color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if(color == null) color = new GuiColorStatic(0xFFFFFFFF); - } catch(Exception ignored) - { - color = new GuiColorStatic(0xFFFFFFFF); - } - - return new ColorTexture(color, new GuiPadding(bounds[0], bounds[1], bounds[2], bounds[3])); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; +public class FactoryColorTexture implements IFactoryData { + public static final FactoryColorTexture INSTANCE = new FactoryColorTexture(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_color"); + + @Override + public ColorTexture loadFromData(JsonObject data) { + int[] bounds = new int[] { 0, 0, 0, 0 }; + JsonArray jAry = JsonHelper.GetArray(data, "padding"); + for (int i = 0; i < jAry.size() && i < bounds.length; i++) { + if (!(jAry.get(i).isJsonPrimitive())) { continue; } + try { + bounds[i] = jAry.get(i).getAsInt(); + } catch (Exception ignored) { } } - - @Override - public ColorTexture createNew() - { - return new ColorTexture(new GuiColorStatic(0xFFFFFFFF), new GuiPadding(0, 0, 0, 0)); + + IGuiColor color; + JsonObject jCol = JsonHelper.GetObject(data, "color"); + try { + color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); + if (color == null) { color = new GuiColorStatic(0xFFFFFFFF); } + } catch (Exception ignored) { + color = new GuiColorStatic(0xFFFFFFFF); } + + return new ColorTexture(color, new GuiPadding(bounds[0], bounds[1], bounds[2], bounds[3])); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public ColorTexture createNew() { + return new ColorTexture(new GuiColorStatic(0xFFFFFFFF), new GuiPadding(0, 0, 0, 0)); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryEmptyTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryEmptyTexture.java index 1f443abd8..0e6d9e0d1 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryEmptyTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryEmptyTexture.java @@ -6,27 +6,23 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactoryEmptyTexture implements IFactoryData -{ - public static final FactoryEmptyTexture INSTANCE = new FactoryEmptyTexture(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_none"); - - @Override - public IGuiTexture loadFromData(JsonObject data) - { - return createNew(); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public IGuiTexture createNew() - { - return new EmptyTexture(); - } +public class FactoryEmptyTexture implements IFactoryData { + public static final FactoryEmptyTexture INSTANCE = new FactoryEmptyTexture(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_none"); + + @Override + public IGuiTexture loadFromData(JsonObject data) { + return createNew(); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public IGuiTexture createNew() { + return new EmptyTexture(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java index 00855c571..88f5dcc27 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java @@ -17,46 +17,42 @@ import java.util.ArrayList; import java.util.List; -public class FactoryLayeredTexture implements IFactoryData -{ - public static final FactoryLayeredTexture INSTANCE = new FactoryLayeredTexture(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_layered"); - private static final IGuiTexture NULL_TX = new SimpleTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16)).maintainAspect(false); - - @Override - public LayeredTexture loadFromData(JsonObject data) - { - List layers = new ArrayList<>(); - - JsonArray jAry = JsonHelper.GetArray(data, "layers"); - for(JsonElement je : jAry) - { - if(!je.isJsonObject()) continue; - JsonObject jo = je.getAsJsonObject(); - - try - { - IGuiTexture tFact = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getTexReg().createNew(new ResourceLocation(JsonHelper.GetString(jo, "textureType", "null")), jo); - layers.add(tFact); - } catch(Exception ignored) - { - layers.add(NULL_TX); - } - } - - return new LayeredTexture(layers.toArray(new IGuiTexture[0])); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public LayeredTexture createNew() - { - return new LayeredTexture(); +public class FactoryLayeredTexture implements IFactoryData { + public static final FactoryLayeredTexture INSTANCE = new FactoryLayeredTexture(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_layered"); + private static final IGuiTexture NULL_TX = + new SimpleTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16)).maintainAspect(false); + + @Override + public LayeredTexture loadFromData(JsonObject data) { + List layers = new ArrayList<>(); + + JsonArray jAry = JsonHelper.GetArray(data, "layers"); + for (JsonElement je : jAry) { + if (!je.isJsonObject()) { continue; } + JsonObject jo = je.getAsJsonObject(); + + try { + IGuiTexture tFact = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getTexReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jo, "textureType", "null")), + jo); + layers.add(tFact); + } catch (Exception ignored) { + layers.add(NULL_TX); + } } + + return new LayeredTexture(layers.toArray(new IGuiTexture[0])); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public LayeredTexture createNew() { + return new LayeredTexture(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java index 265d199a1..b8031d8f3 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java @@ -13,63 +13,55 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactoryPolyTextureC implements IFactoryData -{ - public static final FactoryPolyTextureC INSTANCE = new FactoryPolyTextureC(); - private static final ResourceLocation ID_NAME = new ResourceLocation(BetterQuesting.MODID, "poly_custom"); - - @Override - public IGuiTexture loadFromData(JsonObject data) - { - JsonArray jAry = JsonHelper.GetArray(data, "verts"); - double[] verts = new double[jAry.size()]; - for(int i = 0; i < jAry.size() && i < verts.length; i++) - { - if(!(jAry.get(i).isJsonPrimitive())) continue; - try - { - verts[i] = jAry.get(i).getAsDouble(); - } catch(Exception ignored){} - } - - boolean shadow = JsonHelper.GetBoolean(data, "shadow", true); - - IGuiColor color; - JsonObject jCol = JsonHelper.GetObject(data, "color"); - try - { - color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if(color == null) color = new GuiColorStatic(0xFFFFFFFF); - } catch(Exception ignored) - { - color = new GuiColorStatic(0xFFFFFFFF); - } - - int borderSize = JsonHelper.GetNumber(data, "borderSize", 0).intValue(); - IGuiColor borColor; - jCol = JsonHelper.GetObject(data, "borderColor"); - try - { - borColor = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if(borColor == null) borColor = new GuiColorStatic(0xFFFFFFFF); - } catch(Exception ignored) - { - borColor = new GuiColorStatic(0xFFFFFFFF); - } - - - return new PolyTexture(verts, shadow, color).setBorder(borderSize, borColor); +public class FactoryPolyTextureC implements IFactoryData { + public static final FactoryPolyTextureC INSTANCE = new FactoryPolyTextureC(); + private static final ResourceLocation ID_NAME = new ResourceLocation(BetterQuesting.MODID, "poly_custom"); + + @Override + public IGuiTexture loadFromData(JsonObject data) { + JsonArray jAry = JsonHelper.GetArray(data, "verts"); + double[] verts = new double[jAry.size()]; + for (int i = 0; i < jAry.size() && i < verts.length; i++) { + if (!(jAry.get(i).isJsonPrimitive())) { continue; } + try { + verts[i] = jAry.get(i).getAsDouble(); + } catch (Exception ignored) { } } - - @Override - public ResourceLocation getRegistryName() - { - return ID_NAME; + + boolean shadow = JsonHelper.GetBoolean(data, "shadow", true); + + IGuiColor color; + JsonObject jCol = JsonHelper.GetObject(data, "color"); + try { + color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); + if (color == null) { color = new GuiColorStatic(0xFFFFFFFF); } + } catch (Exception ignored) { + color = new GuiColorStatic(0xFFFFFFFF); } - - @Override - public IGuiTexture createNew() - { - return new PolyTexture(4, 45D, true, new GuiColorStatic(0xFFFFFFFF)); + + int borderSize = JsonHelper.GetNumber(data, "borderSize", 0).intValue(); + IGuiColor borColor; + jCol = JsonHelper.GetObject(data, "borderColor"); + try { + borColor = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); + if (borColor == null) { borColor = new GuiColorStatic(0xFFFFFFFF); } + } catch (Exception ignored) { + borColor = new GuiColorStatic(0xFFFFFFFF); } + + + return new PolyTexture(verts, shadow, color).setBorder(borderSize, borColor); + } + + @Override + public ResourceLocation getRegistryName() { + return ID_NAME; + } + + @Override + public IGuiTexture createNew() { + return new PolyTexture(4, 45D, true, new GuiColorStatic(0xFFFFFFFF)); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java index 1d9f4c301..86565950f 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java @@ -12,54 +12,48 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactoryPolyTextureR implements IFactoryData -{ - public static final FactoryPolyTextureR INSTANCE = new FactoryPolyTextureR(); - private static final ResourceLocation ID_NAME = new ResourceLocation(BetterQuesting.MODID, "poly_regular"); - - @Override - public IGuiTexture loadFromData(JsonObject data) - { - int points = JsonHelper.GetNumber(data, "points", 4).intValue(); - boolean shadow = JsonHelper.GetBoolean(data, "shadow", true); - double rotation = JsonHelper.GetNumber(data, "rotation", 45D).doubleValue(); - - IGuiColor color; - JsonObject jCol = JsonHelper.GetObject(data, "color"); - try - { - color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if(color == null) color = new GuiColorStatic(0xFFFFFFFF); - } catch(Exception ignored) - { - color = new GuiColorStatic(0xFFFFFFFF); - } - - int borderSize = JsonHelper.GetNumber(data, "borderSize", 0).intValue(); - IGuiColor borColor; - jCol = JsonHelper.GetObject(data, "borderColor"); - try - { - borColor = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg().createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if(borColor == null) borColor = new GuiColorStatic(0xFFFFFFFF); - } catch(Exception ignored) - { - borColor = new GuiColorStatic(0xFFFFFFFF); - } - - - return new PolyTexture(points, rotation, shadow, color).setBorder(borderSize, borColor); - } - - @Override - public ResourceLocation getRegistryName() - { - return ID_NAME; +public class FactoryPolyTextureR implements IFactoryData { + public static final FactoryPolyTextureR INSTANCE = new FactoryPolyTextureR(); + private static final ResourceLocation ID_NAME = new ResourceLocation(BetterQuesting.MODID, "poly_regular"); + + @Override + public IGuiTexture loadFromData(JsonObject data) { + int points = JsonHelper.GetNumber(data, "points", 4).intValue(); + boolean shadow = JsonHelper.GetBoolean(data, "shadow", true); + double rotation = JsonHelper.GetNumber(data, "rotation", 45D).doubleValue(); + + IGuiColor color; + JsonObject jCol = JsonHelper.GetObject(data, "color"); + try { + color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); + if (color == null) { color = new GuiColorStatic(0xFFFFFFFF); } + } catch (Exception ignored) { + color = new GuiColorStatic(0xFFFFFFFF); } - - @Override - public IGuiTexture createNew() - { - return new PolyTexture(4, 45D, true, new GuiColorStatic(0xFFFFFFFF)); + + int borderSize = JsonHelper.GetNumber(data, "borderSize", 0).intValue(); + IGuiColor borColor; + jCol = JsonHelper.GetObject(data, "borderColor"); + try { + borColor = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); + if (borColor == null) { borColor = new GuiColorStatic(0xFFFFFFFF); } + } catch (Exception ignored) { + borColor = new GuiColorStatic(0xFFFFFFFF); } + + + return new PolyTexture(points, rotation, shadow, color).setBorder(borderSize, borColor); + } + + @Override + public ResourceLocation getRegistryName() { + return ID_NAME; + } + + @Override + public IGuiTexture createNew() { + return new PolyTexture(4, 45D, true, new GuiColorStatic(0xFFFFFFFF)); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java index ced517b82..bb32004f5 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java @@ -10,41 +10,37 @@ import com.google.gson.JsonObject; import net.minecraft.util.ResourceLocation; -public class FactorySimpleTexture implements IFactoryData -{ - public static final FactorySimpleTexture INSTANCE = new FactorySimpleTexture(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_simple"); - - @Override - public SimpleTexture loadFromData(JsonObject data) - { - ResourceLocation atlas = new ResourceLocation(JsonHelper.GetString(data, "atlas", PresetTexture.TX_NULL.toString())); - boolean aspect = !JsonHelper.GetBoolean(data, "stretch", false); - - int[] bounds = new int[]{0,0,16,16}; - JsonArray jAry = JsonHelper.GetArray(data, "bounds"); - for(int i = 0; i < jAry.size() && i < bounds.length; i++) - { - if(!(jAry.get(i).isJsonPrimitive())) continue; - try - { - bounds[i] = jAry.get(i).getAsInt(); - } catch(Exception ignored){} - } - - return new SimpleTexture(atlas, new GuiRectangle(bounds[0], bounds[1], bounds[2], bounds[3])).maintainAspect(aspect); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public SimpleTexture createNew() - { - return new SimpleTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16)); +public class FactorySimpleTexture implements IFactoryData { + public static final FactorySimpleTexture INSTANCE = new FactorySimpleTexture(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_simple"); + + @Override + public SimpleTexture loadFromData(JsonObject data) { + ResourceLocation atlas = + new ResourceLocation(JsonHelper.GetString(data, "atlas", PresetTexture.TX_NULL.toString())); + boolean aspect = !JsonHelper.GetBoolean(data, "stretch", false); + + int[] bounds = new int[] { 0, 0, 16, 16 }; + JsonArray jAry = JsonHelper.GetArray(data, "bounds"); + for (int i = 0; i < jAry.size() && i < bounds.length; i++) { + if (!(jAry.get(i).isJsonPrimitive())) { continue; } + try { + bounds[i] = jAry.get(i).getAsInt(); + } catch (Exception ignored) { } } + + return new SimpleTexture(atlas, new GuiRectangle(bounds[0], bounds[1], bounds[2], bounds[3])).maintainAspect( + aspect); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public SimpleTexture createNew() { + return new SimpleTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16)); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java index 329364c0b..ebf0480b4 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java @@ -13,52 +13,48 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; -public class FactorySlicedTexture implements IFactoryData -{ - public static final FactorySlicedTexture INSTANCE = new FactorySlicedTexture(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_sliced"); - - @Override - public SlicedTexture loadFromData(JsonObject data) - { - ResourceLocation atlas = new ResourceLocation(JsonHelper.GetString(data, "atlas", PresetTexture.TX_NULL.toString())); - int sliceMode = MathHelper.clamp(JsonHelper.GetNumber(data, "sliceMode", 0).intValue(), 0, SliceMode.values().length); - - int[] bounds = new int[]{0,0,16,16}; - JsonArray jAry = JsonHelper.GetArray(data, "bounds"); - for(int i = 0; i < jAry.size() && i < bounds.length; i++) - { - if(!(jAry.get(i).isJsonPrimitive())) continue; - try - { - bounds[i] = jAry.get(i).getAsInt(); - } catch(Exception ignored){} - } - - int[] padding = new int[]{0,0,16,16}; - JsonArray jAry2 = JsonHelper.GetArray(data, "padding"); - for(int i = 0; i < jAry.size() && i < padding.length; i++) - { - if(!(jAry2.get(i).isJsonPrimitive())) continue; - try - { - padding[i] = jAry2.get(i).getAsInt(); - } catch(Exception ignored){} - } - - return new SlicedTexture(atlas, new GuiRectangle(bounds[0], bounds[1], bounds[2], bounds[3]), new GuiPadding(padding[0], padding[1], padding[2], padding[3])).setSliceMode(SliceMode.values()[sliceMode]); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; +public class FactorySlicedTexture implements IFactoryData { + public static final FactorySlicedTexture INSTANCE = new FactorySlicedTexture(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_sliced"); + + @Override + public SlicedTexture loadFromData(JsonObject data) { + ResourceLocation atlas = + new ResourceLocation(JsonHelper.GetString(data, "atlas", PresetTexture.TX_NULL.toString())); + int sliceMode = + MathHelper.clamp(JsonHelper.GetNumber(data, "sliceMode", 0).intValue(), 0, SliceMode.values().length); + + int[] bounds = new int[] { 0, 0, 16, 16 }; + JsonArray jAry = JsonHelper.GetArray(data, "bounds"); + for (int i = 0; i < jAry.size() && i < bounds.length; i++) { + if (!(jAry.get(i).isJsonPrimitive())) { continue; } + try { + bounds[i] = jAry.get(i).getAsInt(); + } catch (Exception ignored) { } } - - @Override - public SlicedTexture createNew() - { - return new SlicedTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16), new GuiPadding(1, 1, 1, 1)); + + int[] padding = new int[] { 0, 0, 16, 16 }; + JsonArray jAry2 = JsonHelper.GetArray(data, "padding"); + for (int i = 0; i < jAry.size() && i < padding.length; i++) { + if (!(jAry2.get(i).isJsonPrimitive())) { continue; } + try { + padding[i] = jAry2.get(i).getAsInt(); + } catch (Exception ignored) { } } + + return new SlicedTexture(atlas, new GuiRectangle(bounds[0], bounds[1], bounds[2], bounds[3]), + new GuiPadding(padding[0], padding[1], padding[2], padding[3])).setSliceMode( + SliceMode.values()[sliceMode]); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public SlicedTexture createNew() { + return new SlicedTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16), new GuiPadding(1, 1, 1, 1)); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java index 49e86d13d..e129d4394 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java @@ -17,48 +17,43 @@ import java.util.ArrayList; import java.util.List; -public class FactorySlideShowTexture implements IFactoryData -{ - public static final FactorySlideShowTexture INSTANCE = new FactorySlideShowTexture(); - - private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_slides"); - private static final IGuiTexture NULL_TX = new SimpleTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16)).maintainAspect(false); - - @Override - public SlideShowTexture loadFromData(JsonObject data) - { - List layers = new ArrayList<>(); - - float interval = JsonHelper.GetNumber(data, "interval", 1F).floatValue(); - - JsonArray jAry = JsonHelper.GetArray(data, "slides"); - for(JsonElement je : jAry) - { - if(!je.isJsonObject()) continue; - JsonObject jo = je.getAsJsonObject(); - - try - { - IGuiTexture tFact = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getTexReg().createNew(new ResourceLocation(JsonHelper.GetString(jo, "textureType", "null")), jo); - layers.add(tFact); - } catch(Exception ignored) - { - layers.add(NULL_TX); - } - } - - return new SlideShowTexture(interval, layers.toArray(new IGuiTexture[0])); - } - - @Override - public ResourceLocation getRegistryName() - { - return RES_ID; - } - - @Override - public SlideShowTexture createNew() - { - return new SlideShowTexture(1F); +public class FactorySlideShowTexture implements IFactoryData { + public static final FactorySlideShowTexture INSTANCE = new FactorySlideShowTexture(); + + private static final ResourceLocation RES_ID = new ResourceLocation("betterquesting", "texture_slides"); + private static final IGuiTexture NULL_TX = + new SimpleTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 16, 16)).maintainAspect(false); + + @Override + public SlideShowTexture loadFromData(JsonObject data) { + List layers = new ArrayList<>(); + + float interval = JsonHelper.GetNumber(data, "interval", 1F).floatValue(); + + JsonArray jAry = JsonHelper.GetArray(data, "slides"); + for (JsonElement je : jAry) { + if (!je.isJsonObject()) { continue; } + JsonObject jo = je.getAsJsonObject(); + + try { + IGuiTexture tFact = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getTexReg() + .createNew(new ResourceLocation(JsonHelper.GetString(jo, "textureType", "null")), jo); + layers.add(tFact); + } catch (Exception ignored) { + layers.add(NULL_TX); + } } + + return new SlideShowTexture(interval, layers.toArray(new IGuiTexture[0])); + } + + @Override + public ResourceLocation getRegistryName() { + return RES_ID; + } + + @Override + public SlideShowTexture createNew() { + return new SlideShowTexture(1F); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java b/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java index dbe4bd921..dc5a6ac7a 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java @@ -5,53 +5,49 @@ import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.opengl.GL11; -public class BoxLine implements IGuiLine -{ - private final short pattern; - private final int scale; - - public BoxLine() - { - this(1, (short)0xFFFF); - } - - public BoxLine(int stippleScale, short stipplePattern) - { - this.pattern = stipplePattern; - this.scale = stippleScale; - } - - @Override - public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) - { - int minX = Math.min(start.getX(), end.getX()); - int minY = Math.min(start.getY(), end.getY()); - int maxX = Math.max(start.getX() + start.getWidth(), end.getX() + end.getWidth()); - int maxY = Math.max(start.getY() + start.getHeight(), end.getY() + end.getHeight()); - - GlStateManager.pushMatrix(); - - GlStateManager.disableTexture2D(); - GL11.glEnable(GL11.GL_LINE_STIPPLE); - color.applyGlColor(); - GL11.glLineWidth(width); - GL11.glLineStipple(scale, pattern); - - GL11.glBegin(GL11.GL_LINE_LOOP); - - GL11.glVertex2i(minX, minY); - GL11.glVertex2i(maxX, minY); - GL11.glVertex2i(maxX, maxY); - GL11.glVertex2i(minX, maxY); - - GL11.glEnd(); - - GL11.glLineStipple(1, (short)0xFFFF); - GL11.glLineWidth(1F); - GL11.glDisable(GL11.GL_LINE_STIPPLE); - GlStateManager.enableTexture2D(); - GlStateManager.color(1F, 1F, 1F, 1F); - - GlStateManager.popMatrix(); - } +public class BoxLine implements IGuiLine { + private final short pattern; + private final int scale; + + public BoxLine() { + this(1, (short) 0xFFFF); + } + + public BoxLine(int stippleScale, short stipplePattern) { + this.pattern = stipplePattern; + this.scale = stippleScale; + } + + @Override + public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) { + int minX = Math.min(start.getX(), end.getX()); + int minY = Math.min(start.getY(), end.getY()); + int maxX = Math.max(start.getX() + start.getWidth(), end.getX() + end.getWidth()); + int maxY = Math.max(start.getY() + start.getHeight(), end.getY() + end.getHeight()); + + GlStateManager.pushMatrix(); + + GlStateManager.disableTexture2D(); + GL11.glEnable(GL11.GL_LINE_STIPPLE); + color.applyGlColor(); + GL11.glLineWidth(width); + GL11.glLineStipple(scale, pattern); + + GL11.glBegin(GL11.GL_LINE_LOOP); + + GL11.glVertex2i(minX, minY); + GL11.glVertex2i(maxX, minY); + GL11.glVertex2i(maxX, maxY); + GL11.glVertex2i(minX, maxY); + + GL11.glEnd(); + + GL11.glLineStipple(1, (short) 0xFFFF); + GL11.glLineWidth(1F); + GL11.glDisable(GL11.GL_LINE_STIPPLE); + GlStateManager.enableTexture2D(); + GlStateManager.color(1F, 1F, 1F, 1F); + + GlStateManager.popMatrix(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/lines/GuiLineSequence.java b/src/main/java/betterquesting/api2/client/gui/resources/lines/GuiLineSequence.java index 36f19427b..ae197ede6 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/lines/GuiLineSequence.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/lines/GuiLineSequence.java @@ -3,30 +3,25 @@ import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.resources.colors.IGuiColor; -public class GuiLineSequence implements IGuiLine -{ - public final IGuiLine[] lines; - private final float interval; - - public GuiLineSequence(float interval, IGuiLine... lines) - { - this.lines = lines; - this.interval = interval; - } - - @Override - public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) - { - getCurrentLine().drawLine(start, end, width, color, partialTick); - } - - public IGuiLine getCurrentLine() - { - return lines[(int)Math.floor((System.currentTimeMillis()/1000D)%(lines.length * interval) / interval)]; - } - - public IGuiLine[] getAllLines() - { - return lines; - } +public class GuiLineSequence implements IGuiLine { + public final IGuiLine[] lines; + private final float interval; + + public GuiLineSequence(float interval, IGuiLine... lines) { + this.lines = lines; + this.interval = interval; + } + + @Override + public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) { + getCurrentLine().drawLine(start, end, width, color, partialTick); + } + + public IGuiLine getCurrentLine() { + return lines[(int) Math.floor((System.currentTimeMillis() / 1000D) % (lines.length * interval) / interval)]; + } + + public IGuiLine[] getAllLines() { + return lines; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/lines/IGuiLine.java b/src/main/java/betterquesting/api2/client/gui/resources/lines/IGuiLine.java index a36ca92f9..81d482ab2 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/lines/IGuiLine.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/lines/IGuiLine.java @@ -3,7 +3,6 @@ import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.resources.colors.IGuiColor; -public interface IGuiLine -{ - void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick); +public interface IGuiLine { + void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/lines/LineTaxiCab.java b/src/main/java/betterquesting/api2/client/gui/resources/lines/LineTaxiCab.java index 0f95b3d23..490787959 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/lines/LineTaxiCab.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/lines/LineTaxiCab.java @@ -6,94 +6,82 @@ import net.minecraft.util.math.MathHelper; import org.lwjgl.opengl.GL11; -public class LineTaxiCab implements IGuiLine -{ - private final float bias; - private final boolean isVertical; - private final short stipMask; - private final int stipScale; - - public LineTaxiCab() - { - this(0.5F, false, 1, (short)0xFFFF); +public class LineTaxiCab implements IGuiLine { + private final float bias; + private final boolean isVertical; + private final short stipMask; + private final int stipScale; + + public LineTaxiCab() { + this(0.5F, false, 1, (short) 0xFFFF); + } + + public LineTaxiCab(float bias, boolean isVertical, int stipScale, short stipMask) { + this.bias = MathHelper.clamp(bias, 0F, 1F); + this.isVertical = isVertical; + + this.stipScale = stipScale; + this.stipMask = stipMask; + } + + @Override + public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) { + GlStateManager.pushMatrix(); + + GlStateManager.disableTexture2D(); + GL11.glEnable(GL11.GL_LINE_STIPPLE); + color.applyGlColor(); + GL11.glLineWidth(width); + GL11.glLineStipple(stipScale, stipMask); + + int x1 = start.getX() + start.getWidth() / 2; + int y1 = start.getY() + start.getHeight() / 2; + int x2 = end.getX() + end.getWidth() / 2; + int y2 = end.getY() + end.getHeight() / 2; + + int x3 = x1 + Math.round((x2 - x1) * bias); + int y3 = y1 + Math.round((y2 - y1) * bias); + + if (bias > 0F) { + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(x1, y1); + if (isVertical) { + GL11.glVertex2f(x1, y3); + } else { + GL11.glVertex2f(x3, y1); + } + GL11.glEnd(); } - - public LineTaxiCab(float bias, boolean isVertical, int stipScale, short stipMask) - { - this.bias = MathHelper.clamp(bias, 0F, 1F); - this.isVertical = isVertical; - - this.stipScale = stipScale; - this.stipMask = stipMask; + + if (isVertical) { + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(x1, y3); + GL11.glVertex2f(x2, y3); + GL11.glEnd(); + } else { + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(x3, y1); + GL11.glVertex2f(x3, y2); + GL11.glEnd(); } - - @Override - public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) - { - GlStateManager.pushMatrix(); - - GlStateManager.disableTexture2D(); - GL11.glEnable(GL11.GL_LINE_STIPPLE); - color.applyGlColor(); - GL11.glLineWidth(width); - GL11.glLineStipple(stipScale, stipMask); - - int x1 = start.getX() + start.getWidth() / 2; - int y1 = start.getY() + start.getHeight() / 2; - int x2 = end.getX() + end.getWidth() / 2; - int y2 = end.getY() + end.getHeight() / 2; - - int x3 = x1 + Math.round((x2 - x1) * bias); - int y3 = y1 + Math.round((y2 - y1) * bias); - - if(bias > 0F) - { - GL11.glBegin(GL11.GL_LINES); - GL11.glVertex2f(x1, y1); - if(isVertical) - { - GL11.glVertex2f(x1, y3); - } else - { - GL11.glVertex2f(x3, y1); - } - GL11.glEnd(); - } - - if(isVertical) - { - GL11.glBegin(GL11.GL_LINES); - GL11.glVertex2f(x1, y3); - GL11.glVertex2f(x2, y3); - GL11.glEnd(); - } else - { - GL11.glBegin(GL11.GL_LINES); - GL11.glVertex2f(x3, y1); - GL11.glVertex2f(x3, y2); - GL11.glEnd(); - } - - if(bias < 1F) - { - GL11.glBegin(GL11.GL_LINES); - if(isVertical) - { - GL11.glVertex2f(x2, y3); - } else - { - GL11.glVertex2f(x3, y2); - } - GL11.glVertex2f(x2, y2); - GL11.glEnd(); - } - - GL11.glLineStipple(1, (short)0xFFFF); - GL11.glLineWidth(1F); - GL11.glDisable(GL11.GL_LINE_STIPPLE); - GlStateManager.enableTexture2D(); - GlStateManager.color(1F, 1F, 1F, 1F); - - GlStateManager.popMatrix(); + + if (bias < 1F) { + GL11.glBegin(GL11.GL_LINES); + if (isVertical) { + GL11.glVertex2f(x2, y3); + } else { + GL11.glVertex2f(x3, y2); + } + GL11.glVertex2f(x2, y2); + GL11.glEnd(); } + + GL11.glLineStipple(1, (short) 0xFFFF); + GL11.glLineWidth(1F); + GL11.glDisable(GL11.GL_LINE_STIPPLE); + GlStateManager.enableTexture2D(); + GlStateManager.color(1F, 1F, 1F, 1F); + + GlStateManager.popMatrix(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java b/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java index 8dba73615..791bcee09 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java @@ -1,48 +1,44 @@ package betterquesting.api2.client.gui.resources.lines; +import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.resources.colors.IGuiColor; import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.opengl.GL11; -import betterquesting.api2.client.gui.misc.IGuiRect; -public class SimpleLine implements IGuiLine -{ - private final short pattern; - private final int scale; - - public SimpleLine() - { - this(1, (short)0xFFFF); - } - - public SimpleLine(int stippleScale, short stipplePattern) - { - this.pattern = stipplePattern; - this.scale = stippleScale; - } - - @Override - public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) - { - GlStateManager.pushMatrix(); - - GlStateManager.disableTexture2D(); - GL11.glEnable(GL11.GL_LINE_STIPPLE); - color.applyGlColor(); - GL11.glLineWidth(width); - GL11.glLineStipple(scale, pattern); - - GL11.glBegin(GL11.GL_LINES); - GL11.glVertex2f(start.getX() + start.getWidth() / 2F, start.getY() + start.getHeight() / 2F); - GL11.glVertex2f(end.getX() + end.getWidth() / 2F, end.getY() + end.getHeight() / 2F); - GL11.glEnd(); - - GL11.glLineStipple(1, (short)0xFFFF); - GL11.glLineWidth(1F); - GL11.glDisable(GL11.GL_LINE_STIPPLE); - GlStateManager.enableTexture2D(); - GlStateManager.color(1F, 1F, 1F, 1F); - - GlStateManager.popMatrix(); - } +public class SimpleLine implements IGuiLine { + private final short pattern; + private final int scale; + + public SimpleLine() { + this(1, (short) 0xFFFF); + } + + public SimpleLine(int stippleScale, short stipplePattern) { + this.pattern = stipplePattern; + this.scale = stippleScale; + } + + @Override + public void drawLine(IGuiRect start, IGuiRect end, int width, IGuiColor color, float partialTick) { + GlStateManager.pushMatrix(); + + GlStateManager.disableTexture2D(); + GL11.glEnable(GL11.GL_LINE_STIPPLE); + color.applyGlColor(); + GL11.glLineWidth(width); + GL11.glLineStipple(scale, pattern); + + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(start.getX() + start.getWidth() / 2F, start.getY() + start.getHeight() / 2F); + GL11.glVertex2f(end.getX() + end.getWidth() / 2F, end.getY() + end.getHeight() / 2F); + GL11.glEnd(); + + GL11.glLineStipple(1, (short) 0xFFFF); + GL11.glLineWidth(1F); + GL11.glDisable(GL11.GL_LINE_STIPPLE); + GlStateManager.enableTexture2D(); + GlStateManager.color(1F, 1F, 1F, 1F); + + GlStateManager.popMatrix(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java index 3dfde52a8..45effb44e 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java @@ -9,59 +9,52 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; -public class ColorTexture implements IGuiTexture -{ - private final IGuiColor baseColor; - private final GuiRectangle rect = new GuiRectangle(0, 0, 0, 0); - private final GuiPadding pad; - // Dummy value - private final IGuiRect bounds = new GuiRectangle(0, 0, 16, 16); - - public ColorTexture(IGuiColor baseColor) - { - this(baseColor, new GuiPadding(0, 0, 0, 0)); - } - - // Really only used for item slot highlighting but could be used elsewhere - public ColorTexture(IGuiColor baseColor, GuiPadding padding) - { - this.baseColor = baseColor; - this.pad = padding; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) - { - drawTexture(x, y, width, height, zDepth, partialTick, baseColor); - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0) return; - - GlStateManager.pushMatrix(); - - // Just so we're not wasting heap memory making a new GuiRectangle every time - rect.x = x + pad.l; - rect.y = y + pad.t; - rect.w = width - (pad.r + pad.l); - rect.h = height - (pad.b + pad.r); - - RenderUtils.drawColoredRect(rect, color); - - GlStateManager.popMatrix(); - } - - @Override - public ResourceLocation getTexture() - { - return PresetTexture.TX_SIMPLE; - } - - @Override - public IGuiRect getBounds() - { - return bounds; - } +public class ColorTexture implements IGuiTexture { + private final IGuiColor baseColor; + private final GuiRectangle rect = new GuiRectangle(0, 0, 0, 0); + private final GuiPadding pad; + // Dummy value + private final IGuiRect bounds = new GuiRectangle(0, 0, 16, 16); + + public ColorTexture(IGuiColor baseColor) { + this(baseColor, new GuiPadding(0, 0, 0, 0)); + } + + // Really only used for item slot highlighting but could be used elsewhere + public ColorTexture(IGuiColor baseColor, GuiPadding padding) { + this.baseColor = baseColor; + this.pad = padding; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { + drawTexture(x, y, width, height, zDepth, partialTick, baseColor); + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0) { return; } + + GlStateManager.pushMatrix(); + + // Just so we're not wasting heap memory making a new GuiRectangle every time + rect.x = x + pad.l; + rect.y = y + pad.t; + rect.w = width - (pad.r + pad.l); + rect.h = height - (pad.b + pad.r); + + RenderUtils.drawColoredRect(rect, color); + + GlStateManager.popMatrix(); + } + + @Override + public ResourceLocation getTexture() { + return PresetTexture.TX_SIMPLE; + } + + @Override + public IGuiRect getBounds() { + return bounds; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java index 63f9f3dbb..9cdf9ed85 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java @@ -5,27 +5,22 @@ import net.minecraft.util.ResourceLocation; // Literally does nothing... -public class EmptyTexture implements IGuiTexture -{ - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) - { - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) - { - } - - @Override - public ResourceLocation getTexture() - { - return null; - } - - @Override - public IGuiRect getBounds() - { - return null; - } +public class EmptyTexture implements IGuiTexture { + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { + } + + @Override + public ResourceLocation getTexture() { + return null; + } + + @Override + public IGuiRect getBounds() { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java index abdd64f13..149ad40ed 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java @@ -16,107 +16,102 @@ import net.minecraftforge.fluids.FluidStack; import org.lwjgl.opengl.GL11; -public class FluidTexture implements IGuiTexture -{ - private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); - - private final FluidStack fluid; - private final boolean showCount; - private final boolean keepAspect; - - // Dummy value - private final IGuiRect bounds = new GuiRectangle(0, 0, 16, 16); - - public FluidTexture(FluidStack fluid) - { - this(fluid, false, true); - } - - public FluidTexture(FluidStack fluid, boolean showCount, boolean keepAspect) - { - this.fluid = fluid; - this.showCount = showCount; - this.keepAspect = keepAspect; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) - { - this.drawTexture(x, y, width, height, zDepth, partialTick, defColor); - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0) return; - - float sx = width/16F; - float sy = height/16F; - - double dx = 0; - double dy = 0; - - if(keepAspect) - { - float sa = Math.min(sx, sy); - - dx = Math.floor((sx - sa) * 8F); - dy = Math.floor((sy - sa) * 8F); - - sx = sa; - sy = sa; - } - - GlStateManager.pushMatrix(); - - GlStateManager.translate(x + dx, y + dy, 0); - GlStateManager.scale(sx, sy, 1F); - - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); - - int fCol = fluid.getFluid().getColor(fluid); - float a = (fCol >> 24 & 255) / 255F; - float r = (fCol >> 16 & 255) / 255F; - float g = (fCol >> 8 & 255) / 255F; - float b = (fCol & 255) / 255F; - a = a + color.getAlpha() / 2F; - r = r + color.getRed() / 2F; - g = g + color.getGreen() / 2F; - b = b + color.getBlue() / 2F; - GlStateManager.color(r, g, b, a); - - // TODO: Add tiling option - - Minecraft mc = Minecraft.getMinecraft(); - mc.renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); - TextureAtlasSprite fluidTx = mc.getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getStill().toString()); - this.drawTexturedModalRect(0, 0, 0, fluidTx, 16, 16); - - GlStateManager.popMatrix(); - } - - @Override - public ResourceLocation getTexture() - { - return PresetTexture.TX_NULL; - } - - @Override - public IGuiRect getBounds() - { - return bounds; - } - - private void drawTexturedModalRect(double xCoord, double yCoord, double zDepth, TextureAtlasSprite textureSprite, double widthIn, double heightIn) - { - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder bufferbuilder = tessellator.getBuffer(); - bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX); - bufferbuilder.pos(xCoord, yCoord + heightIn, zDepth).tex(textureSprite.getMinU(), textureSprite.getMaxV()).endVertex(); - bufferbuilder.pos(xCoord + widthIn, yCoord + heightIn, zDepth).tex(textureSprite.getMaxU(), textureSprite.getMaxV()).endVertex(); - bufferbuilder.pos(xCoord + widthIn, yCoord, zDepth).tex(textureSprite.getMaxU(), textureSprite.getMinV()).endVertex(); - bufferbuilder.pos(xCoord, yCoord, zDepth).tex(textureSprite.getMinU(), textureSprite.getMinV()).endVertex(); - tessellator.draw(); +public class FluidTexture implements IGuiTexture { + private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); + + private final FluidStack fluid; + private final boolean showCount; + private final boolean keepAspect; + + // Dummy value + private final IGuiRect bounds = new GuiRectangle(0, 0, 16, 16); + + public FluidTexture(FluidStack fluid) { + this(fluid, false, true); + } + + public FluidTexture(FluidStack fluid, boolean showCount, boolean keepAspect) { + this.fluid = fluid; + this.showCount = showCount; + this.keepAspect = keepAspect; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { + this.drawTexture(x, y, width, height, zDepth, partialTick, defColor); + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0) { return; } + + float sx = width / 16F; + float sy = height / 16F; + + double dx = 0; + double dy = 0; + + if (keepAspect) { + float sa = Math.min(sx, sy); + + dx = Math.floor((sx - sa) * 8F); + dy = Math.floor((sy - sa) * 8F); + + sx = sa; + sy = sa; } + + GlStateManager.pushMatrix(); + + GlStateManager.translate(x + dx, y + dy, 0); + GlStateManager.scale(sx, sy, 1F); + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); + + int fCol = fluid.getFluid().getColor(fluid); + float a = (fCol >> 24 & 255) / 255F; + float r = (fCol >> 16 & 255) / 255F; + float g = (fCol >> 8 & 255) / 255F; + float b = (fCol & 255) / 255F; + a = a + color.getAlpha() / 2F; + r = r + color.getRed() / 2F; + g = g + color.getGreen() / 2F; + b = b + color.getBlue() / 2F; + GlStateManager.color(r, g, b, a); + + // TODO: Add tiling option + + Minecraft mc = Minecraft.getMinecraft(); + mc.renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); + TextureAtlasSprite fluidTx = mc.getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getStill().toString()); + this.drawTexturedModalRect(0, 0, 0, fluidTx, 16, 16); + + GlStateManager.popMatrix(); + } + + @Override + public ResourceLocation getTexture() { + return PresetTexture.TX_NULL; + } + + @Override + public IGuiRect getBounds() { + return bounds; + } + + private void drawTexturedModalRect(double xCoord, double yCoord, double zDepth, TextureAtlasSprite textureSprite, + double widthIn, double heightIn) { + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder bufferbuilder = tessellator.getBuffer(); + bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX); + bufferbuilder.pos(xCoord, yCoord + heightIn, zDepth).tex(textureSprite.getMinU(), textureSprite.getMaxV()) + .endVertex(); + bufferbuilder.pos(xCoord + widthIn, yCoord + heightIn, zDepth).tex(textureSprite.getMaxU(), textureSprite.getMaxV()) + .endVertex(); + bufferbuilder.pos(xCoord + widthIn, yCoord, zDepth).tex(textureSprite.getMaxU(), textureSprite.getMinV()) + .endVertex(); + bufferbuilder.pos(xCoord, yCoord, zDepth).tex(textureSprite.getMinU(), textureSprite.getMinV()).endVertex(); + tessellator.draw(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java index 3250fbfb3..3799c7883 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java @@ -7,43 +7,37 @@ /** * Wraps an existing IGuiTexture with an IGuiColor */ -public class GuiTextureColored implements IGuiTexture -{ - private final IGuiTexture texture; - private final IGuiColor color; - - public GuiTextureColored(IGuiTexture texture, IGuiColor color) - { - this.texture = texture; - this.color = color; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) - { - if(width <= 0 || height <= 0) return; - - texture.drawTexture(x, y, width, height, zDepth, partialTick, color); - } - - @Override - @Deprecated - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor c) - { - if(width <= 0 || height <= 0) return; - - texture.drawTexture(x, y, width, height, zDepth, partialTick, c); - } - - @Override - public ResourceLocation getTexture() - { - return texture.getTexture(); - } - - @Override - public IGuiRect getBounds() - { - return texture.getBounds(); - } +public class GuiTextureColored implements IGuiTexture { + private final IGuiTexture texture; + private final IGuiColor color; + + public GuiTextureColored(IGuiTexture texture, IGuiColor color) { + this.texture = texture; + this.color = color; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { + if (width <= 0 || height <= 0) { return; } + + texture.drawTexture(x, y, width, height, zDepth, partialTick, color); + } + + @Override + @Deprecated + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor c) { + if (width <= 0 || height <= 0) { return; } + + texture.drawTexture(x, y, width, height, zDepth, partialTick, c); + } + + @Override + public ResourceLocation getTexture() { + return texture.getTexture(); + } + + @Override + public IGuiRect getBounds() { + return texture.getBounds(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/IGuiTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/IGuiTexture.java index aa5812f0f..df40d7c9d 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/IGuiTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/IGuiTexture.java @@ -4,11 +4,12 @@ import betterquesting.api2.client.gui.resources.colors.IGuiColor; import net.minecraft.util.ResourceLocation; -public interface IGuiTexture -{ - void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick); - void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color); - - ResourceLocation getTexture(); - IGuiRect getBounds(); +public interface IGuiTexture { + void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick); + + void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color); + + ResourceLocation getTexture(); + + IGuiRect getBounds(); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java index e4b4f664e..2535c0ccf 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java @@ -12,85 +12,77 @@ import net.minecraft.util.ResourceLocation; // Wrapper to allow embedding items into panels as IGuiTextures -public class ItemTexture implements IGuiTexture -{ - private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); - - private final BigItemStack stack; - private final boolean showCount; - private final boolean keepAspect; - - private float zDepth = 16F; - - // Dummy value - private final IGuiRect bounds = new GuiRectangle(0, 0, 16, 16); - - public ItemTexture(BigItemStack stack) - { - this(stack, false, true); - } - - public ItemTexture(BigItemStack stack, boolean showCount, boolean keepAspect) - { - this.stack = stack; - this.showCount = showCount; - this.keepAspect = keepAspect; - } - - public ItemTexture setDepth(float z) - { - this.zDepth = z; - return this; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) - { - drawTexture(x, y, width, height, zLevel, partialTick, defColor); - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0) return; - - float sx = width/16F; - float sy = height/16F; - - double dx = 0; - double dy = 0; - - if(keepAspect) - { - float sa = Math.min(sx, sy); - - dx = Math.floor((sx - sa) * 8F); - dy = Math.floor((sy - sa) * 8F); - - sx = sa; - sy = sa; - } - - GlStateManager.pushMatrix(); - - GlStateManager.translate(x + dx, y + dy, 0); - GlStateManager.scale(sx, sy, 1F); - color.applyGlColor(); - - RenderUtils.RenderItemStack(Minecraft.getMinecraft(), stack.getBaseStack(), 0, 0, zDepth, (showCount && stack.stackSize > 1) ? ("" + stack.stackSize) : "", 0xFFFFFFFF); - - GlStateManager.popMatrix(); - } - - @Override - public ResourceLocation getTexture() - { - return PresetTexture.TX_NULL; - } - - @Override - public IGuiRect getBounds() - { - return bounds; +public class ItemTexture implements IGuiTexture { + private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); + + private final BigItemStack stack; + private final boolean showCount; + private final boolean keepAspect; + + private float zDepth = 16F; + + // Dummy value + private final IGuiRect bounds = new GuiRectangle(0, 0, 16, 16); + + public ItemTexture(BigItemStack stack) { + this(stack, false, true); + } + + public ItemTexture(BigItemStack stack, boolean showCount, boolean keepAspect) { + this.stack = stack; + this.showCount = showCount; + this.keepAspect = keepAspect; + } + + public ItemTexture setDepth(float z) { + this.zDepth = z; + return this; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) { + drawTexture(x, y, width, height, zLevel, partialTick, defColor); + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0) { return; } + + float sx = width / 16F; + float sy = height / 16F; + + double dx = 0; + double dy = 0; + + if (keepAspect) { + float sa = Math.min(sx, sy); + + dx = Math.floor((sx - sa) * 8F); + dy = Math.floor((sy - sa) * 8F); + + sx = sa; + sy = sa; } + + GlStateManager.pushMatrix(); + + GlStateManager.translate(x + dx, y + dy, 0); + GlStateManager.scale(sx, sy, 1F); + color.applyGlColor(); + + RenderUtils.RenderItemStack(Minecraft.getMinecraft(), stack.getBaseStack(), 0, 0, zDepth, + (showCount && stack.stackSize > 1) ? ("" + stack.stackSize) : "", 0xFFFFFFFF); + + GlStateManager.popMatrix(); + } + + @Override + public ResourceLocation getTexture() { + return PresetTexture.TX_NULL; + } + + @Override + public IGuiRect getBounds() { + return bounds; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java index c1f69edc7..7f6ed3b5a 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java @@ -4,46 +4,38 @@ import betterquesting.api2.client.gui.resources.colors.IGuiColor; import net.minecraft.util.ResourceLocation; -public class LayeredTexture implements IGuiTexture -{ - private final IGuiTexture[] layers; - - public LayeredTexture(IGuiTexture... layers) - { - this.layers = layers; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) - { - if(width <= 0 || height <= 0) return; - - for(IGuiTexture tex : layers) - { - tex.drawTexture(x, y, width, height, zDepth, partialTick); - } - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0) return; - - for(IGuiTexture tex : layers) - { - tex.drawTexture(x, y, width, height, zDepth, partialTick, color); - } - } - - @Override - public ResourceLocation getTexture() - { - return layers.length <= 0 ? null : layers[0].getTexture(); +public class LayeredTexture implements IGuiTexture { + private final IGuiTexture[] layers; + + public LayeredTexture(IGuiTexture... layers) { + this.layers = layers; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { + if (width <= 0 || height <= 0) { return; } + + for (IGuiTexture tex : layers) { + tex.drawTexture(x, y, width, height, zDepth, partialTick); } - - @Override - public IGuiRect getBounds() - { - return layers.length <= 0 ? null : layers[0].getBounds(); + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0) { return; } + + for (IGuiTexture tex : layers) { + tex.drawTexture(x, y, width, height, zDepth, partialTick, color); } + } + + @Override + public ResourceLocation getTexture() { + return layers.length == 0 ? null : layers[0].getTexture(); + } + + @Override + public IGuiRect getBounds() { + return layers.length == 0 ? null : layers[0].getBounds(); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/OreDictTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/OreDictTexture.java index 4cd075635..804316b04 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/OreDictTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/OreDictTexture.java @@ -6,28 +6,27 @@ import net.minecraft.util.NonNullList; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; -public class OreDictTexture extends SlideShowTexture -{ - public OreDictTexture(float interval, BigItemStack stack, boolean showCount, boolean keepAspect) - { - super(interval, splitOreTextures(stack, showCount, keepAspect).toArray(new ItemTexture[0])); - } - - public OreDictTexture(float interval, Collection list, boolean showCount, boolean keepAspect) - { - super(interval, buildTextures(list, showCount, keepAspect).toArray(new ItemTexture[0])); - } - - private static List buildTextures(Collection subItems, boolean showCount, boolean keepAspect) - { - List list = new ArrayList<>(); - subItems.forEach((is) -> list.add(new ItemTexture(is, showCount, keepAspect))); - return list; - } - - // TODO: Put this somewhere useful +public class OreDictTexture extends SlideShowTexture { + public OreDictTexture(float interval, BigItemStack stack, boolean showCount, boolean keepAspect) { + super(interval, splitOreTextures(stack, showCount, keepAspect).toArray(new ItemTexture[0])); + } + + public OreDictTexture(float interval, Collection list, boolean showCount, boolean keepAspect) { + super(interval, buildTextures(list, showCount, keepAspect).toArray(new ItemTexture[0])); + } + + private static List buildTextures(Collection subItems, boolean showCount, + boolean keepAspect) { + List list = new ArrayList<>(); + subItems.forEach((is) -> list.add(new ItemTexture(is, showCount, keepAspect))); + return list; + } + + // TODO: Put this somewhere useful /*private static Collection splitVariants(BigItemStack stack) { Set list = new HashSet<>(); @@ -71,50 +70,42 @@ private static List buildTextures(Collection subItems return list; }*/ - - private static List splitOreTextures(BigItemStack stack, boolean showCount, boolean keepAspect) - { - List list = new ArrayList<>(); - - if(!stack.hasOreDict()) - { - if(stack.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE) - { - NonNullList subItems = NonNullList.create(); - stack.getBaseStack().getItem().getSubItems(CreativeTabs.SEARCH, subItems); - subItems.forEach((is) -> { - BigItemStack bis = new BigItemStack(is); - bis.stackSize = stack.stackSize; - list.add(new ItemTexture(bis, showCount, keepAspect)); - }); - } else - { - list.add(new ItemTexture(stack, showCount, keepAspect)); - } - return list; - } - - for(ItemStack iStack : stack.getOreIngredient().getMatchingStacks()) - { - if(iStack.getItemDamage() == OreDictionary.WILDCARD_VALUE) - { - NonNullList subItems = NonNullList.create(); - iStack.getItem().getSubItems(CreativeTabs.SEARCH, subItems); - - for(ItemStack sStack : subItems) - { - BigItemStack bStack = new BigItemStack(sStack); - bStack.stackSize = stack.stackSize; - list.add(new ItemTexture(bStack, showCount, keepAspect)); - } - } else - { - BigItemStack bStack = new BigItemStack(iStack); - bStack.stackSize = stack.stackSize; - list.add(new ItemTexture(bStack, showCount, keepAspect)); - } + + private static List splitOreTextures(BigItemStack stack, boolean showCount, boolean keepAspect) { + List list = new ArrayList<>(); + + if (!stack.hasOreDict()) { + if (stack.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE) { + NonNullList subItems = NonNullList.create(); + stack.getBaseStack().getItem().getSubItems(CreativeTabs.SEARCH, subItems); + subItems.forEach((is) -> { + BigItemStack bis = new BigItemStack(is); + bis.stackSize = stack.stackSize; + list.add(new ItemTexture(bis, showCount, keepAspect)); + }); + } else { + list.add(new ItemTexture(stack, showCount, keepAspect)); + } + return list; + } + + for (ItemStack iStack : stack.getOreIngredient().getMatchingStacks()) { + if (iStack.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + NonNullList subItems = NonNullList.create(); + iStack.getItem().getSubItems(CreativeTabs.SEARCH, subItems); + + for (ItemStack sStack : subItems) { + BigItemStack bStack = new BigItemStack(sStack); + bStack.stackSize = stack.stackSize; + list.add(new ItemTexture(bStack, showCount, keepAspect)); } - - return list; + } else { + BigItemStack bStack = new BigItemStack(iStack); + bStack.stackSize = stack.stackSize; + list.add(new ItemTexture(bStack, showCount, keepAspect)); + } } + + return list; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java index f0cee4fb5..fb08071a1 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java @@ -12,145 +12,135 @@ import javax.annotation.Nonnull; -public class PolyTexture implements IGuiTexture -{ - private final IGuiColor defColor; - private final boolean shadow; - private final double[] verts; - - private int borderSize = 1; - private IGuiColor borColor = new GuiColorStatic(0xFFFFFFFF); - - public PolyTexture(int points, double rotation, boolean shadow, @Nonnull IGuiColor color) - { - this.defColor = color; - this.shadow = shadow; - - if(points <= 0) points = 32; - verts = new double[points * 2]; // XY positions of all outer verticies - double min = 0.0001D; - - // Generate points - for(int i = 0; i < points; i++) - { - double angle = 360D * (i/(double)points); - double x = -Math.sin(Math.toRadians(angle + rotation)); - double y = -Math.cos(Math.toRadians(angle + rotation)); - min = Math.max(min, Math.max(Math.abs(x), Math.abs(y))); - - verts[i * 2] = x; - verts[i * 2 + 1] = y; - } - - // Fit to 0D - 1D bounds - for(int i = 0; i < verts.length; i++) - { - double x = verts[i]; - x = (x / 2D / min) + 0.5D; - verts[i] = x; - } - } - - public PolyTexture(@Nonnull double[] verts, boolean shadow, IGuiColor color) - { - this.defColor = color; - this.shadow = shadow; - this.verts = new double[verts.length]; - System.arraycopy(verts, 0, this.verts, 0, verts.length); - } - - public IGuiTexture setBorder(int size, IGuiColor color) - { - this.borderSize = size; - this.borColor = color; - return this; +public class PolyTexture implements IGuiTexture { + private final IGuiColor defColor; + private final boolean shadow; + private final double[] verts; + + private int borderSize = 1; + private IGuiColor borColor = new GuiColorStatic(0xFFFFFFFF); + + public PolyTexture(int points, double rotation, boolean shadow, @Nonnull IGuiColor color) { + this.defColor = color; + this.shadow = shadow; + + if (points <= 0) { points = 32; } + verts = new double[points * 2]; // XY positions of all outer verticies + double min = 0.0001D; + + // Generate points + for (int i = 0; i < points; i++) { + double angle = 360D * (i / (double) points); + double x = -Math.sin(Math.toRadians(angle + rotation)); + double y = -Math.cos(Math.toRadians(angle + rotation)); + min = Math.max(min, Math.max(Math.abs(x), Math.abs(y))); + + verts[i * 2] = x; + verts[i * 2 + 1] = y; } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) - { - drawTexture(x, y, width, height, zDepth, partialTick, defColor); + + // Fit to 0D - 1D bounds + for (int i = 0; i < verts.length; i++) { + double x = verts[i]; + x = (x / 2D / min) + 0.5D; + verts[i] = x; } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0) return; - - GlStateManager.pushMatrix(); - - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder vertexbuffer = tessellator.getBuffer(); - GlStateManager.enableBlend(); - GlStateManager.disableTexture2D(); - GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); - - int w = shadow ? width - 2 : width; - int h = shadow ? height - 2 : height; - int dx = shadow ? x + 1 : x; - int dy = shadow ? y + 1 : y; - int sx = x + 2; - int sy = y + 2; - - int points = verts.length/2; - - if(shadow) - { - GlStateManager.color(0F, 0F, 0F, 0.5F); - vertexbuffer.begin(GL11.GL_POLYGON, DefaultVertexFormats.POSITION);; - - for(int i = 0; i < points + 1; i++) // Wraps around by one point - { - int index = (i % points) * 2; - vertexbuffer.pos(sx + (w * verts[index]), sy + (h * verts[index + 1]), 0D).endVertex(); - } - - tessellator.draw(); - } - - color.applyGlColor(); - vertexbuffer.begin(GL11.GL_POLYGON, DefaultVertexFormats.POSITION);; - - for(int i = 0; i < points + 1; i++) // Wraps around by one point - { - int index = (i % points) * 2; - vertexbuffer.pos(dx + (w * verts[index]), dy + (h * verts[index + 1]), 0D).endVertex(); - } - - tessellator.draw(); - - if(borderSize > 0 && borColor != null) - { - borColor.applyGlColor(); - vertexbuffer.begin(GL11.GL_QUAD_STRIP, DefaultVertexFormats.POSITION); - - for(int i = 0; i < points + 1; i++) // Wraps around by one point - { - int index = (i % points) * 2; - double bx = (verts[index] - 0.5D) * -borderSize * 2D; - double by = (verts[index + 1] - 0.5D) * -borderSize * 2D; - vertexbuffer.pos(dx + (w * verts[index]) + bx, dy + (h * verts[index + 1]) + by, 0D).endVertex(); - vertexbuffer.pos(dx + (w * verts[index]), dy + (h * verts[index + 1]), 0D).endVertex(); - } - - tessellator.draw(); - } - - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - - GlStateManager.popMatrix(); + } + + public PolyTexture(@Nonnull double[] verts, boolean shadow, IGuiColor color) { + this.defColor = color; + this.shadow = shadow; + this.verts = new double[verts.length]; + System.arraycopy(verts, 0, this.verts, 0, verts.length); + } + + public IGuiTexture setBorder(int size, IGuiColor color) { + this.borderSize = size; + this.borColor = color; + return this; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { + drawTexture(x, y, width, height, zDepth, partialTick, defColor); + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0) { return; } + + GlStateManager.pushMatrix(); + + Tessellator tessellator = Tessellator.getInstance(); + BufferBuilder vertexbuffer = tessellator.getBuffer(); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, + GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, + GlStateManager.DestFactor.ZERO); + + int w = shadow ? width - 2 : width; + int h = shadow ? height - 2 : height; + int dx = shadow ? x + 1 : x; + int dy = shadow ? y + 1 : y; + int sx = x + 2; + int sy = y + 2; + + int points = verts.length / 2; + + if (shadow) { + GlStateManager.color(0F, 0F, 0F, 0.5F); + vertexbuffer.begin(GL11.GL_POLYGON, DefaultVertexFormats.POSITION); + + for (int i = 0; i < points + 1; i++) // Wraps around by one point + { + int index = (i % points) * 2; + vertexbuffer.pos(sx + (w * verts[index]), sy + (h * verts[index + 1]), 0D).endVertex(); + } + + tessellator.draw(); } - - @Override - public ResourceLocation getTexture() + + color.applyGlColor(); + vertexbuffer.begin(GL11.GL_POLYGON, DefaultVertexFormats.POSITION); + + for (int i = 0; i < points + 1; i++) // Wraps around by one point { - return null; + int index = (i % points) * 2; + vertexbuffer.pos(dx + (w * verts[index]), dy + (h * verts[index + 1]), 0D).endVertex(); } - - @Override - public IGuiRect getBounds() - { - return null; + + tessellator.draw(); + + if (borderSize > 0 && borColor != null) { + borColor.applyGlColor(); + vertexbuffer.begin(GL11.GL_QUAD_STRIP, DefaultVertexFormats.POSITION); + + for (int i = 0; i < points + 1; i++) // Wraps around by one point + { + int index = (i % points) * 2; + double bx = (verts[index] - 0.5D) * -borderSize * 2D; + double by = (verts[index + 1] - 0.5D) * -borderSize * 2D; + vertexbuffer.pos(dx + (w * verts[index]) + bx, dy + (h * verts[index + 1]) + by, 0D).endVertex(); + vertexbuffer.pos(dx + (w * verts[index]), dy + (h * verts[index + 1]), 0D).endVertex(); + } + + tessellator.draw(); } + + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + + GlStateManager.popMatrix(); + } + + @Override + public ResourceLocation getTexture() { + return null; + } + + @Override + public IGuiRect getBounds() { + return null; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java index 18c138be2..4cca1d45c 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java @@ -1,5 +1,6 @@ package betterquesting.api2.client.gui.resources.textures; +import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.resources.colors.GuiColorStatic; import betterquesting.api2.client.gui.resources.colors.IGuiColor; import net.minecraft.client.Minecraft; @@ -7,78 +8,69 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.client.config.GuiUtils; import org.lwjgl.opengl.GL11; -import betterquesting.api2.client.gui.misc.IGuiRect; -public class SimpleTexture implements IGuiTexture -{ - private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); - - private final ResourceLocation texture; - private final IGuiRect texBounds; - private boolean maintainAspect = false; - - public SimpleTexture(ResourceLocation texture, IGuiRect bounds) - { - this.texture = texture; - this.texBounds = bounds; - } - - public SimpleTexture maintainAspect(boolean enable) - { - this.maintainAspect = enable; - return this; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) - { - drawTexture(x, y, width, height, zLevel, partialTick, defColor); - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0) return; - - GlStateManager.pushMatrix(); - - float sx = (float)width / (float)texBounds.getWidth(); - float sy = (float)height / (float)texBounds.getHeight(); - - if(maintainAspect) - { - float sa = Math.min(sx, sy); - float dx = (sx - sa) * texBounds.getWidth() / 2F; - float dy = (sy - sa) * texBounds.getHeight() / 2F; - sx = sa; - sy = sa; - GlStateManager.translate(x + dx, y + dy, 0F); - } else - { - GlStateManager.translate(x, y, 0F); - } - - GlStateManager.scale(sx, sy, 1F); - color.applyGlColor(); - - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); - - Minecraft.getMinecraft().renderEngine.bindTexture(texture); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY(), texBounds.getWidth(), texBounds.getHeight(), zLevel); - - GlStateManager.popMatrix(); - } - - @Override - public ResourceLocation getTexture() - { - return this.texture; - } - - @Override - public IGuiRect getBounds() - { - return this.texBounds; - } +public class SimpleTexture implements IGuiTexture { + private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); + + private final ResourceLocation texture; + private final IGuiRect texBounds; + private boolean maintainAspect = false; + + public SimpleTexture(ResourceLocation texture, IGuiRect bounds) { + this.texture = texture; + this.texBounds = bounds; + } + + public SimpleTexture maintainAspect(boolean enable) { + this.maintainAspect = enable; + return this; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) { + drawTexture(x, y, width, height, zLevel, partialTick, defColor); + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0) { return; } + + GlStateManager.pushMatrix(); + + float sx = (float) width / (float) texBounds.getWidth(); + float sy = (float) height / (float) texBounds.getHeight(); + + if (maintainAspect) { + float sa = Math.min(sx, sy); + float dx = (sx - sa) * texBounds.getWidth() / 2F; + float dy = (sy - sa) * texBounds.getHeight() / 2F; + sx = sa; + sy = sa; + GlStateManager.translate(x + dx, y + dy, 0F); + } else { + GlStateManager.translate(x, y, 0F); + } + + GlStateManager.scale(sx, sy, 1F); + color.applyGlColor(); + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); + + Minecraft.getMinecraft().renderEngine.bindTexture(texture); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY(), texBounds.getWidth(), + texBounds.getHeight(), zLevel); + + GlStateManager.popMatrix(); + } + + @Override + public ResourceLocation getTexture() { + return this.texture; + } + + @Override + public IGuiRect getBounds() { + return this.texBounds; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java index 9c3cb1ec5..58e62d651 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java @@ -1,254 +1,265 @@ package betterquesting.api2.client.gui.resources.textures; +import betterquesting.api.utils.JsonHelper; +import betterquesting.api2.client.gui.misc.GuiPadding; +import betterquesting.api2.client.gui.misc.GuiRectangle; +import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.resources.colors.GuiColorStatic; import betterquesting.api2.client.gui.resources.colors.IGuiColor; +import com.google.gson.JsonObject; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.client.config.GuiUtils; import org.lwjgl.opengl.GL11; -import betterquesting.api.utils.JsonHelper; -import betterquesting.api2.client.gui.misc.GuiPadding; -import betterquesting.api2.client.gui.misc.GuiRectangle; -import betterquesting.api2.client.gui.misc.IGuiRect; -import com.google.gson.JsonObject; -public class SlicedTexture implements IGuiTexture -{ - private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); - - private final ResourceLocation texture; - private final IGuiRect texBounds; - private final GuiPadding texBorder; - private SliceMode sliceMode = SliceMode.SLICED_TILE; - - public SlicedTexture(ResourceLocation tex, IGuiRect bounds, GuiPadding border) - { - this.texture = tex; - this.texBounds = bounds; - this.texBorder = border; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) - { - drawTexture(x, y, width, height, zLevel, partialTick, defColor); - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0) return; - - int w = Math.max(width, texBorder.getLeft() + texBorder.getRight()); - int h = Math.max(height, texBorder.getTop() + texBorder.getBottom()); - int dx = x; - int dy = y; - - GlStateManager.pushMatrix(); - color.applyGlColor(); - - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); - - if(w != width || h != height) - { - dx = 0; - dy = 0; - GlStateManager.translate(x, y, 0); - GlStateManager.scale(width / (double)w, height / (double)h, 1D); - } - - if(sliceMode == SliceMode.SLICED_TILE) - { - drawContinuousTexturedBox(texture, dx, dy, texBounds.getX(), texBounds.getY(), w, h, texBounds.getWidth(), texBounds.getHeight(), texBorder.getTop(), texBorder.getBottom(), texBorder.getLeft(), texBorder.getRight(), zLevel); - } else if(sliceMode == SliceMode.SLICED_STRETCH) - { - int iu = texBounds.getX() + texBorder.getLeft(); - int iv = texBounds.getY() + texBorder.getTop(); - int iw = texBounds.getWidth() - texBorder.getLeft() - texBorder.getRight(); - int ih = texBounds.getHeight() - texBorder.getTop() - texBorder.getBottom(); - - float sx = (float)(w - (texBounds.getWidth() - iw)) / (float)iw; - float sy = (float)(h - (texBounds.getHeight() - ih)) / (float)ih; - - Minecraft.getMinecraft().renderEngine.bindTexture(texture); - - // TOP LEFT - GlStateManager.pushMatrix(); - GlStateManager.translate(dx, dy, 0F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY(), texBorder.getLeft(), texBorder.getTop(), zLevel); - GlStateManager.popMatrix(); - - // TOP SIDE - GlStateManager.pushMatrix(); - GlStateManager.translate(dx + texBorder.getLeft(), dy, 0F); - GlStateManager.scale(sx, 1F, 1F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft(), texBounds.getY(), iw, texBorder.getTop(), zLevel); - GlStateManager.popMatrix(); - - // TOP RIGHT - GlStateManager.pushMatrix(); - GlStateManager.translate(dx + w - texBorder.getRight(), dy, 0F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft() + iw, texBounds.getY(), texBorder.getRight(), texBorder.getTop(), zLevel); - GlStateManager.popMatrix(); - - // LEFT SIDE - GlStateManager.pushMatrix(); - GlStateManager.translate(dx, dy + texBorder.getTop(), 0F); - GlStateManager.scale(1F, sy, 1F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY() + texBorder.getTop(), texBorder.getLeft(), ih, zLevel); - GlStateManager.popMatrix(); - - // MIDDLE - GlStateManager.pushMatrix(); - GlStateManager.translate(dx + texBorder.getLeft(), dy + texBorder.getTop(), 0F); - GlStateManager.scale(sx, sy, 1F); - GuiUtils.drawTexturedModalRect(0, 0, iu, iv, iw, ih, zLevel); - GlStateManager.popMatrix(); - - // RIGHT SIDE - GlStateManager.pushMatrix(); - GlStateManager.translate(dx + w - texBorder.getRight(), dy + texBorder.getTop(), 0F); - GlStateManager.scale(1F, sy, 1F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft() + iw, texBounds.getY() + texBorder.getTop(), texBorder.getRight(), ih, zLevel); - GlStateManager.popMatrix(); - - // BOTTOM LEFT - GlStateManager.pushMatrix(); - GlStateManager.translate(dx, dy + h - texBorder.getBottom(), 0F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY() + texBorder.getTop() + ih, texBorder.getLeft(), texBorder.getBottom(), zLevel); - GlStateManager.popMatrix(); - - // BOTTOM SIDE - GlStateManager.pushMatrix(); - GlStateManager.translate(dx + texBorder.getLeft(), dy + h - texBorder.getBottom(), 0F); - GlStateManager.scale(sx, 1F, 1F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft(), texBounds.getY() + texBorder.getTop() + ih, iw, texBorder.getBottom(), zLevel); - GlStateManager.popMatrix(); - - // BOTTOM RIGHT - GlStateManager.pushMatrix(); - GlStateManager.translate(dx + w - texBorder.getRight(), dy + h - texBorder.getBottom(), 0F); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft() + iw, texBounds.getY() + texBorder.getTop() + ih, texBorder.getRight(), texBorder.getBottom(), zLevel); - GlStateManager.popMatrix(); - } else - { - float sx = (float)w / (float)texBounds.getWidth(); - float sy = (float)h / (float)texBounds.getHeight(); - GlStateManager.translate(dx, dy, 0F); - GlStateManager.scale(sx, sy, 1F); - - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); - - Minecraft.getMinecraft().renderEngine.bindTexture(texture); - GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY(), texBounds.getWidth(), texBounds.getHeight(), zLevel); - } - - GlStateManager.popMatrix(); - } - - @Override - public ResourceLocation getTexture() - { - return this.texture; - } - - @Override - public IGuiRect getBounds() - { - return this.texBounds; - } - - public GuiPadding getBorder() - { - return this.texBorder; - } - - /** - * Enables texture slicing. Will stretch to fit if disabled - */ - public SlicedTexture setSliceMode(SliceMode mode) - { - this.sliceMode = mode; - return this; - } - - public static SlicedTexture readFromJson(JsonObject json) - { - ResourceLocation res = new ResourceLocation(JsonHelper.GetString(json, "texture", "minecraft:missingno")); - int slice = JsonHelper.GetNumber(json, "sliceMode", 1).intValue(); - - JsonObject jOut = JsonHelper.GetObject(json, "coordinates"); - int ox = JsonHelper.GetNumber(jOut, "u", 0).intValue(); - int oy = JsonHelper.GetNumber(jOut, "v", 0).intValue(); - int ow = JsonHelper.GetNumber(jOut, "w", 48).intValue(); - int oh = JsonHelper.GetNumber(jOut, "h", 48).intValue(); - - JsonObject jIn = JsonHelper.GetObject(json, "border"); - int il = JsonHelper.GetNumber(jIn, "l", 16).intValue(); - int it = JsonHelper.GetNumber(jIn, "t", 16).intValue(); - int ir = JsonHelper.GetNumber(jIn, "r", 16).intValue(); - int ib = JsonHelper.GetNumber(jIn, "b", 16).intValue(); - - return new SlicedTexture(res, new GuiRectangle(ox, oy, ow, oh), new GuiPadding(il, it, ir, ib)).setSliceMode(SliceMode.values()[slice%3]); - } - - // Slightly modified version from GuiUtils.class - private static void drawContinuousTexturedBox(ResourceLocation res, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int topBorder, int bottomBorder, int leftBorder, int rightBorder, float zLevel) - { - Minecraft.getMinecraft().renderEngine.bindTexture(res); - - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); - - int fillerWidth = textureWidth - leftBorder - rightBorder; - int fillerHeight = textureHeight - topBorder - bottomBorder; - if(fillerWidth <= 0 || fillerHeight <= 0) return; - int canvasWidth = width - leftBorder - rightBorder; - int canvasHeight = height - topBorder - bottomBorder; - int xPasses = canvasWidth / fillerWidth; - int remainderWidth = canvasWidth % fillerWidth; - int yPasses = canvasHeight / fillerHeight; - int remainderHeight = canvasHeight % fillerHeight; - - // Draw Border - // Top Left - GuiUtils.drawTexturedModalRect(x, y, u, v, leftBorder, topBorder, zLevel); - // Top Right - GuiUtils.drawTexturedModalRect(x + leftBorder + canvasWidth, y, u + leftBorder + fillerWidth, v, rightBorder, topBorder, zLevel); - // Bottom Left - GuiUtils.drawTexturedModalRect(x, y + topBorder + canvasHeight, u, v + topBorder + fillerHeight, leftBorder, bottomBorder, zLevel); - // Bottom Right - GuiUtils.drawTexturedModalRect(x + leftBorder + canvasWidth, y + topBorder + canvasHeight, u + leftBorder + fillerWidth, v + topBorder + fillerHeight, rightBorder, bottomBorder, zLevel); - - for(int i = 0; i < xPasses + (remainderWidth > 0 ? 1 : 0); i++) - { - // Top Border - GuiUtils.drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y, u + leftBorder, v, (i == xPasses ? remainderWidth : fillerWidth), topBorder, zLevel); - // Bottom Border - GuiUtils.drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y + topBorder + canvasHeight, u + leftBorder, v + topBorder + fillerHeight, (i == xPasses ? remainderWidth : fillerWidth), bottomBorder, zLevel); - - // Throw in some filler for good measure - for(int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++) - GuiUtils.drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y + topBorder + (j * fillerHeight), u + leftBorder, v + topBorder, (i == xPasses ? remainderWidth : fillerWidth), (j == yPasses ? remainderHeight : fillerHeight), zLevel); - } - - // Side Borders - for(int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++) - { - // Left Border - GuiUtils.drawTexturedModalRect(x, y + topBorder + (j * fillerHeight), u, v + topBorder, leftBorder, (j == yPasses ? remainderHeight : fillerHeight), zLevel); - // Right Border - GuiUtils.drawTexturedModalRect(x + leftBorder + canvasWidth, y + topBorder + (j * fillerHeight), u + leftBorder + fillerWidth, v + topBorder, rightBorder, (j == yPasses ? remainderHeight : fillerHeight), zLevel); - } - } - - public enum SliceMode - { - STRETCH, - SLICED_TILE, - SLICED_STRETCH - } +public class SlicedTexture implements IGuiTexture { + private static final IGuiColor defColor = new GuiColorStatic(255, 255, 255, 255); + + private final ResourceLocation texture; + private final IGuiRect texBounds; + private final GuiPadding texBorder; + private SliceMode sliceMode = SliceMode.SLICED_TILE; + + public SlicedTexture(ResourceLocation tex, IGuiRect bounds, GuiPadding border) { + this.texture = tex; + this.texBounds = bounds; + this.texBorder = border; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) { + drawTexture(x, y, width, height, zLevel, partialTick, defColor); + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0) { return; } + + int w = Math.max(width, texBorder.getLeft() + texBorder.getRight()); + int h = Math.max(height, texBorder.getTop() + texBorder.getBottom()); + int dx = x; + int dy = y; + + GlStateManager.pushMatrix(); + color.applyGlColor(); + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); + + if (w != width || h != height) { + dx = 0; + dy = 0; + GlStateManager.translate(x, y, 0); + GlStateManager.scale(width / (double) w, height / (double) h, 1D); + } + + if (sliceMode == SliceMode.SLICED_TILE) { + drawContinuousTexturedBox(texture, dx, dy, texBounds.getX(), texBounds.getY(), w, h, texBounds.getWidth(), + texBounds.getHeight(), texBorder.getTop(), texBorder.getBottom(), texBorder.getLeft(), + texBorder.getRight(), zLevel); + } else if (sliceMode == SliceMode.SLICED_STRETCH) { + int iu = texBounds.getX() + texBorder.getLeft(); + int iv = texBounds.getY() + texBorder.getTop(); + int iw = texBounds.getWidth() - texBorder.getLeft() - texBorder.getRight(); + int ih = texBounds.getHeight() - texBorder.getTop() - texBorder.getBottom(); + + float sx = (float) (w - (texBounds.getWidth() - iw)) / (float) iw; + float sy = (float) (h - (texBounds.getHeight() - ih)) / (float) ih; + + Minecraft.getMinecraft().renderEngine.bindTexture(texture); + + // TOP LEFT + GlStateManager.pushMatrix(); + GlStateManager.translate(dx, dy, 0F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY(), texBorder.getLeft(), texBorder.getTop(), + zLevel); + GlStateManager.popMatrix(); + + // TOP SIDE + GlStateManager.pushMatrix(); + GlStateManager.translate(dx + texBorder.getLeft(), dy, 0F); + GlStateManager.scale(sx, 1F, 1F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft(), texBounds.getY(), iw, + texBorder.getTop(), zLevel); + GlStateManager.popMatrix(); + + // TOP RIGHT + GlStateManager.pushMatrix(); + GlStateManager.translate(dx + w - texBorder.getRight(), dy, 0F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft() + iw, texBounds.getY(), + texBorder.getRight(), texBorder.getTop(), zLevel); + GlStateManager.popMatrix(); + + // LEFT SIDE + GlStateManager.pushMatrix(); + GlStateManager.translate(dx, dy + texBorder.getTop(), 0F); + GlStateManager.scale(1F, sy, 1F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY() + texBorder.getTop(), texBorder.getLeft(), + ih, zLevel); + GlStateManager.popMatrix(); + + // MIDDLE + GlStateManager.pushMatrix(); + GlStateManager.translate(dx + texBorder.getLeft(), dy + texBorder.getTop(), 0F); + GlStateManager.scale(sx, sy, 1F); + GuiUtils.drawTexturedModalRect(0, 0, iu, iv, iw, ih, zLevel); + GlStateManager.popMatrix(); + + // RIGHT SIDE + GlStateManager.pushMatrix(); + GlStateManager.translate(dx + w - texBorder.getRight(), dy + texBorder.getTop(), 0F); + GlStateManager.scale(1F, sy, 1F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft() + iw, + texBounds.getY() + texBorder.getTop(), texBorder.getRight(), ih, zLevel); + GlStateManager.popMatrix(); + + // BOTTOM LEFT + GlStateManager.pushMatrix(); + GlStateManager.translate(dx, dy + h - texBorder.getBottom(), 0F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY() + texBorder.getTop() + ih, + texBorder.getLeft(), texBorder.getBottom(), zLevel); + GlStateManager.popMatrix(); + + // BOTTOM SIDE + GlStateManager.pushMatrix(); + GlStateManager.translate(dx + texBorder.getLeft(), dy + h - texBorder.getBottom(), 0F); + GlStateManager.scale(sx, 1F, 1F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft(), + texBounds.getY() + texBorder.getTop() + ih, iw, texBorder.getBottom(), zLevel); + GlStateManager.popMatrix(); + + // BOTTOM RIGHT + GlStateManager.pushMatrix(); + GlStateManager.translate(dx + w - texBorder.getRight(), dy + h - texBorder.getBottom(), 0F); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX() + texBorder.getLeft() + iw, + texBounds.getY() + texBorder.getTop() + ih, texBorder.getRight(), + texBorder.getBottom(), zLevel); + GlStateManager.popMatrix(); + } else { + float sx = (float) w / (float) texBounds.getWidth(); + float sy = (float) h / (float) texBounds.getHeight(); + GlStateManager.translate(dx, dy, 0F); + GlStateManager.scale(sx, sy, 1F); + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); + + Minecraft.getMinecraft().renderEngine.bindTexture(texture); + GuiUtils.drawTexturedModalRect(0, 0, texBounds.getX(), texBounds.getY(), texBounds.getWidth(), + texBounds.getHeight(), zLevel); + } + + GlStateManager.popMatrix(); + } + + @Override + public ResourceLocation getTexture() { + return this.texture; + } + + @Override + public IGuiRect getBounds() { + return this.texBounds; + } + + public GuiPadding getBorder() { + return this.texBorder; + } + + /** + * Enables texture slicing. Will stretch to fit if disabled + */ + public SlicedTexture setSliceMode(SliceMode mode) { + this.sliceMode = mode; + return this; + } + + public static SlicedTexture readFromJson(JsonObject json) { + ResourceLocation res = new ResourceLocation(JsonHelper.GetString(json, "texture", "minecraft:missingno")); + int slice = JsonHelper.GetNumber(json, "sliceMode", 1).intValue(); + + JsonObject jOut = JsonHelper.GetObject(json, "coordinates"); + int ox = JsonHelper.GetNumber(jOut, "u", 0).intValue(); + int oy = JsonHelper.GetNumber(jOut, "v", 0).intValue(); + int ow = JsonHelper.GetNumber(jOut, "w", 48).intValue(); + int oh = JsonHelper.GetNumber(jOut, "h", 48).intValue(); + + JsonObject jIn = JsonHelper.GetObject(json, "border"); + int il = JsonHelper.GetNumber(jIn, "l", 16).intValue(); + int it = JsonHelper.GetNumber(jIn, "t", 16).intValue(); + int ir = JsonHelper.GetNumber(jIn, "r", 16).intValue(); + int ib = JsonHelper.GetNumber(jIn, "b", 16).intValue(); + + return new SlicedTexture(res, new GuiRectangle(ox, oy, ow, oh), new GuiPadding(il, it, ir, ib)).setSliceMode( + SliceMode.values()[slice % 3]); + } + + // Slightly modified version from GuiUtils.class + private static void drawContinuousTexturedBox(ResourceLocation res, int x, int y, int u, int v, int width, int height, + int textureWidth, int textureHeight, int topBorder, int bottomBorder, + int leftBorder, int rightBorder, float zLevel) { + Minecraft.getMinecraft().renderEngine.bindTexture(res); + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); + + int fillerWidth = textureWidth - leftBorder - rightBorder; + int fillerHeight = textureHeight - topBorder - bottomBorder; + if (fillerWidth <= 0 || fillerHeight <= 0) { return; } + int canvasWidth = width - leftBorder - rightBorder; + int canvasHeight = height - topBorder - bottomBorder; + int xPasses = canvasWidth / fillerWidth; + int remainderWidth = canvasWidth % fillerWidth; + int yPasses = canvasHeight / fillerHeight; + int remainderHeight = canvasHeight % fillerHeight; + + // Draw Border + // Top Left + GuiUtils.drawTexturedModalRect(x, y, u, v, leftBorder, topBorder, zLevel); + // Top Right + GuiUtils.drawTexturedModalRect(x + leftBorder + canvasWidth, y, u + leftBorder + fillerWidth, v, rightBorder, + topBorder, zLevel); + // Bottom Left + GuiUtils.drawTexturedModalRect(x, y + topBorder + canvasHeight, u, v + topBorder + fillerHeight, leftBorder, + bottomBorder, zLevel); + // Bottom Right + GuiUtils.drawTexturedModalRect(x + leftBorder + canvasWidth, y + topBorder + canvasHeight, + u + leftBorder + fillerWidth, v + topBorder + fillerHeight, rightBorder, + bottomBorder, zLevel); + + for (int i = 0; i < xPasses + (remainderWidth > 0 ? 1 : 0); i++) { + // Top Border + GuiUtils.drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y, u + leftBorder, v, + (i == xPasses ? remainderWidth : fillerWidth), topBorder, zLevel); + // Bottom Border + GuiUtils.drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y + topBorder + canvasHeight, u + leftBorder, + v + topBorder + fillerHeight, (i == xPasses ? remainderWidth : fillerWidth), + bottomBorder, zLevel); + + // Throw in some filler for good measure + for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++) { + GuiUtils.drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y + topBorder + (j * fillerHeight), + u + leftBorder, v + topBorder, (i == xPasses ? remainderWidth : fillerWidth), + (j == yPasses ? remainderHeight : fillerHeight), zLevel); + } + } + + // Side Borders + for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++) { + // Left Border + GuiUtils.drawTexturedModalRect(x, y + topBorder + (j * fillerHeight), u, v + topBorder, leftBorder, + (j == yPasses ? remainderHeight : fillerHeight), zLevel); + // Right Border + GuiUtils.drawTexturedModalRect(x + leftBorder + canvasWidth, y + topBorder + (j * fillerHeight), + u + leftBorder + fillerWidth, v + topBorder, rightBorder, + (j == yPasses ? remainderHeight : fillerHeight), zLevel); + } + } + + public enum SliceMode { + STRETCH, + SLICED_TILE, + SLICED_STRETCH + } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java index 76d050f2d..c9353dd23 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java @@ -6,60 +6,52 @@ import javax.annotation.Nullable; -public class SlideShowTexture implements IGuiTexture -{ - private final IGuiTexture[] slides; - private final float interval; - - public SlideShowTexture(float interval, IGuiTexture... slides) - { - this.slides = slides; - this.interval = interval; - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) - { - if(width <= 0 || height <= 0 || slides.length <= 0) return; - - IGuiTexture tex = getCurrentFrame(); - if(tex != null) tex.drawTexture(x, y, width, height, zLevel, partialTick); - } - - @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) - { - if(width <= 0 || height <= 0 || slides.length <= 0) return; - - IGuiTexture tex = getCurrentFrame(); - if(tex != null) tex.drawTexture(x, y, width, height, zDepth, partialTick, color); - } - - @Override - @Deprecated - public ResourceLocation getTexture() - { - IGuiTexture tex = getCurrentFrame(); - return tex == null ? null : tex.getTexture(); - } - - @Override - @Deprecated - public IGuiRect getBounds() - { - IGuiTexture tex = getCurrentFrame(); - return tex == null ? null : tex.getBounds(); - } - - @Nullable - public IGuiTexture getCurrentFrame() - { - if(slides.length <= 0) return null; - return slides[(int)Math.floor((System.currentTimeMillis()/1000D)%(slides.length * interval) / interval)]; - } - - public IGuiTexture[] getAllFrames() - { - return slides; - } +public class SlideShowTexture implements IGuiTexture { + private final IGuiTexture[] slides; + private final float interval; + + public SlideShowTexture(float interval, IGuiTexture... slides) { + this.slides = slides; + this.interval = interval; + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) { + if (width <= 0 || height <= 0 || slides.length == 0) { return; } + + IGuiTexture tex = getCurrentFrame(); + if (tex != null) { tex.drawTexture(x, y, width, height, zLevel, partialTick); } + } + + @Override + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { + if (width <= 0 || height <= 0 || slides.length == 0) { return; } + + IGuiTexture tex = getCurrentFrame(); + if (tex != null) { tex.drawTexture(x, y, width, height, zDepth, partialTick, color); } + } + + @Override + @Deprecated + public ResourceLocation getTexture() { + IGuiTexture tex = getCurrentFrame(); + return tex == null ? null : tex.getTexture(); + } + + @Override + @Deprecated + public IGuiRect getBounds() { + IGuiTexture tex = getCurrentFrame(); + return tex == null ? null : tex.getBounds(); + } + + @Nullable + public IGuiTexture getCurrentFrame() { + if (slides.length == 0) { return null; } + return slides[(int) Math.floor((System.currentTimeMillis() / 1000D) % (slides.length * interval) / interval)]; + } + + public IGuiTexture[] getAllFrames() { + return slides; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java b/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java index 230355c77..2ab5137cb 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java @@ -5,24 +5,20 @@ import javax.annotation.Nonnull; // This class is mostly for convenience and including type info to the ID -public class GuiKey -{ - private final ResourceLocation ID; - - public GuiKey(@Nonnull ResourceLocation id) - { - this.ID = id; - } - - @Nonnull - public ResourceLocation getID() - { - return this.ID; - } - - @Override - public boolean equals(Object obj) - { - return obj instanceof GuiKey && ((GuiKey)obj).ID.equals(ID); - } +public class GuiKey { + private final ResourceLocation ID; + + public GuiKey(@Nonnull ResourceLocation id) { + this.ID = id; + } + + @Nonnull + public ResourceLocation getID() { + return this.ID; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof GuiKey && ((GuiKey) obj).ID.equals(ID); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/IGuiTheme.java b/src/main/java/betterquesting/api2/client/gui/themes/IGuiTheme.java index 25ac449f8..25d0a0ff4 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/IGuiTheme.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/IGuiTheme.java @@ -9,18 +9,20 @@ import javax.annotation.Nullable; import java.util.function.Function; -public interface IGuiTheme -{ - String getName(); - ResourceLocation getID(); - - @Nullable - IGuiTexture getTexture(ResourceLocation key); - @Nullable - IGuiLine getLine(ResourceLocation key); - @Nullable - IGuiColor getColor(ResourceLocation key); - - @Nullable - Function getGui(GuiKey key); +public interface IGuiTheme { + String getName(); + + ResourceLocation getID(); + + @Nullable + IGuiTexture getTexture(ResourceLocation key); + + @Nullable + IGuiLine getLine(ResourceLocation key); + + @Nullable + IGuiColor getColor(ResourceLocation key); + + @Nullable + Function getGui(GuiKey key); } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/IResourceReg.java b/src/main/java/betterquesting/api2/client/gui/themes/IResourceReg.java index 979d87d0a..e199bb68d 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/IResourceReg.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/IResourceReg.java @@ -6,10 +6,13 @@ import betterquesting.api2.registry.FunctionRegistry; import com.google.gson.JsonObject; -/** Registry for BQ GUI resource type loaders. Used primarily for loading themes from JSON */ -public interface IResourceReg -{ - FunctionRegistry getTexReg(); - FunctionRegistry getColorReg(); - FunctionRegistry getLineReg(); +/** + * Registry for BQ GUI resource type loaders. Used primarily for loading themes from JSON + */ +public interface IResourceReg { + FunctionRegistry getTexReg(); + + FunctionRegistry getColorReg(); + + FunctionRegistry getLineReg(); } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/IThemeRegistry.java b/src/main/java/betterquesting/api2/client/gui/themes/IThemeRegistry.java index 00e4fe3f9..4f36603e0 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/IThemeRegistry.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/IThemeRegistry.java @@ -9,31 +9,41 @@ import java.util.List; import java.util.function.Function; -public interface IThemeRegistry -{ - void registerTheme(IGuiTheme theme); - - IGuiTheme getCurrentTheme(); - IGuiTheme getTheme(ResourceLocation key); - void setTheme(ResourceLocation key); - - void loadResourceThemes(); - - IGuiTexture getTexture(ResourceLocation key); - IGuiColor getColor(ResourceLocation key); - IGuiLine getLine(ResourceLocation key); - GuiScreen getGui(GuiKey key, T args); - - void setDefaultTexture(ResourceLocation key, IGuiTexture tex); - void setDefaultColor(ResourceLocation key, IGuiColor color); - void setDefaultLine(ResourceLocation key, IGuiLine line); - void setDefaultGui(GuiKey key, Function func); - - List getAllThemes(); - - // === Future Editor Stuff === - ResourceLocation[] getKnownTextures(); - ResourceLocation[] getKnownColors(); - ResourceLocation[] getKnownLines(); - GuiKey[] getKnownGuis(); +public interface IThemeRegistry { + void registerTheme(IGuiTheme theme); + + IGuiTheme getCurrentTheme(); + + IGuiTheme getTheme(ResourceLocation key); + + void setTheme(ResourceLocation key); + + void loadResourceThemes(); + + IGuiTexture getTexture(ResourceLocation key); + + IGuiColor getColor(ResourceLocation key); + + IGuiLine getLine(ResourceLocation key); + + GuiScreen getGui(GuiKey key, T args); + + void setDefaultTexture(ResourceLocation key, IGuiTexture tex); + + void setDefaultColor(ResourceLocation key, IGuiColor color); + + void setDefaultLine(ResourceLocation key, IGuiLine line); + + void setDefaultGui(GuiKey key, Function func); + + List getAllThemes(); + + // === Future Editor Stuff === + ResourceLocation[] getKnownTextures(); + + ResourceLocation[] getKnownColors(); + + ResourceLocation[] getKnownLines(); + + GuiKey[] getKnownGuis(); } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsCallback.java b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsCallback.java index 9ef00369d..b386591a0 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsCallback.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsCallback.java @@ -3,15 +3,13 @@ import betterquesting.api.misc.ICallback; import net.minecraft.client.gui.GuiScreen; -public class GArgsCallback extends GArgsNone -{ - public final T value; - public final ICallback callback; - - public GArgsCallback(GuiScreen parent, T value, ICallback callback) - { - super(parent); - this.value = value; - this.callback = callback; - } +public class GArgsCallback extends GArgsNone { + public final T value; + public final ICallback callback; + + public GArgsCallback(GuiScreen parent, T value, ICallback callback) { + super(parent); + this.value = value; + this.callback = callback; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsFileBrowser.java b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsFileBrowser.java index 0cc9b70d2..0678d3785 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsFileBrowser.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsFileBrowser.java @@ -7,19 +7,18 @@ import java.io.File; import java.io.FileFilter; -public class GArgsFileBrowser extends GArgsNone -{ - public final File root; - public final ICallback callback; - public final FileFilter filter; - public final boolean multiSelect; - - public GArgsFileBrowser(@Nullable GuiScreen parent, File root, ICallback callback, FileFilter filter, boolean multiSelect) - { - super(parent); - this.root = root; - this.callback = callback; - this.filter = filter; - this.multiSelect = multiSelect; - } +public class GArgsFileBrowser extends GArgsNone { + public final File root; + public final ICallback callback; + public final FileFilter filter; + public final boolean multiSelect; + + public GArgsFileBrowser(@Nullable GuiScreen parent, File root, ICallback callback, FileFilter filter, + boolean multiSelect) { + super(parent); + this.root = root; + this.callback = callback; + this.filter = filter; + this.multiSelect = multiSelect; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNBT.java b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNBT.java index f94fb4270..84531a0da 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNBT.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNBT.java @@ -7,13 +7,11 @@ import javax.annotation.Nullable; -public class GArgsNBT extends GArgsCallback -{ - public final INbtDoc doc; - - public GArgsNBT(@Nullable GuiScreen parent, T nbt, ICallback callback, INbtDoc doc) - { - super(parent, nbt, callback); - this.doc = doc; - } +public class GArgsNBT extends GArgsCallback { + public final INbtDoc doc; + + public GArgsNBT(@Nullable GuiScreen parent, T nbt, ICallback callback, INbtDoc doc) { + super(parent, nbt, callback); + this.doc = doc; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNone.java b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNone.java index da2d83ce3..686953aff 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNone.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/gui_args/GArgsNone.java @@ -4,15 +4,13 @@ import javax.annotation.Nullable; -public class GArgsNone -{ - public static final GArgsNone NONE = new GArgsNone(null); - - @Nullable - public final GuiScreen parent; - - public GArgsNone(@Nullable GuiScreen parent) - { - this.parent = parent; - } +public class GArgsNone { + public static final GArgsNone NONE = new GArgsNone(null); + + @Nullable + public final GuiScreen parent; + + public GArgsNone(@Nullable GuiScreen parent) { + this.parent = parent; + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java index 0e28e5e16..873827800 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java @@ -4,103 +4,102 @@ import betterquesting.api2.client.gui.resources.colors.GuiColorStatic; import betterquesting.api2.client.gui.resources.colors.IGuiColor; import betterquesting.api2.client.gui.themes.IThemeRegistry; -import net.minecraft.util.ResourceLocation; import betterquesting.client.themes.ThemeRegistry; import betterquesting.core.BetterQuesting; +import net.minecraft.util.ResourceLocation; // WARNING: Don't use the ordinal indexes. I'll probably be adding/removing enums infrequently -public enum PresetColor -{ - TEXT_HEADER("text_header"), - TEXT_MAIN("text_main"), - TEXT_AUX_0("text_aux_0"), - TEXT_AUX_1("text_aux_1"), - TEXT_HIGHLIGHT("text_highlight"), - TEXT_WATERMARK("text_watermark"), - - ITEM_HIGHLIGHT("item_highlight"), - - GUI_DIVIDER("gui_divider"), - - UPDATE_NOTICE("update_notice"), - - GRID_MAJOR("grid_major"), - GRID_MINOR("grid_minor"), - - BTN_DISABLED("btn_disabled"), - BTN_IDLE("btn_idle"), - BTN_HOVER("btn_hover"), - - QUEST_LINE_LOCKED("quest_line_locked"), - QUEST_LINE_UNLOCKED("quest_line_unlocked"), - QUEST_LINE_PENDING("quest_line_pending"), - QUEST_LINE_COMPLETE("quest_line_complete"), - - QUEST_ICON_LOCKED("quest_icon_locked"), - QUEST_ICON_UNLOCKED("quest_icon_unlocked"), - QUEST_ICON_PENDING("quest_icon_pending"), - QUEST_ICON_COMPLETE("quest_icon_complete"); - - private final ResourceLocation key; - - PresetColor(String key) - { - this.key = new ResourceLocation(BetterQuesting.MODID, key); - } - - public IGuiColor getColor() - { - return ThemeRegistry.INSTANCE.getColor(this.key); - } - - public ResourceLocation getKey() - { - return this.key; - } - - public static void registerColors(IThemeRegistry reg) - { - reg.setDefaultColor(TEXT_HEADER.key, new GuiColorStatic(0, 0, 0, 255)); // Headers - reg.setDefaultColor(TEXT_MAIN.key, new GuiColorStatic(0, 0, 0, 255)); // Paragraphs - reg.setDefaultColor(TEXT_AUX_0.key, new GuiColorStatic(255, 255, 255, 255)); // Dark panels (White Text) - reg.setDefaultColor(TEXT_AUX_1.key, new GuiColorStatic(0, 0, 0, 255)); // Light panels (Black Text) - reg.setDefaultColor(TEXT_HIGHLIGHT.key, new GuiColorStatic(0, 0, 255, 255)); // Selection Highlight (Blue Invert) - reg.setDefaultColor(TEXT_WATERMARK.key, new GuiColorStatic(128, 128, 128, 255)); // Text Field Watermark (Grey Text) - - reg.setDefaultColor(ITEM_HIGHLIGHT.key, new GuiColorStatic(255, 255, 255, 128)); - - reg.setDefaultColor(GUI_DIVIDER.key, new GuiColorStatic(0, 0, 0, 255)); - - reg.setDefaultColor(UPDATE_NOTICE.key, new GuiColorPulse(quickMix(255, 255, 0, 255), quickMix(128, 128, 0, 255), 1F, 0F)); - - reg.setDefaultColor(GRID_MAJOR.key, new GuiColorStatic(0, 0, 0, 255)); - reg.setDefaultColor(GRID_MINOR.key, new GuiColorStatic(0, 0, 0, 255)); - - reg.setDefaultColor(BTN_DISABLED.key, new GuiColorStatic(128, 128, 128, 255)); - reg.setDefaultColor(BTN_IDLE.key, new GuiColorStatic(255, 255, 255, 255)); - reg.setDefaultColor(BTN_HOVER.key, new GuiColorStatic(16777120)); - - reg.setDefaultColor(QUEST_LINE_LOCKED.key, new GuiColorStatic(192, 0, 0, 255)); - reg.setDefaultColor(QUEST_LINE_UNLOCKED.key, new GuiColorPulse(quickMix(255, 255, 0, 255), quickMix(128, 128, 0, 255), 1F, 0F)); - reg.setDefaultColor(QUEST_LINE_PENDING.key, new GuiColorStatic(0, 255, 0, 255)); - reg.setDefaultColor(QUEST_LINE_COMPLETE.key, new GuiColorStatic(0, 255, 0, 255)); - - reg.setDefaultColor(QUEST_ICON_LOCKED.key, new GuiColorStatic(128, 128, 128, 255)); - reg.setDefaultColor(QUEST_ICON_UNLOCKED.key, new GuiColorPulse(quickMix(192, 0, 0, 255), quickMix(96, 0, 0, 255), 1F, 0F)); - reg.setDefaultColor(QUEST_ICON_PENDING.key, new GuiColorPulse(quickMix(0, 255, 255, 255), quickMix(0, 128, 128, 255), 1F, 0F)); - reg.setDefaultColor(QUEST_ICON_COMPLETE.key, new GuiColorStatic(0, 255, 0, 255)); - } - - /** - * Colour mixing for the lazy - * @param red Red colour channel - * @param green Green colour channel - * @param blue Blue colour channel - * @param alpha Alpha transparency channel - * @return RGBA integer representation of the colour - */ - public static int quickMix(int red, int green, int blue, int alpha) - { - return ((alpha & 255) << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255); - } +public enum PresetColor { + TEXT_HEADER("text_header"), + TEXT_MAIN("text_main"), + TEXT_AUX_0("text_aux_0"), + TEXT_AUX_1("text_aux_1"), + TEXT_HIGHLIGHT("text_highlight"), + TEXT_WATERMARK("text_watermark"), + + ITEM_HIGHLIGHT("item_highlight"), + + GUI_DIVIDER("gui_divider"), + + UPDATE_NOTICE("update_notice"), + + GRID_MAJOR("grid_major"), + GRID_MINOR("grid_minor"), + + BTN_DISABLED("btn_disabled"), + BTN_IDLE("btn_idle"), + BTN_HOVER("btn_hover"), + + QUEST_LINE_LOCKED("quest_line_locked"), + QUEST_LINE_UNLOCKED("quest_line_unlocked"), + QUEST_LINE_PENDING("quest_line_pending"), + QUEST_LINE_COMPLETE("quest_line_complete"), + + QUEST_ICON_LOCKED("quest_icon_locked"), + QUEST_ICON_UNLOCKED("quest_icon_unlocked"), + QUEST_ICON_PENDING("quest_icon_pending"), + QUEST_ICON_COMPLETE("quest_icon_complete"); + + private final ResourceLocation key; + + PresetColor(String key) { + this.key = new ResourceLocation(BetterQuesting.MODID, key); + } + + public IGuiColor getColor() { + return ThemeRegistry.INSTANCE.getColor(this.key); + } + + public ResourceLocation getKey() { + return this.key; + } + + public static void registerColors(IThemeRegistry reg) { + reg.setDefaultColor(TEXT_HEADER.key, new GuiColorStatic(0, 0, 0, 255)); // Headers + reg.setDefaultColor(TEXT_MAIN.key, new GuiColorStatic(0, 0, 0, 255)); // Paragraphs + reg.setDefaultColor(TEXT_AUX_0.key, new GuiColorStatic(255, 255, 255, 255)); // Dark panels (White Text) + reg.setDefaultColor(TEXT_AUX_1.key, new GuiColorStatic(0, 0, 0, 255)); // Light panels (Black Text) + reg.setDefaultColor(TEXT_HIGHLIGHT.key, new GuiColorStatic(0, 0, 255, 255)); // Selection Highlight (Blue Invert) + reg.setDefaultColor(TEXT_WATERMARK.key, new GuiColorStatic(128, 128, 128, 255)); // Text Field Watermark (Grey Text) + + reg.setDefaultColor(ITEM_HIGHLIGHT.key, new GuiColorStatic(255, 255, 255, 128)); + + reg.setDefaultColor(GUI_DIVIDER.key, new GuiColorStatic(0, 0, 0, 255)); + + reg.setDefaultColor(UPDATE_NOTICE.key, + new GuiColorPulse(quickMix(255, 255, 0, 255), quickMix(128, 128, 0, 255), 1F, 0F)); + + reg.setDefaultColor(GRID_MAJOR.key, new GuiColorStatic(0, 0, 0, 255)); + reg.setDefaultColor(GRID_MINOR.key, new GuiColorStatic(0, 0, 0, 255)); + + reg.setDefaultColor(BTN_DISABLED.key, new GuiColorStatic(128, 128, 128, 255)); + reg.setDefaultColor(BTN_IDLE.key, new GuiColorStatic(255, 255, 255, 255)); + reg.setDefaultColor(BTN_HOVER.key, new GuiColorStatic(16777120)); + + reg.setDefaultColor(QUEST_LINE_LOCKED.key, new GuiColorStatic(192, 0, 0, 255)); + reg.setDefaultColor(QUEST_LINE_UNLOCKED.key, + new GuiColorPulse(quickMix(255, 255, 0, 255), quickMix(128, 128, 0, 255), 1F, 0F)); + reg.setDefaultColor(QUEST_LINE_PENDING.key, new GuiColorStatic(0, 255, 0, 255)); + reg.setDefaultColor(QUEST_LINE_COMPLETE.key, new GuiColorStatic(0, 255, 0, 255)); + + reg.setDefaultColor(QUEST_ICON_LOCKED.key, new GuiColorStatic(128, 128, 128, 255)); + reg.setDefaultColor(QUEST_ICON_UNLOCKED.key, + new GuiColorPulse(quickMix(192, 0, 0, 255), quickMix(96, 0, 0, 255), 1F, 0F)); + reg.setDefaultColor(QUEST_ICON_PENDING.key, + new GuiColorPulse(quickMix(0, 255, 255, 255), quickMix(0, 128, 128, 255), 1F, 0F)); + reg.setDefaultColor(QUEST_ICON_COMPLETE.key, new GuiColorStatic(0, 255, 0, 255)); + } + + /** + * Colour mixing for the lazy + * + * @param red Red colour channel + * @param green Green colour channel + * @param blue Blue colour channel + * @param alpha Alpha transparency channel + * @return RGBA integer representation of the colour + */ + public static int quickMix(int red, int green, int blue, int alpha) { + return ((alpha & 255) << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetGUIs.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetGUIs.java index 1d7aa9471..3d340403c 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetGUIs.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetGUIs.java @@ -10,15 +10,19 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; -public class PresetGUIs -{ - public static final GuiKey HOME = new GuiKey<>(new ResourceLocation("betterquesting", "home")); - - public static final GuiKey EDIT_NBT = new GuiKey<>(new ResourceLocation("betterquesting", "edit_nbt")); - public static final GuiKey> EDIT_ITEM = new GuiKey<>(new ResourceLocation("betterquesting", "edit_item")); - public static final GuiKey> EDIT_FLUID = new GuiKey<>(new ResourceLocation("betterquesting", "edit_fluid")); - public static final GuiKey> EDIT_ENTITY = new GuiKey<>(new ResourceLocation("betterquesting", "edit_entity")); - - public static final GuiKey> EDIT_TEXT = new GuiKey<>(new ResourceLocation("betterquesting", "edit_text")); - public static final GuiKey FILE_EXPLORE = new GuiKey<>(new ResourceLocation("betterquesting", "file_explore")); +public class PresetGUIs { + public static final GuiKey HOME = new GuiKey<>(new ResourceLocation("betterquesting", "home")); + + public static final GuiKey> EDIT_NBT = new GuiKey<>(new ResourceLocation("betterquesting", "edit_nbt")); + public static final GuiKey> EDIT_ITEM = + new GuiKey<>(new ResourceLocation("betterquesting", "edit_item")); + public static final GuiKey> EDIT_FLUID = + new GuiKey<>(new ResourceLocation("betterquesting", "edit_fluid")); + public static final GuiKey> EDIT_ENTITY = + new GuiKey<>(new ResourceLocation("betterquesting", "edit_entity")); + + public static final GuiKey> EDIT_TEXT = + new GuiKey<>(new ResourceLocation("betterquesting", "edit_text")); + public static final GuiKey FILE_EXPLORE = + new GuiKey<>(new ResourceLocation("betterquesting", "file_explore")); } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java index df5fe93bd..1df2a3513 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java @@ -1,200 +1,260 @@ package betterquesting.api2.client.gui.themes.presets; -import betterquesting.api2.client.gui.themes.IThemeRegistry; -import net.minecraft.util.ResourceLocation; import betterquesting.api2.client.gui.misc.GuiRectangle; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; import betterquesting.api2.client.gui.resources.textures.SimpleTexture; +import betterquesting.api2.client.gui.themes.IThemeRegistry; import betterquesting.client.themes.ThemeRegistry; import betterquesting.core.BetterQuesting; +import net.minecraft.util.ResourceLocation; // TODO: Reorganise these when the icon atlas is no longer bound by legacy constraints -public enum PresetIcon -{ - // === SIMPLE === - ICON_TICK("icon_tick"), - ICON_CROSS("icon_cross"), - - ICON_POSITIVE("icon_positive"), - ICON_NEGATIVE("icon_negative"), - - ICON_LEFT("icon_left"), - ICON_RIGHT("icon_right"), - ICON_UP("icon_up"), - ICON_DOWN("icon_down"), - ICON_INFO("icon_info"), - ICON_DESC("icon_desc"), - ICON_IMAGE("icon_image"), - ICON_BOOKS("icon_books"), - - // === TOOLS === - ICON_PROPS("icon_props"), - ICON_GEAR("icon_gear"), - ICON_TRASH("icon_trash"), - ICON_SELECTION("icon_selection"), - ICON_COPY("icon_copy"), - ICON_GRAB("icon_grab"), - ICON_NEW("icon_new"), - ICON_GRID("icon_grid"), - ICON_TWO_WAY("icon_two_way"), - ICON_LINK("icon_link"), - ICON_SORT("icon_sort"), - ICON_VIEW("icon_view"), - ICON_FUNC("icon_func"), - ICON_CURSOR("icon_cursor"), - ICON_REFRESH("icon_refresh"), - ICON_ITEM("icon_item"), - ICON_SCALE("icon_scale"), - - ICON_EXIT("icon_exit"), - ICON_NOTICE("icon_notice"), - ICON_PARTY("icon_party"), - ICON_THEME("icon_theme"), - ICON_HOME("icon_home"), - +public enum PresetIcon { + // === SIMPLE === + ICON_TICK("icon_tick"), + ICON_CROSS("icon_cross"), + + ICON_POSITIVE("icon_positive"), + ICON_NEGATIVE("icon_negative"), + + ICON_LEFT("icon_left"), + ICON_RIGHT("icon_right"), + ICON_UP("icon_up"), + ICON_DOWN("icon_down"), + ICON_INFO("icon_info"), + ICON_DESC("icon_desc"), + ICON_IMAGE("icon_image"), + ICON_BOOKS("icon_books"), + + // === TOOLS === + ICON_PROPS("icon_props"), + ICON_GEAR("icon_gear"), + ICON_TRASH("icon_trash"), + ICON_SELECTION("icon_selection"), + ICON_COPY("icon_copy"), + ICON_GRAB("icon_grab"), + ICON_NEW("icon_new"), + ICON_GRID("icon_grid"), + ICON_TWO_WAY("icon_two_way"), + ICON_LINK("icon_link"), + ICON_SORT("icon_sort"), + ICON_VIEW("icon_view"), + ICON_FUNC("icon_func"), + ICON_CURSOR("icon_cursor"), + ICON_REFRESH("icon_refresh"), + ICON_ITEM("icon_item"), + ICON_SCALE("icon_scale"), + + ICON_EXIT("icon_exit"), + ICON_NOTICE("icon_notice"), + ICON_PARTY("icon_party"), + ICON_THEME("icon_theme"), + ICON_HOME("icon_home"), + + // === AUDIO === + ICON_AV_PLAY("icon_av_play"), + ICON_AV_PAUSE("icon_av_pause"), + ICON_AV_STOP("icon_av_stop"), + ICON_AV_BACK("icon_av_back"), + ICON_AV_SKIP("icon_av_skip"), + ICON_AV_FF("icon_av_fastforward"), + ICON_AV_REWIND("icon_av_rewind"), + ICON_AV_SOUND("icon_av_sound"), + ICON_AV_VOL_UP("icon_av_vol_up"), + ICON_AV_VOL_DOWN("icon_av_vol_down"), + ICON_AV_VOL_MUTE("icon_av_vol_mute"), + + // === FILES === + ICON_FILE("icon_file"), + ICON_FOLDER_OPEN("icon_folder_open"), + ICON_FOLDER_CLOSED("icon_folder_closed"), + ICON_DIR_UP("icon_dir_up"), + ICON_PG_NEXT("icon_pg_next"), + ICON_PG_PREV("icon_pg_prev"), + ICON_UPLOAD("icon_upload"), + ICON_SAVE("icon_save"), + + // === PARTY === + + // === VALUES === + + // === OPTIONS === + + ICON_LOCKED("icon_locked"), + ICON_UNLOCKED("icon_unlocked"), + + // == MISC === + + ICON_BOX_FIT("icon_box_fit"), + ICON_ZOOM("icon_zoom"), + ICON_ZOOM_IN("icon_zoom_in"), + ICON_ZOOM_OUT("icon_zoom_out"), + + ICON_CHEST("icon_chest"), + ICON_CHEST_ALL("icon_chest_all"), + ICON_BOOKMARK("icon_bookmark"), + ICON_MENU("icon_menu"), + + ICON_PATREON("icon_patreon"), + ICON_TWITCH("icon_twitch"); + + public static final ResourceLocation TX_ICONS = + new ResourceLocation(BetterQuesting.MODID, "textures/gui/editor_icons.png"); + + private final ResourceLocation key; + + PresetIcon(String key) { + this.key = new ResourceLocation(BetterQuesting.MODID, key); + } + + public IGuiTexture getTexture() { + return ThemeRegistry.INSTANCE.getTexture(this.key); + } + + public ResourceLocation getKey() { + return this.key; + } + + public static void registerIcons(IThemeRegistry reg) { + reg.setDefaultTexture(ICON_TICK.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(128, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_CROSS.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(160, 16, 16, 16)).maintainAspect(true)); + + reg.setDefaultTexture(ICON_POSITIVE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(32, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_NEGATIVE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(112, 16, 16, 16)).maintainAspect(true)); + + reg.setDefaultTexture(ICON_LEFT.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(208, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_RIGHT.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(224, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_UP.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(176, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_DOWN.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(192, 16, 16, 16)).maintainAspect(true)); + + reg.setDefaultTexture(ICON_PROPS.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(0, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_GEAR.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(0, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_TRASH.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(16, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_SELECTION.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(16, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_COPY.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(32, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_GRAB.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(48, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_NEW.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(48, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_GRID.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(64, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_TWO_WAY.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(64, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_LINK.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(80, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_SORT.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(80, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_VIEW.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(96, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_FUNC.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(96, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_CURSOR.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(112, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_REFRESH.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(128, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_ITEM.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(144, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_SCALE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(144, 16, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_EXIT.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(160, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_NOTICE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(176, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_PARTY.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(192, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_THEME.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(208, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_HOME.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(224, 0, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_INFO.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(64, 80, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_DESC.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(208, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_BOOKS.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(224, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_IMAGE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(240, 64, 16, 16)).maintainAspect(true)); + // === AUDIO === - ICON_AV_PLAY("icon_av_play"), - ICON_AV_PAUSE("icon_av_pause"), - ICON_AV_STOP("icon_av_stop"), - ICON_AV_BACK("icon_av_back"), - ICON_AV_SKIP("icon_av_skip"), - ICON_AV_FF("icon_av_fastforward"), - ICON_AV_REWIND("icon_av_rewind"), - ICON_AV_SOUND("icon_av_sound"), - ICON_AV_VOL_UP("icon_av_vol_up"), - ICON_AV_VOL_DOWN("icon_av_vol_down"), - ICON_AV_VOL_MUTE("icon_av_vol_mute"), - - // === FILES === - ICON_FILE("icon_file"), - ICON_FOLDER_OPEN("icon_folder_open"), - ICON_FOLDER_CLOSED("icon_folder_closed"), - ICON_DIR_UP("icon_dir_up"), - ICON_PG_NEXT("icon_pg_next"), - ICON_PG_PREV("icon_pg_prev"), - ICON_UPLOAD("icon_upload"), - ICON_SAVE("icon_save"), - - // === PARTY === - - // === VALUES === - + reg.setDefaultTexture(ICON_AV_PLAY.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(0, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_PAUSE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(32, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_STOP.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(16, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_BACK.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(48, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_SKIP.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(64, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_FF.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(32, 80, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_REWIND.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(48, 80, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_VOL_UP.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(80, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_VOL_DOWN.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(96, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_VOL_MUTE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(112, 32, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_AV_SOUND.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(128, 32, 16, 16)).maintainAspect(true)); + + // === FILES == + reg.setDefaultTexture(ICON_FILE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(0, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_FOLDER_OPEN.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(16, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_FOLDER_CLOSED.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(32, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_DIR_UP.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(48, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_PG_PREV.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(224, 48, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_PG_NEXT.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(240, 48, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_SAVE.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(0, 80, 16, 16)).maintainAspect(true)); + // === OPTIONS === - - ICON_LOCKED("icon_locked"), - ICON_UNLOCKED("icon_unlocked"), - - // == MISC === - - ICON_BOX_FIT("icon_box_fit"), - ICON_ZOOM("icon_zoom"), - ICON_ZOOM_IN("icon_zoom_in"), - ICON_ZOOM_OUT("icon_zoom_out"), - - ICON_CHEST("icon_chest"), - ICON_CHEST_ALL("icon_chest_all"), - ICON_BOOKMARK("icon_bookmark"), - ICON_MENU("icon_menu"), - - ICON_PATREON("icon_patreon"), - ICON_TWITCH("icon_twitch"); - - public static final ResourceLocation TX_ICONS = new ResourceLocation(BetterQuesting.MODID, "textures/gui/editor_icons.png"); - - private final ResourceLocation key; - - PresetIcon(String key) - { - this.key = new ResourceLocation(BetterQuesting.MODID, key); - } - - public IGuiTexture getTexture() - { - return ThemeRegistry.INSTANCE.getTexture(this.key); - } - - public ResourceLocation getKey() - { - return this.key; - } - - public static void registerIcons(IThemeRegistry reg) - { - reg.setDefaultTexture(ICON_TICK.key, new SimpleTexture(TX_ICONS, new GuiRectangle(128, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_CROSS.key, new SimpleTexture(TX_ICONS, new GuiRectangle(160, 16, 16, 16)).maintainAspect(true)); - - reg.setDefaultTexture(ICON_POSITIVE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(32, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_NEGATIVE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(112, 16, 16, 16)).maintainAspect(true)); - - reg.setDefaultTexture(ICON_LEFT.key, new SimpleTexture(TX_ICONS, new GuiRectangle(208, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_RIGHT.key, new SimpleTexture(TX_ICONS, new GuiRectangle(224, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_UP.key, new SimpleTexture(TX_ICONS, new GuiRectangle(176, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_DOWN.key, new SimpleTexture(TX_ICONS, new GuiRectangle(192, 16, 16, 16)).maintainAspect(true)); - - reg.setDefaultTexture(ICON_PROPS.key, new SimpleTexture(TX_ICONS, new GuiRectangle(0, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_GEAR.key, new SimpleTexture(TX_ICONS, new GuiRectangle(0, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_TRASH.key, new SimpleTexture(TX_ICONS, new GuiRectangle(16, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_SELECTION.key, new SimpleTexture(TX_ICONS, new GuiRectangle(16, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_COPY.key, new SimpleTexture(TX_ICONS, new GuiRectangle(32, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_GRAB.key, new SimpleTexture(TX_ICONS, new GuiRectangle(48, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_NEW.key, new SimpleTexture(TX_ICONS, new GuiRectangle(48, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_GRID.key, new SimpleTexture(TX_ICONS, new GuiRectangle(64, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_TWO_WAY.key, new SimpleTexture(TX_ICONS, new GuiRectangle(64, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_LINK.key, new SimpleTexture(TX_ICONS, new GuiRectangle(80, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_SORT.key, new SimpleTexture(TX_ICONS, new GuiRectangle(80, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_VIEW.key, new SimpleTexture(TX_ICONS, new GuiRectangle(96, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_FUNC.key, new SimpleTexture(TX_ICONS, new GuiRectangle(96, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_CURSOR.key, new SimpleTexture(TX_ICONS, new GuiRectangle(112, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_REFRESH.key, new SimpleTexture(TX_ICONS, new GuiRectangle(128, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_ITEM.key, new SimpleTexture(TX_ICONS, new GuiRectangle(144, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_SCALE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(144, 16, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_EXIT.key, new SimpleTexture(TX_ICONS, new GuiRectangle(160, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_NOTICE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(176, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_PARTY.key, new SimpleTexture(TX_ICONS, new GuiRectangle(192, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_THEME.key, new SimpleTexture(TX_ICONS, new GuiRectangle(208, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_HOME.key, new SimpleTexture(TX_ICONS, new GuiRectangle(224, 0, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_INFO.key, new SimpleTexture(TX_ICONS, new GuiRectangle(64, 80, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_DESC.key, new SimpleTexture(TX_ICONS, new GuiRectangle(208, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_BOOKS.key, new SimpleTexture(TX_ICONS, new GuiRectangle(224, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_IMAGE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(240, 64, 16, 16)).maintainAspect(true)); - - // === AUDIO === - reg.setDefaultTexture(ICON_AV_PLAY.key, new SimpleTexture(TX_ICONS, new GuiRectangle(0, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_PAUSE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(32, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_STOP.key, new SimpleTexture(TX_ICONS, new GuiRectangle(16, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_BACK.key, new SimpleTexture(TX_ICONS, new GuiRectangle(48, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_SKIP.key, new SimpleTexture(TX_ICONS, new GuiRectangle(64, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_FF.key, new SimpleTexture(TX_ICONS, new GuiRectangle(32, 80, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_REWIND.key, new SimpleTexture(TX_ICONS, new GuiRectangle(48, 80, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_VOL_UP.key, new SimpleTexture(TX_ICONS, new GuiRectangle(80, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_VOL_DOWN.key, new SimpleTexture(TX_ICONS, new GuiRectangle(96, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_VOL_MUTE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(112, 32, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_AV_SOUND.key, new SimpleTexture(TX_ICONS, new GuiRectangle(128, 32, 16, 16)).maintainAspect(true)); - - // === FILES == - reg.setDefaultTexture(ICON_FILE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(0, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_FOLDER_OPEN.key, new SimpleTexture(TX_ICONS, new GuiRectangle(16, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_FOLDER_CLOSED.key, new SimpleTexture(TX_ICONS, new GuiRectangle(32, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_DIR_UP.key, new SimpleTexture(TX_ICONS, new GuiRectangle(48, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_PG_PREV.key, new SimpleTexture(TX_ICONS, new GuiRectangle(224, 48, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_PG_NEXT.key, new SimpleTexture(TX_ICONS, new GuiRectangle(240, 48, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_SAVE.key, new SimpleTexture(TX_ICONS, new GuiRectangle(0, 80, 16, 16)).maintainAspect(true)); - - // === OPTIONS === - reg.setDefaultTexture(ICON_LOCKED.key, new SimpleTexture(TX_ICONS, new GuiRectangle(80, 48, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_UNLOCKED.key, new SimpleTexture(TX_ICONS, new GuiRectangle(96, 48, 16, 16)).maintainAspect(true)); - - // === MISC === - reg.setDefaultTexture(ICON_BOX_FIT.key, new SimpleTexture(TX_ICONS, new GuiRectangle(80, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_ZOOM.key, new SimpleTexture(TX_ICONS, new GuiRectangle(96, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_ZOOM_IN.key, new SimpleTexture(TX_ICONS, new GuiRectangle(112, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_ZOOM_OUT.key, new SimpleTexture(TX_ICONS, new GuiRectangle(128, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_CHEST_ALL.key, new SimpleTexture(TX_ICONS, new GuiRectangle(144, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_CHEST.key, new SimpleTexture(TX_ICONS, new GuiRectangle(160, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_BOOKMARK.key, new SimpleTexture(TX_ICONS, new GuiRectangle(176, 64, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_MENU.key, new SimpleTexture(TX_ICONS, new GuiRectangle(192, 64, 16, 16)).maintainAspect(true)); - - reg.setDefaultTexture(ICON_PATREON.key, new SimpleTexture(TX_ICONS, new GuiRectangle(144, 80, 16, 16)).maintainAspect(true)); - reg.setDefaultTexture(ICON_TWITCH.key, new SimpleTexture(TX_ICONS, new GuiRectangle(160, 80, 16, 16)).maintainAspect(true)); - } + reg.setDefaultTexture(ICON_LOCKED.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(80, 48, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_UNLOCKED.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(96, 48, 16, 16)).maintainAspect(true)); + + // === MISC === + reg.setDefaultTexture(ICON_BOX_FIT.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(80, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_ZOOM.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(96, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_ZOOM_IN.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(112, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_ZOOM_OUT.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(128, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_CHEST_ALL.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(144, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_CHEST.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(160, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_BOOKMARK.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(176, 64, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_MENU.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(192, 64, 16, 16)).maintainAspect(true)); + + reg.setDefaultTexture(ICON_PATREON.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(144, 80, 16, 16)).maintainAspect(true)); + reg.setDefaultTexture(ICON_TWITCH.key, + new SimpleTexture(TX_ICONS, new GuiRectangle(160, 80, 16, 16)).maintainAspect(true)); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java index 1c87d5bbc..bb8e5b587 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java @@ -1,51 +1,46 @@ package betterquesting.api2.client.gui.themes.presets; -import betterquesting.api2.client.gui.themes.IThemeRegistry; -import net.minecraft.util.ResourceLocation; import betterquesting.api2.client.gui.resources.lines.IGuiLine; import betterquesting.api2.client.gui.resources.lines.SimpleLine; +import betterquesting.api2.client.gui.themes.IThemeRegistry; import betterquesting.client.themes.ThemeRegistry; import betterquesting.core.BetterQuesting; +import net.minecraft.util.ResourceLocation; + +public enum PresetLine { + GUI_DIVIDER("gui_divider"), + + GRID_MAJOR("grid_major"), + GRID_MINOR("grid_minor"), + + QUEST_LOCKED("quest_locked"), + QUEST_UNLOCKED("quest_unlocked"), + QUEST_PENDING("quest_pending"), + QUEST_COMPLETE("quest_complete"); + + private final ResourceLocation key; + + PresetLine(String key) { + this.key = new ResourceLocation(BetterQuesting.MODID, key); + } + + public IGuiLine getLine() { + return ThemeRegistry.INSTANCE.getLine(this.key); + } + + public ResourceLocation getKey() { + return this.key; + } + + public static void registerLines(IThemeRegistry reg) { + reg.setDefaultLine(GUI_DIVIDER.key, new SimpleLine()); + + reg.setDefaultLine(GRID_MAJOR.key, new SimpleLine()); + reg.setDefaultLine(GRID_MINOR.key, new SimpleLine(2, (short) 43690)); -public enum PresetLine -{ - GUI_DIVIDER("gui_divider"), - - GRID_MAJOR("grid_major"), - GRID_MINOR("grid_minor"), - - QUEST_LOCKED("quest_locked"), - QUEST_UNLOCKED("quest_unlocked"), - QUEST_PENDING("quest_pending"), - QUEST_COMPLETE("quest_complete"); - - private final ResourceLocation key; - - PresetLine(String key) - { - this.key = new ResourceLocation(BetterQuesting.MODID, key); - } - - public IGuiLine getLine() - { - return ThemeRegistry.INSTANCE.getLine(this.key); - } - - public ResourceLocation getKey() - { - return this.key; - } - - public static void registerLines(IThemeRegistry reg) - { - reg.setDefaultLine(GUI_DIVIDER.key, new SimpleLine()); - - reg.setDefaultLine(GRID_MAJOR.key, new SimpleLine()); - reg.setDefaultLine(GRID_MINOR.key, new SimpleLine(2, (short)43690)); - - reg.setDefaultLine(QUEST_LOCKED.key, new SimpleLine()); - reg.setDefaultLine(QUEST_UNLOCKED.key, new SimpleLine()); - reg.setDefaultLine(QUEST_PENDING.key, new SimpleLine()); - reg.setDefaultLine(QUEST_COMPLETE.key, new SimpleLine()); - } + reg.setDefaultLine(QUEST_LOCKED.key, new SimpleLine()); + reg.setDefaultLine(QUEST_UNLOCKED.key, new SimpleLine()); + reg.setDefaultLine(QUEST_PENDING.key, new SimpleLine()); + reg.setDefaultLine(QUEST_COMPLETE.key, new SimpleLine()); + } } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java index 1f998107e..73bb1811e 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java @@ -1,161 +1,220 @@ - package betterquesting.api2.client.gui.themes.presets; +package betterquesting.api2.client.gui.themes.presets; -import betterquesting.api2.client.gui.themes.IThemeRegistry; -import net.minecraft.util.ResourceLocation; import betterquesting.api2.client.gui.misc.GuiPadding; import betterquesting.api2.client.gui.misc.GuiRectangle; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; import betterquesting.api2.client.gui.resources.textures.SlicedTexture; import betterquesting.api2.client.gui.resources.textures.SlicedTexture.SliceMode; +import betterquesting.api2.client.gui.themes.IThemeRegistry; import betterquesting.client.themes.ThemeRegistry; import betterquesting.core.BetterQuesting; +import net.minecraft.util.ResourceLocation; + +public enum PresetTexture { + PANEL_MAIN("panel_main"), + PANEL_DARK("panel_dark"), + PANEL_INNER("panel_inner"), + + ITEM_FRAME("item_frame"), + AUX_FRAME_0("aux_frame_0"), + AUX_FRAME_1("aux_frame_1"), + + BTN_NORMAL_0("btn_normal_0"), + BTN_NORMAL_1("btn_normal_1"), + BTN_NORMAL_2("btn_normal_2"), + + BTN_CLEAN_0("btn_clean_0"), + BTN_CLEAN_1("btn_clean_1"), + BTN_CLEAN_2("btn_clean_2"), + + BTN_ALT_0("btn_alt_0"), + BTN_ALT_1("btn_alt_1"), + BTN_ALT_2("btn_alt_2"), + + HOTBAR_0("hotbar_0"), + HOTBAR_1("hotbar_1"), + + SCROLL_V_BG("scroll_v_bg"), + SCROLL_V_0("scroll_v_0"), + SCROLL_V_1("scroll_v_1"), + SCROLL_V_2("scroll_v_2"), + + SCROLL_H_BG("scroll_h_bg"), + SCROLL_H_0("scroll_h_0"), + SCROLL_H_1("scroll_h_1"), + SCROLL_H_2("scroll_h_2"), + + METER_V_0("meter_v_0"), + METER_V_1("meter_v_1"), + + METER_H_0("meter_h_0"), + METER_H_1("meter_h_1"), + + // Normal quest frame + QUEST_NORM_0("quest_norm_0"), + QUEST_NORM_1("quest_norm_1"), + QUEST_NORM_2("quest_norm_2"), + QUEST_NORM_3("quest_norm_3"), + + // Main quest frame + QUEST_MAIN_0("quest_main_0"), + QUEST_MAIN_1("quest_main_1"), + QUEST_MAIN_2("quest_main_2"), + QUEST_MAIN_3("quest_main_3"), + + // Auxiliary quest frame (not normally used) + QUEST_AUX_0("quest_aux_0"), + QUEST_AUX_1("quest_aux_1"), + QUEST_AUX_2("quest_aux_2"), + QUEST_AUX_3("quest_aux_3"), + + TEXT_BOX_0("text_box_0"), + TEXT_BOX_1("text_box_1"), + TEXT_BOX_2("text_box_2"), + + TOOLTIP_BG("tooltip_bg"); + + public static final ResourceLocation TX_SIMPLE = + new ResourceLocation(BetterQuesting.MODID, "textures/gui/simple_frames.png"); + public static final ResourceLocation TX_QUEST = + new ResourceLocation(BetterQuesting.MODID, "textures/gui/quest_frames.png"); + public static final ResourceLocation TX_NULL = + new ResourceLocation(BetterQuesting.MODID, "textures/gui/null_texture.png"); + + private final ResourceLocation key; + + PresetTexture(String key) { + this.key = new ResourceLocation(BetterQuesting.MODID, key); + } + + public IGuiTexture getTexture() { + return ThemeRegistry.INSTANCE.getTexture(this.key); + } + + public ResourceLocation getKey() { + return this.key; + } + + public static void registerTextures(IThemeRegistry reg) { + reg.setDefaultTexture(PANEL_MAIN.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 0, 12, 12), new GuiPadding(4, 4, 4, 4))); + reg.setDefaultTexture(PANEL_DARK.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(12, 0, 12, 12), new GuiPadding(4, 4, 4, 4))); + reg.setDefaultTexture(PANEL_INNER.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(24, 0, 12, 12), new GuiPadding(3, 3, 3, 3))); + + reg.setDefaultTexture(ITEM_FRAME.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(36, 0, 12, 12), new GuiPadding(1, 1, 1, 1))); + reg.setDefaultTexture(AUX_FRAME_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(48, 0, 12, 12), new GuiPadding(1, 1, 1, 1))); + reg.setDefaultTexture(AUX_FRAME_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(60, 0, 12, 12), new GuiPadding(1, 1, 1, 1))); + + reg.setDefaultTexture(BTN_NORMAL_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(72, 0, 12, 12), new GuiPadding(2, 2, 2, 3))); + reg.setDefaultTexture(BTN_NORMAL_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(84, 0, 12, 12), new GuiPadding(2, 2, 2, 3))); + reg.setDefaultTexture(BTN_NORMAL_2.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(96, 0, 12, 12), new GuiPadding(2, 2, 2, 3))); + + reg.setDefaultTexture(BTN_CLEAN_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(108, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); + reg.setDefaultTexture(BTN_CLEAN_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(120, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); + reg.setDefaultTexture(BTN_CLEAN_2.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(132, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); + + reg.setDefaultTexture(BTN_ALT_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(144, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); + reg.setDefaultTexture(BTN_ALT_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(156, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); + reg.setDefaultTexture(BTN_ALT_2.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(178, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); + + reg.setDefaultTexture(HOTBAR_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(190, 0, 12, 12), new GuiPadding(3, 3, 2, 2))); + reg.setDefaultTexture(HOTBAR_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(202, 0, 12, 12), new GuiPadding(3, 3, 3, 3))); + + reg.setDefaultTexture(SCROLL_V_BG.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(SCROLL_V_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(8, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(SCROLL_V_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(16, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(SCROLL_V_2.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(24, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + + reg.setDefaultTexture(SCROLL_H_BG.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(SCROLL_H_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(8, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(SCROLL_H_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(16, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(SCROLL_H_2.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(24, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); + + reg.setDefaultTexture(METER_V_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(48, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(METER_V_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(56, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + + reg.setDefaultTexture(METER_H_0.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(48, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + reg.setDefaultTexture(METER_H_1.key, + new SlicedTexture(TX_SIMPLE, new GuiRectangle(56, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); + + reg.setDefaultTexture(QUEST_NORM_0.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 0, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(QUEST_NORM_1.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 24, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(QUEST_NORM_2.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 48, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(QUEST_NORM_3.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 72, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + + reg.setDefaultTexture(QUEST_MAIN_0.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 0, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.STRETCH)); + reg.setDefaultTexture(QUEST_MAIN_1.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 24, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.STRETCH)); + reg.setDefaultTexture(QUEST_MAIN_2.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 48, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.STRETCH)); + reg.setDefaultTexture(QUEST_MAIN_3.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 72, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.STRETCH)); + + reg.setDefaultTexture(QUEST_AUX_0.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 0, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(QUEST_AUX_1.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 24, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(QUEST_AUX_2.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 48, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(QUEST_AUX_3.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 72, 24, 24), + new GuiPadding(8, 8, 8, 8)).setSliceMode( + SliceMode.SLICED_STRETCH)); + + reg.setDefaultTexture(TEXT_BOX_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 28, 8, 8), + new GuiPadding(1, 1, 1, 1)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(TEXT_BOX_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(8, 28, 8, 8), + new GuiPadding(1, 1, 1, 1)).setSliceMode( + SliceMode.SLICED_STRETCH)); + reg.setDefaultTexture(TEXT_BOX_2.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(16, 28, 8, 8), + new GuiPadding(1, 1, 1, 1)).setSliceMode( + SliceMode.SLICED_STRETCH)); -public enum PresetTexture -{ - PANEL_MAIN("panel_main"), - PANEL_DARK("panel_dark"), - PANEL_INNER("panel_inner"), - - ITEM_FRAME("item_frame"), - AUX_FRAME_0("aux_frame_0"), - AUX_FRAME_1("aux_frame_1"), - - BTN_NORMAL_0("btn_normal_0"), - BTN_NORMAL_1("btn_normal_1"), - BTN_NORMAL_2("btn_normal_2"), - - BTN_CLEAN_0("btn_clean_0"), - BTN_CLEAN_1("btn_clean_1"), - BTN_CLEAN_2("btn_clean_2"), - - BTN_ALT_0("btn_alt_0"), - BTN_ALT_1("btn_alt_1"), - BTN_ALT_2("btn_alt_2"), - - HOTBAR_0("hotbar_0"), - HOTBAR_1("hotbar_1"), - - SCROLL_V_BG("scroll_v_bg"), - SCROLL_V_0("scroll_v_0"), - SCROLL_V_1("scroll_v_1"), - SCROLL_V_2("scroll_v_2"), - - SCROLL_H_BG("scroll_h_bg"), - SCROLL_H_0("scroll_h_0"), - SCROLL_H_1("scroll_h_1"), - SCROLL_H_2("scroll_h_2"), - - METER_V_0("meter_v_0"), - METER_V_1("meter_v_1"), - - METER_H_0("meter_h_0"), - METER_H_1("meter_h_1"), - - // Normal quest frame - QUEST_NORM_0("quest_norm_0"), - QUEST_NORM_1("quest_norm_1"), - QUEST_NORM_2("quest_norm_2"), - QUEST_NORM_3("quest_norm_3"), - - // Main quest frame - QUEST_MAIN_0("quest_main_0"), - QUEST_MAIN_1("quest_main_1"), - QUEST_MAIN_2("quest_main_2"), - QUEST_MAIN_3("quest_main_3"), - - // Auxiliary quest frame (not normally used) - QUEST_AUX_0("quest_aux_0"), - QUEST_AUX_1("quest_aux_1"), - QUEST_AUX_2("quest_aux_2"), - QUEST_AUX_3("quest_aux_3"), - - TEXT_BOX_0("text_box_0"), - TEXT_BOX_1("text_box_1"), - TEXT_BOX_2("text_box_2"), - - TOOLTIP_BG("tooltip_bg"); - - public static final ResourceLocation TX_SIMPLE = new ResourceLocation(BetterQuesting.MODID, "textures/gui/simple_frames.png"); - public static final ResourceLocation TX_QUEST = new ResourceLocation(BetterQuesting.MODID, "textures/gui/quest_frames.png"); - public static final ResourceLocation TX_NULL = new ResourceLocation(BetterQuesting.MODID, "textures/gui/null_texture.png"); - - private final ResourceLocation key; - - PresetTexture(String key) - { - this.key = new ResourceLocation(BetterQuesting.MODID, key); - } - - public IGuiTexture getTexture() - { - return ThemeRegistry.INSTANCE.getTexture(this.key); - } - - public ResourceLocation getKey() - { - return this.key; - } - - public static void registerTextures(IThemeRegistry reg) - { - reg.setDefaultTexture(PANEL_MAIN.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 0, 12, 12), new GuiPadding(4, 4, 4, 4))); - reg.setDefaultTexture(PANEL_DARK.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(12, 0, 12, 12), new GuiPadding(4, 4, 4, 4))); - reg.setDefaultTexture(PANEL_INNER.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(24, 0, 12, 12), new GuiPadding(3, 3, 3, 3))); - - reg.setDefaultTexture(ITEM_FRAME.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(36, 0, 12, 12), new GuiPadding(1, 1, 1, 1))); - reg.setDefaultTexture(AUX_FRAME_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(48, 0, 12, 12), new GuiPadding(1, 1, 1, 1))); - reg.setDefaultTexture(AUX_FRAME_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(60, 0, 12, 12), new GuiPadding(1, 1, 1, 1))); - - reg.setDefaultTexture(BTN_NORMAL_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(72, 0, 12, 12), new GuiPadding(2, 2, 2, 3))); - reg.setDefaultTexture(BTN_NORMAL_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(84, 0, 12, 12), new GuiPadding(2, 2, 2, 3))); - reg.setDefaultTexture(BTN_NORMAL_2.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(96, 0, 12, 12), new GuiPadding(2, 2, 2, 3))); - - reg.setDefaultTexture(BTN_CLEAN_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(108, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); - reg.setDefaultTexture(BTN_CLEAN_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(120, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); - reg.setDefaultTexture(BTN_CLEAN_2.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(132, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); - - reg.setDefaultTexture(BTN_ALT_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(144, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); - reg.setDefaultTexture(BTN_ALT_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(156, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); - reg.setDefaultTexture(BTN_ALT_2.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(178, 0, 12, 12), new GuiPadding(2, 2, 2, 2))); - - reg.setDefaultTexture(HOTBAR_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(190, 0, 12, 12), new GuiPadding(3, 3, 2, 2))); - reg.setDefaultTexture(HOTBAR_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(202, 0, 12, 12), new GuiPadding(3, 3, 3, 3))); - - reg.setDefaultTexture(SCROLL_V_BG.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(SCROLL_V_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(8, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(SCROLL_V_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(16, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(SCROLL_V_2.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(24, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - - reg.setDefaultTexture(SCROLL_H_BG.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(SCROLL_H_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(8, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(SCROLL_H_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(16, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(SCROLL_H_2.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(24, 20, 8, 8), new GuiPadding(3, 3, 3, 3))); - - reg.setDefaultTexture(METER_V_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(48, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(METER_V_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(56, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - - reg.setDefaultTexture(METER_H_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(48, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - reg.setDefaultTexture(METER_H_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(56, 12, 8, 8), new GuiPadding(3, 3, 3, 3))); - - reg.setDefaultTexture(QUEST_NORM_0.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 0, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(QUEST_NORM_1.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 24, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(QUEST_NORM_2.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 48, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(QUEST_NORM_3.key, new SlicedTexture(TX_QUEST, new GuiRectangle(0, 72, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - - reg.setDefaultTexture(QUEST_MAIN_0.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 0, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.STRETCH)); - reg.setDefaultTexture(QUEST_MAIN_1.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 24, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.STRETCH)); - reg.setDefaultTexture(QUEST_MAIN_2.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 48, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.STRETCH)); - reg.setDefaultTexture(QUEST_MAIN_3.key, new SlicedTexture(TX_QUEST, new GuiRectangle(24, 72, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.STRETCH)); - - reg.setDefaultTexture(QUEST_AUX_0.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 0, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(QUEST_AUX_1.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 24, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(QUEST_AUX_2.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 48, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(QUEST_AUX_3.key, new SlicedTexture(TX_QUEST, new GuiRectangle(48, 72, 24, 24), new GuiPadding(8, 8, 8, 8)).setSliceMode(SliceMode.SLICED_STRETCH)); - - reg.setDefaultTexture(TEXT_BOX_0.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(0, 28, 8, 8), new GuiPadding(1, 1, 1, 1)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(TEXT_BOX_1.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(8, 28, 8, 8), new GuiPadding(1, 1, 1, 1)).setSliceMode(SliceMode.SLICED_STRETCH)); - reg.setDefaultTexture(TEXT_BOX_2.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(16, 28, 8, 8), new GuiPadding(1, 1, 1, 1)).setSliceMode(SliceMode.SLICED_STRETCH)); - - reg.setDefaultTexture(TOOLTIP_BG.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(204, 0, 12, 12), new GuiPadding(2, 2, 2, 2)).setSliceMode(SliceMode.SLICED_STRETCH)); - } + reg.setDefaultTexture(TOOLTIP_BG.key, new SlicedTexture(TX_SIMPLE, new GuiRectangle(204, 0, 12, 12), + new GuiPadding(2, 2, 2, 2)).setSliceMode( + SliceMode.SLICED_STRETCH)); + } } diff --git a/src/main/java/betterquesting/api2/client/toolbox/IToolTab.java b/src/main/java/betterquesting/api2/client/toolbox/IToolTab.java index 0692415d1..ac8f546e2 100644 --- a/src/main/java/betterquesting/api2/client/toolbox/IToolTab.java +++ b/src/main/java/betterquesting/api2/client/toolbox/IToolTab.java @@ -5,12 +5,11 @@ import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine; import betterquesting.client.gui2.editors.designer.PanelToolController; -public interface IToolTab -{ - String getUnlocalisedName(); - - // TODO: Figure out a reasonable way of adding tools - //void registerTool(IToolboxTool tool, ResourceLocation icon); - - IGuiPanel getTabGui(IGuiRect rect, CanvasQuestLine questLine, PanelToolController toolController); +public interface IToolTab { + String getUnlocalisedName(); + + // TODO: Figure out a reasonable way of adding tools + //void registerTool(IToolboxTool tool, ResourceLocation icon); + + IGuiPanel getTabGui(IGuiRect rect, CanvasQuestLine questLine, PanelToolController toolController); } diff --git a/src/main/java/betterquesting/api2/package-info.java b/src/main/java/betterquesting/api2/package-info.java index 99ff19900..164267a70 100644 --- a/src/main/java/betterquesting/api2/package-info.java +++ b/src/main/java/betterquesting/api2/package-info.java @@ -1,4 +1,5 @@ @API(owner = "betterquesting", apiVersion = "3.1", provides = "BetterQuesting|API2") package betterquesting.api2; + import net.minecraftforge.fml.common.API; diff --git a/src/main/java/betterquesting/api2/registry/FunctionRegistry.java b/src/main/java/betterquesting/api2/registry/FunctionRegistry.java index 96589cc78..3f0d51041 100644 --- a/src/main/java/betterquesting/api2/registry/FunctionRegistry.java +++ b/src/main/java/betterquesting/api2/registry/FunctionRegistry.java @@ -10,55 +10,46 @@ import java.util.Set; import java.util.function.Function; -public class FunctionRegistry -{ - private final HashMap> factories = new HashMap<>(); - private final HashMap def_args = new HashMap<>(); - - public void register(@Nonnull ResourceLocation idname, @Nonnull Function factory, E template) - { - if(factories.containsKey(idname)) - { - throw new IllegalArgumentException("Cannot register duplicate factory or registry name"); - } - - factories.put(idname, factory); - def_args.put(idname, template); - } - - @Nullable - public T createNew(@Nonnull ResourceLocation idName) - { - E arg = def_args.get(idName); - if(arg != null) return createNew(idName, arg); - - BetterQuesting.logger.error("Registry failed to instantiate new object with ID: " + idName.toString()); - return null; - } - - @Nullable - public T createNew(@Nonnull ResourceLocation idName, @Nonnull E info) - { - Function fact = factories.get(idName); - try - { - return fact == null ? null : fact.apply(info); - } catch(Exception e) - { - BetterQuesting.logger.error("Registry failed to instantiate new object with ID: " + idName.toString(), e); - return null; - } - } - - @Nullable - public E getTemplate(@Nonnull ResourceLocation idname) - { - return def_args.get(idname); +public class FunctionRegistry { + private final HashMap> factories = new HashMap<>(); + private final HashMap def_args = new HashMap<>(); + + public void register(@Nonnull ResourceLocation idname, @Nonnull Function factory, E template) { + if (factories.containsKey(idname)) { + throw new IllegalArgumentException("Cannot register duplicate factory or registry name"); } - - @Nonnull - public Set getAll() - { - return Collections.unmodifiableSet(factories.keySet()); + + factories.put(idname, factory); + def_args.put(idname, template); + } + + @Nullable + public T createNew(@Nonnull ResourceLocation idName) { + E arg = def_args.get(idName); + if (arg != null) { return createNew(idName, arg); } + + BetterQuesting.logger.error("Registry failed to instantiate new object with ID: " + idName); + return null; + } + + @Nullable + public T createNew(@Nonnull ResourceLocation idName, @Nonnull E info) { + Function fact = factories.get(idName); + try { + return fact == null ? null : fact.apply(info); + } catch (Exception e) { + BetterQuesting.logger.error("Registry failed to instantiate new object with ID: " + idName, e); + return null; } + } + + @Nullable + public E getTemplate(@Nonnull ResourceLocation idname) { + return def_args.get(idname); + } + + @Nonnull + public Set getAll() { + return Collections.unmodifiableSet(factories.keySet()); + } } diff --git a/src/main/java/betterquesting/api2/registry/IFactory.java b/src/main/java/betterquesting/api2/registry/IFactory.java index 5a99d1a86..1bb3576ec 100644 --- a/src/main/java/betterquesting/api2/registry/IFactory.java +++ b/src/main/java/betterquesting/api2/registry/IFactory.java @@ -3,8 +3,8 @@ import net.minecraft.util.ResourceLocation; @Deprecated // Stop... just use lambdas -public interface IFactory -{ - ResourceLocation getRegistryName(); - T createNew(); +public interface IFactory { + ResourceLocation getRegistryName(); + + T createNew(); } diff --git a/src/main/java/betterquesting/api2/registry/IFactoryData.java b/src/main/java/betterquesting/api2/registry/IFactoryData.java index b4f8b00a4..dd2baf30f 100644 --- a/src/main/java/betterquesting/api2/registry/IFactoryData.java +++ b/src/main/java/betterquesting/api2/registry/IFactoryData.java @@ -1,7 +1,6 @@ package betterquesting.api2.registry; @Deprecated // This is stupid and can be done with lambdas -public interface IFactoryData extends IFactory -{ - T loadFromData(E data); +public interface IFactoryData extends IFactory { + T loadFromData(E data); } diff --git a/src/main/java/betterquesting/api2/registry/IRegistry.java b/src/main/java/betterquesting/api2/registry/IRegistry.java index 7c4bbbef9..12a16012b 100644 --- a/src/main/java/betterquesting/api2/registry/IRegistry.java +++ b/src/main/java/betterquesting/api2/registry/IRegistry.java @@ -6,13 +6,13 @@ import java.util.List; @Deprecated -public interface IRegistry, E> -{ - void register(T factory); - T getFactory(ResourceLocation idName); - - @Nullable - E createNew(ResourceLocation idName); - - List getAll(); +public interface IRegistry, E> { + void register(T factory); + + T getFactory(ResourceLocation idName); + + @Nullable + E createNew(ResourceLocation idName); + + List getAll(); } diff --git a/src/main/java/betterquesting/api2/registry/SimpleRegistry.java b/src/main/java/betterquesting/api2/registry/SimpleRegistry.java index 7176734cc..b936c5fa6 100644 --- a/src/main/java/betterquesting/api2/registry/SimpleRegistry.java +++ b/src/main/java/betterquesting/api2/registry/SimpleRegistry.java @@ -10,36 +10,29 @@ import java.util.Set; import java.util.concurrent.Callable; -public class SimpleRegistry -{ - private final HashMap> factories = new HashMap<>(); - - public void register(@Nonnull ResourceLocation idname, @Nonnull Callable factory) - { - if(factories.containsKey(idname)) - { - throw new IllegalArgumentException("Cannot register duplicate factory or registry name"); - } - - factories.put(idname, factory); - } - - @Nullable - public T createNew(@Nonnull ResourceLocation idName) - { - Callable fact = factories.get(idName); - try - { - return fact == null ? null : fact.call(); - } catch(Exception e) - { - BetterQuesting.logger.error("Registry failed to instantiate new object with ID: " + idName.toString(), e); - return null; - } +public class SimpleRegistry { + private final HashMap> factories = new HashMap<>(); + + public void register(@Nonnull ResourceLocation idname, @Nonnull Callable factory) { + if (factories.containsKey(idname)) { + throw new IllegalArgumentException("Cannot register duplicate factory or registry name"); } - - public Set getAll() - { - return Collections.unmodifiableSet(factories.keySet()); + + factories.put(idname, factory); + } + + @Nullable + public T createNew(@Nonnull ResourceLocation idName) { + Callable fact = factories.get(idName); + try { + return fact == null ? null : fact.call(); + } catch (Exception e) { + BetterQuesting.logger.error("Registry failed to instantiate new object with ID: " + idName, e); + return null; } + } + + public Set getAll() { + return Collections.unmodifiableSet(factories.keySet()); + } } diff --git a/src/main/java/betterquesting/api2/storage/DBEntry.java b/src/main/java/betterquesting/api2/storage/DBEntry.java index f9e463f59..f3ba653b9 100644 --- a/src/main/java/betterquesting/api2/storage/DBEntry.java +++ b/src/main/java/betterquesting/api2/storage/DBEntry.java @@ -2,53 +2,42 @@ import javax.annotation.Nonnull; -public final class DBEntry implements Comparable> -{ - private final int id; - @Nonnull - private final T obj; - - public DBEntry(int id, T obj) - { - if(id < 0) - { - throw new IllegalArgumentException("Entry ID cannot be negative"); - } else if(obj == null) - { - throw new NullPointerException("Entry value cannot be null"); - } - - this.id = id; - this.obj = obj; - } - - public final int getID() - { - return this.id; - } - - @Nonnull - public final T getValue() - { - return obj; - } - - @Override - public int compareTo(DBEntry o) - { - return Integer.compare(id, o.id); +public final class DBEntry implements Comparable> { + private final int id; + @Nonnull + private final T obj; + + public DBEntry(int id, @Nonnull T obj) { + if (id < 0) { + throw new IllegalArgumentException("Entry ID cannot be negative"); } - - @Override - public boolean equals(Object obj) - { - if(!(obj instanceof DBEntry)) - { - return false; - } - - DBEntry entry = (DBEntry)obj; - - return this.getID() == entry.getID() && this.getValue().equals(entry.getValue()); + + this.id = id; + this.obj = obj; + } + + public int getID() { + return this.id; + } + + @Nonnull + public T getValue() { + return obj; + } + + @Override + public int compareTo(DBEntry o) { + return Integer.compare(id, o.id); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof DBEntry)) { + return false; } + + DBEntry entry = (DBEntry) obj; + + return this.getID() == entry.getID() && this.getValue().equals(entry.getValue()); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/storage/IDatabase.java b/src/main/java/betterquesting/api2/storage/IDatabase.java index 58099ad87..e24006c97 100644 --- a/src/main/java/betterquesting/api2/storage/IDatabase.java +++ b/src/main/java/betterquesting/api2/storage/IDatabase.java @@ -2,20 +2,24 @@ import java.util.List; -public interface IDatabase -{ - int nextID(); - - DBEntry add(int id, T value); - boolean removeID(int key); - boolean removeValue(T value); - - int getID(T value); - T getValue(int id); - - int size(); - void reset(); - - List> getEntries(); - List> bulkLookup(int... keys); +public interface IDatabase { + int nextID(); + + DBEntry add(int id, T value); + + boolean removeID(int key); + + boolean removeValue(T value); + + int getID(T value); + + T getValue(int id); + + int size(); + + void reset(); + + List> getEntries(); + + List> bulkLookup(int... keys); } diff --git a/src/main/java/betterquesting/api2/storage/IDatabaseNBT.java b/src/main/java/betterquesting/api2/storage/IDatabaseNBT.java index f6034ece2..687d31aef 100644 --- a/src/main/java/betterquesting/api2/storage/IDatabaseNBT.java +++ b/src/main/java/betterquesting/api2/storage/IDatabaseNBT.java @@ -2,6 +2,6 @@ import net.minecraft.nbt.NBTBase; -public interface IDatabaseNBT extends IDatabase, INBTPartial, INBTProgress -{ +public interface IDatabaseNBT + extends IDatabase, INBTPartial, INBTProgress { } diff --git a/src/main/java/betterquesting/api2/storage/INBTPartial.java b/src/main/java/betterquesting/api2/storage/INBTPartial.java index e4699a807..5aa96155b 100644 --- a/src/main/java/betterquesting/api2/storage/INBTPartial.java +++ b/src/main/java/betterquesting/api2/storage/INBTPartial.java @@ -6,8 +6,8 @@ import java.util.List; // Used when the base data set can safely be split. Can be used in place of INBTSaveLoad -public interface INBTPartial -{ - T writeToNBT(T nbt, @Nullable List subset); - void readFromNBT(T nbt, boolean merge); +public interface INBTPartial { + T writeToNBT(T nbt, @Nullable List subset); + + void readFromNBT(T nbt, boolean merge); } diff --git a/src/main/java/betterquesting/api2/storage/INBTProgress.java b/src/main/java/betterquesting/api2/storage/INBTProgress.java index 6c33d3b99..de264e30f 100644 --- a/src/main/java/betterquesting/api2/storage/INBTProgress.java +++ b/src/main/java/betterquesting/api2/storage/INBTProgress.java @@ -7,8 +7,8 @@ import java.util.UUID; // Used when progress specific data is being handled (usually split per user) -public interface INBTProgress -{ - T writeProgressToNBT(T nbt, @Nullable List users); - void readProgressFromNBT(T nbt, boolean merge); +public interface INBTProgress { + T writeProgressToNBT(T nbt, @Nullable List users); + + void readProgressFromNBT(T nbt, boolean merge); } diff --git a/src/main/java/betterquesting/api2/storage/INBTSaveLoad.java b/src/main/java/betterquesting/api2/storage/INBTSaveLoad.java index 672f57dfc..e20228e38 100644 --- a/src/main/java/betterquesting/api2/storage/INBTSaveLoad.java +++ b/src/main/java/betterquesting/api2/storage/INBTSaveLoad.java @@ -3,8 +3,8 @@ import net.minecraft.nbt.NBTBase; // TODO: Replace usage with INBTSerializable? -public interface INBTSaveLoad -{ - T writeToNBT(T nbt); - void readFromNBT(T nbt); +public interface INBTSaveLoad { + T writeToNBT(T nbt); + + void readFromNBT(T nbt); } diff --git a/src/main/java/betterquesting/api2/storage/SimpleDatabase.java b/src/main/java/betterquesting/api2/storage/SimpleDatabase.java index 98de60eef..8e415f424 100644 --- a/src/main/java/betterquesting/api2/storage/SimpleDatabase.java +++ b/src/main/java/betterquesting/api2/storage/SimpleDatabase.java @@ -1,134 +1,120 @@ package betterquesting.api2.storage; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; + import java.util.*; -import java.util.Map.Entry; -public class SimpleDatabase implements IDatabase -{ - private final TreeMap mapDB = new TreeMap<>(); - - private final BitSet idMap = new BitSet(); - private List> refCache = null; - - @Override - public synchronized int nextID() - { - return idMap.nextClearBit(0); - } - - @Override - public synchronized DBEntry add(int id, T value) - { - if(value == null) - { - throw new NullPointerException("Value cannot be null"); - } else if(id < 0) - { - throw new IllegalArgumentException("ID cannot be negative"); - } else - { - if(mapDB.putIfAbsent(id, value) == null) - { - idMap.set(id); - refCache = null; - return new DBEntry<>(id, value); - } else - { - throw new IllegalArgumentException("ID or value is already contained within database"); - } - } +public class SimpleDatabase implements IDatabase { + private final Int2ObjectMap map = new Int2ObjectOpenHashMap<>(); + private final Object2IntMap inverseMap = new Object2IntOpenHashMap<>(); + + { + inverseMap.defaultReturnValue(-1); + } + + private final BitSet idMap = new BitSet(); + private List> refCache = null; + + @Override + public synchronized int nextID() { + return idMap.nextClearBit(0); + } + + @Override + public synchronized DBEntry add(int id, T value) { + Objects.requireNonNull(value, "Value cannot be null"); + if (id < 0) { + throw new IllegalArgumentException("ID cannot be negative"); } - - @Override - public synchronized boolean removeID(int key) - { - if(key < 0) return false; - - if(mapDB.remove(key) != null) - { - idMap.clear(key); - refCache = null; - return true; - } - - return false; + if (map.putIfAbsent(id, value) == null && inverseMap.putIfAbsent(value, id) == null) { + idMap.set(id); + refCache = null; + return new DBEntry<>(id, value); + } else { + throw new IllegalArgumentException("ID or value is already contained within database"); } - - @Override - public synchronized boolean removeValue(T value) - { - return value != null && removeID(getID(value)); + } + + @Override + public synchronized boolean removeID(int key) { + if (key < 0) { + return false; } - - @Override - public synchronized int getID(T value) - { - if(value == null) return -1; - - for(DBEntry entry : getEntries()) - { - if(entry.getValue() == value) return entry.getID(); - } - - return -1; + T removed = map.remove(key); + if (removed == null) { + return false; } - - @Override - public synchronized T getValue(int id) - { - if(id < 0 || mapDB.size() <= 0) return null; - return mapDB.get(id); + inverseMap.removeInt(removed); + idMap.clear(key); + refCache = null; + return true; + } + + @Override + public synchronized boolean removeValue(T value) { + if (value == null) { + return false; } - - @Override - public synchronized int size() - { - return mapDB.size(); + int removed = inverseMap.removeInt(value); + if (removed == -1) { + return false; } - - @Override - public synchronized void reset() - { - mapDB.clear(); - idMap.clear(); - refCache = Collections.emptyList(); + map.remove(removed); + idMap.clear(removed); + refCache = null; + return true; + } + + @Override + public synchronized int getID(T value) { + return inverseMap.getInt(value); + } + + @Override + public synchronized T getValue(int id) { + return map.get(id); + } + + @Override + public synchronized int size() { + return map.size(); + } + + @Override + public synchronized void reset() { + map.clear(); + idMap.clear(); + refCache = Collections.emptyList(); + } + + @Override + public synchronized List> getEntries() { + if (refCache == null) { + List> list = new ArrayList<>(); + map.forEach((k, v) -> list.add(new DBEntry<>(k, v))); + list.sort(Comparator.comparingInt(DBEntry::getID)); + refCache = Collections.unmodifiableList(list); } - - @Override - public synchronized List> getEntries() - { - if(refCache == null) - { - List> temp = new ArrayList<>(); - for(Entry entry : mapDB.entrySet()) - { - temp.add(new DBEntry<>(entry.getKey(), entry.getValue())); - } - refCache = Collections.unmodifiableList(temp); - } - - return refCache; + return refCache; + } + + @Override + public synchronized List> bulkLookup(int... keys) { + if (keys.length == 0) { + return Collections.emptyList(); } - - @Override - public synchronized List> bulkLookup(int... keys) - { - if(keys.length <= 0) return Collections.emptyList(); - - int[] sortedKeys = new int[keys.length]; - System.arraycopy(keys, 0, sortedKeys, 0, keys.length); - Arrays.sort(sortedKeys); - - List> subList = new ArrayList<>(); - int n = 0; - - for(DBEntry entry : getEntries()) - { - while(n < sortedKeys.length && sortedKeys[n] < entry.getID()) n++; - if(n >= sortedKeys.length) break; - if(sortedKeys[n] == entry.getID()) subList.add(entry); - } - - return subList; + int[] sortedKeys = keys.clone(); + Arrays.sort(sortedKeys); + List> result = new ArrayList<>(); + for (int i : sortedKeys) { + T t = map.get(i); + if (t != null) { + result.add(new DBEntry<>(i, t)); + } } + return result; + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java b/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java index 9f71aed1b..a36b80b63 100644 --- a/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java +++ b/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java @@ -18,104 +18,95 @@ import java.util.Collection; import java.util.UUID; -public class MCLinkAPI -{ - private static final String MCL_TOKEN = "Yo1nkbXn7uVptLoL3GpkAaT7HsU8QFGJ"; - - private static String userAgent = null; - - @Nonnull - public JsonObject getApiStatus() - { - return new JsonObject(); - } - - public void updateSupporterInfo(@Nonnull Collection playerIDs, Collection tokens) - { - JsonObject jsonBase = new JsonObject(); - - JsonObject jsonTokens = new JsonObject(); - - JsonObject jsonServices = new JsonObject(); - JsonArray teirArgs = new JsonArray(); - teirArgs.add(0); // Just report any tier for now - jsonServices.add("Patreon", teirArgs); - jsonServices.add("Twitch", new JsonArray()); - - tokens.forEach((key) -> jsonTokens.add(key, jsonServices)); - jsonBase.add("tokens", jsonTokens); - - JsonArray jsonIds = new JsonArray(); - playerIDs.forEach((id) -> jsonIds.add(id.toString())); - jsonBase.add("uuids", jsonIds); - - try - { - JsonElement response = sendJsonPost(McLinkEndpoint.API_AUTH.URL, jsonBase); - } catch(Exception e) - { - BetterQuesting.logger.error("Unable to lookup supporter info", e); - } - } - - private static JsonElement sendJsonPost(String endpoint, JsonElement json) throws IOException - { - if(userAgent == null) setupMetadata(); - - URL url = new URL(endpoint); - String redirect = url.toString(); - HttpURLConnection con; - - do - { - url = new URL(url, redirect); - con = (HttpURLConnection)url.openConnection(); - con.setRequestMethod("POST"); - con.setInstanceFollowRedirects(true); - con.setAllowUserInteraction(false); - con.setConnectTimeout(30000); - con.setReadTimeout(30000); - con.setDoOutput(true); - - con.setRequestProperty("User-Agent", userAgent); - con.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name()); - con.setRequestProperty("Accept", "application/json"); - con.setRequestProperty("Content-Type", "application/json; charset=" + StandardCharsets.UTF_8.name()); - - try(OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)) - { - JsonHelper.GSON.toJson(json, osw); - osw.flush(); - redirect = con.getHeaderField("Location"); - } - } while(redirect != null && con.getResponseCode() / 100 == 3); // Continue following redirects - - //TODO: Flag the JSON response as an error when necessary so it can be handled as such - InputStream is = con.getErrorStream(); - if(is == null) is = con.getInputStream(); - - try(InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) - { - JsonElement jsonOut = JsonHelper.GSON.fromJson(isr, JsonElement.class); - return jsonOut != null ? jsonOut : new JsonObject(); - } +public class MCLinkAPI { + private static final String MCL_TOKEN = "Yo1nkbXn7uVptLoL3GpkAaT7HsU8QFGJ"; + + private static String userAgent = null; + + @Nonnull + public JsonObject getApiStatus() { + return new JsonObject(); + } + + public void updateSupporterInfo(@Nonnull Collection playerIDs, Collection tokens) { + JsonObject jsonBase = new JsonObject(); + + JsonObject jsonTokens = new JsonObject(); + + JsonObject jsonServices = new JsonObject(); + JsonArray teirArgs = new JsonArray(); + teirArgs.add(0); // Just report any tier for now + jsonServices.add("Patreon", teirArgs); + jsonServices.add("Twitch", new JsonArray()); + + tokens.forEach((key) -> jsonTokens.add(key, jsonServices)); + jsonBase.add("tokens", jsonTokens); + + JsonArray jsonIds = new JsonArray(); + playerIDs.forEach((id) -> jsonIds.add(id.toString())); + jsonBase.add("uuids", jsonIds); + + try { + JsonElement response = sendJsonPost(McLinkEndpoint.API_AUTH.URL, jsonBase); + } catch (Exception e) { + BetterQuesting.logger.error("Unable to lookup supporter info", e); } - - // This is setup to match what MC Link expects the user agent metadata to contain. - private static void setupMetadata() - { - //noinspection ConstantConditions - String modVersion = BetterQuesting.VERSION.equalsIgnoreCase("@VERSION@") ? "DEV" : BetterQuesting.VERSION; - String mcVersion = "1.12.2"; - String branding = "Forge"; - - StringBuilder sb = new StringBuilder(BetterQuesting.NAME); - sb.append('/').append(modVersion.replaceAll("[;()\n\r]", "")); - sb.append(" (APIv").append(1).append("; "); - sb.append("MCv").append(mcVersion.replaceAll("[;()\n\r]", "")).append("; "); - sb.append(branding.replaceAll("[;()\n\r]", "")).append("; "); - String os = System.getProperty("os.name") + ' ' + System.getProperty("os.arch") + ' ' + System.getProperty("os.version"); - sb.append(os.replaceAll("[;()\n\r]", "")); - userAgent = sb.append(')').toString(); + } + + private static JsonElement sendJsonPost(String endpoint, JsonElement json) throws IOException { + if (userAgent == null) { setupMetadata(); } + + URL url = new URL(endpoint); + String redirect = url.toString(); + HttpURLConnection con; + + do { + url = new URL(url, redirect); + con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + con.setInstanceFollowRedirects(true); + con.setAllowUserInteraction(false); + con.setConnectTimeout(30000); + con.setReadTimeout(30000); + con.setDoOutput(true); + + con.setRequestProperty("User-Agent", userAgent); + con.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name()); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("Content-Type", "application/json; charset=" + StandardCharsets.UTF_8.name()); + + try (OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)) { + JsonHelper.GSON.toJson(json, osw); + osw.flush(); + redirect = con.getHeaderField("Location"); + } + } while (redirect != null && con.getResponseCode() / 100 == 3); // Continue following redirects + + //TODO: Flag the JSON response as an error when necessary so it can be handled as such + InputStream is = con.getErrorStream(); + if (is == null) { is = con.getInputStream(); } + + try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) { + JsonElement jsonOut = JsonHelper.GSON.fromJson(isr, JsonElement.class); + return jsonOut != null ? jsonOut : new JsonObject(); } + } + + // This is setup to match what MC Link expects the user agent metadata to contain. + private static void setupMetadata() { + //noinspection ConstantConditions + String modVersion = BetterQuesting.VERSION.equalsIgnoreCase("@VERSION@") ? "DEV" : BetterQuesting.VERSION; + String mcVersion = "1.12.2"; + String branding = "Forge"; + + StringBuilder sb = new StringBuilder(BetterQuesting.NAME); + sb.append('/').append(modVersion.replaceAll("[;()\n\r]", "")); + sb.append(" (APIv").append(1).append("; "); + sb.append("MCv").append(mcVersion.replaceAll("[;()\n\r]", "")).append("; "); + sb.append(branding.replaceAll("[;()\n\r]", "")).append("; "); + String os = + System.getProperty("os.name") + ' ' + System.getProperty("os.arch") + ' ' + System.getProperty("os.version"); + sb.append(os.replaceAll("[;()\n\r]", "")); + userAgent = sb.append(')').toString(); + } } diff --git a/src/main/java/betterquesting/api2/supporter/RgbTexture.java b/src/main/java/betterquesting/api2/supporter/RgbTexture.java index d9a133cc2..1ba217007 100644 --- a/src/main/java/betterquesting/api2/supporter/RgbTexture.java +++ b/src/main/java/betterquesting/api2/supporter/RgbTexture.java @@ -9,28 +9,25 @@ import java.awt.image.DataBufferInt; import java.io.IOException; -public class RgbTexture extends AbstractTexture -{ - private final int[] rgbAry; - - private final int w; - private final int h; - - public RgbTexture(int w, int h, int[] rgbAry) - { - this.w = w; - this.h = h; - this.rgbAry = rgbAry; - } - - @Override - public void loadTexture(@Nonnull IResourceManager resourceManager) throws IOException - { - this.deleteGlTexture(); - - BufferedImage bufImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - final int[] imgData = ((DataBufferInt)bufImg.getRaster().getDataBuffer()).getData(); - System.arraycopy(rgbAry, 0, imgData, 0, imgData.length); - TextureUtil.uploadTextureImageAllocate(this.getGlTextureId(), bufImg, false, false); - } +public class RgbTexture extends AbstractTexture { + private final int[] rgbAry; + + private final int w; + private final int h; + + public RgbTexture(int w, int h, int[] rgbAry) { + this.w = w; + this.h = h; + this.rgbAry = rgbAry; + } + + @Override + public void loadTexture(@Nonnull IResourceManager resourceManager) { + this.deleteGlTexture(); + + BufferedImage bufImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); + final int[] imgData = ((DataBufferInt) bufImg.getRaster().getDataBuffer()).getData(); + System.arraycopy(rgbAry, 0, imgData, 0, imgData.length); + TextureUtil.uploadTextureImageAllocate(this.getGlTextureId(), bufImg, false, false); + } } diff --git a/src/main/java/betterquesting/api2/supporter/SupporterAPI.java b/src/main/java/betterquesting/api2/supporter/SupporterAPI.java index a0d16f7e8..bc438199e 100644 --- a/src/main/java/betterquesting/api2/supporter/SupporterAPI.java +++ b/src/main/java/betterquesting/api2/supporter/SupporterAPI.java @@ -3,6 +3,7 @@ import betterquesting.api.api.QuestingAPI; import betterquesting.api.utils.JsonHelper; import betterquesting.client.themes.ResourceTheme; +import betterquesting.core.BetterQuesting; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; @@ -18,232 +19,219 @@ import java.awt.image.BufferedImage; import java.io.*; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -public class SupporterAPI -{ - private static Gson GSON = new GsonBuilder().create(); // No pretty print - private static final String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv0123456789"; - private static final Random rand = new Random(); - - @Nullable - public static JsonObject readManifest(File loc) - { - try(DataInputStream dis = new DataInputStream(new GZIPInputStream(new FileInputStream(loc)))) - { - return GSON.fromJson(new String(Base64.getDecoder().decode(dis.readUTF())), JsonObject.class); - } catch(Exception ignored){ return null; } - } - - public static ResourceTheme readCompressedFile(File loc) - { - // Yes this obscurity not security. No I don't really care for your opinion. Leave me alone to tinker in peace... - // Reversing this isn't necessarily hard but it takes more effort than just making a new theme or donating a dollar - - // Manifest is in charge of constructing this class and checking if the supporter goals were met before install. - // By this point the file should have been approved so if this fails something is wrong or tampered with. - - try(DataInputStream dis = new DataInputStream(new GZIPInputStream(new FileInputStream(loc)))) - { - JsonObject manifest = GSON.fromJson(new String(Base64.getDecoder().decode(dis.readUTF()), StandardCharsets.UTF_8), JsonObject.class); - - int format = JsonHelper.GetNumber(manifest, "format", 0).intValue(); - ResourceLocation parID = manifest.has("parentID") ? new ResourceLocation(JsonHelper.GetString(manifest, "parentID", "minecraft:null")) : null; - ResourceLocation thmID = new ResourceLocation(JsonHelper.GetString(manifest, "themeID", "betterquesting:untitled")); - String thmName = JsonHelper.GetString(manifest, "themeName", "Untitled Theme"); - - ResourceTheme theme = new ResourceTheme(parID, thmID, thmName); - - // Subject to change depending on format - byte[] fileKey = readFileKey(dis, format); - - // Read out first but not applied until the remaining textures have been loaded so fallbacks kick in for missing things - JsonObject themeJson = GSON.fromJson(decode(dis.readUTF(), fileKey), JsonObject.class); - - int numTex = dis.readInt(); - for(int n = 0; n < numTex; n++) - { - ResourceLocation resID = new ResourceLocation(decode(dis.readUTF(), fileKey)); - int w = dis.readInt(); - int h = dis.readInt(); - int[] rgb = new int[w * h]; - for(int i = 0; i < rgb.length; i++) - { - int flip = fileKey[(i * 4) % fileKey.length]; - flip |= fileKey[(i * 4 + 1) % fileKey.length] << 8; - flip |= fileKey[(i * 4 + 2) % fileKey.length] << 16; - flip |= fileKey[(i * 4 + 3) % fileKey.length] << 24; - rgb[i] = dis.readInt() ^ flip; - } - final RgbTexture texture = new RgbTexture(w, h, rgb); - Minecraft.getMinecraft().addScheduledTask(() -> Minecraft.getMinecraft().getTextureManager().loadTexture(resID, texture)); - } - - // TODO: Support other resource types? - - theme.loadFromJson(themeJson); - return theme; - } catch(Exception ignored){} // I'm not telling you why. You should know if you got this far - return null; - } - - public static void buildCompressedFile(File fileOut, JsonObject jsonDetails, JsonObject jsonTheme, Collection> textures, String token, String service, int tier) - { - if(fileOut.exists()) - { - try - { - fileOut.delete(); - } catch(Exception ignored){} - } - - try(DataOutputStream dos = new DataOutputStream(new GZIPOutputStream(new FileOutputStream(fileOut)))) - { - int format = JsonHelper.GetNumber(jsonDetails, "format", 0).intValue(); - - dos.writeUTF(Base64.getEncoder().encodeToString(GSON.toJson(jsonDetails).getBytes(StandardCharsets.UTF_8))); - - final byte[] key = format == 0 ? makeFormat_0(dos, rand.nextLong()) : makeFormat_1(dos, token, 3 + rand.nextInt(6), service, tier); - - dos.writeUTF(encode(GSON.toJson(jsonTheme), key)); - - dos.writeInt(textures.size()); // Texture count - - for(Tuple t : textures) - { - dos.writeUTF(encode(t.getFirst().toString(), key)); - BufferedImage bufImg = ImageIO.read(t.getSecond()); - int[] rgb = bufImg.getRGB(0, 0, bufImg.getWidth(), bufImg.getHeight(), null, 0, bufImg.getWidth()); - dos.writeInt(bufImg.getWidth()); - dos.writeInt(bufImg.getHeight()); - for(int i = 0; i < rgb.length; i++) - { - int flip = key[(i * 4) % key.length]; - flip |= key[(i * 4 + 1) % key.length] << 8; - flip |= key[(i * 4 + 2) % key.length] << 16; - flip |= key[(i * 4 + 3) % key.length] << 24; - dos.writeInt(rgb[i] ^ flip); - } - } - } catch(Exception e) - { - e.printStackTrace(); - } - } - - private static String encode(String s, byte[] key) - { - return Base64.getEncoder().encodeToString(flipBytes(s.getBytes(StandardCharsets.UTF_8), key)); - } - - private static String decode(String s, byte[] key) - { - return new String(flipBytes(Base64.getDecoder().decode(s), key), StandardCharsets.UTF_8); - } - - private static byte[] flipBytes(@Nonnull byte[] input, @Nonnull byte[] key) - { - byte[] output = new byte[input.length]; - for(int i = 0; i < input.length; i++) output[i] = (byte)(input[i] ^ key[i % key.length]); - return output; - } - - private static byte[] makeFormat_0(@Nonnull DataOutputStream dos, long seed) throws IOException - { - byte[] b = new byte[16]; - new Random(seed).nextBytes(b); - dos.writeLong(seed); - return b; - } - - private static byte[] makeFormat_1(@Nonnull DataOutputStream dos, @Nonnull String token, int salts, String service, int threshold) throws IOException - { - List> list = new ArrayList<>(); - list.add(new Tuple<>(true, token)); - for(int i = 0; i < salts; i++) - { - StringBuilder sb = new StringBuilder(); - for(int j = rand.nextInt(9) + 16; j >= 0; j--) sb.append(charSet.charAt(rand.nextInt(charSet.length()))); - list.add(new Tuple<>(false,sb.toString())); +public class SupporterAPI { + private static final Gson GSON = new GsonBuilder().create(); // No pretty print + private static final String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv0123456789"; + private static final Random rand = new Random(); + + @Nullable + public static JsonObject readManifest(File loc) { + try (DataInputStream dis = new DataInputStream(new GZIPInputStream(Files.newInputStream(loc.toPath())))) { + return GSON.fromJson(new String(Base64.getDecoder().decode(dis.readUTF())), JsonObject.class); + } catch (Exception ignored) { return null; } + } + + public static ResourceTheme readCompressedFile(File loc) { + // Yes this obscurity not security. No I don't really care for your opinion. Leave me alone to tinker in peace... + // Reversing this isn't necessarily hard but it takes more effort than just making a new theme or donating a dollar + + // Manifest is in charge of constructing this class and checking if the supporter goals were met before install. + // By this point the file should have been approved so if this fails something is wrong or tampered with. + + try (DataInputStream dis = new DataInputStream(new GZIPInputStream(Files.newInputStream(loc.toPath())))) { + JsonObject manifest = GSON.fromJson(new String(Base64.getDecoder().decode(dis.readUTF()), StandardCharsets.UTF_8), + JsonObject.class); + + int format = JsonHelper.GetNumber(manifest, "format", 0).intValue(); + ResourceLocation parID = + manifest.has("parentID") ? new ResourceLocation(JsonHelper.GetString(manifest, "parentID", "minecraft:null")) + : null; + ResourceLocation thmID = + new ResourceLocation(JsonHelper.GetString(manifest, "themeID", "betterquesting:untitled")); + String thmName = JsonHelper.GetString(manifest, "themeName", "Untitled Theme"); + + ResourceTheme theme = new ResourceTheme(parID, thmID, thmName); + + // Subject to change depending on format + byte[] fileKey = readFileKey(dis, format); + + // Read out first but not applied until the remaining textures have been loaded so fallbacks kick in for missing things + JsonObject themeJson = GSON.fromJson(decode(dis.readUTF(), fileKey), JsonObject.class); + + int numTex = dis.readInt(); + for (int n = 0; n < numTex; n++) { + ResourceLocation resID = new ResourceLocation(decode(dis.readUTF(), fileKey)); + int w = dis.readInt(); + int h = dis.readInt(); + int[] rgb = new int[w * h]; + for (int i = 0; i < rgb.length; i++) { + int flip = fileKey[(i * 4) % fileKey.length]; + flip |= fileKey[(i * 4 + 1) % fileKey.length] << 8; + flip |= fileKey[(i * 4 + 2) % fileKey.length] << 16; + flip |= fileKey[(i * 4 + 3) % fileKey.length] << 24; + rgb[i] = dis.readInt() ^ flip; } - Collections.shuffle(list,rand); - return makeFormat_1(dos, list, service, threshold); + final RgbTexture texture = new RgbTexture(w, h, rgb); + Minecraft.getMinecraft() + .addScheduledTask(() -> Minecraft.getMinecraft().getTextureManager().loadTexture(resID, texture)); + } + + // TODO: Support other resource types? + + theme.loadFromJson(themeJson); + return theme; + } catch (Exception ignored) { } // I'm not telling you why. You should know if you got this far + return null; + } + + public static void buildCompressedFile(File fileOut, JsonObject jsonDetails, JsonObject jsonTheme, + Collection> textures, String token, + String service, int tier) { + if (fileOut.exists()) { + try { + fileOut.delete(); + } catch (Exception ignored) { } } - - private static byte[] makeFormat_1(@Nonnull DataOutputStream dos, @Nonnull Collection> tokens, String service, int threshold) throws IOException - { - dos.writeInt(tokens.size()); - int s = 0; - Set l = new HashSet<>(); - for(Tuple t : tokens) - { - byte[] b = t.getFirst() ? t.getSecond().getBytes(StandardCharsets.UTF_8) : new byte[16]; - if(!t.getFirst()) new Random(t.getSecond().hashCode()).nextBytes(b); - l.add(b); - if(s < b.length) s = b.length; - dos.writeUTF(Base64.getEncoder().encodeToString(t.getSecond().getBytes(StandardCharsets.UTF_8))); + + try (DataOutputStream dos = new DataOutputStream(new GZIPOutputStream(Files.newOutputStream(fileOut.toPath())))) { + int format = JsonHelper.GetNumber(jsonDetails, "format", 0).intValue(); + + dos.writeUTF(Base64.getEncoder().encodeToString(GSON.toJson(jsonDetails).getBytes(StandardCharsets.UTF_8))); + + final byte[] key = format == 0 ? makeFormat_0(dos, rand.nextLong()) + : makeFormat_1(dos, token, 3 + rand.nextInt(6), service, tier); + + dos.writeUTF(encode(GSON.toJson(jsonTheme), key)); + + dos.writeInt(textures.size()); // Texture count + + for (Tuple t : textures) { + dos.writeUTF(encode(t.getFirst().toString(), key)); + BufferedImage bufImg = ImageIO.read(t.getSecond()); + int[] rgb = bufImg.getRGB(0, 0, bufImg.getWidth(), bufImg.getHeight(), null, 0, bufImg.getWidth()); + dos.writeInt(bufImg.getWidth()); + dos.writeInt(bufImg.getHeight()); + for (int i = 0; i < rgb.length; i++) { + int flip = key[(i * 4) % key.length]; + flip |= key[(i * 4 + 1) % key.length] << 8; + flip |= key[(i * 4 + 2) % key.length] << 16; + flip |= key[(i * 4 + 3) % key.length] << 24; + dos.writeInt(rgb[i] ^ flip); } - - dos.writeUTF(Base64.getEncoder().encodeToString(service.getBytes(StandardCharsets.UTF_8))); - dos.writeInt(threshold); - - byte[] k = new byte[s]; - for(int i = 0; i < s; i++) for(byte[] e : l) k[i] ^= e[i % e.length]; - return k; + } + } catch (Exception e) { + BetterQuesting.logger.warn(e); } - - @SideOnly(Side.CLIENT) - private static byte[] readFileKey(@Nonnull DataInputStream dis, int format) - { - switch(format) - { - case -1: return new byte[] {127}; - case 0: return readFormat_0(dis); - case 1: return readFormat_1(dis); - default: return new byte[]{ 127}; - } + } + + private static String encode(String s, byte[] key) { + return Base64.getEncoder().encodeToString(flipBytes(s.getBytes(StandardCharsets.UTF_8), key)); + } + + private static String decode(String s, byte[] key) { + return new String(flipBytes(Base64.getDecoder().decode(s), key), StandardCharsets.UTF_8); + } + + private static byte[] flipBytes(@Nonnull byte[] input, @Nonnull byte[] key) { + byte[] output = new byte[input.length]; + for (int i = 0; i < input.length; i++) { output[i] = (byte) (input[i] ^ key[i % key.length]); } + return output; + } + + private static byte[] makeFormat_0(@Nonnull DataOutputStream dos, long seed) throws IOException { + byte[] b = new byte[16]; + new Random(seed).nextBytes(b); + dos.writeLong(seed); + return b; + } + + private static byte[] makeFormat_1(@Nonnull DataOutputStream dos, @Nonnull String token, int salts, String service, + int threshold) throws IOException { + List> list = new ArrayList<>(); + list.add(new Tuple<>(true, token)); + for (int i = 0; i < salts; i++) { + StringBuilder sb = new StringBuilder(); + for (int j = rand.nextInt(9) + 16; j >= 0; j--) { sb.append(charSet.charAt(rand.nextInt(charSet.length()))); } + list.add(new Tuple<>(false, sb.toString())); } - - private static byte[] readFormat_0(@Nonnull DataInputStream dis) - { - try - { - byte[] b = new byte[16]; - long seed = dis.readLong(); - new Random(seed).nextBytes(b); - return b; - } catch(Exception ignored) { return new byte[]{127}; } + Collections.shuffle(list, rand); + return makeFormat_1(dos, list, service, threshold); + } + + private static byte[] makeFormat_1(@Nonnull DataOutputStream dos, @Nonnull Collection> tokens, + String service, int threshold) throws IOException { + dos.writeInt(tokens.size()); + int s = 0; + Set l = new HashSet<>(); + for (Tuple t : tokens) { + byte[] b = t.getFirst() ? t.getSecond().getBytes(StandardCharsets.UTF_8) : new byte[16]; + if (!t.getFirst()) { new Random(t.getSecond().hashCode()).nextBytes(b); } + l.add(b); + if (s < b.length) { s = b.length; } + dos.writeUTF(Base64.getEncoder().encodeToString(t.getSecond().getBytes(StandardCharsets.UTF_8))); } - - @SideOnly(Side.CLIENT) - private static byte[] readFormat_1(@Nonnull DataInputStream dis) - { - try - { - String[] tokens = new String[dis.readInt()]; - for(int n = 0; n < tokens.length; n++) tokens[n] = new String(Base64.getDecoder().decode(dis.readUTF())); - String service = new String(Base64.getDecoder().decode(dis.readUTF())); - int threshold = dis.readInt(); - - UUID playerID = QuestingAPI.getQuestingUUID(Minecraft.getMinecraft().player); - SupporterEntry entry = SupporterDB.INSTANCE.getValue(playerID); - - int m = 0; - Set encoded = new HashSet<>(); - for(String k : tokens) - { - boolean c = entry != null && entry.getServices(k).entrySet().stream().anyMatch((v) -> v.getKey().equals(service) && v.getValue() >= threshold); - byte[] b = c ? k.getBytes(StandardCharsets.UTF_8) : new byte[16]; - if(c) new Random(k.hashCode()).nextBytes(b); - encoded.add(b); - if(b.length > m) m = b.length; - } - - byte[] merged = new byte[m]; - for(int i = 0; i < m; i++) for(byte[] e : encoded) merged[i] ^= e[i % e.length]; - return merged; - } catch(Exception ignored) { return new byte[]{127}; } + + dos.writeUTF(Base64.getEncoder().encodeToString(service.getBytes(StandardCharsets.UTF_8))); + dos.writeInt(threshold); + + byte[] k = new byte[s]; + for (int i = 0; i < s; i++) { for (byte[] e : l) { k[i] ^= e[i % e.length]; } } + return k; + } + + @SideOnly(Side.CLIENT) + private static byte[] readFileKey(@Nonnull DataInputStream dis, int format) { + switch (format) { + case -1: + return new byte[] { 127 }; + case 0: + return readFormat_0(dis); + case 1: + return readFormat_1(dis); + default: + return new byte[] { 127 }; } + } + + private static byte[] readFormat_0(@Nonnull DataInputStream dis) { + try { + byte[] b = new byte[16]; + long seed = dis.readLong(); + new Random(seed).nextBytes(b); + return b; + } catch (Exception ignored) { return new byte[] { 127 }; } + } + + @SideOnly(Side.CLIENT) + private static byte[] readFormat_1(@Nonnull DataInputStream dis) { + try { + String[] tokens = new String[dis.readInt()]; + for (int n = 0; n < tokens.length; n++) { tokens[n] = new String(Base64.getDecoder().decode(dis.readUTF())); } + String service = new String(Base64.getDecoder().decode(dis.readUTF())); + int threshold = dis.readInt(); + + UUID playerID = QuestingAPI.getQuestingUUID(Minecraft.getMinecraft().player); + SupporterEntry entry = SupporterDB.INSTANCE.getValue(playerID); + + int m = 0; + Set encoded = new HashSet<>(); + for (String k : tokens) { + boolean c = entry != null && entry.getServices(k).entrySet().stream() + .anyMatch((v) -> v.getKey().equals(service) && v.getValue() >= threshold); + byte[] b = c ? k.getBytes(StandardCharsets.UTF_8) : new byte[16]; + if (c) { new Random(k.hashCode()).nextBytes(b); } + encoded.add(b); + if (b.length > m) { m = b.length; } + } + + byte[] merged = new byte[m]; + for (int i = 0; i < m; i++) { for (byte[] e : encoded) { merged[i] ^= e[i % e.length]; } } + return merged; + } catch (Exception ignored) { return new byte[] { 127 }; } + } } diff --git a/src/main/java/betterquesting/api2/supporter/SupporterDB.java b/src/main/java/betterquesting/api2/supporter/SupporterDB.java index e1df9cbfb..ec0aa5fa4 100644 --- a/src/main/java/betterquesting/api2/supporter/SupporterDB.java +++ b/src/main/java/betterquesting/api2/supporter/SupporterDB.java @@ -9,33 +9,28 @@ import java.util.TreeMap; import java.util.UUID; -public class SupporterDB implements INBTSaveLoad -{ - public static final SupporterDB INSTANCE = new SupporterDB(); - - private final TreeMap mapDB = new TreeMap<>(); - - public synchronized SupporterEntry add(@Nonnull UUID playerID) - { - SupporterEntry entry = new SupporterEntry(); - if(mapDB.putIfAbsent(playerID, entry) != null) - { - BetterQuesting.logger.warn("Tried to add duplicate supporter to DB: " + playerID.toString()); - return mapDB.get(playerID); - } - return entry; - } - - public synchronized boolean removeID(@Nonnull UUID playerID) - { - return mapDB.remove(playerID) != null; - } - - @Nullable - public synchronized SupporterEntry getValue(@Nonnull UUID playerID) - { - return mapDB.get(playerID); +public class SupporterDB implements INBTSaveLoad { + public static final SupporterDB INSTANCE = new SupporterDB(); + + private final TreeMap mapDB = new TreeMap<>(); + + public synchronized SupporterEntry add(@Nonnull UUID playerID) { + SupporterEntry entry = new SupporterEntry(); + if (mapDB.putIfAbsent(playerID, entry) != null) { + BetterQuesting.logger.warn("Tried to add duplicate supporter to DB: " + playerID); + return mapDB.get(playerID); } + return entry; + } + + public synchronized boolean removeID(@Nonnull UUID playerID) { + return mapDB.remove(playerID) != null; + } + + @Nullable + public synchronized SupporterEntry getValue(@Nonnull UUID playerID) { + return mapDB.get(playerID); + } /*@Nullable public UUID getKey(@Nonnull SupporterEntry entry) @@ -47,26 +42,23 @@ public UUID getKey(@Nonnull SupporterEntry entry) return null; }*/ - - @Nonnull - @Override - public synchronized NBTTagCompound writeToNBT(@Nonnull NBTTagCompound nbt) - { - mapDB.forEach((key, value) -> nbt.setTag(key.toString(), value.writeToNBT(new NBTTagCompound()))); - return nbt; - } - - @Override - public synchronized void readFromNBT(@Nonnull NBTTagCompound nbt) - { - mapDB.clear(); - nbt.getKeySet().forEach((key) -> { - try - { - SupporterEntry entry = new SupporterEntry(); - entry.readFromNBT(nbt.getCompoundTag(key)); - mapDB.put(UUID.fromString(key), entry); - } catch(Exception ignored){} - }); - } + + @Nonnull + @Override + public synchronized NBTTagCompound writeToNBT(@Nonnull NBTTagCompound nbt) { + mapDB.forEach((key, value) -> nbt.setTag(key.toString(), value.writeToNBT(new NBTTagCompound()))); + return nbt; + } + + @Override + public synchronized void readFromNBT(@Nonnull NBTTagCompound nbt) { + mapDB.clear(); + nbt.getKeySet().forEach((key) -> { + try { + SupporterEntry entry = new SupporterEntry(); + entry.readFromNBT(nbt.getCompoundTag(key)); + mapDB.put(UUID.fromString(key), entry); + } catch (Exception ignored) { } + }); + } } diff --git a/src/main/java/betterquesting/api2/supporter/SupporterEntry.java b/src/main/java/betterquesting/api2/supporter/SupporterEntry.java index 71b2c6685..b9161b18c 100644 --- a/src/main/java/betterquesting/api2/supporter/SupporterEntry.java +++ b/src/main/java/betterquesting/api2/supporter/SupporterEntry.java @@ -6,25 +6,21 @@ import javax.annotation.Nonnull; import java.util.HashMap; -public class SupporterEntry implements INBTSaveLoad -{ - private final HashMap> services = new HashMap<>(); - - @Nonnull - public HashMap getServices(@Nonnull String token) - { - return this.services.computeIfAbsent(token, (t) -> new HashMap<>()); - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) - { - return nbt; - } - - @Override - public void readFromNBT(NBTTagCompound nbt) - { - - } +public class SupporterEntry implements INBTSaveLoad { + private final HashMap> services = new HashMap<>(); + + @Nonnull + public HashMap getServices(@Nonnull String token) { + return this.services.computeIfAbsent(token, (t) -> new HashMap<>()); + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + return nbt; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java b/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java index e54294c80..3ae335e54 100644 --- a/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java +++ b/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java @@ -2,16 +2,14 @@ import javax.annotation.Nonnull; -public enum McLinkEndpoint -{ - API_AUTH("https://mclink.dries007.net/api/1/authenticate"), - API_INFO("https://mclink.dries007.net/api/1/info"), - API_STATUS("https://mclink.dries007.net/api/1/status"); - - public final String URL; - - McLinkEndpoint(@Nonnull String url) - { - this.URL = url; - } +public enum McLinkEndpoint { + API_AUTH("https://mclink.dries007.net/api/1/authenticate"), + API_INFO("https://mclink.dries007.net/api/1/info"), + API_STATUS("https://mclink.dries007.net/api/1/status"); + + public final String URL; + + McLinkEndpoint(@Nonnull String url) { + this.URL = url; + } } diff --git a/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java b/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java index 20f10f28e..649644920 100644 --- a/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java +++ b/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java @@ -12,65 +12,59 @@ import java.util.List; import java.util.concurrent.Future; -public class CatalogueEntry -{ - public final String author; - public final String name; - public final ResourceLocation themeID; - public final String downloadLink; - - public final List reqMods = new ArrayList<>(); - public final List reqThemes = new ArrayList<>(); - - private String token; - private String service; - private int subTier; - private String subLink; - - public CatalogueEntry(String author, String themeName, String themeID, String downloadLink, String subLink) - { - this.author = author; - this.name = themeName; - this.themeID = new ResourceLocation(themeID); - this.downloadLink = downloadLink; - this.subLink = subLink; - } - - public CatalogueEntry setRequirement(@Nonnull String token, @Nonnull String service, int amount, @Nonnull String subLink) - { - this.token = token; - this.service = service; - this.subTier = amount; - this.subLink = subLink; - return this; - } - - public CatalogueEntry(@Nonnull JsonObject json) - { - this.author = JsonHelper.GetString(json, "author", "Unknown"); - this.name = JsonHelper.GetString(json, "themeName", "Untitled"); - this.themeID = new ResourceLocation(JsonHelper.GetString(json, "themeID", "minecraft:untitled")); - this.downloadLink = JsonHelper.GetString(json, "themeID", "127.0.0.1"); - - reqMods.clear(); - JsonArray aryMods = JsonHelper.GetArray(json, "reqMods"); - for(JsonElement je : aryMods) - { - if(!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) continue; - reqMods.add(je.getAsString()); - } - - reqMods.clear(); - JsonArray aryThms = JsonHelper.GetArray(json, "reqThemes"); - for(JsonElement je : aryThms) - { - if(!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) continue; - reqThemes.add(je.getAsString()); - } +public class CatalogueEntry { + public final String author; + public final String name; + public final ResourceLocation themeID; + public final String downloadLink; + + public final List reqMods = new ArrayList<>(); + public final List reqThemes = new ArrayList<>(); + + private String token; + private String service; + private int subTier; + private String subLink; + + public CatalogueEntry(String author, String themeName, String themeID, String downloadLink, String subLink) { + this.author = author; + this.name = themeName; + this.themeID = new ResourceLocation(themeID); + this.downloadLink = downloadLink; + this.subLink = subLink; + } + + public CatalogueEntry setRequirement(@Nonnull String token, @Nonnull String service, int amount, + @Nonnull String subLink) { + this.token = token; + this.service = service; + this.subTier = amount; + this.subLink = subLink; + return this; + } + + public CatalogueEntry(@Nonnull JsonObject json) { + this.author = JsonHelper.GetString(json, "author", "Unknown"); + this.name = JsonHelper.GetString(json, "themeName", "Untitled"); + this.themeID = new ResourceLocation(JsonHelper.GetString(json, "themeID", "minecraft:untitled")); + this.downloadLink = JsonHelper.GetString(json, "themeID", "127.0.0.1"); + + reqMods.clear(); + JsonArray aryMods = JsonHelper.GetArray(json, "reqMods"); + for (JsonElement je : aryMods) { + if (!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) { continue; } + reqMods.add(je.getAsString()); } - - public Future downloadTheme() - { - return null; + + reqMods.clear(); + JsonArray aryThms = JsonHelper.GetArray(json, "reqThemes"); + for (JsonElement je : aryThms) { + if (!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) { continue; } + reqThemes.add(je.getAsString()); } + } + + public Future downloadTheme() { + return null; + } } diff --git a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java index e1ecebcc6..29d8a4899 100644 --- a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java +++ b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java @@ -3,21 +3,17 @@ import java.util.ArrayList; import java.util.List; -public class ThemeCatalogue -{ - private static final List catUrls = new ArrayList<>(); - - - - // Download database of DLC themes - public static void refreshCatalogue() - { - - } - - // Update the refresh the local DLC themes - public static void refreshManifests() - { - - } +public class ThemeCatalogue { + private static final List catUrls = new ArrayList<>(); + + + // Download database of DLC themes + public static void refreshCatalogue() { + + } + + // Update the refresh the local DLC themes + public static void refreshManifests() { + + } } diff --git a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java index 882489ff5..c2c967e7a 100644 --- a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java +++ b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java @@ -8,30 +8,25 @@ import java.util.Collections; import java.util.List; -public class ThemeRepository -{ - private final String repoAddress; - public String repoName = "Unknown Theme Repository"; - - private final List entries = new ArrayList<>(); - - public ThemeRepository(@Nonnull String address) - { - repoAddress = address; - } - - public String getAddress() - { - return this.repoAddress; - } - - public List getEntries() - { - return Collections.unmodifiableList(entries); - } - - public void loadRepository(@Nonnull JsonObject json) - { - repoName = JsonHelper.GetString(json, "repoName", "Unknown Repository"); - } +public class ThemeRepository { + private final String repoAddress; + public String repoName = "Unknown Theme Repository"; + + private final List entries = new ArrayList<>(); + + public ThemeRepository(@Nonnull String address) { + repoAddress = address; + } + + public String getAddress() { + return this.repoAddress; + } + + public List getEntries() { + return Collections.unmodifiableList(entries); + } + + public void loadRepository(@Nonnull JsonObject json) { + repoName = JsonHelper.GetString(json, "repoName", "Unknown Repository"); + } } diff --git a/src/main/java/betterquesting/api2/utils/BQThreadedIO.java b/src/main/java/betterquesting/api2/utils/BQThreadedIO.java index 9c8622a42..6e5274238 100644 --- a/src/main/java/betterquesting/api2/utils/BQThreadedIO.java +++ b/src/main/java/betterquesting/api2/utils/BQThreadedIO.java @@ -5,53 +5,42 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -public class BQThreadedIO -{ - public static final BQThreadedIO INSTANCE = new BQThreadedIO(); - - private ExecutorService exService; - - public BQThreadedIO() - { - this.init(); - } - - public void init() - { - if(exService == null || exService.isShutdown()) - { - exService = Executors.newSingleThreadExecutor(); - } - } - - public void shutdown() - { - exService.shutdownNow(); +public class BQThreadedIO { + public static final BQThreadedIO INSTANCE = new BQThreadedIO(); + + private ExecutorService exService; + + public BQThreadedIO() { + this.init(); + } + + public void init() { + if (exService == null || exService.isShutdown()) { + exService = Executors.newSingleThreadExecutor(); } - - public void enqueue(Runnable job) - { - if(exService == null || exService.isShutdown()) - { - throw new RuntimeException("Attempted to schedule task before service was initialised!"); - } else if(job == null) - { - throw new NullPointerException("Attempted to schedule null job!"); - } - - exService.submit(job); + } + + public void shutdown() { + exService.shutdownNow(); + } + + public void enqueue(Runnable job) { + if (exService == null || exService.isShutdown()) { + throw new RuntimeException("Attempted to schedule task before service was initialised!"); + } else if (job == null) { + throw new NullPointerException("Attempted to schedule null job!"); } - - public Future enqueue(Callable job) - { - if(exService == null || exService.isShutdown()) - { - throw new RuntimeException("Attempted to schedule task before service was initialised!"); - } else if(job == null) - { - throw new NullPointerException("Attempted to schedule null job!"); - } - - return exService.submit(job); + + exService.submit(job); + } + + public Future enqueue(Callable job) { + if (exService == null || exService.isShutdown()) { + throw new RuntimeException("Attempted to schedule task before service was initialised!"); + } else if (job == null) { + throw new NullPointerException("Attempted to schedule null job!"); } + + return exService.submit(job); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/utils/BqFontRenderer.java b/src/main/java/betterquesting/api2/utils/BqFontRenderer.java index 31831fcd0..0cd6543d4 100644 --- a/src/main/java/betterquesting/api2/utils/BqFontRenderer.java +++ b/src/main/java/betterquesting/api2/utils/BqFontRenderer.java @@ -7,278 +7,233 @@ import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; -public class BqFontRenderer extends FontRenderer -{ - public static final BqFontRenderer FONT_UNICODE = new BqFontRenderer(true); - public static final BqFontRenderer FONT_STANDARD = new BqFontRenderer(false); - - private static final ResourceLocation[] UNICODE_PAGE_LOCATIONS = new ResourceLocation[256]; - - private boolean isSmall = false; - - public BqFontRenderer(boolean unicode) - { - super(Minecraft.getMinecraft().gameSettings, new ResourceLocation("minecraft:textures/font/ascii.png"), Minecraft.getMinecraft().renderEngine, unicode); - ((IReloadableResourceManager)Minecraft.getMinecraft().getResourceManager()).registerReloadListener(this); +import javax.annotation.Nonnull; + +public class BqFontRenderer extends FontRenderer { + public static final BqFontRenderer FONT_UNICODE = new BqFontRenderer(true); + public static final BqFontRenderer FONT_STANDARD = new BqFontRenderer(false); + + private static final ResourceLocation[] UNICODE_PAGE_LOCATIONS = new ResourceLocation[256]; + + private boolean isSmall = false; + + public BqFontRenderer(boolean unicode) { + super(Minecraft.getMinecraft().gameSettings, new ResourceLocation("minecraft:textures/font/ascii.png"), + Minecraft.getMinecraft().renderEngine, unicode); + ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(this); + } + + @Override + public int drawString(@Nonnull String text, float x, float y, int color, boolean dropShadow) { + return drawStringScaled(text, x, y, color, dropShadow, 1F); + } + + public int drawStringScaled(String text, float x, float y, int color, boolean shadow, float scale) { + if (scale <= 0F) { return 0; } + + Minecraft mc = Minecraft.getMinecraft(); + + if (scale == 1F && !(mc.gameSettings.guiScale > 0 && mc.gameSettings.guiScale < 3)) { + isSmall = false; + return super.drawString(text, x, y, color, shadow); + } else { + isSmall = (mc.gameSettings.guiScale > 0 && mc.gameSettings.guiScale < 3) || scale <= 0.5F; + + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y, 0F); + GlStateManager.scale(scale, scale, 0F); + + int r = super.drawString(text, 0, 0, color, shadow); + + GlStateManager.popMatrix(); + + return r; } - - @Override - public int drawString(String text, float x, float y, int color, boolean dropShadow) - { - return drawStringScaled(text, x, y, color, dropShadow, 1F); + } + + @Override + protected float renderUnicodeChar(char ch, boolean italic) { + int i = this.glyphWidth[ch] & 255; + + if (i == 0) { + return 0.0F; + } else { + int j = ch / 256; + this.loadGlyphTexture(j); + int k = i >>> 4; + int l = i & 15; + double f = k; + double f1 = l + 1; + double f2 = (double) (ch % 16 * 16) + f; + double f3 = (ch & 255) / 16 * 16; + double f4 = f1 - f - 0.02D; + double f5 = italic ? 1.0D : 0.0D; + double ys = 7.99D; + + if (isSmall) { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); + } + + //GlStateManager.glTexCoord2f(f2 / 256.0F, f3 / 256.0F); + //GlStateManager.glVertex3f(this.posX + f5, this.posY, 0.0F); + //GlStateManager.glTexCoord2f(f2 / 256.0F, (f3 + 15.98F) / 256.0F); + //GlStateManager.glVertex3f(this.posX - f5, this.posY + ys, 0.0F); + //GlStateManager.glTexCoord2f((f2 + f4) / 256.0F, f3 / 256.0F); + //GlStateManager.glVertex3f(this.posX + f4 / 2.0F + f5, this.posY, 0.0F); + //GlStateManager.glTexCoord2f((f2 + f4) / 256.0F, (f3 + 15.98F) / 256.0F); + //GlStateManager.glVertex3f(this.posX + f4 / 2.0F - f5, this.posY + ys, 0.0F); + + GlStateManager.glBegin(GL11.GL_TRIANGLE_STRIP); + GL11.glTexCoord2d(f2 / 256.0D, f3 / 256.0D); + GL11.glVertex3d(this.posX + f5, this.posY, 0.0D); + GL11.glTexCoord2d(f2 / 256.0D, (f3 + 15.98D) / 256.0D); + GL11.glVertex3d(this.posX - f5, this.posY + ys, 0.0D); + GL11.glTexCoord2d((f2 + f4) / 256.0D, f3 / 256.0D); + GL11.glVertex3d(this.posX + f4 / 2.0D + f5, this.posY, 0.0D); + GL11.glTexCoord2d((f2 + f4) / 256.0D, (f3 + 15.98D) / 256.0D); + GL11.glVertex3d(this.posX + f4 / 2.0D - f5, this.posY + ys, 0.0D); + GlStateManager.glEnd(); + + if (isSmall) { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); + } + + return (float) ((f1 - f) / 2.0D + 1.0D); } - - public int drawStringScaled(String text, float x, float y, int color, boolean shadow, float scale) - { - if(scale <= 0F) return 0; - - Minecraft mc = Minecraft.getMinecraft(); - - if(scale == 1F && !(mc.gameSettings.guiScale > 0 && mc.gameSettings.guiScale < 3)) - { - isSmall = false; - return super.drawString(text, x, y, color, shadow); - } else - { - isSmall = (mc.gameSettings.guiScale > 0 && mc.gameSettings.guiScale < 3) || scale <= 0.5F; - - GlStateManager.pushMatrix(); - GlStateManager.translate(x, y, 0F); - GlStateManager.scale(scale, scale, 0F); - - int r = super.drawString(text, 0, 0, color, shadow); - - GlStateManager.popMatrix(); - - return r; - } + } + + @Override + protected float renderDefaultChar(int ch, boolean italic) { + int i = ch % 16 * 8; + int j = ch / 16 * 8; + int k = italic ? 1 : 0; + bindTexture(this.locationFontTexture); + int l = this.charWidth[ch]; + float f = (float) l - 0.01F; + + if (isSmall) { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); } - - @Override - protected float renderUnicodeChar(char ch, boolean italic) - { - int i = this.glyphWidth[ch] & 255; - - if (i == 0) - { - return 0.0F; - } - else - { - int j = ch / 256; - this.loadGlyphTexture(j); - int k = i >>> 4; - int l = i & 15; - double f = (double)k; - double f1 = (double)(l + 1); - double f2 = (double)(ch % 16 * 16) + f; - double f3 = (double)((ch & 255) / 16 * 16); - double f4 = f1 - f - 0.02D; - double f5 = italic ? 1.0D : 0.0D; - double ys = 7.99D; - - if(isSmall) - { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - } - - //GlStateManager.glTexCoord2f(f2 / 256.0F, f3 / 256.0F); - //GlStateManager.glVertex3f(this.posX + f5, this.posY, 0.0F); - //GlStateManager.glTexCoord2f(f2 / 256.0F, (f3 + 15.98F) / 256.0F); - //GlStateManager.glVertex3f(this.posX - f5, this.posY + ys, 0.0F); - //GlStateManager.glTexCoord2f((f2 + f4) / 256.0F, f3 / 256.0F); - //GlStateManager.glVertex3f(this.posX + f4 / 2.0F + f5, this.posY, 0.0F); - //GlStateManager.glTexCoord2f((f2 + f4) / 256.0F, (f3 + 15.98F) / 256.0F); - //GlStateManager.glVertex3f(this.posX + f4 / 2.0F - f5, this.posY + ys, 0.0F); - - GlStateManager.glBegin(GL11.GL_TRIANGLE_STRIP); - GL11.glTexCoord2d(f2 / 256.0D, f3 / 256.0D); - GL11.glVertex3d(this.posX + f5, this.posY, 0.0D); - GL11.glTexCoord2d(f2 / 256.0D, (f3 + 15.98D) / 256.0D); - GL11.glVertex3d(this.posX - f5, this.posY + ys, 0.0D); - GL11.glTexCoord2d((f2 + f4) / 256.0D, f3 / 256.0D); - GL11.glVertex3d(this.posX + f4 / 2.0D + f5, this.posY, 0.0D); - GL11.glTexCoord2d((f2 + f4) / 256.0D, (f3 + 15.98D) / 256.0D); - GL11.glVertex3d(this.posX + f4 / 2.0D - f5, this.posY + ys, 0.0D); - GlStateManager.glEnd(); - - if(isSmall) - { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - } - - return (float)((f1 - f) / 2.0D + 1.0D); - } + + GlStateManager.glBegin(GL11.GL_TRIANGLE_STRIP); + GlStateManager.glTexCoord2f((float) i / 128.0F, (float) j / 128.0F); + GlStateManager.glVertex3f(this.posX + (float) k, this.posY, 0.0F); + GlStateManager.glTexCoord2f((float) i / 128.0F, ((float) j + 7.99F) / 128.0F); + GlStateManager.glVertex3f(this.posX - (float) k, this.posY + 7.99F, 0.0F); + GlStateManager.glTexCoord2f(((float) i + f - 1.0F) / 128.0F, (float) j / 128.0F); + GlStateManager.glVertex3f(this.posX + f - 1.0F + (float) k, this.posY, 0.0F); + GlStateManager.glTexCoord2f(((float) i + f - 1.0F) / 128.0F, ((float) j + 7.99F) / 128.0F); + GlStateManager.glVertex3f(this.posX + f - 1.0F - (float) k, this.posY + 7.99F, 0.0F); + GlStateManager.glEnd(); + + if (isSmall) { + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); } - - @Override - protected float renderDefaultChar(int ch, boolean italic) - { - int i = ch % 16 * 8; - int j = ch / 16 * 8; - int k = italic ? 1 : 0; - bindTexture(this.locationFontTexture); - int l = this.charWidth[ch]; - float f = (float)l - 0.01F; - - if(isSmall) - { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - } - - GlStateManager.glBegin(GL11.GL_TRIANGLE_STRIP); - GlStateManager.glTexCoord2f((float)i / 128.0F, (float)j / 128.0F); - GlStateManager.glVertex3f(this.posX + (float)k, this.posY, 0.0F); - GlStateManager.glTexCoord2f((float)i / 128.0F, ((float)j + 7.99F) / 128.0F); - GlStateManager.glVertex3f(this.posX - (float)k, this.posY + 7.99F, 0.0F); - GlStateManager.glTexCoord2f(((float)i + f - 1.0F) / 128.0F, (float)j / 128.0F); - GlStateManager.glVertex3f(this.posX + f - 1.0F + (float)k, this.posY, 0.0F); - GlStateManager.glTexCoord2f(((float)i + f - 1.0F) / 128.0F, ((float)j + 7.99F) / 128.0F); - GlStateManager.glVertex3f(this.posX + f - 1.0F - (float)k, this.posY + 7.99F, 0.0F); - GlStateManager.glEnd(); - - if(isSmall) - { - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - } - - return (float)l; + + return (float) l; + } + + private ResourceLocation getUnicodePageLocation(int page) { + if (UNICODE_PAGE_LOCATIONS[page] == null) { + UNICODE_PAGE_LOCATIONS[page] = new ResourceLocation(String.format("textures/font/unicode_page_%02x.png", page)); } - - private ResourceLocation getUnicodePageLocation(int page) - { - if (UNICODE_PAGE_LOCATIONS[page] == null) - { - UNICODE_PAGE_LOCATIONS[page] = new ResourceLocation(String.format("textures/font/unicode_page_%02x.png", page)); + + return UNICODE_PAGE_LOCATIONS[page]; + } + + private void loadGlyphTexture(int page) { + bindTexture(this.getUnicodePageLocation(page)); + } + + // Fixed version of vanilla + @Nonnull + @Override + public String trimStringToWidth(@Nonnull String text, int width, boolean reverse) { + StringBuilder stringbuilder = new StringBuilder(); + int i = 0; + int j = reverse ? text.length() - 1 : 0; + int k = reverse ? -1 : 1; + boolean flag = false; + boolean flag1 = false; + + for (int l = j; l >= 0 && l < text.length() && i < width; l += k) { + char c0 = text.charAt(l); + int i1 = this.getCharWidth(c0); + + if (flag) { + flag = false; + + if (c0 != 'l' && c0 != 'L') { + if (c0 == 'r' || c0 == 'R' || isFormatColor(c0)) { + flag1 = false; + } + } else { + flag1 = true; } + } else if (i1 < 0) { + flag = true; + } else { + i += i1; - return UNICODE_PAGE_LOCATIONS[page]; - } - - private void loadGlyphTexture(int page) - { - bindTexture(this.getUnicodePageLocation(page)); - } - - // Fixed version of vanilla - @Override - public String trimStringToWidth(String text, int width, boolean reverse) - { - StringBuilder stringbuilder = new StringBuilder(); - int i = 0; - int j = reverse ? text.length() - 1 : 0; - int k = reverse ? -1 : 1; - boolean flag = false; - boolean flag1 = false; - - for (int l = j; l >= 0 && l < text.length() && i < width; l += k) - { - char c0 = text.charAt(l); - int i1 = this.getCharWidth(c0); - - if (flag) - { - flag = false; - - if (c0 != 'l' && c0 != 'L') - { - if (c0 == 'r' || c0 == 'R' || isFormatColor(c0)) - { - flag1 = false; - } - } - else - { - flag1 = true; - } - } - else if (i1 < 0) - { - flag = true; - } - else - { - i += i1; - - if (flag1) - { - ++i; - } - } - - if (i > width) - { - break; - } - - if (reverse) - { - stringbuilder.insert(0, c0); - } - else - { - stringbuilder.append(c0); - } + if (flag1) { + ++i; } + } - return stringbuilder.toString(); + if (i > width) { + break; + } + + if (reverse) { + stringbuilder.insert(0, c0); + } else { + stringbuilder.append(c0); + } } - - @Override - public int getStringWidth(String text) - { - if (text == null) - { - return 0; - } - else - { - int i = 0; - boolean flag = false; - - for (int j = 0; j < text.length(); ++j) - { - char c0 = text.charAt(j); - int k = this.getCharWidth(c0); - - if (k < 0 && j < text.length() - 1) - { - ++j; - c0 = text.charAt(j); - - if (c0 != 'l' && c0 != 'L') - { - if (c0 == 'r' || c0 == 'R' || isFormatColor(c0)) - { - flag = false; - } - } - else - { - flag = true; - } - - k = 0; - } - - i += k; - - if (flag && k > 0) - { - ++i; - } - } - - return i; + + return stringbuilder.toString(); + } + + @Override + public int getStringWidth(String text) { + int i = 0; + boolean flag = false; + + for (int j = 0; j < text.length(); ++j) { + char c0 = text.charAt(j); + int k = this.getCharWidth(c0); + + if (k < 0 && j < text.length() - 1) { + ++j; + c0 = text.charAt(j); + + if (c0 != 'l' && c0 != 'L') { + if (c0 == 'r' || c0 == 'R' || isFormatColor(c0)) { + flag = false; + } + } else { + flag = true; } + + k = 0; + } + + i += k; + + if (flag && k > 0) { + ++i; + } } - - public static boolean isFormatColor(char colorChar) - { - return colorChar >= '0' && colorChar <= '9' || colorChar >= 'a' && colorChar <= 'f' || colorChar >= 'A' && colorChar <= 'F'; - } + + return i; + } + + public static boolean isFormatColor(char colorChar) { + return colorChar >= '0' && colorChar <= '9' || colorChar >= 'a' && colorChar <= 'f' || + colorChar >= 'A' && colorChar <= 'F'; + } } diff --git a/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java b/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java index 83ac5d147..7337f5f95 100644 --- a/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java +++ b/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java @@ -1,5 +1,7 @@ package betterquesting.api2.utils; +import betterquesting.core.BetterQuesting; +import com.mojang.authlib.GameProfile; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.entity.player.EnumPlayerModelParts; import net.minecraft.util.ResourceLocation; @@ -8,56 +10,50 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import betterquesting.core.BetterQuesting; -import com.mojang.authlib.GameProfile; -public class EntityPlayerPreview extends EntityOtherPlayerMP -{ - private final ResourceLocation resource; - - /** - * Backup constructor. DO NOT USE - */ - public EntityPlayerPreview(World worldIn) - { - this(worldIn, new GameProfile(null, "Notch")); - } - - public EntityPlayerPreview(World worldIn, GameProfile gameProfileIn) - { - super(worldIn, gameProfileIn); - this.resource = new ResourceLocation(BetterQuesting.MODID, "textures/skin_cache/" + gameProfileIn.getName()); - this.getDataManager().set(PLAYER_MODEL_FLAG, (byte)1); - } - - @Override - public ResourceLocation getLocationSkin() - { - return this.resource; - } - - @Override - public ResourceLocation getLocationCape() - { - return null; - } - - @Override - public boolean hasSkin() - { - return true; - } - - @Override - public ITextComponent getDisplayName() - { - return new TextComponentString(""); - } - - @Override - @SideOnly(Side.CLIENT) - public boolean isWearing(EnumPlayerModelParts part) - { - return true; - } +import javax.annotation.Nonnull; + +public class EntityPlayerPreview extends EntityOtherPlayerMP { + private final ResourceLocation resource; + + /** + * Backup constructor. DO NOT USE + */ + public EntityPlayerPreview(World worldIn) { + this(worldIn, new GameProfile(null, "Notch")); + } + + public EntityPlayerPreview(World worldIn, GameProfile gameProfileIn) { + super(worldIn, gameProfileIn); + this.resource = new ResourceLocation(BetterQuesting.MODID, "textures/skin_cache/" + gameProfileIn.getName()); + this.getDataManager().set(PLAYER_MODEL_FLAG, (byte) 1); + } + + @Nonnull + @Override + public ResourceLocation getLocationSkin() { + return this.resource; + } + + @Override + public ResourceLocation getLocationCape() { + return null; + } + + @Override + public boolean hasSkin() { + return true; + } + + @Nonnull + @Override + public ITextComponent getDisplayName() { + return new TextComponentString(""); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isWearing(@Nonnull EnumPlayerModelParts part) { + return true; + } } diff --git a/src/main/java/betterquesting/api2/utils/ParticipantInfo.java b/src/main/java/betterquesting/api2/utils/ParticipantInfo.java index 04303e110..49f6d8dcb 100644 --- a/src/main/java/betterquesting/api2/utils/ParticipantInfo.java +++ b/src/main/java/betterquesting/api2/utils/ParticipantInfo.java @@ -14,82 +14,78 @@ import javax.annotation.Nonnull; import java.util.*; -public class ParticipantInfo -{ - public final EntityPlayer PLAYER; - public final UUID UUID; - - public final List ALL_UUIDS; - public final List ACTIVE_PLAYERS; - public final List ACTIVE_UUIDS; - - public final DBEntry PARTY_INSTANCE; - - public ParticipantInfo(@Nonnull EntityPlayer player) - { - this.PLAYER = player; - this.UUID = QuestingAPI.getQuestingUUID(player); - this.PARTY_INSTANCE = PartyManager.INSTANCE.getParty(this.UUID); - - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - - if(PARTY_INSTANCE == null || server == null || player instanceof FakePlayer) - { - ACTIVE_PLAYERS = Collections.singletonList(player); - ACTIVE_UUIDS = Collections.singletonList(UUID); - ALL_UUIDS = Collections.singletonList(UUID); - return; - } - - List actPl = new ArrayList<>(); - List actID = new ArrayList<>(); - List allID = new ArrayList<>(); - - for(UUID mem : PARTY_INSTANCE.getValue().getMembers()) - { - allID.add(mem); - EntityPlayer pMem = server.getPlayerList().getPlayerByUUID(mem); - //noinspection ConstantConditions - if(pMem != null) - { - actPl.add(pMem); - actID.add(mem); - } - } - - // Really shouldn't be modifying these lists anyway but just for safety - this.ACTIVE_PLAYERS = Collections.unmodifiableList(actPl); - this.ACTIVE_UUIDS = Collections.unmodifiableList(actID); - this.ALL_UUIDS = Collections.unmodifiableList(allID); - } - - public void markDirty(@Nonnull List questIDs) // Only marks quests dirty for the immediate participating player - { - QuestCache qc = PLAYER.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if(qc != null) questIDs.forEach(qc::markQuestDirty); - } - - public void markDirtyParty(@Nonnull List questIDs) // Marks quests as dirty for the entire (active) party - { - if(ACTIVE_PLAYERS.size() <= 0 || questIDs.size() <= 0) return; - ACTIVE_PLAYERS.forEach((value) -> { - QuestCache qc = value.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if(qc != null) questIDs.forEach(qc::markQuestDirty); - }); +public class ParticipantInfo { + public final EntityPlayer PLAYER; + public final UUID UUID; + + public final List ALL_UUIDS; + public final List ACTIVE_PLAYERS; + public final List ACTIVE_UUIDS; + + public final DBEntry PARTY_INSTANCE; + + public ParticipantInfo(@Nonnull EntityPlayer player) { + this.PLAYER = player; + this.UUID = QuestingAPI.getQuestingUUID(player); + this.PARTY_INSTANCE = PartyManager.INSTANCE.getParty(this.UUID); + + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + + if (PARTY_INSTANCE == null || server == null || player instanceof FakePlayer) { + ACTIVE_PLAYERS = Collections.singletonList(player); + ACTIVE_UUIDS = Collections.singletonList(UUID); + ALL_UUIDS = Collections.singletonList(UUID); + return; } - - @Nonnull - public int[] getSharedQuests() // Returns an array of all quests which one or more participants have unlocked - { - TreeSet active = new TreeSet<>(); - ACTIVE_PLAYERS.forEach((p) -> { - QuestCache qc = p.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if(qc != null) for(int value : qc.getActiveQuests()) active.add(value); - }); - - int[] shared = new int[active.size()]; - int i = 0; - for(int value : active) shared[i++] = value; - return shared; + + List actPl = new ArrayList<>(); + List actID = new ArrayList<>(); + List allID = new ArrayList<>(); + + for (UUID mem : PARTY_INSTANCE.getValue().getMembers()) { + allID.add(mem); + EntityPlayer pMem = server.getPlayerList().getPlayerByUUID(mem); + //noinspection ConstantConditions + if (pMem != null) { + actPl.add(pMem); + actID.add(mem); + } } + + // Really shouldn't be modifying these lists anyway but just for safety + this.ACTIVE_PLAYERS = Collections.unmodifiableList(actPl); + this.ACTIVE_UUIDS = Collections.unmodifiableList(actID); + this.ALL_UUIDS = Collections.unmodifiableList(allID); + } + + public void markDirty( + @Nonnull List questIDs) // Only marks quests dirty for the immediate participating player + { + QuestCache qc = PLAYER.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc != null) { questIDs.forEach(qc::markQuestDirty); } + } + + public void markDirtyParty(@Nonnull List questIDs) // Marks quests as dirty for the entire (active) party + { + if (ACTIVE_PLAYERS.isEmpty() || questIDs.isEmpty()) { return; } + ACTIVE_PLAYERS.forEach((value) -> { + QuestCache qc = value.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc != null) { questIDs.forEach(qc::markQuestDirty); } + }); + } + + @Nonnull + public int[] getSharedQuests() // Returns an array of all quests which one or more participants have unlocked + { + TreeSet active = new TreeSet<>(); + ACTIVE_PLAYERS.forEach((p) -> { + QuestCache qc = p.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc != null) { for (int value : qc.getActiveQuests()) { active.add(value); } } + }); + + int[] shared = new int[active.size()]; + int i = 0; + for (int value : active) { shared[i++] = value; } + return shared; + } } diff --git a/src/main/java/betterquesting/api2/utils/QuestLineSorter.java b/src/main/java/betterquesting/api2/utils/QuestLineSorter.java index 784256aea..658ae4652 100644 --- a/src/main/java/betterquesting/api2/utils/QuestLineSorter.java +++ b/src/main/java/betterquesting/api2/utils/QuestLineSorter.java @@ -3,20 +3,18 @@ import betterquesting.api.questing.IQuestLine; import betterquesting.api.questing.IQuestLineDatabase; import betterquesting.api2.storage.DBEntry; + import java.util.Comparator; -public class QuestLineSorter implements Comparator> -{ - private final IQuestLineDatabase QL_DB; - - public QuestLineSorter(IQuestLineDatabase database) - { - this.QL_DB = database; - } - - @Override - public int compare(DBEntry objA, DBEntry objB) - { - return Integer.compare(QL_DB.getOrderIndex(objA.getID()), QL_DB.getOrderIndex(objB.getID())); - } +public class QuestLineSorter implements Comparator> { + private final IQuestLineDatabase QL_DB; + + public QuestLineSorter(IQuestLineDatabase database) { + this.QL_DB = database; + } + + @Override + public int compare(DBEntry objA, DBEntry objB) { + return Integer.compare(QL_DB.getOrderIndex(objA.getID()), QL_DB.getOrderIndex(objB.getID())); + } } diff --git a/src/main/java/betterquesting/api2/utils/QuestTranslation.java b/src/main/java/betterquesting/api2/utils/QuestTranslation.java index 1166b3ce0..55be5aefb 100644 --- a/src/main/java/betterquesting/api2/utils/QuestTranslation.java +++ b/src/main/java/betterquesting/api2/utils/QuestTranslation.java @@ -2,20 +2,16 @@ import net.minecraft.client.resources.I18n; -public class QuestTranslation -{ - public static String translate(String text, Object... args) - { - if(!I18n.hasKey(text)) - { - return text; - } - - return I18n.format(text, args); - } - - public static String translateTrimmed(String text, Object... args) - { - return translate(text, args).replaceAll("\r", ""); +public class QuestTranslation { + public static String translate(String text, Object... args) { + if (!I18n.hasKey(text)) { + return text; } + + return I18n.format(text, args); + } + + public static String translateTrimmed(String text, Object... args) { + return translate(text, args).replaceAll("\r", ""); + } } diff --git a/src/main/java/betterquesting/blocks/BlockSubmitStation.java b/src/main/java/betterquesting/blocks/BlockSubmitStation.java index 8fc8c82a0..7fe7bca85 100644 --- a/src/main/java/betterquesting/blocks/BlockSubmitStation.java +++ b/src/main/java/betterquesting/blocks/BlockSubmitStation.java @@ -1,65 +1,69 @@ package betterquesting.blocks; +import betterquesting.core.BetterQuesting; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.InventoryHelper; +import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import betterquesting.core.BetterQuesting; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.IItemHandler; -public class BlockSubmitStation extends BlockContainer -{ - public BlockSubmitStation() - { - super(Material.WOOD); - this.setHardness(1); - this.setTranslationKey("betterquesting.submit_station"); - this.setCreativeTab(BetterQuesting.tabQuesting); - } +import javax.annotation.Nonnull; - @Override - public TileEntity createNewTileEntity(World world, int meta) - { - return new TileSubmitStation(); - } - - /** - * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render - */ - @Override - public EnumBlockRenderType getRenderType(IBlockState state) - { - return EnumBlockRenderType.MODEL; - } +public class BlockSubmitStation extends BlockContainer { + public BlockSubmitStation() { + super(Material.WOOD); + this.setHardness(1); + this.setTranslationKey("betterquesting.submit_station"); + this.setCreativeTab(BetterQuesting.tabQuesting); + } + + @Override + public TileEntity createNewTileEntity(@Nonnull World world, int meta) { + return new TileSubmitStation(); + } + + /** + * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render + */ + @Nonnull + @Override + public EnumBlockRenderType getRenderType(@Nonnull IBlockState state) { + return EnumBlockRenderType.MODEL; + } - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing heldItem, float side, float hitX, float hitY) - { - if(!world.isRemote) - { - player.openGui(BetterQuesting.instance, 0, world, pos.getX(), pos.getY(), pos.getZ()); - } - return true; + /** + * Called upon block activation (right click on the block.) + */ + @Override + public boolean onBlockActivated(World world, @Nonnull BlockPos pos, @Nonnull IBlockState state, + @Nonnull EntityPlayer player, @Nonnull EnumHand hand, + @Nonnull EnumFacing heldItem, float side, float hitX, float hitY) { + if (!world.isRemote) { + player.openGui(BetterQuesting.instance, 0, world, pos.getX(), pos.getY(), pos.getZ()); } + return true; + } - public void breakBlock(World world, BlockPos pos, IBlockState state) - { - TileSubmitStation tileStation = (TileSubmitStation)world.getTileEntity(pos); - - if(tileStation != null) - { - InventoryHelper.dropInventoryItems(world, pos, tileStation); + public void breakBlock(World world, @Nonnull BlockPos pos, @Nonnull IBlockState state) { + TileEntity te = world.getTileEntity(pos); + if (te != null) { + IItemHandler handler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); + if (handler != null) { + for (int i = 0; i < handler.getSlots(); i++) { + ItemStack stack = handler.extractItem(i, Integer.MAX_VALUE, false); + InventoryHelper.spawnItemStack(world, pos.getX(), pos.getY(), pos.getZ(), stack); } - - super.breakBlock(world, pos, state); + } } + super.breakBlock(world, pos, state); + } } diff --git a/src/main/java/betterquesting/blocks/SSItemHandler.java b/src/main/java/betterquesting/blocks/SSItemHandler.java deleted file mode 100644 index bb4751801..000000000 --- a/src/main/java/betterquesting/blocks/SSItemHandler.java +++ /dev/null @@ -1,116 +0,0 @@ -package betterquesting.blocks; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.items.IItemHandlerModifiable; - -import javax.annotation.Nonnull; - -public class SSItemHandler implements IItemHandlerModifiable -{ - private final TileSubmitStation tile; - - public SSItemHandler(TileSubmitStation tile) - { - this.tile = tile; - } - - @Override - public int getSlots() - { - return tile.getSizeInventory(); - } - - @Nonnull - @Override - public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) - { - if(stack.isEmpty() || !tile.isItemValidForSlot(slot, stack)) - { - return stack; - } - - // Existing stack - ItemStack ts1 = getStackInSlot(slot); - - if(!ts1.isEmpty() && !stack.isItemEqual(ts1)) - { - return stack; - } - - int inMax = Math.min(stack.getCount(), stack.getMaxStackSize() - ts1.getCount()); - // Input stack - ItemStack ts2 = stack.copy(); - ts2.setCount(inMax); - - if(!simulate) - { - if(ts1.isEmpty()) - { - ts1 = ts2; - } else - { - ts1.grow(ts2.getCount()); - } - - tile.setInventorySlotContents(slot, ts1); - } - - if(stack.getCount() > inMax) - { - // Left over stack - ItemStack ts3 = stack.copy(); - ts3.setCount(stack.getCount() - inMax); - return ts3; - } - - return ItemStack.EMPTY; - } - - @Nonnull - @Override - public ItemStack extractItem(int slot, int amount, boolean simulate) - { - if(slot != 1 || amount <= 0) - { - return ItemStack.EMPTY; - } - - if(!simulate) - { - return tile.decrStackSize(slot, amount); - } - - ItemStack stack = getStackInSlot(slot); - - if(stack.isEmpty()) - { - return ItemStack.EMPTY; - } - - int outMax = Math.min(stack.getCount(), amount); - - ItemStack ts1 = stack.copy(); - ts1.setCount(outMax); - - return ts1; - } - - @Override - public void setStackInSlot(int slot, @Nonnull ItemStack stack) - { - tile.setInventorySlotContents(slot, stack); - } - - @Nonnull - @Override - public ItemStack getStackInSlot(int idx) - { - return tile.getStackInSlot(idx); - } - - @Override - public int getSlotLimit(int slot) - { - return 64; - } -} diff --git a/src/main/java/betterquesting/blocks/TileSubmitStation.java b/src/main/java/betterquesting/blocks/TileSubmitStation.java index 320598902..15608d17b 100644 --- a/src/main/java/betterquesting/blocks/TileSubmitStation.java +++ b/src/main/java/betterquesting/blocks/TileSubmitStation.java @@ -1,503 +1,490 @@ package betterquesting.blocks; -import betterquesting.api.properties.NativeProps; import betterquesting.api.questing.IQuest; +import betterquesting.api.questing.tasks.IEnergyTask; import betterquesting.api.questing.tasks.IFluidTask; import betterquesting.api.questing.tasks.IItemTask; import betterquesting.api.questing.tasks.ITask; -import betterquesting.api2.cache.CapabilityProviderQuestCache; -import betterquesting.api2.cache.QuestCache; import betterquesting.api2.storage.DBEntry; import betterquesting.core.BetterQuesting; import betterquesting.questing.QuestDatabase; -import betterquesting.storage.QuestSettings; +import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.inventory.ItemStackHelper; +import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; -import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; -import net.minecraft.util.ITickable; -import net.minecraft.util.NonNullList; +import net.minecraft.util.Tuple; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.energy.CapabilityEnergy; +import net.minecraftforge.energy.IEnergyStorage; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.items.CapabilityItemHandler; -import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.IItemHandlerModifiable; +import net.minecraftforge.items.ItemHandlerHelper; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.UUID; -public class TileSubmitStation extends TileEntity implements IFluidHandler, ISidedInventory, ITickable, IFluidTankProperties -{ - private final IItemHandler itemHandler; - private final IFluidHandler fluidHandler; - private NonNullList itemStack = NonNullList.withSize(2, ItemStack.EMPTY); - private boolean needsUpdate = false; - public UUID owner = null; - public int questID = -1; - public int taskID = -1; - - private DBEntry qCached; - - @SuppressWarnings("WeakerAccess") - public TileSubmitStation() - { - super(); - - this.itemHandler = new SSItemHandler(this); - this.fluidHandler = this; - } - - public DBEntry getQuest() - { - if(questID < 0) return null; - - if(qCached == null) - { - IQuest tmp = QuestDatabase.INSTANCE.getValue(questID); - if(tmp != null) qCached = new DBEntry<>(questID, tmp); +public class TileSubmitStation extends TileEntity implements IInventory { + private final ItemHandler itemHandler = new ItemHandler(); + private final FluidHandler fluidHandler = new FluidHandler(); + private final EnergyHandler energyStorage = new EnergyHandler(); + public UUID owner = null; + public int questID = -1; + public int taskID = -1; + + @Nullable + public Tuple, T> getQuestTask(Class taskClazz) { + if (questID < 0) { + return null; + } + IQuest quest = QuestDatabase.INSTANCE.getValue(questID); + if (quest == null) { + reset(); + return null; + } + ITask task = quest.getTasks().getValue(taskID); + if (task == null) { + reset(); + return null; + } + if (!taskClazz.isInstance(task)) { + return null; + } + return new Tuple<>(new DBEntry<>(questID, quest), taskClazz.cast(task)); + } + + private void syncBlockState() { + if (world.getMinecraftServer() != null) { + IBlockState state = blockType.getStateFromMeta(getBlockMetadata()); + world.notifyBlockUpdate(pos, state, state, 2); //Per Forge documentation this is the proper way to cause block update. + } + } + + public void setupTask(UUID owner, int questID, int taskID) { + if (owner == null || questID < 0 || taskID < 0) { + reset(); + return; + } + this.questID = questID; + this.taskID = taskID; + this.owner = owner; + this.markDirty(); + } + + public boolean isSetup() { + return owner != null && questID >= 0 && taskID >= 0; + } + + public void reset() { + owner = null; + questID = -1; + taskID = -1; + this.markDirty(); + } + + @Nonnull + @Override + public SPacketUpdateTileEntity getUpdatePacket() { + return new SPacketUpdateTileEntity(pos, 0, writeToNBT(new NBTTagCompound())); + } + + @Nonnull + @Override + public NBTTagCompound getUpdateTag() { + return writeToNBT(new NBTTagCompound()); + } + + @Override + public void onDataPacket(@Nonnull NetworkManager net, SPacketUpdateTileEntity pkt) { + readFromNBT(pkt.getNbtCompound()); + } + + @Override + public void readFromNBT(@Nonnull NBTTagCompound tags) { + super.readFromNBT(tags); + + try { + owner = UUID.fromString(tags.getString("owner")); + } catch (Exception e) { + this.reset(); + return; + } + + questID = tags.hasKey("questID") ? tags.getInteger("questID") : -1; + taskID = tags.hasKey("task") ? tags.getInteger("task") : -1; + + itemHandler.fromTag(tags); + + // All data must be present for this to run correctly + if (!isSetup()) { + this.reset(); + } + } + + @Override + @Nonnull + public NBTTagCompound writeToNBT(@Nonnull NBTTagCompound tags) { + super.writeToNBT(tags); + tags.setString("owner", owner != null ? owner.toString() : ""); + tags.setInteger("questID", questID); + tags.setInteger("task", taskID); + itemHandler.toTag(tags); + return tags; + } + + @Nonnull + @Override + public String getName() { + return "Submit Station"; + } + + @Override + public boolean hasCustomName() { + return false; + } + + @Override + @Nonnull + public ITextComponent getDisplayName() { + return new TextComponentString(BetterQuesting.submitStation.getLocalizedName()); + } + + @Override + public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + return capability == CapabilityEnergy.ENERGY || capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || + capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); + + } + + @Override + @Nullable + public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + if (capability == CapabilityEnergy.ENERGY) { + return CapabilityEnergy.ENERGY.cast(energyStorage); + } else if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(itemHandler); + } else if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { + return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(fluidHandler); + } + + return super.getCapability(capability, facing); + } + + @Override + public int getSizeInventory() { + return 2; + } + + @Override + public boolean isEmpty() { + return !itemHandler.outputStack.isEmpty(); + } + + @Nonnull + @Override + public ItemStack getStackInSlot(int index) { + return itemHandler.getStackInSlot(index); + } + + @Nonnull + @Override + public ItemStack decrStackSize(int index, int count) { + return itemHandler.extractItem(index, count, false); + } + + @Nonnull + @Override + public ItemStack removeStackFromSlot(int index) { + ItemStack oldStack = itemHandler.getStackInSlot(index); + itemHandler.setStackInSlot(index, ItemStack.EMPTY); + return oldStack; + } + + @Override + public void setInventorySlotContents(int index, @Nonnull ItemStack stack) { + itemHandler.setStackInSlot(index, stack); + } + + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public boolean isUsableByPlayer(@Nonnull EntityPlayer player) { + return (owner == null || player.getUniqueID().equals(owner)) && player.getDistanceSq(this.pos) < 256; + } + + @Override + public void openInventory(@Nonnull EntityPlayer player) { } + + @Override + public void closeInventory(@Nonnull EntityPlayer player) { } + + @Override + public boolean isItemValidForSlot(int index, @Nonnull ItemStack stack) { + return itemHandler.isItemValid(index, stack); + } + + @Override + public int getField(int id) { + return 0; + } + + @Override + public void setField(int id, int value) { } + + @Override + public int getFieldCount() { + return 0; + } + + @Override + public void clear() { + itemHandler.setStackInSlot(1, ItemStack.EMPTY); + } + + private class FluidHandler implements IFluidHandler { + private final IFluidTankProperties[] properties = { new IFluidTankProperties() { + @Nullable + @Override + public FluidStack getContents() { + return null; + } + + @Override + public int getCapacity() { + return Integer.MAX_VALUE; + } + + @Override + public boolean canFill() { + Tuple, IFluidTask> questTask = getQuestTask(IFluidTask.class); + return questTask != null && !questTask.getSecond().isComplete(owner); + } + + @Override + public boolean canDrain() { + return false; + } + + @Override + public boolean canFillFluidType(FluidStack fluidStack) { + Tuple, IFluidTask> questTask = getQuestTask(IFluidTask.class); + return questTask != null && questTask.getSecond().canAcceptFluid(owner, questTask.getFirst(), fluidStack); + } + + @Override + public boolean canDrainFluidType(FluidStack fluidStack) { + return false; + } + } }; + + @Override + public IFluidTankProperties[] getTankProperties() { + return properties; + } + + @Override + public int fill(FluidStack fluid, boolean doFill) { + Tuple, IFluidTask> questTask = getQuestTask(IFluidTask.class); + if (questTask == null) { + return 0; + } + doFill &= !world.isRemote; + DBEntry quest = questTask.getFirst(); + IFluidTask task = questTask.getSecond(); + fluid = fluid.copy(); + FluidStack remainder = task.submitFluid(owner, quest, fluid, doFill); + int accepted = remainder == null ? fluid.amount : fluid.amount - remainder.amount; + if (doFill) { + if (task.isComplete(owner)) { + reset(); + syncBlockState(); } - - return qCached; - } - - @SuppressWarnings("WeakerAccess") - public ITask getRawTask() - { - DBEntry q = getQuest(); - if(q == null || taskID < 0) return null; - return q.getValue().getTasks().getValue(taskID); - } - - @SuppressWarnings("WeakerAccess") - public IItemTask getItemTask() - { - ITask t = getRawTask(); - return t == null? null : (t instanceof IItemTask? (IItemTask)t : null); - } - - @SuppressWarnings("WeakerAccess") - public IFluidTask getFluidTask() - { - ITask t = getRawTask(); - return t == null? null : (t instanceof IFluidTask? (IFluidTask)t : null); - } - - @Override - public int getSizeInventory() - { - return 2; - } - - @Override - @Nonnull - public ItemStack getStackInSlot(int idx) - { - if(idx < 0 || idx >= itemStack.size()) - { - return ItemStack.EMPTY; - } - - return itemStack.get(idx); - } - - @Override - @Nonnull - public ItemStack decrStackSize(int idx, int amount) - { - return ItemStackHelper.getAndSplit(itemStack, idx, amount); - } - - @Override - public void setInventorySlotContents(int idx, @Nonnull ItemStack stack) - { - if(idx < 0 || idx >= itemStack.size()) return; - itemStack.set(idx, stack); - } - - @Override - @Nonnull - public String getName() - { - return BetterQuesting.submitStation.getLocalizedName(); - } - - @Override - public boolean hasCustomName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return 64; - } - - @Override - public boolean isUsableByPlayer(@Nonnull EntityPlayer player) - { - return (owner == null || player.getUniqueID().equals(owner)) && player.getDistanceSq(this.pos) < 256; + } + + return accepted; } - @Override - public void openInventory(@Nonnull EntityPlayer player) - { - } - - @Override - public void closeInventory(@Nonnull EntityPlayer player) - { - } - - @Override - public boolean isItemValidForSlot(int idx, @Nonnull ItemStack stack) - { - if(idx != 0 || !isSetup()) return false; - - IItemTask t = getItemTask(); - - return t != null && itemStack.get(idx).isEmpty() && !t.isComplete(owner) && t.canAcceptItem(owner, getQuest(), stack); - } - - @Override - public int fill(FluidStack fluid, boolean doFill) - { - IFluidTask t = getFluidTask(); - - if(!isSetup() || t == null) return 0; - - FluidStack remainder; - int amount = fluid.amount; - int consumed = !doFill ? amount : 0; - - if(doFill) - { - remainder = t.submitFluid(owner, getQuest(), fluid); - consumed = remainder != null? amount - remainder.amount : amount; - - if(t.isComplete(owner)) - { - needsUpdate = true; - reset(); - if(world.getMinecraftServer() != null) world.getMinecraftServer().getPlayerList().sendToAllNearExcept(null, pos.getX(), pos.getY(), pos.getZ(), 128, world.provider.getDimension(), getUpdatePacket()); - } else - { - needsUpdate = consumed > 0; - } - } - - return consumed; - } - - @Override - public FluidStack drain(FluidStack resource, boolean doDrain) - { - return null; - } - - @Override - public FluidStack drain(int maxDrain, boolean doDrain) - { - return null; - } - - @Override - public boolean canFill() - { - return true; - } - - @Override - public boolean canFillFluidType(FluidStack fluid) - { - IFluidTask t = getFluidTask(); - - return t != null && !t.isComplete(owner) && t.canAcceptFluid(owner, getQuest(), new FluidStack(fluid, 1)); - } - - @Override - public boolean canDrain() - { - return false; - } - - @Override - public boolean canDrainFluidType(FluidStack fluid) - { - return false; - } - - @Override - public int getCapacity() - { - return Integer.MAX_VALUE; - } - - @Override - public FluidStack getContents() - { - return null; - } - - @Override - public IFluidTankProperties[] getTankProperties() - { - return new IFluidTankProperties[]{this}; - } - - @Override - public void update() - { - if(world.isRemote || !isSetup() || QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) return; - - long wtt = world.getTotalWorldTime(); - if(wtt%5 == 0 && owner != null) - { - if(wtt%20 == 0) qCached = null; // Reset and lookup quest again once every second - DBEntry q = getQuest(); - IItemTask t = getItemTask(); - MinecraftServer server = world.getMinecraftServer(); - EntityPlayerMP player = server == null ? null : server.getPlayerList().getPlayerByUUID(owner); - QuestCache qc = player == null ? null : player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - - // Check quest & task is present. Check input is populated and output is clear. - if(q != null && t != null && !itemStack.get(0).isEmpty() && itemStack.get(1).isEmpty()) - { - ItemStack inStack = itemStack.get(0).copy(); - ItemStack beforeStack = itemStack.get(0).copy(); - - if(t.canAcceptItem(owner, getQuest(), inStack)) - { - // Even if this returns an invalid item for submission it will be moved next pass. Done this way for container items - itemStack.set(0, t.submitItem(owner, getQuest(), inStack)); - - // If the task was completed or partial progress submitted. Sync the new progress with the client - if(t.isComplete(owner) || !itemStack.get(0).equals(beforeStack)) needsUpdate = true; - } else - { - itemStack.set(1, inStack); - itemStack.set(0, ItemStack.EMPTY); - } - } - - if(t != null && t.isComplete(owner)) - { - reset(); - world.getMinecraftServer().getPlayerList().sendToAllNearExcept(null, pos.getX(), pos.getY(), pos.getZ(), 128, world.provider.getDimension(), getUpdatePacket()); - needsUpdate = true; - } - - if(needsUpdate) - { - if(q != null && qc != null) qc.markQuestDirty(q.getID()); // Let the cache take care of syncing - needsUpdate = false; - - } - } - } - - public void setupTask(UUID owner, IQuest quest, ITask task) - { - if(owner == null || quest == null || task == null) - { - reset(); - return; - } - - this.questID = QuestDatabase.INSTANCE.getID(quest); - this.qCached = new DBEntry<>(questID, quest); - this.taskID = quest.getTasks().getID(task); - - if(this.questID < 0 || this.taskID < 0) - { - reset(); - return; - } - - this.owner = owner; - this.markDirty(); - } - - public boolean isSetup() - { - return owner != null && questID >= 0 && taskID >= 0; - } - - public void reset() - { - owner = null; - questID = -1; - taskID = -1; - qCached = null; - this.markDirty(); - } - - /** - * Overridden in a sign to provide the text. - */ - @Nonnull - @Override - public SPacketUpdateTileEntity getUpdatePacket() - { - return new SPacketUpdateTileEntity(pos, 0, this.writeToNBT(new NBTTagCompound())); + @Nullable + @Override + public FluidStack drain(FluidStack resource, boolean doDrain) { + return null; } - /** - * Called when you receive a TileEntityData packet for the location this - * TileEntity is currently in. On the client, the NetworkManager will always - * be the remote server. On the server, it will be whomever is responsible for - * sending the packet. - * - * @param net The NetworkManager the packet originated from - * @param pkt The data packet - */ + @Nullable @Override - public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) - { - this.readFromNBT(pkt.getNbtCompound()); + public FluidStack drain(int maxDrain, boolean doDrain) { + return null; } - - @Override - public void readFromNBT(NBTTagCompound tags) - { - super.readFromNBT(tags); - - ItemStackHelper.loadAllItems(tags.getCompoundTag("inventory"), itemStack); - - try - { - owner = UUID.fromString(tags.getString("owner")); - } catch(Exception e) - { - this.reset(); - return; - } - - questID = tags.hasKey("questID")? tags.getInteger("questID") : -1; - taskID = tags.hasKey("task")? tags.getInteger("task") : -1; - - if(!isSetup()) // All data must be present for this to run correctly - { - this.reset(); - } - } - - @Override + } + + private class ItemHandler implements IItemHandlerModifiable { @Nonnull - public NBTTagCompound writeToNBT(NBTTagCompound tags) - { - super.writeToNBT(tags); - tags.setString("owner", owner != null? owner.toString() : ""); - tags.setInteger("questID", questID); - tags.setInteger("task", taskID); - - tags.setTag("inventory", ItemStackHelper.saveAllItems(new NBTTagCompound(), itemStack)); - - return tags; - } - - private static final int[] slotsForFace = new int[]{0, 1}; - - @Override + private ItemStack outputStack = ItemStack.EMPTY; + + @Override + public int getSlots() { + return 2; + } + @Nonnull - public int[] getSlotsForFace(@Nullable EnumFacing side) - { - return slotsForFace; - } - - @Override - public boolean canInsertItem(int slot, @Nonnull ItemStack stack, @Nullable EnumFacing side) - { - return isItemValidForSlot(slot, stack); - } - - @Override - public boolean canExtractItem(int slot, @Nonnull ItemStack stack, @Nullable EnumFacing side) - { - return slot == 1; - } - - @Override + @Override + public ItemStack getStackInSlot(int slot) { + return slot == 1 ? outputStack : ItemStack.EMPTY; + } + @Nonnull - public ItemStack removeStackFromSlot(int index) - { - return ItemStackHelper.getAndRemove(itemStack, index); - } - - @Override - public int getField(int id) - { - return 0; - } - - @Override - public void setField(int id, int value) - { - } - - @Override - public int getFieldCount() - { - return 0; - } - - @Override - public void clear() - { - itemStack.clear(); - } - - @Override + @Override + public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { + if (slot != 0 || stack.isEmpty()) { + return stack; + } + simulate |= world.isRemote; + Tuple, IItemTask> questTask = getQuestTask(IItemTask.class); + if (questTask == null) { + return stack; + } + DBEntry quest = questTask.getFirst(); + IItemTask task = questTask.getSecond(); + stack = stack.copy(); + ItemStack remainder = task.submitItem(owner, quest, stack, !simulate); + if (remainder.isEmpty() || ItemHandlerHelper.canItemStacksStack(remainder, stack)) { + if (!simulate) { + if (task.isComplete(owner)) { + reset(); + syncBlockState(); + } + } + return remainder; + } else { + int maxCount = Math.min(remainder.getMaxStackSize(), 64); + if (!outputStack.isEmpty() && !ItemHandlerHelper.canItemStacksStack(remainder, outputStack) || + remainder.getCount() + outputStack.getCount() > maxCount) { + return stack; + } + if (!simulate) { + int count = outputStack.getCount() + remainder.getCount(); + outputStack = remainder; + remainder.setCount(count); + if (task.isComplete(owner)) { + reset(); + syncBlockState(); + } + markDirty(); + } + return ItemStack.EMPTY; + } + } + @Nonnull - public ITextComponent getDisplayName() - { - return new TextComponentString(BetterQuesting.submitStation.getLocalizedName()); - } - - @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) - { - if(capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) - { - return true; - } else if(capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) - { - return true; - } - - return super.hasCapability(capability, facing); + @Override + public ItemStack extractItem(int slot, int amount, boolean simulate) { + if (slot == 1) { + ItemStack stack; + if (simulate) { + stack = outputStack.copy(); + stack.setCount(amount); + } else { + stack = outputStack.splitStack(amount); + markDirty(); + } + return stack; + } + return ItemStack.EMPTY; } - - @Override - @Nullable - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) - { - if(capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) - { - return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(itemHandler); - } else if(capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) - { - return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(fluidHandler); - } - - return super.getCapability(capability, facing); + + @Override + public int getSlotLimit(int slot) { + return slot == 0 ? Integer.MAX_VALUE : 64; + } + + @Override + public boolean isItemValid(int slot, @Nonnull ItemStack stack) { + if (slot != 0) { + return false; + } + Tuple, IItemTask> questTask = getQuestTask(IItemTask.class); + return questTask != null && questTask.getSecond().canAcceptItem(owner, questTask.getFirst(), stack); + } + + public void toTag(NBTTagCompound tag) { + tag.setTag("OutputStack", outputStack.writeToNBT(new NBTTagCompound())); + } + + public void fromTag(NBTTagCompound tag) { + outputStack = new ItemStack(tag.getCompoundTag("OutputStack")); + } + + @Override + public void setStackInSlot(int slot, @Nonnull ItemStack stack) { + if (slot == 0) { + if (!stack.isEmpty()) { + insertItem(0, stack, false); + } + } else { + outputStack = stack.copy(); + markDirty(); + } + } + } + + private class EnergyHandler implements IEnergyStorage { + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + Tuple, IEnergyTask> questTask = getQuestTask(IEnergyTask.class); + if (questTask == null) { + return 0; + } + simulate |= world.isRemote; + DBEntry quest = questTask.getFirst(); + IEnergyTask task = questTask.getSecond(); + int remainder = task.submitEnergy(owner, quest, maxReceive, !simulate); + int accepted = maxReceive - remainder; + if (!simulate) { + if (task.isComplete(owner)) { + reset(); + syncBlockState(); + } + } + return accepted; } - @Override - public boolean isEmpty() - { - return itemStack.isEmpty(); - } + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + return 0; + } + + @Override + public int getEnergyStored() { + return 0; + } + + @Override + public int getMaxEnergyStored() { + return Integer.MAX_VALUE; + } + + @Override + public boolean canExtract() { + return false; + } + + @Override + public boolean canReceive() { + return true; + } + } } diff --git a/src/main/java/betterquesting/client/BQ_Keybindings.java b/src/main/java/betterquesting/client/BQ_Keybindings.java index 64fa24e32..b64efd5ad 100644 --- a/src/main/java/betterquesting/client/BQ_Keybindings.java +++ b/src/main/java/betterquesting/client/BQ_Keybindings.java @@ -1,18 +1,16 @@ package betterquesting.client; +import betterquesting.core.BetterQuesting; import net.minecraft.client.settings.KeyBinding; import net.minecraftforge.fml.client.registry.ClientRegistry; import org.lwjgl.input.Keyboard; -import betterquesting.core.BetterQuesting; -public class BQ_Keybindings -{ - public static KeyBinding openQuests; - - public static void RegisterKeys() - { - openQuests = new KeyBinding("key.betterquesting.quests", Keyboard.KEY_GRAVE, BetterQuesting.NAME); - - ClientRegistry.registerKeyBinding(openQuests); - } +public class BQ_Keybindings { + public static KeyBinding openQuests; + + public static void RegisterKeys() { + openQuests = new KeyBinding("key.betterquesting.quests", Keyboard.KEY_GRAVE, BetterQuesting.NAME); + + ClientRegistry.registerKeyBinding(openQuests); + } } diff --git a/src/main/java/betterquesting/client/CreativeTabQuesting.java b/src/main/java/betterquesting/client/CreativeTabQuesting.java index 34e640c43..871beba2e 100644 --- a/src/main/java/betterquesting/client/CreativeTabQuesting.java +++ b/src/main/java/betterquesting/client/CreativeTabQuesting.java @@ -1,26 +1,25 @@ package betterquesting.client; +import betterquesting.core.BetterQuesting; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; -import betterquesting.core.BetterQuesting; -public class CreativeTabQuesting extends CreativeTabs -{ - private ItemStack tabStack; - - public CreativeTabQuesting() - { - super(BetterQuesting.MODID); - } - - @Override - public ItemStack createIcon() - { - if(tabStack == null) - { - this.tabStack = new ItemStack(BetterQuesting.extraLife); - } - - return tabStack; - } +import javax.annotation.Nonnull; + +public class CreativeTabQuesting extends CreativeTabs { + private ItemStack tabStack; + + public CreativeTabQuesting() { + super(BetterQuesting.MODID); + } + + @Nonnull + @Override + public ItemStack createIcon() { + if (tabStack == null) { + this.tabStack = new ItemStack(BetterQuesting.extraLife); + } + + return tabStack; + } } diff --git a/src/main/java/betterquesting/client/QuestNotification.java b/src/main/java/betterquesting/client/QuestNotification.java index 95de274ce..e21cb804a 100644 --- a/src/main/java/betterquesting/client/QuestNotification.java +++ b/src/main/java/betterquesting/client/QuestNotification.java @@ -25,111 +25,100 @@ import java.util.List; @SideOnly(Side.CLIENT) -public class QuestNotification -{ - public static void ScheduleNotice(String mainTxt, String subTxt, ItemStack icon, String sound) - { - if(BQ_Settings.questNotices) notices.add(new QuestNotice(mainTxt, subTxt, icon, sound)); - } - - private static final List notices = new ArrayList<>(); - - public static void resetNotices() - { - notices.clear(); - } - - @SubscribeEvent - public void onDrawScreen(RenderGameOverlayEvent.Post event) - { - if(event.getType() != ElementType.ALL) return; - if(notices.size() <= 0) return; - - if(notices.size() >= 20 || !BQ_Settings.questNotices) - { - notices.clear(); - return; - } - - Minecraft mc = Minecraft.getMinecraft(); - ScaledResolution resolution = new ScaledResolution(mc); - int width = resolution.getScaledWidth(); - int height = resolution.getScaledHeight(); - QuestNotice notice = notices.get(0); - - if(!notice.init) - { - if(mc.isGamePaused() || mc.currentScreen != null) - { - return; // Do not start showing a new notice if the player isn't looking - } - - notice.init = true; - notice.startTime = Minecraft.getSystemTime(); - mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(new SoundEvent(new ResourceLocation(notice.sound)), 1.0F)); - } - - if(notice.getTime() >= 6F) - { - notices.remove(0); - return; - } - - GlStateManager.pushMatrix(); - - float scale = width > 600? 1.5F : 1F; - - GlStateManager.scale(scale, scale, scale); - width = MathHelper.ceil(width/scale); - height = MathHelper.ceil(height/scale); - - float alpha = notice.getTime() <= 4F? Math.min(1F, notice.getTime()) : Math.max(0F, 5F - notice.getTime()); - alpha = MathHelper.clamp(alpha, 0.02F, 1F); - int color = new Color(1F, 1F, 1F, alpha).getRGB(); - - GlStateManager.color(1F, 1F, 1F, alpha); - - if(notice.icon != null) - { - RenderUtils.RenderItemStack(mc, notice.icon, width/2 - 8, height/4 - 20, "", new Color(1F, 1F, 1F, alpha)); - } - - GlStateManager.enableBlend(); - GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA); - - String tmp = TextFormatting.UNDERLINE + "" + TextFormatting.BOLD + QuestTranslation.translate(notice.mainTxt); - int txtW = RenderUtils.getStringWidth(tmp, mc.fontRenderer); - mc.fontRenderer.drawString(tmp, width/2 - txtW/2, height/4, color, false); - - tmp = QuestTranslation.translate(notice.subTxt); - txtW = RenderUtils.getStringWidth(tmp, mc.fontRenderer); - mc.fontRenderer.drawString(tmp, width/2 - txtW/2, height/4 + 12, color, false); - - //GlStateManager.disableBlend(); - GlStateManager.popMatrix(); - } - - public static class QuestNotice - { - public long startTime; - public boolean init = false; - private final String mainTxt; - private final String subTxt; - private final ItemStack icon; - private final String sound; - - public QuestNotice(String mainTxt, String subTxt, ItemStack icon, String sound) - { - this.startTime = Minecraft.getSystemTime(); - this.mainTxt = mainTxt; - this.subTxt = subTxt; - this.icon = icon; - this.sound = sound; - } - - public float getTime() - { - return (Minecraft.getSystemTime() - startTime)/1000F; - } - } +public class QuestNotification { + public static void ScheduleNotice(String mainTxt, String subTxt, ItemStack icon, String sound) { + if (BQ_Settings.questNotices) { notices.add(new QuestNotice(mainTxt, subTxt, icon, sound)); } + } + + private static final List notices = new ArrayList<>(); + + public static void resetNotices() { + notices.clear(); + } + + @SubscribeEvent + public void onDrawScreen(RenderGameOverlayEvent.Post event) { + if (event.getType() != ElementType.ALL) { return; } + if (notices.isEmpty()) { return; } + + if (notices.size() >= 20 || !BQ_Settings.questNotices) { + notices.clear(); + return; + } + + Minecraft mc = Minecraft.getMinecraft(); + ScaledResolution resolution = new ScaledResolution(mc); + int width = resolution.getScaledWidth(); + int height = resolution.getScaledHeight(); + QuestNotice notice = notices.get(0); + + if (!notice.init) { + if (mc.isGamePaused() || mc.currentScreen != null) { + return; // Do not start showing a new notice if the player isn't looking + } + + notice.init = true; + notice.startTime = Minecraft.getSystemTime(); + mc.getSoundHandler() + .playSound(PositionedSoundRecord.getMasterRecord(new SoundEvent(new ResourceLocation(notice.sound)), 1.0F)); + } + + if (notice.getTime() >= 6F) { + notices.remove(0); + return; + } + + GlStateManager.pushMatrix(); + + float scale = width > 600 ? 1.5F : 1F; + + GlStateManager.scale(scale, scale, scale); + width = MathHelper.ceil(width / scale); + height = MathHelper.ceil(height / scale); + + float alpha = notice.getTime() <= 4F ? Math.min(1F, notice.getTime()) : Math.max(0F, 5F - notice.getTime()); + alpha = MathHelper.clamp(alpha, 0.02F, 1F); + int color = new Color(1F, 1F, 1F, alpha).getRGB(); + + GlStateManager.color(1F, 1F, 1F, alpha); + + if (notice.icon != null) { + RenderUtils.RenderItemStack(mc, notice.icon, width / 2 - 8, height / 4 - 20, "", new Color(1F, 1F, 1F, alpha)); + } + + GlStateManager.enableBlend(); + GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA); + + String tmp = TextFormatting.UNDERLINE + "" + TextFormatting.BOLD + QuestTranslation.translate(notice.mainTxt); + int txtW = RenderUtils.getStringWidth(tmp, mc.fontRenderer); + mc.fontRenderer.drawString(tmp, width / 2 - txtW / 2, height / 4, color, false); + + tmp = QuestTranslation.translate(notice.subTxt); + txtW = RenderUtils.getStringWidth(tmp, mc.fontRenderer); + mc.fontRenderer.drawString(tmp, width / 2 - txtW / 2, height / 4 + 12, color, false); + + //GlStateManager.disableBlend(); + GlStateManager.popMatrix(); + } + + public static class QuestNotice { + public long startTime; + public boolean init = false; + private final String mainTxt; + private final String subTxt; + private final ItemStack icon; + private final String sound; + + public QuestNotice(String mainTxt, String subTxt, ItemStack icon, String sound) { + this.startTime = Minecraft.getSystemTime(); + this.mainTxt = mainTxt; + this.subTxt = subTxt; + this.icon = icon; + this.sound = sound; + } + + public float getTime() { + return (Minecraft.getSystemTime() - startTime) / 1000F; + } + } } diff --git a/src/main/java/betterquesting/client/gui/GuiBQConfig.java b/src/main/java/betterquesting/client/gui/GuiBQConfig.java index 08e539707..2628089b0 100644 --- a/src/main/java/betterquesting/client/gui/GuiBQConfig.java +++ b/src/main/java/betterquesting/client/gui/GuiBQConfig.java @@ -14,17 +14,14 @@ import java.util.List; @SideOnly(Side.CLIENT) -public class GuiBQConfig extends GuiConfig -{ - public GuiBQConfig(GuiScreen parent) - { - super(parent, getCategories(ConfigHandler.config), BetterQuesting.MODID, false, false, BetterQuesting.NAME); - } - - private static List getCategories(Configuration config) - { - List cats = new ArrayList<>(); - config.getCategoryNames().forEach((s) -> cats.add(new ConfigElement(config.getCategory(s)))); - return cats; - } +public class GuiBQConfig extends GuiConfig { + public GuiBQConfig(GuiScreen parent) { + super(parent, getCategories(ConfigHandler.config), BetterQuesting.MODID, false, false, BetterQuesting.NAME); + } + + private static List getCategories(Configuration config) { + List cats = new ArrayList<>(); + config.getCategoryNames().forEach((s) -> cats.add(new ConfigElement(config.getCategory(s)))); + return cats; + } } diff --git a/src/main/java/betterquesting/client/gui2/GuiHome.java b/src/main/java/betterquesting/client/gui2/GuiHome.java index 17e70e039..4544dd2b8 100644 --- a/src/main/java/betterquesting/client/gui2/GuiHome.java +++ b/src/main/java/betterquesting/client/gui2/GuiHome.java @@ -54,148 +54,151 @@ import java.util.function.Consumer; @SideOnly(Side.CLIENT) -public class GuiHome extends GuiScreenCanvas -{ - public static GuiScreen bookmark; - - public GuiHome(GuiScreen parent) - { - super(parent); - } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register((Consumer)this::onButtonPress, PEventButton.class); - - ResourceLocation homeGui = new ResourceLocation(QuestSettings.INSTANCE.getProperty(NativeProps.HOME_IMAGE)); - IGuiTexture homeSplashBG = new SimpleTexture(homeGui, new GuiRectangle(0, 0, 256, 128)); - IGuiTexture homeSplashTitle = new SimpleTexture(homeGui, new GuiRectangle(0, 128, 256, 128)).maintainAspect(true); - float ancX = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_ANC_X); - float ancY = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_ANC_Y); - int offX = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_OFF_X); - int offY = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_OFF_Y); - - // Background panel - CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(bgCan); - - // Inner canvas bounds - CanvasEmpty inCan = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0)); - bgCan.addPanel(inCan); - - CanvasTextured splashCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 32), 0), homeSplashBG); - inCan.addPanel(splashCan); - CanvasTextured splashTitle = new CanvasTextured(new GuiTransform(new Vector4f(ancX, ancY, ancX, ancY), new GuiPadding(offX, offY, -256 - offX, -128 - offY), 0), homeSplashTitle); - splashCan.addPanel(splashTitle); - - PanelButton btnExit = new PanelButton(new GuiTransform(new Vector4f(0F, 1F, 0.25F, 1F), new GuiPadding(0, -32, 0, 0), 0), 0, QuestTranslation.translate("betterquesting.home.exit")); - inCan.addPanel(btnExit); - - PanelButton btnQuests = new PanelButton(new GuiTransform(new Vector4f(0.25F, 1F, 0.5F, 1F), new GuiPadding(0, -32, 0, 0), 0), 1, QuestTranslation.translate("betterquesting.home.quests")); - inCan.addPanel(btnQuests); - PanelButton btnParty = new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.75F, 1F), new GuiPadding(0, -32, 0, 0), 0), 2, QuestTranslation.translate("betterquesting.home.party")); - btnParty.setActive(QuestSettings.INSTANCE.getProperty(NativeProps.PARTY_ENABLE)); - inCan.addPanel(btnParty); - PanelButton btnTheme = new PanelButton(new GuiTransform(new Vector4f(0.75F, 1F, 1F, 1F), new GuiPadding(0, -32, 0, 0), 0), 3, QuestTranslation.translate("betterquesting.home.theme")); - inCan.addPanel(btnTheme); - - if(QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player)) - { - PanelButton btnEdit = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, new GuiPadding(0, 0, -16, -16), 0), 4, "").setIcon(PresetIcon.ICON_GEAR.getTexture()); - inCan.addPanel(btnEdit); - } - - if(Minecraft.getMinecraft().isIntegratedServerRunning() && SaveLoadHandler.INSTANCE.hasUpdate()) - { - PanelButton tstBtn = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -16, 0, 16, 16, 0), 5, ""); - tstBtn.setIcon(PresetIcon.ICON_NOTICE.getTexture(), PresetColor.UPDATE_NOTICE.getColor(), 0); - tstBtn.setTooltip(Collections.singletonList(QuestTranslation.translateTrimmed("betterquesting.tooltip.update_quests", true))); - inCan.addPanel(tstBtn); - } - - if((Boolean)Launch.blackboard.get("fml.deobfuscatedEnvironment")) - { - PanelButton tstBtn = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 16, 16, 0), -2, "?") - { - @Override - public void onButtonClick() - { - mc.displayGuiScreen(new GuiStatus(GuiHome.this)); - //mc.displayGuiScreen(new GuiBuilderMain(GuiHome.this)); - } - }; // Test screen - inCan.addPanel(tstBtn); +public class GuiHome extends GuiScreenCanvas { + public static GuiScreen bookmark; + + public GuiHome(GuiScreen parent) { + super(parent); + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register((Consumer) this::onButtonPress, PEventButton.class); + + ResourceLocation homeGui = new ResourceLocation(QuestSettings.INSTANCE.getProperty(NativeProps.HOME_IMAGE)); + IGuiTexture homeSplashBG = new SimpleTexture(homeGui, new GuiRectangle(0, 0, 256, 128)); + IGuiTexture homeSplashTitle = new SimpleTexture(homeGui, new GuiRectangle(0, 128, 256, 128)).maintainAspect(true); + float ancX = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_ANC_X); + float ancY = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_ANC_Y); + int offX = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_OFF_X); + int offY = QuestSettings.INSTANCE.getProperty(NativeProps.HOME_OFF_Y); + + // Background panel + CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(bgCan); + + // Inner canvas bounds + CanvasEmpty inCan = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0)); + bgCan.addPanel(inCan); + + CanvasTextured splashCan = + new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 32), 0), homeSplashBG); + inCan.addPanel(splashCan); + CanvasTextured splashTitle = new CanvasTextured( + new GuiTransform(new Vector4f(ancX, ancY, ancX, ancY), new GuiPadding(offX, offY, -256 - offX, -128 - offY), 0), + homeSplashTitle); + splashCan.addPanel(splashTitle); + + PanelButton btnExit = + new PanelButton(new GuiTransform(new Vector4f(0F, 1F, 0.25F, 1F), new GuiPadding(0, -32, 0, 0), 0), 0, + QuestTranslation.translate("betterquesting.home.exit")); + inCan.addPanel(btnExit); + + PanelButton btnQuests = + new PanelButton(new GuiTransform(new Vector4f(0.25F, 1F, 0.5F, 1F), new GuiPadding(0, -32, 0, 0), 0), 1, + QuestTranslation.translate("betterquesting.home.quests")); + inCan.addPanel(btnQuests); + PanelButton btnParty = + new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.75F, 1F), new GuiPadding(0, -32, 0, 0), 0), 2, + QuestTranslation.translate("betterquesting.home.party")); + btnParty.setActive(QuestSettings.INSTANCE.getProperty(NativeProps.PARTY_ENABLE)); + inCan.addPanel(btnParty); + PanelButton btnTheme = + new PanelButton(new GuiTransform(new Vector4f(0.75F, 1F, 1F, 1F), new GuiPadding(0, -32, 0, 0), 0), 3, + QuestTranslation.translate("betterquesting.home.theme")); + inCan.addPanel(btnTheme); + + if (QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player)) { + PanelButton btnEdit = + new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, new GuiPadding(0, 0, -16, -16), 0), 4, "").setIcon( + PresetIcon.ICON_GEAR.getTexture()); + inCan.addPanel(btnEdit); + } + + if (Minecraft.getMinecraft().isIntegratedServerRunning() && SaveLoadHandler.INSTANCE.hasUpdate()) { + PanelButton tstBtn = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -16, 0, 16, 16, 0), 5, ""); + tstBtn.setIcon(PresetIcon.ICON_NOTICE.getTexture(), PresetColor.UPDATE_NOTICE.getColor(), 0); + tstBtn.setTooltip( + Collections.singletonList(QuestTranslation.translateTrimmed("betterquesting.tooltip.update_quests", true))); + inCan.addPanel(tstBtn); + } + + if ((Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) { + PanelButton tstBtn = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 16, 16, 0), -2, "?") { + @Override + public void onButtonClick() { + mc.displayGuiScreen(new GuiStatus(GuiHome.this)); + //mc.displayGuiScreen(new GuiBuilderMain(GuiHome.this)); } - } - - private void onButtonPress(PanelEvent event) - { - if(!(event instanceof PEventButton)) return; - - Minecraft mc = Minecraft.getMinecraft(); - IPanelButton btn = ((PEventButton)event).getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1) // Quests - { - mc.displayGuiScreen(new GuiQuestLines(this)); - } else if(btn.getButtonID() == 2) // Party - { - DBEntry party = PartyManager.INSTANCE.getParty(QuestingAPI.getQuestingUUID(mc.player)); - - if(party != null) - { - mc.displayGuiScreen(new GuiPartyManage(this)); - } else - { - mc.displayGuiScreen(new GuiPartyCreate(this)); - } - } else if(btn.getButtonID() == 3) // Theme - { - mc.displayGuiScreen(new GuiThemes(this)); - } else if(btn.getButtonID() == 4) // Editor - { - mc.displayGuiScreen(new GuiNbtEditor(this, QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound()), (value) -> - { - QuestSettings.INSTANCE.readFromNBT(value); - NetSettingSync.requestEdit(); - })); - } else if(btn.getButtonID() == 5) // Update me - { - final File qFile = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); - - if(qFile.exists()) - { - FMLCommonHandler.instance().getMinecraftServerInstance().addScheduledTask(() -> { - boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); - boolean hardMode = QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); - - NBTTagList jsonP = QuestDatabase.INSTANCE.writeProgressToNBT(new NBTTagList(), null); - NBTTagCompound j1 = NBTConverter.JSONtoNBT_Object(JsonHelper.ReadFromFile(qFile), new NBTTagCompound(), true); - QuestSettings.INSTANCE.readFromNBT(j1.getCompoundTag("questSettings")); - QuestDatabase.INSTANCE.readFromNBT(j1.getTagList("questDatabase", 10), false); - QuestLineDatabase.INSTANCE.readFromNBT(j1.getTagList("questLines", 10), false); - QuestDatabase.INSTANCE.readProgressFromNBT(jsonP, false); - - QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, editMode); - QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, hardMode); - - NetSettingSync.sendSync(null); - NetQuestSync.quickSync(-1, true, true); - NetChapterSync.sendSync(null, null); - - SaveLoadHandler.INSTANCE.resetUpdate(); - SaveLoadHandler.INSTANCE.markDirty(); - }); - - //this.initGui(); // Reset the whole thing - mc.displayGuiScreen(null); - } - } - } + }; // Test screen + inCan.addPanel(tstBtn); + } + } + + private void onButtonPress(PanelEvent event) { + if (!(event instanceof PEventButton)) { return; } + + Minecraft mc = Minecraft.getMinecraft(); + IPanelButton btn = ((PEventButton) event).getButton(); + + if (btn.getButtonID() == 0) // Exit + { + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1) // Quests + { + mc.displayGuiScreen(new GuiQuestLines(this)); + } else if (btn.getButtonID() == 2) // Party + { + DBEntry party = PartyManager.INSTANCE.getParty(QuestingAPI.getQuestingUUID(mc.player)); + + if (party != null) { + mc.displayGuiScreen(new GuiPartyManage(this)); + } else { + mc.displayGuiScreen(new GuiPartyCreate(this)); + } + } else if (btn.getButtonID() == 3) // Theme + { + mc.displayGuiScreen(new GuiThemes(this)); + } else if (btn.getButtonID() == 4) // Editor + { + mc.displayGuiScreen(new GuiNbtEditor(this, QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound()), (value) -> + { + QuestSettings.INSTANCE.readFromNBT(value); + NetSettingSync.requestEdit(); + })); + } else if (btn.getButtonID() == 5) // Update me + { + final File qFile = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); + + if (qFile.exists()) { + FMLCommonHandler.instance().getMinecraftServerInstance().addScheduledTask(() -> { + boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); + boolean hardMode = QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); + + NBTTagList jsonP = QuestDatabase.INSTANCE.writeProgressToNBT(new NBTTagList(), null); + NBTTagCompound j1 = NBTConverter.JSONtoNBT_Object(JsonHelper.ReadFromFile(qFile), new NBTTagCompound(), true); + QuestSettings.INSTANCE.readFromNBT(j1.getCompoundTag("questSettings")); + QuestDatabase.INSTANCE.readFromNBT(j1.getTagList("questDatabase", 10), false); + QuestLineDatabase.INSTANCE.readFromNBT(j1.getTagList("questLines", 10), false); + QuestDatabase.INSTANCE.readProgressFromNBT(jsonP, false); + + QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, editMode); + QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, hardMode); + + NetSettingSync.sendSync(null); + NetQuestSync.quickSync(-1, true, true); + NetChapterSync.sendSync(null, null); + + SaveLoadHandler.INSTANCE.resetUpdate(); + SaveLoadHandler.INSTANCE.markDirty(); + }); + + //this.initGui(); // Reset the whole thing + mc.displayGuiScreen(null); + } + } + } } diff --git a/src/main/java/betterquesting/client/gui2/GuiQuest.java b/src/main/java/betterquesting/client/gui2/GuiQuest.java index 005322535..c93b62e2e 100644 --- a/src/main/java/betterquesting/client/gui2/GuiQuest.java +++ b/src/main/java/betterquesting/client/gui2/GuiQuest.java @@ -35,334 +35,328 @@ import net.minecraft.util.math.MathHelper; import org.lwjgl.util.vector.Vector4f; -public class GuiQuest extends GuiScreenCanvas implements IPEventListener, INeedsRefresh -{ - private final int questID; - - private IQuest quest; - - private PanelButton btnTaskLeft; - private PanelButton btnTaskRight; - private PanelButton btnRewardLeft; - private PanelButton btnRewardRight; - - private PanelButton btnDetect; - private PanelButton btnClaim; - - private PanelTextBox titleReward; - private PanelTextBox titleTask; - - private CanvasEmpty cvInner; - - private IGuiRect rectReward; - private IGuiRect rectTask; - - private IGuiPanel pnReward; - private IGuiPanel pnTask; - - private int rewardIndex = 0; - private int taskIndex = 0; - - public GuiQuest(GuiScreen parent, int questID) - { - super(parent); - this.questID = questID; +public class GuiQuest extends GuiScreenCanvas implements IPEventListener, INeedsRefresh { + private final int questID; + + private IQuest quest; + + private PanelButton btnTaskLeft; + private PanelButton btnTaskRight; + private PanelButton btnRewardLeft; + private PanelButton btnRewardRight; + + private PanelButton btnDetect; + private PanelButton btnClaim; + + private PanelTextBox titleReward; + private PanelTextBox titleTask; + + private CanvasEmpty cvInner; + + private IGuiRect rectReward; + private IGuiRect rectTask; + + private IGuiPanel pnReward; + private IGuiPanel pnTask; + + private int rewardIndex = 0; + private int taskIndex = 0; + + public GuiQuest(GuiScreen parent, int questID) { + super(parent); + this.questID = questID; + } + + @Override + public void initPanel() { + super.initPanel(); + + this.quest = QuestDatabase.INSTANCE.getValue(questID); + + if (quest == null) { + mc.displayGuiScreen(this.parent); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - this.quest = QuestDatabase.INSTANCE.getValue(questID); - - if(quest == null) - { - mc.displayGuiScreen(this.parent); - return; - } - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate(quest.getProperty(NativeProps.NAME))).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - if(QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player)) - { - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 100, 16, 0), 0, QuestTranslation.translate("gui.back"))); - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -16, 100, 16, 0), 1, QuestTranslation.translate("betterquesting.btn.edit"))); - } else - { - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - } - - cvInner = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 32, 16, 24), 0)); - cvBackground.addPanel(cvInner); - - if(quest.getRewards().size() > 0) - { - CanvasScrolling cvDesc = new CanvasScrolling(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.5F), new GuiPadding(0, 0, 16, 16), 0)); - cvInner.addPanel(cvDesc); - PanelTextBox paDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 0), QuestTranslation.translate(quest.getProperty(NativeProps.DESC)), true); - paDesc.setColor(PresetColor.TEXT_MAIN.getColor());//.setFontSize(4); - cvDesc.addCulledPanel(paDesc, false); - - PanelVScrollBar paDescScroll = new PanelVScrollBar(new GuiTransform(GuiAlign.quickAnchor(GuiAlign.TOP_CENTER, GuiAlign.MID_CENTER), new GuiPadding(-16, 0, 8, 16), 0)); - cvInner.addPanel(paDescScroll); - cvDesc.setScrollDriverY(paDescScroll); - paDescScroll.setEnabled(cvDesc.getScrollBounds().getHeight() > 0); - - btnClaim = new PanelButton(new GuiTransform(new Vector4f(0F, 1F, 0.5F, 1F), new GuiPadding(16, -16, 24, 0), 0), 6, QuestTranslation.translate("betterquesting.btn.claim")); - btnClaim.setActive(false); - cvInner.addPanel(btnClaim); - - btnRewardLeft = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, new GuiPadding(0, -16, -16, 0), 0), 2, "<"); - btnRewardLeft.setActive(rewardIndex > 0); - cvInner.addPanel(btnRewardLeft); - - btnRewardRight = new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.5F, 1F), new GuiPadding(-24, -16, 8, 0), 0), 3, ">"); - btnRewardRight.setActive(rewardIndex < quest.getRewards().size() - 1); - cvInner.addPanel(btnRewardRight); - - rectReward = new GuiTransform(new Vector4f(0F, 0.5F, 0.5F, 1F), new GuiPadding(0, 0, 8, 16), 0); - rectReward.setParent(cvInner.getTransform()); - - titleReward = new PanelTextBox(new GuiTransform(new Vector4f(0F, 0.5F, 0.5F, 0.5F), new GuiPadding(0, -16, 8, 0), 0), "?"); - titleReward.setColor(PresetColor.TEXT_HEADER.getColor()).setAlignment(1); - cvInner.addPanel(titleReward); - - refreshRewardPanel(); - } else - { - CanvasScrolling cvDesc = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(0, 0, 16, 0), 0)); - cvInner.addPanel(cvDesc); - PanelTextBox paDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 0), QuestTranslation.translate(quest.getProperty(NativeProps.DESC)), true); - paDesc.setColor(PresetColor.TEXT_MAIN.getColor());//.setFontSize(4); - cvDesc.addCulledPanel(paDesc, false); - - PanelVScrollBar paDescScroll = new PanelVScrollBar(new GuiTransform(GuiAlign.quickAnchor(GuiAlign.TOP_CENTER, GuiAlign.BOTTOM_CENTER), new GuiPadding(-16, 0, 8, 0), 0)); - cvInner.addPanel(paDescScroll); - cvDesc.setScrollDriverY(paDescScroll); - paDescScroll.setEnabled(cvDesc.getScrollBounds().getHeight() > 0); - } - - //if(quest.getTasks().size() > 0) - { - btnDetect = new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 1F, 1F), new GuiPadding(24, -16, 16, 0), 0), 7, QuestTranslation.translate("betterquesting.btn.detect_submit")); - btnDetect.setActive(false); - cvInner.addPanel(btnDetect); - - btnTaskLeft = new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.5F, 1F), new GuiPadding(8, -16, -24, 0), 0), 4, "<"); - btnTaskLeft.setActive(taskIndex > 0); - cvInner.addPanel(btnTaskLeft); - - btnTaskRight = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_RIGHT, new GuiPadding(-16, -16, 0, 0), 0), 5, ">"); - btnTaskRight.setActive(taskIndex < quest.getTasks().size() - 1); - cvInner.addPanel(btnTaskRight); - - rectTask = new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 16, 0, 16), 0); - rectTask.setParent(cvInner.getTransform()); - - titleTask = new PanelTextBox(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(8, 0, 0, -16), 0), "?"); - titleTask.setColor(PresetColor.TEXT_HEADER.getColor()).setAlignment(1); - cvInner.addPanel(titleTask); - - refreshTaskPanel(); - } - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 0, 0, 0, 0); - ls0.setParent(cvInner.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, 0, 0, 0, 0); - le0.setParent(cvInner.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvInner.addPanel(paLine0); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + quest.getProperty(NativeProps.NAME))).setAlignment(1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + if (QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player)) { + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 100, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -16, 100, 16, 0), 1, + QuestTranslation.translate("betterquesting.btn.edit"))); + } else { + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); } - - @Override - public void refreshGui() - { - this.refreshTaskPanel(); - this.refreshRewardPanel(); - this.updateButtons(); + + cvInner = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 32, 16, 24), 0)); + cvBackground.addPanel(cvInner); + + if (quest.getRewards().size() > 0) { + CanvasScrolling cvDesc = + new CanvasScrolling(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.5F), new GuiPadding(0, 0, 16, 16), 0)); + cvInner.addPanel(cvDesc); + PanelTextBox paDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 0), + QuestTranslation.translate(quest.getProperty(NativeProps.DESC)), true); + paDesc.setColor(PresetColor.TEXT_MAIN.getColor());//.setFontSize(4); + cvDesc.addCulledPanel(paDesc, false); + + PanelVScrollBar paDescScroll = new PanelVScrollBar( + new GuiTransform(GuiAlign.quickAnchor(GuiAlign.TOP_CENTER, GuiAlign.MID_CENTER), + new GuiPadding(-16, 0, 8, 16), 0)); + cvInner.addPanel(paDescScroll); + cvDesc.setScrollDriverY(paDescScroll); + paDescScroll.setEnabled(cvDesc.getScrollBounds().getHeight() > 0); + + btnClaim = new PanelButton(new GuiTransform(new Vector4f(0F, 1F, 0.5F, 1F), new GuiPadding(16, -16, 24, 0), 0), 6, + QuestTranslation.translate("betterquesting.btn.claim")); + btnClaim.setActive(false); + cvInner.addPanel(btnClaim); + + btnRewardLeft = + new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, new GuiPadding(0, -16, -16, 0), 0), 2, "<"); + btnRewardLeft.setActive(rewardIndex > 0); + cvInner.addPanel(btnRewardLeft); + + btnRewardRight = + new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.5F, 1F), new GuiPadding(-24, -16, 8, 0), 0), 3, + ">"); + btnRewardRight.setActive(rewardIndex < quest.getRewards().size() - 1); + cvInner.addPanel(btnRewardRight); + + rectReward = new GuiTransform(new Vector4f(0F, 0.5F, 0.5F, 1F), new GuiPadding(0, 0, 8, 16), 0); + rectReward.setParent(cvInner.getTransform()); + + titleReward = + new PanelTextBox(new GuiTransform(new Vector4f(0F, 0.5F, 0.5F, 0.5F), new GuiPadding(0, -16, 8, 0), 0), "?"); + titleReward.setColor(PresetColor.TEXT_HEADER.getColor()).setAlignment(1); + cvInner.addPanel(titleReward); + + refreshRewardPanel(); + } else { + CanvasScrolling cvDesc = + new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(0, 0, 16, 0), 0)); + cvInner.addPanel(cvDesc); + PanelTextBox paDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 0), + QuestTranslation.translate(quest.getProperty(NativeProps.DESC)), true); + paDesc.setColor(PresetColor.TEXT_MAIN.getColor());//.setFontSize(4); + cvDesc.addCulledPanel(paDesc, false); + + PanelVScrollBar paDescScroll = new PanelVScrollBar( + new GuiTransform(GuiAlign.quickAnchor(GuiAlign.TOP_CENTER, GuiAlign.BOTTOM_CENTER), + new GuiPadding(-16, 0, 8, 0), 0)); + cvInner.addPanel(paDescScroll); + cvDesc.setScrollDriverY(paDescScroll); + paDescScroll.setEnabled(cvDesc.getScrollBounds().getHeight() > 0); } - - @Override - public boolean onMouseClick(int mx, int my, int click) + + //if(quest.getTasks().size() > 0) { - if(super.onMouseClick(mx, my, click)) - { - this.updateButtons(); - return true; - } - - return false; + btnDetect = + new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 1F, 1F), new GuiPadding(24, -16, 16, 0), 0), 7, + QuestTranslation.translate("betterquesting.btn.detect_submit")); + btnDetect.setActive(false); + cvInner.addPanel(btnDetect); + + btnTaskLeft = + new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.5F, 1F), new GuiPadding(8, -16, -24, 0), 0), 4, + "<"); + btnTaskLeft.setActive(taskIndex > 0); + cvInner.addPanel(btnTaskLeft); + + btnTaskRight = + new PanelButton(new GuiTransform(GuiAlign.BOTTOM_RIGHT, new GuiPadding(-16, -16, 0, 0), 0), 5, ">"); + btnTaskRight.setActive(taskIndex < quest.getTasks().size() - 1); + cvInner.addPanel(btnTaskRight); + + rectTask = new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 16, 0, 16), 0); + rectTask.setParent(cvInner.getTransform()); + + titleTask = + new PanelTextBox(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(8, 0, 0, -16), 0), "?"); + titleTask.setColor(PresetColor.TEXT_HEADER.getColor()).setAlignment(1); + cvInner.addPanel(titleTask); + + refreshTaskPanel(); } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - if(super.onMouseScroll(mx, my, scroll)) - { - this.updateButtons(); - return true; - } - - return false; + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 0, 0, 0, 0); + ls0.setParent(cvInner.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, 0, 0, 0, 0); + le0.setParent(cvInner.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvInner.addPanel(paLine0); + } + + @Override + public void refreshGui() { + this.refreshTaskPanel(); + this.refreshRewardPanel(); + this.updateButtons(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (super.onMouseClick(mx, my, click)) { + this.updateButtons(); + return true; } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - if(super.onKeyTyped(c, keycode)) - { - this.updateButtons(); - return true; - } - - return false; + + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + if (super.onMouseScroll(mx, my, scroll)) { + this.updateButtons(); + return true; } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + if (super.onKeyTyped(c, keycode)) { + this.updateButtons(); + return true; } - - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1) // Edit - { - mc.displayGuiScreen(new GuiQuestEditor(this, questID)); - } else if(btn.getButtonID() == 2) // Reward previous - { - rewardIndex = MathHelper.clamp(rewardIndex - 1, 0, quest.getRewards().size() - 1); - refreshRewardPanel(); - } else if(btn.getButtonID() == 3) // Reward next - { - rewardIndex = MathHelper.clamp(rewardIndex + 1, 0, quest.getRewards().size() - 1); - refreshRewardPanel(); - } else if(btn.getButtonID() == 4) // Task previous - { - taskIndex = MathHelper.clamp(taskIndex - 1, 0, quest.getTasks().size() - 1); - refreshTaskPanel(); - } else if(btn.getButtonID() == 5) // Task next - { - taskIndex = MathHelper.clamp(taskIndex + 1, 0, quest.getTasks().size() - 1); - refreshTaskPanel(); - } else if(btn.getButtonID() == 6) // Reward claim - { - NetQuestAction.requestClaim(new int[]{questID}); - } else if(btn.getButtonID() == 7) // Task detect/submit - { - NetQuestAction.requestDetect(new int[]{questID}); - } + + return false; + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void refreshRewardPanel() + } + + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - if(pnReward != null) - { - cvInner.removePanel(pnReward); - } - - if(rewardIndex < 0 || rewardIndex >= quest.getRewards().size()) - { - if(titleReward != null) - { - titleReward.setText("?"); - titleReward.setEnabled(false); - } - updateButtons(); - - return; - } else if(rectReward == null) - { - this.initPanel(); - return; - } - - IReward rew = quest.getRewards().getEntries().get(rewardIndex).getValue(); - - pnReward = rew.getRewardGui(rectReward, new DBEntry<>(questID, quest)); - - if(pnReward != null) - { - cvInner.addPanel(pnReward); - } - - if(titleReward != null) - { - titleReward.setText(QuestTranslation.translate(rew.getUnlocalisedName())); - titleReward.setEnabled(true); - } - - updateButtons(); - } - - private void refreshTaskPanel() + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1) // Edit { - if(pnTask != null) - { - cvInner.removePanel(pnTask); - } - - if(taskIndex < 0 || taskIndex >= quest.getTasks().size()) - { - titleTask.setText("?"); - titleTask.setEnabled(false); - updateButtons(); - - return; - } - - ITask tsk = quest.getTasks().getEntries().get(taskIndex).getValue(); - - pnTask = tsk.getTaskGui(rectTask, new DBEntry<>(questID, quest)); - - if(pnTask != null) - { - cvInner.addPanel(pnTask); - } - - titleTask.setText(QuestTranslation.translate(tsk.getUnlocalisedName())); - titleTask.setEnabled(true); - - updateButtons(); - } - - private void updateButtons() + mc.displayGuiScreen(new GuiQuestEditor(this, questID)); + } else if (btn.getButtonID() == 2) // Reward previous + { + rewardIndex = MathHelper.clamp(rewardIndex - 1, 0, quest.getRewards().size() - 1); + refreshRewardPanel(); + } else if (btn.getButtonID() == 3) // Reward next + { + rewardIndex = MathHelper.clamp(rewardIndex + 1, 0, quest.getRewards().size() - 1); + refreshRewardPanel(); + } else if (btn.getButtonID() == 4) // Task previous + { + taskIndex = MathHelper.clamp(taskIndex - 1, 0, quest.getTasks().size() - 1); + refreshTaskPanel(); + } else if (btn.getButtonID() == 5) // Task next { - Minecraft mc = Minecraft.getMinecraft(); - - if(btnRewardLeft != null && btnRewardRight != null && btnClaim != null) - { - btnRewardLeft.setActive(rewardIndex > 0); - btnRewardRight.setActive(rewardIndex < quest.getRewards().size() - 1); - - // Claim button state - btnClaim.setActive(quest.getRewards().size() > 0 && quest.canClaim(mc.player)); - } - - if(btnTaskLeft != null && btnTaskRight != null && btnDetect != null) - { - btnTaskLeft.setActive(taskIndex > 0); - btnTaskRight.setActive(taskIndex < quest.getTasks().size() - 1); - - // Detect/submit button state - btnDetect.setActive(quest.canSubmit(mc.player)); - } + taskIndex = MathHelper.clamp(taskIndex + 1, 0, quest.getTasks().size() - 1); + refreshTaskPanel(); + } else if (btn.getButtonID() == 6) // Reward claim + { + NetQuestAction.requestClaim(new int[] { questID }); + } else if (btn.getButtonID() == 7) // Task detect/submit + { + NetQuestAction.requestDetect(new int[] { questID }); + } + } + + private void refreshRewardPanel() { + if (pnReward != null) { + cvInner.removePanel(pnReward); + } + + if (rewardIndex < 0 || rewardIndex >= quest.getRewards().size()) { + if (titleReward != null) { + titleReward.setText("?"); + titleReward.setEnabled(false); + } + updateButtons(); + + return; + } else if (rectReward == null) { + this.initPanel(); + return; + } + + IReward rew = quest.getRewards().getEntries().get(rewardIndex).getValue(); + + pnReward = rew.getRewardGui(rectReward, new DBEntry<>(questID, quest)); + + if (pnReward != null) { + cvInner.addPanel(pnReward); + } + + if (titleReward != null) { + titleReward.setText(QuestTranslation.translate(rew.getUnlocalisedName())); + titleReward.setEnabled(true); + } + + updateButtons(); + } + + private void refreshTaskPanel() { + if (pnTask != null) { + cvInner.removePanel(pnTask); + } + + if (taskIndex < 0 || taskIndex >= quest.getTasks().size()) { + titleTask.setText("?"); + titleTask.setEnabled(false); + updateButtons(); + + return; + } + + ITask tsk = quest.getTasks().getEntries().get(taskIndex).getValue(); + + pnTask = tsk.getTaskGui(rectTask, new DBEntry<>(questID, quest)); + + if (pnTask != null) { + cvInner.addPanel(pnTask); + } + + titleTask.setText(QuestTranslation.translate(tsk.getUnlocalisedName())); + titleTask.setEnabled(true); + + updateButtons(); + } + + private void updateButtons() { + Minecraft mc = Minecraft.getMinecraft(); + + if (btnRewardLeft != null && btnRewardRight != null && btnClaim != null) { + btnRewardLeft.setActive(rewardIndex > 0); + btnRewardRight.setActive(rewardIndex < quest.getRewards().size() - 1); + + // Claim button state + btnClaim.setActive(quest.getRewards().size() > 0 && quest.canClaim(mc.player)); + } + + if (btnTaskLeft != null && btnTaskRight != null && btnDetect != null) { + btnTaskLeft.setActive(taskIndex > 0); + btnTaskRight.setActive(taskIndex < quest.getTasks().size() - 1); + + // Detect/submit button state + btnDetect.setActive(quest.canSubmit(mc.player)); } + } } diff --git a/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java b/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java index 521d1ce24..8e3be6c26 100644 --- a/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java +++ b/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java @@ -18,68 +18,74 @@ import betterquesting.api2.utils.QuestTranslation; import net.minecraft.client.gui.GuiScreen; -public class GuiQuestHelp extends GuiScreenCanvas -{ - public GuiQuestHelp(GuiScreen parent) - { - super(parent); - } - - @Override - public void initPanel() - { - super.initPanel(); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("item.betterquesting.guide.name")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - PanelButton btnBack = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back")) - { - @Override - public void onButtonClick() - { - mc.displayGuiScreen(parent); - } - }; - cvBackground.addPanel(btnBack); - - CanvasScrolling cvTopics = new CanvasScrolling(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(16, 32, -108, 24), 0)); - cvBackground.addPanel(cvTopics); - - PanelVScrollBar scTopic = new PanelVScrollBar(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(108, 32, -116, 24), 0)); - cvBackground.addPanel(scTopic); - cvTopics.setScrollDriverY(scTopic); - - CanvasScrolling cvDesc = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(124, 48, 24, 24), 0)).enableBlocking(false); - cvBackground.addPanel(cvDesc); - - PanelVScrollBar scDesc = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 48, 16, 24), 0)); - cvBackground.addPanel(scDesc); - cvDesc.setScrollDriverY(scDesc); - - PanelTextBox txtTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(124, 36, 16, -48), 0), "").setAlignment(1); - txtTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txtTitle); - - PanelTextBox txtDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 16, 0), "", true); - txtDesc.setColor(PresetColor.TEXT_MAIN.getColor()); - cvDesc.addPanel(txtDesc); - - int width = cvTopics.getTransform().getWidth(); - HelpTopic[] topics = HelpRegistry.INSTANCE.getTopics(); - for(int i = 0; i < topics.length; i++) - { - HelpTopic ht = topics[i]; - cvTopics.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width, 16, 0), -1, ht.getTitle(), ht).setCallback(value -> { +public class GuiQuestHelp extends GuiScreenCanvas { + public GuiQuestHelp(GuiScreen parent) { + super(parent); + } + + @Override + public void initPanel() { + super.initPanel(); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("item.betterquesting.guide.name")).setAlignment( + 1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + PanelButton btnBack = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back")) { + @Override + public void onButtonClick() { + mc.displayGuiScreen(parent); + } + }; + cvBackground.addPanel(btnBack); + + CanvasScrolling cvTopics = + new CanvasScrolling(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(16, 32, -108, 24), 0)); + cvBackground.addPanel(cvTopics); + + PanelVScrollBar scTopic = + new PanelVScrollBar(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(108, 32, -116, 24), 0)); + cvBackground.addPanel(scTopic); + cvTopics.setScrollDriverY(scTopic); + + CanvasScrolling cvDesc = + new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(124, 48, 24, 24), 0)).enableBlocking( + false); + cvBackground.addPanel(cvDesc); + + PanelVScrollBar scDesc = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 48, 16, 24), 0)); + cvBackground.addPanel(scDesc); + cvDesc.setScrollDriverY(scDesc); + + PanelTextBox txtTitle = + new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(124, 36, 16, -48), 0), "").setAlignment(1); + txtTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txtTitle); + + PanelTextBox txtDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 16, 0), "", true); + txtDesc.setColor(PresetColor.TEXT_MAIN.getColor()); + cvDesc.addPanel(txtDesc); + + int width = cvTopics.getTransform().getWidth(); + HelpTopic[] topics = HelpRegistry.INSTANCE.getTopics(); + for (int i = 0; i < topics.length; i++) { + HelpTopic ht = topics[i]; + cvTopics.addPanel( + new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width, 16, 0), -1, ht.getTitle(), ht).setCallback( + value -> { txtTitle.setText(value.getTitle()); txtDesc.setText(value.getDescription()); cvDesc.refreshScrollBounds(); - })); - } + })); } + } } diff --git a/src/main/java/betterquesting/client/gui2/GuiQuestLines.java b/src/main/java/betterquesting/client/gui2/GuiQuestLines.java index 046f5377b..6dd24d331 100644 --- a/src/main/java/betterquesting/client/gui2/GuiQuestLines.java +++ b/src/main/java/betterquesting/client/gui2/GuiQuestLines.java @@ -52,425 +52,411 @@ import java.util.List; import java.util.UUID; -public class GuiQuestLines extends GuiScreenCanvas implements IPEventListener, INeedsRefresh -{ - private IQuestLine selectedLine = null; - private static int selectedLineId = -1; - - private final List, Integer>> visChapters = new ArrayList<>(); - - private CanvasQuestLine cvQuest; - - // Keep these separate for now - private static CanvasHoverTray cvChapterTray; - private static CanvasHoverTray cvDescTray; - private static CanvasHoverTray cvFrame; - - private CanvasScrolling cvDesc; - private PanelVScrollBar scDesc; - private CanvasScrolling cvLines; - private PanelVScrollBar scLines; - - private PanelGeneric icoChapter; - private PanelTextBox txTitle; - private PanelTextBox txDesc; - - private PanelButton claimAll; - - private static boolean trayLock = false; - - private final List>> btnListRef = new ArrayList<>(); - - public GuiQuestLines(GuiScreen parent) - { - super(parent); - } - - @Override - public void refreshGui() - { - refreshChapterVisibility(); - refreshContent(); +public class GuiQuestLines extends GuiScreenCanvas implements IPEventListener, INeedsRefresh { + private IQuestLine selectedLine = null; + private static int selectedLineId = -1; + + private final List, Integer>> visChapters = new ArrayList<>(); + + private CanvasQuestLine cvQuest; + + // Keep these separate for now + private static CanvasHoverTray cvChapterTray; + private static CanvasHoverTray cvDescTray; + private static CanvasHoverTray cvFrame; + + private CanvasScrolling cvDesc; + private PanelVScrollBar scDesc; + private CanvasScrolling cvLines; + private PanelVScrollBar scLines; + + private PanelGeneric icoChapter; + private PanelTextBox txTitle; + private PanelTextBox txDesc; + + private PanelButton claimAll; + + private static boolean trayLock = false; + + private final List>> btnListRef = new ArrayList<>(); + + public GuiQuestLines(GuiScreen parent) { + super(parent); + } + + @Override + public void refreshGui() { + refreshChapterVisibility(); + refreshContent(); + } + + @Override + public void initPanel() { + super.initPanel(); + + if (selectedLineId >= 0) { + selectedLine = QuestLineDatabase.INSTANCE.getValue(selectedLineId); + if (selectedLine == null) { selectedLineId = -1; } + } else { + selectedLine = null; } - - @Override - public void initPanel() - { - super.initPanel(); - - if(selectedLineId >= 0) - { - selectedLine = QuestLineDatabase.INSTANCE.getValue(selectedLineId); - if(selectedLine == null) selectedLineId = -1; - } else - { - selectedLine = null; - } - - boolean canEdit = QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player); - boolean preOpen = false; - if(trayLock && cvChapterTray != null && cvChapterTray.isTrayOpen()) preOpen = true; - if(trayLock && cvDescTray != null && cvDescTray.isTrayOpen()) preOpen = true; - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelButton btnExit = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 8, -24, 32, 16, 0), -1, "").setIcon(PresetIcon.ICON_PG_PREV.getTexture()); - btnExit.setClickAction((b) -> mc.displayGuiScreen(parent)); - btnExit.setTooltip(Collections.singletonList(QuestTranslation.translate("gui.back"))); - cvBackground.addPanel(btnExit); - - if(canEdit) - { - PanelButton btnEdit = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 8, -40, 32, 16, 0), -1, "").setIcon(PresetIcon.ICON_GEAR.getTexture()); - btnEdit.setClickAction((b) -> mc.displayGuiScreen(new GuiQuestLinesEditor(this))); - btnEdit.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.edit"))); - cvBackground.addPanel(btnEdit); - } - - txTitle = new PanelTextBox(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0F), new GuiPadding(60, 12, 0, -24), 0), ""); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - icoChapter = new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, 40, 8, 16, 16, 0), null); - cvBackground.addPanel(icoChapter); - - cvFrame = new CanvasHoverTray(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(40 + 150 + 24, 24, 8, 8), 0), new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(40, 24, 8, 8), 0), PresetTexture.AUX_FRAME_0.getTexture()); - cvFrame.setManualOpen(true); - //CanvasTextured cvFrame = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(40, 24, 8, 8), 0), PresetTexture.AUX_FRAME_0.getTexture()); - cvBackground.addPanel(cvFrame); - cvFrame.setTrayState(!preOpen, 1); - // These would probably be more annoying than useful if you just wanted to check a tray but not lose your position - //cvFrame.setOpenAction(() -> cvQuest.fitToWindow()); - //cvFrame.setCloseAction(() -> cvQuest.fitToWindow()); - - // === CHAPTER TRAY === - - boolean oldState1 = trayLock && cvChapterTray != null && cvChapterTray.isTrayOpen(); - cvChapterTray = new CanvasHoverTray(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -24, 8), -1), new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -40 - 150 - 24, 8), -1), PresetTexture.PANEL_INNER.getTexture()); - cvChapterTray.setManualOpen(true); - cvChapterTray.setOpenAction(() -> { - cvDescTray.setTrayState(false, 200); - cvFrame.setTrayState(false, 200); - buildChapterList(); - }); - cvBackground.addPanel(cvChapterTray); - - cvLines = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 16, 8), 0)); - cvChapterTray.getCanvasOpen().addPanel(cvLines); - - scLines = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-16, 8, 8, 8), 0)); - cvLines.setScrollDriverY(scLines); - cvChapterTray.getCanvasOpen().addPanel(scLines); - - // === DESCRIPTION TRAY === - - boolean oldState2 = trayLock && cvDescTray != null && cvDescTray.isTrayOpen(); - cvDescTray = new CanvasHoverTray(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -24, 8), -1), new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -40 - 150 - 24, 8), -1), PresetTexture.PANEL_INNER.getTexture()); - cvDescTray.setManualOpen(true); - cvDescTray.setOpenAction(() -> { - cvChapterTray.setTrayState(false, 200); - cvFrame.setTrayState(false, 200); - cvDesc.resetCanvas(); - if(selectedLine != null) - { - txDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 0, 0), QuestTranslation.translate(selectedLine.getUnlocalisedDescription()), true); - txDesc.setColor(PresetColor.TEXT_AUX_0.getColor());//.setFontSize(10); - cvDesc.addCulledPanel(txDesc, false); - cvDesc.refreshScrollBounds(); - scDesc.setEnabled(cvDesc.getScrollBounds().getHeight() > 0); - } else - { - scDesc.setEnabled(false); - } - }); - cvBackground.addPanel(cvDescTray); - - cvDesc = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 20, 8), 0)); - cvDescTray.getCanvasOpen().addPanel(cvDesc); - - scDesc = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-16, 8, 8, 8), 0)); - cvDesc.setScrollDriverY(scDesc); - cvDescTray.getCanvasOpen().addPanel(scDesc); - - // === LEFT SIDEBAR === - - PanelButton btnTrayToggle = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 24, 32, 16, 0), -1, ""); - btnTrayToggle.setIcon(PresetIcon.ICON_BOOKMARK.getTexture(), selectedLineId < 0 ? new GuiColorPulse(0xFFFFFFFF, 0xFF444444, 2F, 0F) : new GuiColorStatic(0xFFFFFFFF), 0); - btnTrayToggle.setClickAction((b) -> { - cvFrame.setTrayState(cvChapterTray.isTrayOpen(), 200); - cvChapterTray.setTrayState(!cvChapterTray.isTrayOpen(), 200); - btnTrayToggle.setIcon(PresetIcon.ICON_BOOKMARK.getTexture()); - }); - btnTrayToggle.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.title.quest_lines"))); - cvBackground.addPanel(btnTrayToggle); - - PanelButton btnDescToggle = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 40, 32, 16, 0), -1, "").setIcon(PresetIcon.ICON_DESC.getTexture()); - btnDescToggle.setClickAction((b) -> { - cvFrame.setTrayState(cvDescTray.isTrayOpen(), 200); - cvDescTray.setTrayState(!cvDescTray.isTrayOpen(), 200); - }); - btnDescToggle.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.gui.description"))); - cvBackground.addPanel(btnDescToggle); - - PanelButton fitView = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 72, 32, 16, -2), 5, ""); - fitView.setIcon(PresetIcon.ICON_BOX_FIT.getTexture()); - fitView.setClickAction((b) -> { - if(cvQuest.getQuestLine() != null) cvQuest.fitToWindow(); - }); - fitView.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.zoom_fit"))); - cvBackground.addPanel(fitView); - - claimAll = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 56, 32, 16, -2), -1, ""); - claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture()); - claimAll.setClickAction((b) -> { - if(cvQuest.getQuestButtons().size() <= 0) return; - List claimIdList = new ArrayList<>(); - for(PanelButtonQuest pbQuest : cvQuest.getQuestButtons()) - { - IQuest q = pbQuest.getStoredValue().getValue(); - if(q.getRewards().size() > 0 && q.canClaim(mc.player)) claimIdList.add(pbQuest.getStoredValue().getID()); - } - - int[] cIDs = new int[claimIdList.size()]; - for(int i = 0; i < cIDs.length; i++) - { - cIDs[i] = claimIdList.get(i); - } - - NetQuestAction.requestClaim(cIDs); - claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorStatic(0xFF444444), 0); - }); - claimAll.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.claim_all"))); - cvBackground.addPanel(claimAll); - - // The Jester1147 button - PanelButton btnTrayLock = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 88, 32, 16, -2), -1, "").setIcon(trayLock ? PresetIcon.ICON_LOCKED.getTexture() : PresetIcon.ICON_UNLOCKED.getTexture()); - btnTrayLock.setClickAction((b) -> { - trayLock = !trayLock; - b.setIcon(trayLock ? PresetIcon.ICON_LOCKED.getTexture() : PresetIcon.ICON_UNLOCKED.getTexture()); - }); - btnTrayLock.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.lock_tray"))); - cvBackground.addPanel(btnTrayLock); - - // === CHAPTER VIEWPORT === - - CanvasQuestLine oldCvQuest = cvQuest; - cvQuest = new CanvasQuestLine(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), 2); - cvFrame.addPanel(cvQuest); - - if(selectedLine != null) - { - cvQuest.setQuestLine(selectedLine); - - if(oldCvQuest != null) - { - cvQuest.setZoom(oldCvQuest.getZoom()); - cvQuest.setScrollX(oldCvQuest.getScrollX()); - cvQuest.setScrollY(oldCvQuest.getScrollY()); - cvQuest.refreshScrollBounds(); - cvQuest.updatePanelScroll(); - } - - txTitle.setText(QuestTranslation.translate(selectedLine.getUnlocalisedName())); - icoChapter.setTexture(new OreDictTexture(1F, selectedLine.getProperty(NativeProps.ICON), false, true), null); - } - - // === MISC === - - cvChapterTray.setTrayState(oldState1, 1); - cvDescTray.setTrayState(oldState2, 1); - - refreshChapterVisibility(); - refreshClaimAll(); + + boolean canEdit = QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player); + boolean preOpen = trayLock && cvChapterTray != null && cvChapterTray.isTrayOpen(); + if (trayLock && cvDescTray != null && cvDescTray.isTrayOpen()) { preOpen = true; } + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelButton btnExit = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 8, -24, 32, 16, 0), -1, "").setIcon( + PresetIcon.ICON_PG_PREV.getTexture()); + btnExit.setClickAction((b) -> mc.displayGuiScreen(parent)); + btnExit.setTooltip(Collections.singletonList(QuestTranslation.translate("gui.back"))); + cvBackground.addPanel(btnExit); + + if (canEdit) { + PanelButton btnEdit = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 8, -40, 32, 16, 0), -1, "").setIcon( + PresetIcon.ICON_GEAR.getTexture()); + btnEdit.setClickAction((b) -> mc.displayGuiScreen(new GuiQuestLinesEditor(this))); + btnEdit.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.edit"))); + cvBackground.addPanel(btnEdit); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + txTitle = new PanelTextBox(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0F), new GuiPadding(60, 12, 0, -24), 0), ""); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + icoChapter = new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, 40, 8, 16, 16, 0), null); + cvBackground.addPanel(icoChapter); + + cvFrame = new CanvasHoverTray(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(40 + 150 + 24, 24, 8, 8), 0), + new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(40, 24, 8, 8), 0), + PresetTexture.AUX_FRAME_0.getTexture()); + cvFrame.setManualOpen(true); + //CanvasTextured cvFrame = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(40, 24, 8, 8), 0), PresetTexture.AUX_FRAME_0.getTexture()); + cvBackground.addPanel(cvFrame); + cvFrame.setTrayState(!preOpen, 1); + // These would probably be more annoying than useful if you just wanted to check a tray but not lose your position + //cvFrame.setOpenAction(() -> cvQuest.fitToWindow()); + //cvFrame.setCloseAction(() -> cvQuest.fitToWindow()); + + // === CHAPTER TRAY === + + boolean oldState1 = trayLock && cvChapterTray != null && cvChapterTray.isTrayOpen(); + cvChapterTray = new CanvasHoverTray(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -24, 8), -1), + new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -40 - 150 - 24, 8), + -1), PresetTexture.PANEL_INNER.getTexture()); + cvChapterTray.setManualOpen(true); + cvChapterTray.setOpenAction(() -> { + cvDescTray.setTrayState(false, 200); + cvFrame.setTrayState(false, 200); + buildChapterList(); + }); + cvBackground.addPanel(cvChapterTray); + + cvLines = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 16, 8), 0)); + cvChapterTray.getCanvasOpen().addPanel(cvLines); + + scLines = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-16, 8, 8, 8), 0)); + cvLines.setScrollDriverY(scLines); + cvChapterTray.getCanvasOpen().addPanel(scLines); + + // === DESCRIPTION TRAY === + + boolean oldState2 = trayLock && cvDescTray != null && cvDescTray.isTrayOpen(); + cvDescTray = new CanvasHoverTray(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -24, 8), -1), + new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(40, 24, -40 - 150 - 24, 8), + -1), PresetTexture.PANEL_INNER.getTexture()); + cvDescTray.setManualOpen(true); + cvDescTray.setOpenAction(() -> { + cvChapterTray.setTrayState(false, 200); + cvFrame.setTrayState(false, 200); + cvDesc.resetCanvas(); + if (selectedLine != null) { + txDesc = new PanelTextBox(new GuiRectangle(0, 0, cvDesc.getTransform().getWidth(), 0, 0), + QuestTranslation.translate(selectedLine.getUnlocalisedDescription()), true); + txDesc.setColor(PresetColor.TEXT_AUX_0.getColor());//.setFontSize(10); + cvDesc.addCulledPanel(txDesc, false); + cvDesc.refreshScrollBounds(); + scDesc.setEnabled(cvDesc.getScrollBounds().getHeight() > 0); + } else { + scDesc.setEnabled(false); + } + }); + cvBackground.addPanel(cvDescTray); + + cvDesc = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 20, 8), 0)); + cvDescTray.getCanvasOpen().addPanel(cvDesc); + + scDesc = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-16, 8, 8, 8), 0)); + cvDesc.setScrollDriverY(scDesc); + cvDescTray.getCanvasOpen().addPanel(scDesc); + + // === LEFT SIDEBAR === + + PanelButton btnTrayToggle = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 24, 32, 16, 0), -1, ""); + btnTrayToggle.setIcon(PresetIcon.ICON_BOOKMARK.getTexture(), + selectedLineId < 0 ? new GuiColorPulse(0xFFFFFFFF, 0xFF444444, 2F, 0F) + : new GuiColorStatic(0xFFFFFFFF), 0); + btnTrayToggle.setClickAction((b) -> { + cvFrame.setTrayState(cvChapterTray.isTrayOpen(), 200); + cvChapterTray.setTrayState(!cvChapterTray.isTrayOpen(), 200); + btnTrayToggle.setIcon(PresetIcon.ICON_BOOKMARK.getTexture()); + }); + btnTrayToggle.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.title.quest_lines"))); + cvBackground.addPanel(btnTrayToggle); + + PanelButton btnDescToggle = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 40, 32, 16, 0), -1, "").setIcon( + PresetIcon.ICON_DESC.getTexture()); + btnDescToggle.setClickAction((b) -> { + cvFrame.setTrayState(cvDescTray.isTrayOpen(), 200); + cvDescTray.setTrayState(!cvDescTray.isTrayOpen(), 200); + }); + btnDescToggle.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.gui.description"))); + cvBackground.addPanel(btnDescToggle); + + PanelButton fitView = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 72, 32, 16, -2), 5, ""); + fitView.setIcon(PresetIcon.ICON_BOX_FIT.getTexture()); + fitView.setClickAction((b) -> { + if (cvQuest.getQuestLine() != null) { cvQuest.fitToWindow(); } + }); + fitView.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.zoom_fit"))); + cvBackground.addPanel(fitView); + + claimAll = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 56, 32, 16, -2), -1, ""); + claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture()); + claimAll.setClickAction((b) -> { + if (cvQuest.getQuestButtons().isEmpty()) { return; } + List claimIdList = new ArrayList<>(); + for (PanelButtonQuest pbQuest : cvQuest.getQuestButtons()) { + IQuest q = pbQuest.getStoredValue().getValue(); + if (q.getRewards().size() > 0 && q.canClaim(mc.player)) { claimIdList.add(pbQuest.getStoredValue().getID()); } + } + + int[] cIDs = new int[claimIdList.size()]; + for (int i = 0; i < cIDs.length; i++) { + cIDs[i] = claimIdList.get(i); + } + + NetQuestAction.requestClaim(cIDs); + claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorStatic(0xFF444444), 0); + }); + claimAll.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.claim_all"))); + cvBackground.addPanel(claimAll); + + // The Jester1147 button + PanelButton btnTrayLock = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 88, 32, 16, -2), -1, "").setIcon( + trayLock ? PresetIcon.ICON_LOCKED.getTexture() : PresetIcon.ICON_UNLOCKED.getTexture()); + btnTrayLock.setClickAction((b) -> { + trayLock = !trayLock; + b.setIcon(trayLock ? PresetIcon.ICON_LOCKED.getTexture() : PresetIcon.ICON_UNLOCKED.getTexture()); + }); + btnTrayLock.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.lock_tray"))); + cvBackground.addPanel(btnTrayLock); + + // === CHAPTER VIEWPORT === + + CanvasQuestLine oldCvQuest = cvQuest; + cvQuest = new CanvasQuestLine(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), 2); + cvFrame.addPanel(cvQuest); + + if (selectedLine != null) { + cvQuest.setQuestLine(selectedLine); + + if (oldCvQuest != null) { + cvQuest.setZoom(oldCvQuest.getZoom()); + cvQuest.setScrollX(oldCvQuest.getScrollX()); + cvQuest.setScrollY(oldCvQuest.getScrollY()); + cvQuest.refreshScrollBounds(); + cvQuest.updatePanelScroll(); + } + + txTitle.setText(QuestTranslation.translate(selectedLine.getUnlocalisedName())); + icoChapter.setTexture(new OreDictTexture(1F, selectedLine.getProperty(NativeProps.ICON), false, true), null); } - - // TODO: Change CanvasQuestLine to NOT need these panel events anymore - private void onButtonPress(PEventButton event) - { - Minecraft mc = Minecraft.getMinecraft(); - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Quest Instance Select - { - @SuppressWarnings("unchecked") - DBEntry quest = ((PanelButtonStorage>)btn).getStoredValue(); - GuiHome.bookmark = new GuiQuest(this, quest.getID()); - - mc.displayGuiScreen(GuiHome.bookmark); - } + + // === MISC === + + cvChapterTray.setTrayState(oldState1, 1); + cvDescTray.setTrayState(oldState2, 1); + + refreshChapterVisibility(); + refreshClaimAll(); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void refreshChapterVisibility() + } + + // TODO: Change CanvasQuestLine to NOT need these panel events anymore + private void onButtonPress(PEventButton event) { + Minecraft mc = Minecraft.getMinecraft(); + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Quest Instance Select { - boolean canEdit = QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player); - List> lineList = QuestLineDatabase.INSTANCE.getSortedEntries(); - this.visChapters.clear(); - UUID playerID = QuestingAPI.getQuestingUUID(mc.player); - - for(DBEntry dbEntry : lineList) - { - IQuestLine ql = dbEntry.getValue(); - EnumQuestVisibility vis = ql.getProperty(NativeProps.VISIBILITY); - if(!canEdit && vis == EnumQuestVisibility.HIDDEN) continue; - - boolean show = false; - boolean unlocked = false; - boolean complete = false; - boolean allComplete = true; - boolean pendingClaim = false; - - if(canEdit) - { - show = true; - unlocked = true; - complete = true; - } - - for(DBEntry qID : ql.getEntries()) - { - IQuest q = QuestDatabase.INSTANCE.getValue(qID.getID()); - if(q == null) continue; - - if(allComplete && !q.isComplete(playerID)) allComplete = false; - if(!pendingClaim && q.isComplete(playerID) && !q.hasClaimed(playerID)) pendingClaim = true; - if(!unlocked && q.isUnlocked(playerID)) unlocked = true; - if(!complete && q.isComplete(playerID)) complete = true; - if(!show && QuestCache.isQuestShown(q, playerID, mc.player)) show = true; - if(unlocked && complete && show && pendingClaim && !allComplete) break; - } - - if(vis == EnumQuestVisibility.COMPLETED && !complete) - { - continue; - } else if(vis == EnumQuestVisibility.UNLOCKED && !unlocked) - { - continue; - } - - int val = pendingClaim ? 1 : 0; - if(allComplete) val |= 2; - if(!show) val |= 4; - - visChapters.add(new Tuple<>(dbEntry, val)); - } - - if(cvChapterTray.isTrayOpen()) buildChapterList(); + @SuppressWarnings("unchecked") + DBEntry quest = ((PanelButtonStorage>) btn).getStoredValue(); + GuiHome.bookmark = new GuiQuest(this, quest.getID()); + + mc.displayGuiScreen(GuiHome.bookmark); } - - private void buildChapterList() - { - cvLines.resetCanvas(); - btnListRef.clear(); - - int listW = cvLines.getTransform().getWidth(); - - for(int n = 0; n < visChapters.size(); n++) - { - DBEntry entry = visChapters.get(n).getFirst(); - int vis = visChapters.get(n).getSecond(); - - cvLines.addPanel(new PanelGeneric(new GuiRectangle(0, n * 16, 16, 16, 0), new OreDictTexture(1F, entry.getValue().getProperty(NativeProps.ICON), false, true))); - - if((vis & 1) > 0) - { - cvLines.addPanel(new PanelGeneric(new GuiRectangle(8, n * 16 + 8, 8, 8, -1), new GuiTextureColored(PresetIcon.ICON_NOTICE.getTexture(), new GuiColorStatic(0xFFFFFF00)))); - } else if((vis & 2) > 0) - { - cvLines.addPanel(new PanelGeneric(new GuiRectangle(8, n * 16 + 8, 8, 8, -1), new GuiTextureColored(PresetIcon.ICON_TICK.getTexture(), new GuiColorStatic(0xFF00FF00)))); - } - PanelButtonStorage> btnLine = new PanelButtonStorage<>(new GuiRectangle(16, n * 16, listW - 16, 16, 0), 1, QuestTranslation.translate(entry.getValue().getUnlocalisedName()), entry); - btnLine.setTextAlignment(0); - btnLine.setActive((vis & 4) == 0 && entry.getID() != selectedLineId); - btnLine.setCallback((q) -> { - btnListRef.forEach((b) -> {if(b.getStoredValue().getID() == selectedLineId) b.setActive(true);}); - btnLine.setActive(false); - selectedLine = q.getValue(); - selectedLineId = q.getID(); - cvQuest.setQuestLine(q.getValue()); - icoChapter.setTexture(new OreDictTexture(1F, q.getValue().getProperty(NativeProps.ICON), false, true), null); - txTitle.setText(QuestTranslation.translate(q.getValue().getUnlocalisedName())); - if(!trayLock) - { - cvFrame.setTrayState(true, 200); - cvChapterTray.setTrayState(false, 200); - cvQuest.fitToWindow(); - } - refreshClaimAll(); - }); - cvLines.addPanel(btnLine); - btnListRef.add(btnLine); - } - - cvLines.refreshScrollBounds(); - scLines.setEnabled(cvLines.getScrollBounds().getHeight() > 0); + } + + private void refreshChapterVisibility() { + boolean canEdit = QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player); + List> lineList = QuestLineDatabase.INSTANCE.getSortedEntries(); + this.visChapters.clear(); + UUID playerID = QuestingAPI.getQuestingUUID(mc.player); + + for (DBEntry dbEntry : lineList) { + IQuestLine ql = dbEntry.getValue(); + EnumQuestVisibility vis = ql.getProperty(NativeProps.VISIBILITY); + if (!canEdit && vis == EnumQuestVisibility.HIDDEN) { continue; } + + boolean show = false; + boolean unlocked = false; + boolean complete = false; + boolean allComplete = true; + boolean pendingClaim = false; + + if (canEdit) { + show = true; + unlocked = true; + complete = true; + } + + for (DBEntry qID : ql.getEntries()) { + IQuest q = QuestDatabase.INSTANCE.getValue(qID.getID()); + if (q == null) { continue; } + + if (allComplete && !q.isComplete(playerID)) { allComplete = false; } + if (!pendingClaim && q.isComplete(playerID) && !q.hasClaimed(playerID)) { pendingClaim = true; } + if (!unlocked && q.isUnlocked(playerID)) { unlocked = true; } + if (!complete && q.isComplete(playerID)) { complete = true; } + if (!show && QuestCache.isQuestShown(q, playerID, mc.player)) { show = true; } + if (unlocked && complete && show && pendingClaim && !allComplete) { break; } + } + + if (vis == EnumQuestVisibility.COMPLETED && !complete) { + continue; + } else if (vis == EnumQuestVisibility.UNLOCKED && !unlocked) { + continue; + } + + int val = pendingClaim ? 1 : 0; + if (allComplete) { val |= 2; } + if (!show) { val |= 4; } + + visChapters.add(new Tuple<>(dbEntry, val)); } - - private void refreshContent() - { - if(selectedLineId >= 0) - { - selectedLine = QuestLineDatabase.INSTANCE.getValue(selectedLineId); - if(selectedLine == null) selectedLineId = -1; - } else - { - selectedLine = null; - } - - float zoom = cvQuest.getZoom(); - int sx = cvQuest.getScrollX(); - int sy = cvQuest.getScrollY(); - /*if(cvQuest.getQuestLine() != selectedLine)*/ cvQuest.setQuestLine(selectedLine); - cvQuest.setZoom(zoom); - cvQuest.setScrollX(sx); - cvQuest.setScrollY(sy); - cvQuest.refreshScrollBounds(); - cvQuest.updatePanelScroll(); - - if(selectedLine != null) - { - txTitle.setText(QuestTranslation.translate(selectedLine.getUnlocalisedName())); - icoChapter.setTexture(new OreDictTexture(1F, selectedLine.getProperty(NativeProps.ICON), false, true), null); - } else - { - txTitle.setText(""); - icoChapter.setTexture(null, null); + + if (cvChapterTray.isTrayOpen()) { buildChapterList(); } + } + + private void buildChapterList() { + cvLines.resetCanvas(); + btnListRef.clear(); + + int listW = cvLines.getTransform().getWidth(); + + for (int n = 0; n < visChapters.size(); n++) { + DBEntry entry = visChapters.get(n).getFirst(); + int vis = visChapters.get(n).getSecond(); + + cvLines.addPanel(new PanelGeneric(new GuiRectangle(0, n * 16, 16, 16, 0), + new OreDictTexture(1F, entry.getValue().getProperty(NativeProps.ICON), false, + true))); + + if ((vis & 1) > 0) { + cvLines.addPanel(new PanelGeneric(new GuiRectangle(8, n * 16 + 8, 8, 8, -1), + new GuiTextureColored(PresetIcon.ICON_NOTICE.getTexture(), + new GuiColorStatic(0xFFFFFF00)))); + } else if ((vis & 2) > 0) { + cvLines.addPanel(new PanelGeneric(new GuiRectangle(8, n * 16 + 8, 8, 8, -1), + new GuiTextureColored(PresetIcon.ICON_TICK.getTexture(), + new GuiColorStatic(0xFF00FF00)))); + } + PanelButtonStorage> btnLine = + new PanelButtonStorage<>(new GuiRectangle(16, n * 16, listW - 16, 16, 0), 1, + QuestTranslation.translate(entry.getValue().getUnlocalisedName()), entry); + btnLine.setTextAlignment(0); + btnLine.setActive((vis & 4) == 0 && entry.getID() != selectedLineId); + btnLine.setCallback((q) -> { + btnListRef.forEach((b) -> { if (b.getStoredValue().getID() == selectedLineId) { b.setActive(true); } }); + btnLine.setActive(false); + selectedLine = q.getValue(); + selectedLineId = q.getID(); + cvQuest.setQuestLine(q.getValue()); + icoChapter.setTexture(new OreDictTexture(1F, q.getValue().getProperty(NativeProps.ICON), false, true), null); + txTitle.setText(QuestTranslation.translate(q.getValue().getUnlocalisedName())); + if (!trayLock) { + cvFrame.setTrayState(true, 200); + cvChapterTray.setTrayState(false, 200); + cvQuest.fitToWindow(); } - refreshClaimAll(); + }); + cvLines.addPanel(btnLine); + btnListRef.add(btnLine); } - - private void refreshClaimAll() - { - if(cvQuest.getQuestLine() == null || cvQuest.getQuestButtons().size() <= 0) - { - claimAll.setActive(false); - claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorStatic(0xFF444444), 0); - return; - } - - for(PanelButtonQuest btn : cvQuest.getQuestButtons()) - { - if(btn.getStoredValue().getValue().canClaim(mc.player)) - { - claimAll.setActive(true); - claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorPulse(0xFFFFFFFF, 0xFF444444, 2F, 0F), 0); - return; - } - } - - claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorStatic(0xFF444444), 0); - claimAll.setActive(false); + + cvLines.refreshScrollBounds(); + scLines.setEnabled(cvLines.getScrollBounds().getHeight() > 0); + } + + private void refreshContent() { + if (selectedLineId >= 0) { + selectedLine = QuestLineDatabase.INSTANCE.getValue(selectedLineId); + if (selectedLine == null) { selectedLineId = -1; } + } else { + selectedLine = null; + } + + float zoom = cvQuest.getZoom(); + int sx = cvQuest.getScrollX(); + int sy = cvQuest.getScrollY(); + /*if(cvQuest.getQuestLine() != selectedLine)*/ + cvQuest.setQuestLine(selectedLine); + cvQuest.setZoom(zoom); + cvQuest.setScrollX(sx); + cvQuest.setScrollY(sy); + cvQuest.refreshScrollBounds(); + cvQuest.updatePanelScroll(); + + if (selectedLine != null) { + txTitle.setText(QuestTranslation.translate(selectedLine.getUnlocalisedName())); + icoChapter.setTexture(new OreDictTexture(1F, selectedLine.getProperty(NativeProps.ICON), false, true), null); + } else { + txTitle.setText(""); + icoChapter.setTexture(null, null); } + + refreshClaimAll(); + } + + private void refreshClaimAll() { + if (cvQuest.getQuestLine() == null || cvQuest.getQuestButtons().isEmpty()) { + claimAll.setActive(false); + claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorStatic(0xFF444444), 0); + return; + } + + for (PanelButtonQuest btn : cvQuest.getQuestButtons()) { + if (btn.getStoredValue().getValue().canClaim(mc.player)) { + claimAll.setActive(true); + claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorPulse(0xFFFFFFFF, 0xFF444444, 2F, 0F), 0); + return; + } + } + + claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture(), new GuiColorStatic(0xFF444444), 0); + claimAll.setActive(false); + } } diff --git a/src/main/java/betterquesting/client/gui2/GuiThemes.java b/src/main/java/betterquesting/client/gui2/GuiThemes.java index 7e10fdf4a..ab55a0437 100644 --- a/src/main/java/betterquesting/client/gui2/GuiThemes.java +++ b/src/main/java/betterquesting/client/gui2/GuiThemes.java @@ -35,118 +35,153 @@ import java.util.List; -public class GuiThemes extends GuiScreenCanvas -{ - // Last value of the scrollbar before loading new theme - private PanelVScrollBar scrollPanel; - - public GuiThemes(GuiScreen parent) - { - super(parent); - } - - @Override - public void initPanel() - { - super.initPanel(); - - // Background panel - CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(bgCan); - - // Inner canvas bounds - CanvasEmpty inCan = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0)); - bgCan.addPanel(inCan); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.title.select_theme")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - inCan.addPanel(panTxt); - - PanelButton btnExit = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, new GuiPadding(-100, -16, -100, 0), 0), 0, QuestTranslation.translate("gui.done")); - btnExit.setClickAction((b) -> mc.displayGuiScreen(ThemeRegistry.INSTANCE.getGui(PresetGUIs.HOME, GArgsNone.NONE))); - bgCan.addPanel(btnExit); - - CanvasScrolling canScroll = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(0, 16, 16, 16), 0)); - inCan.addPanel(canScroll); - - ThemeRegistry.INSTANCE.loadResourceThemes(); - List themes = ThemeRegistry.INSTANCE.getAllThemes(); - int width = canScroll.getTransform().getWidth(); - - IGuiTheme curTheme = ThemeRegistry.INSTANCE.getCurrentTheme(); - - for(int i = 0; i < themes.size(); i++) - { - IGuiTheme theme = themes.get(i); - GuiRectangle trans = new GuiRectangle(0, i * 24, width, 24, 0); - PanelButtonStorage pbs = new PanelButtonStorage<>(trans, -1, theme.getName(), theme.getID()); - pbs.setCallback((res) -> { - float scroll = scrollPanel.readValueRaw(); - ThemeRegistry.INSTANCE.setTheme(res); - this.initGui(); - scrollPanel.writeValueRaw(scroll); - }); - canScroll.addPanel(pbs); - pbs.setActive(curTheme == null || !curTheme.getID().equals(theme.getID())); - } - - PanelVScrollBar vsb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); - inCan.addPanel(vsb); - vsb.getTransform().setParent(canScroll.getTransform()); - canScroll.setScrollDriverY(vsb); - - scrollPanel = vsb; - - // === PREVIEW PANELS === - - CanvasEmpty preCan = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 16, 0, 16), 0)); - inCan.addPanel(preCan); - - CanvasTextured preCanIn0 = new CanvasTextured(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - preCan.addPanel(preCanIn0); - - preCanIn0.addPanel(new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -32, -8, 64, 16, 0), "EXAMPLE").setAlignment(1).setColor(PresetColor.TEXT_MAIN.getColor())); - - CanvasTextured preCanIn1 = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_INNER.getTexture()); - preCan.addPanel(preCanIn1); - - preCanIn1.addPanel(new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -32, -8, 64, 16, 0), "EXAMPLE").setAlignment(1).setColor(PresetColor.TEXT_AUX_0.getColor())); - - CanvasTextured preCanIn2 = new CanvasTextured(new GuiTransform(GuiAlign.HALF_BOTTOM, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.AUX_FRAME_0.getTexture()); - preCan.addPanel(preCanIn2); - - IGuiTexture icoSlides = new SlideShowTexture(1F, - new GuiTextureColored(PresetTexture.QUEST_NORM_0.getTexture(), PresetColor.QUEST_ICON_LOCKED.getColor()), - new GuiTextureColored(PresetTexture.QUEST_NORM_1.getTexture(), PresetColor.QUEST_ICON_UNLOCKED.getColor()), - new GuiTextureColored(PresetTexture.QUEST_NORM_2.getTexture(), PresetColor.QUEST_ICON_PENDING.getColor()), - new GuiTextureColored(PresetTexture.QUEST_NORM_3.getTexture(), PresetColor.QUEST_ICON_COMPLETE.getColor()), - new GuiTextureColored(PresetTexture.QUEST_MAIN_0.getTexture(), PresetColor.QUEST_ICON_LOCKED.getColor()), - new GuiTextureColored(PresetTexture.QUEST_MAIN_1.getTexture(), PresetColor.QUEST_ICON_UNLOCKED.getColor()), - new GuiTextureColored(PresetTexture.QUEST_MAIN_2.getTexture(), PresetColor.QUEST_ICON_PENDING.getColor()), - new GuiTextureColored(PresetTexture.QUEST_MAIN_3.getTexture(), PresetColor.QUEST_ICON_COMPLETE.getColor()), - new GuiTextureColored(PresetTexture.QUEST_AUX_0.getTexture(), PresetColor.QUEST_ICON_LOCKED.getColor()), - new GuiTextureColored(PresetTexture.QUEST_AUX_1.getTexture(), PresetColor.QUEST_ICON_UNLOCKED.getColor()), - new GuiTextureColored(PresetTexture.QUEST_AUX_2.getTexture(), PresetColor.QUEST_ICON_PENDING.getColor()), - new GuiTextureColored(PresetTexture.QUEST_AUX_3.getTexture(), PresetColor.QUEST_ICON_COMPLETE.getColor())); - PanelGeneric pqp = new PanelGeneric(new GuiTransform(new Vector4f(0.25F, 0.5F, 0.25F, 0.5F), -12, -12, 24, 24, 0), icoSlides); - preCanIn2.addPanel(pqp); - - CanvasTextured itemFrame = new CanvasTextured(new GuiTransform(new Vector4f(0.75F, 0.5F, 0.75F, 0.5F), -12, -12, 24, 24, 0), PresetTexture.ITEM_FRAME.getTexture()); - preCanIn2.addPanel(itemFrame); - - itemFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(1, 1, 1, 1), 0), new ItemTexture(new BigItemStack(BetterQuesting.guideBook, 9999, 0), true, true))); - - IGuiLine linSeq = new GuiLineSequence(1F, PresetLine.QUEST_LOCKED.getLine(), PresetLine.QUEST_UNLOCKED.getLine(), PresetLine.QUEST_PENDING.getLine(), PresetLine.QUEST_COMPLETE.getLine()); - IGuiColor colSeq = new GuiColorSequence(1F, PresetColor.QUEST_LINE_LOCKED.getColor(), PresetColor.QUEST_LINE_UNLOCKED.getColor(), PresetColor.QUEST_LINE_PENDING.getColor(), PresetColor.QUEST_LINE_COMPLETE.getColor()); - preCanIn2.addPanel(new PanelLine(pqp.getTransform(), itemFrame.getTransform(), linSeq, 4, colSeq, 1)); - - preCanIn2.addPanel(new PanelTextBox(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), "EXAMPLE").setAlignment(1).setColor(PresetColor.TEXT_AUX_1.getColor())); - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 16, 0, 0, 0); - ls0.setParent(inCan.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -16, 0, 0, 0); - le0.setParent(inCan.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - inCan.addPanel(paLine0); - } +public class GuiThemes extends GuiScreenCanvas { + // Last value of the scrollbar before loading new theme + private PanelVScrollBar scrollPanel; + + public GuiThemes(GuiScreen parent) { + super(parent); + } + + @Override + public void initPanel() { + super.initPanel(); + + // Background panel + CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(bgCan); + + // Inner canvas bounds + CanvasEmpty inCan = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0)); + bgCan.addPanel(inCan); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate( + "betterquesting.title.select_theme")).setAlignment(1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + inCan.addPanel(panTxt); + + PanelButton btnExit = + new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, new GuiPadding(-100, -16, -100, 0), 0), 0, + QuestTranslation.translate("gui.done")); + btnExit.setClickAction((b) -> mc.displayGuiScreen(ThemeRegistry.INSTANCE.getGui(PresetGUIs.HOME, GArgsNone.NONE))); + bgCan.addPanel(btnExit); + + CanvasScrolling canScroll = + new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(0, 16, 16, 16), 0)); + inCan.addPanel(canScroll); + + ThemeRegistry.INSTANCE.loadResourceThemes(); + List themes = ThemeRegistry.INSTANCE.getAllThemes(); + int width = canScroll.getTransform().getWidth(); + + IGuiTheme curTheme = ThemeRegistry.INSTANCE.getCurrentTheme(); + + for (int i = 0; i < themes.size(); i++) { + IGuiTheme theme = themes.get(i); + GuiRectangle trans = new GuiRectangle(0, i * 24, width, 24, 0); + PanelButtonStorage pbs = new PanelButtonStorage<>(trans, -1, theme.getName(), theme.getID()); + pbs.setCallback((res) -> { + float scroll = scrollPanel.readValueRaw(); + ThemeRegistry.INSTANCE.setTheme(res); + this.initGui(); + scrollPanel.writeValueRaw(scroll); + }); + canScroll.addPanel(pbs); + pbs.setActive(curTheme == null || !curTheme.getID().equals(theme.getID())); + } + + PanelVScrollBar vsb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); + inCan.addPanel(vsb); + vsb.getTransform().setParent(canScroll.getTransform()); + canScroll.setScrollDriverY(vsb); + + scrollPanel = vsb; + + // === PREVIEW PANELS === + + CanvasEmpty preCan = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 16, 0, 16), 0)); + inCan.addPanel(preCan); + + CanvasTextured preCanIn0 = + new CanvasTextured(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + preCan.addPanel(preCanIn0); + + preCanIn0.addPanel( + new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -32, -8, 64, 16, 0), "EXAMPLE").setAlignment(1).setColor( + PresetColor.TEXT_MAIN.getColor())); + + CanvasTextured preCanIn1 = + new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_INNER.getTexture()); + preCan.addPanel(preCanIn1); + + preCanIn1.addPanel( + new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -32, -8, 64, 16, 0), "EXAMPLE").setAlignment(1).setColor( + PresetColor.TEXT_AUX_0.getColor())); + + CanvasTextured preCanIn2 = new CanvasTextured(new GuiTransform(GuiAlign.HALF_BOTTOM, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.AUX_FRAME_0.getTexture()); + preCan.addPanel(preCanIn2); + + IGuiTexture icoSlides = new SlideShowTexture(1F, + new GuiTextureColored(PresetTexture.QUEST_NORM_0.getTexture(), + PresetColor.QUEST_ICON_LOCKED.getColor()), + new GuiTextureColored(PresetTexture.QUEST_NORM_1.getTexture(), + PresetColor.QUEST_ICON_UNLOCKED.getColor()), + new GuiTextureColored(PresetTexture.QUEST_NORM_2.getTexture(), + PresetColor.QUEST_ICON_PENDING.getColor()), + new GuiTextureColored(PresetTexture.QUEST_NORM_3.getTexture(), + PresetColor.QUEST_ICON_COMPLETE.getColor()), + new GuiTextureColored(PresetTexture.QUEST_MAIN_0.getTexture(), + PresetColor.QUEST_ICON_LOCKED.getColor()), + new GuiTextureColored(PresetTexture.QUEST_MAIN_1.getTexture(), + PresetColor.QUEST_ICON_UNLOCKED.getColor()), + new GuiTextureColored(PresetTexture.QUEST_MAIN_2.getTexture(), + PresetColor.QUEST_ICON_PENDING.getColor()), + new GuiTextureColored(PresetTexture.QUEST_MAIN_3.getTexture(), + PresetColor.QUEST_ICON_COMPLETE.getColor()), + new GuiTextureColored(PresetTexture.QUEST_AUX_0.getTexture(), + PresetColor.QUEST_ICON_LOCKED.getColor()), + new GuiTextureColored(PresetTexture.QUEST_AUX_1.getTexture(), + PresetColor.QUEST_ICON_UNLOCKED.getColor()), + new GuiTextureColored(PresetTexture.QUEST_AUX_2.getTexture(), + PresetColor.QUEST_ICON_PENDING.getColor()), + new GuiTextureColored(PresetTexture.QUEST_AUX_3.getTexture(), + PresetColor.QUEST_ICON_COMPLETE.getColor())); + PanelGeneric pqp = + new PanelGeneric(new GuiTransform(new Vector4f(0.25F, 0.5F, 0.25F, 0.5F), -12, -12, 24, 24, 0), icoSlides); + preCanIn2.addPanel(pqp); + + CanvasTextured itemFrame = + new CanvasTextured(new GuiTransform(new Vector4f(0.75F, 0.5F, 0.75F, 0.5F), -12, -12, 24, 24, 0), + PresetTexture.ITEM_FRAME.getTexture()); + preCanIn2.addPanel(itemFrame); + + itemFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(1, 1, 1, 1), 0), + new ItemTexture(new BigItemStack(BetterQuesting.guideBook, 9999, 0), true, + true))); + + IGuiLine linSeq = new GuiLineSequence(1F, PresetLine.QUEST_LOCKED.getLine(), PresetLine.QUEST_UNLOCKED.getLine(), + PresetLine.QUEST_PENDING.getLine(), PresetLine.QUEST_COMPLETE.getLine()); + IGuiColor colSeq = + new GuiColorSequence(1F, PresetColor.QUEST_LINE_LOCKED.getColor(), PresetColor.QUEST_LINE_UNLOCKED.getColor(), + PresetColor.QUEST_LINE_PENDING.getColor(), PresetColor.QUEST_LINE_COMPLETE.getColor()); + preCanIn2.addPanel(new PanelLine(pqp.getTransform(), itemFrame.getTransform(), linSeq, 4, colSeq, 1)); + + preCanIn2.addPanel( + new PanelTextBox(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), "EXAMPLE").setAlignment(1) + .setColor( + PresetColor.TEXT_AUX_1.getColor())); + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 16, 0, 0, 0); + ls0.setParent(inCan.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -16, 0, 0, 0); + le0.setParent(inCan.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + inCan.addPanel(paLine0); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java b/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java index 5c6d942cc..e782ec515 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java @@ -35,220 +35,217 @@ import java.util.Collections; import java.util.List; -public class GuiFileBrowser extends GuiScreenCanvas implements IPEventListener -{ - private final ICallback callback; - private final FileFilter filter; - private final List selList = new ArrayList<>(); - private PanelTextBox txtTitle; - private File curDirectory; - - private CanvasScrolling cvSelected; - private CanvasFileDirectory cvDirectory; - private boolean multiSelect = true; - - public GuiFileBrowser(GuiScreen parent, ICallback callback, File directory, @Nullable FileFilter filter) - { - super(parent); - this.callback = callback; - this.curDirectory = directory == null ? null : directory.getAbsoluteFile(); - this.filter = filter; - } - - public GuiFileBrowser allowMultiSelect(boolean enable) - { - multiSelect = enable; - return this; - } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - txtTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), curDirectory == null ? "*" : curDirectory.getAbsolutePath()).setAlignment(1); - txtTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txtTitle); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); - - // === LEFT SIDE === - - CanvasEmpty cvLeft = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 24), 0)); - cvBackground.addPanel(cvLeft); - - PanelTextBox txtQuest = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.selection")).setAlignment(1); - txtQuest.setColor(PresetColor.TEXT_HEADER.getColor()); - cvLeft.addPanel(txtQuest); - - cvSelected = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); - cvLeft.addPanel(cvSelected); - - PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); - cvLeft.addPanel(scReq); - cvSelected.setScrollDriverY(scReq); - - // === RIGHT SIDE === - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); - cvBackground.addPanel(cvRight); - - PanelTextBox txtDb = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.folder")).setAlignment(1); - txtDb.setColor(PresetColor.TEXT_HEADER.getColor()); - cvRight.addPanel(txtDb); - - PanelTextField searchBox = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(16, 16, 24, -32), 0), "", FieldFilterString.INSTANCE); - searchBox.setWatermark("Search..."); - cvRight.addPanel(searchBox); - - cvDirectory = new CanvasFileDirectory(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 32, 8, 0), 0), curDirectory, filter) - { - @Override - protected boolean addResult(File entry, int index, int width) - { - if(!entry.isDirectory()) - { - PanelButtonStorage btnAdd = new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), -1, "", entry); - btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); - btnAdd.setActive(!selList.contains(entry)); - btnAdd.setCallback( value -> { - if(!multiSelect) selList.clear(); - selList.add(value); - refreshSelected(); - refreshSearch(); - }); - this.addPanel(btnAdd); - } else - { - // Keeps the scrolling region's left side from auto-cropping when no files are present to select. - PanelGeneric pnDummy = new PanelGeneric(new GuiRectangle(0, index * 16, 16, 16, 0), null); - this.addPanel(pnDummy); - } - - PanelButtonStorage btnEdit = new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), -1, curDirectory == null ? entry.getAbsolutePath() : entry.getName(), entry); - btnEdit.setActive(entry.isDirectory()); - btnEdit.setCallback(value -> { - curDirectory = value; - this.setCurDirectory(curDirectory); - txtTitle.setText(curDirectory == null ? "*" : curDirectory.getAbsolutePath()); - }); - this.addPanel(btnEdit); - - PanelGeneric pnIco = new PanelGeneric(new GuiRectangle(width - 16, index * 16, 16, 16, 0), entry.isDirectory() ? PresetIcon.ICON_FOLDER_OPEN.getTexture() : PresetIcon.ICON_FILE.getTexture()); - this.addPanel(pnIco); - - return true; - } - }; - cvRight.addPanel(cvDirectory); - - PanelButton selAll = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -24, 16, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - if(!multiSelect) return; - boolean changed = false; - - for(File file : cvDirectory.getResults()) - { - if(!file.isDirectory() && !selList.contains(file)) - { - selList.add(file); - changed = true; - } - } - - if(changed) - { - cvDirectory.refreshSearch(); - refreshSelected(); - } - } - }; - selAll.setActive(multiSelect); - selAll.setTooltip(Collections.singletonList("Select All")); - selAll.setIcon(PresetIcon.ICON_SELECTION.getTexture()); - cvRight.addPanel(selAll); - - searchBox.setCallback(cvDirectory::setSearchFilter); - - PanelVScrollBar scDb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 32, 0, 0), 0)); - cvRight.addPanel(scDb); - cvDirectory.setScrollDriverY(scDb); - - PanelButton btnNew = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - if(curDirectory == null) return; - curDirectory = curDirectory.getParentFile(); - cvDirectory.setCurDirectory(curDirectory); - txtTitle.setText(curDirectory == null ? "*" : curDirectory.getAbsolutePath()); +public class GuiFileBrowser extends GuiScreenCanvas implements IPEventListener { + private final ICallback callback; + private final FileFilter filter; + private final List selList = new ArrayList<>(); + private PanelTextBox txtTitle; + private File curDirectory; + + private CanvasScrolling cvSelected; + private CanvasFileDirectory cvDirectory; + private boolean multiSelect = true; + + public GuiFileBrowser(GuiScreen parent, ICallback callback, File directory, @Nullable FileFilter filter) { + super(parent); + this.callback = callback; + this.curDirectory = directory == null ? null : directory.getAbsoluteFile(); + this.filter = filter; + } + + public GuiFileBrowser allowMultiSelect(boolean enable) { + multiSelect = enable; + return this; + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + txtTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + curDirectory == null ? "*" : curDirectory.getAbsolutePath()).setAlignment(1); + txtTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txtTitle); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.done"))); + + // === LEFT SIDE === + + CanvasEmpty cvLeft = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 24), 0)); + cvBackground.addPanel(cvLeft); + + PanelTextBox txtQuest = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("betterquesting.gui.selection")).setAlignment( + 1); + txtQuest.setColor(PresetColor.TEXT_HEADER.getColor()); + cvLeft.addPanel(txtQuest); + + cvSelected = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); + cvLeft.addPanel(cvSelected); + + PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); + cvLeft.addPanel(scReq); + cvSelected.setScrollDriverY(scReq); + + // === RIGHT SIDE === + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); + cvBackground.addPanel(cvRight); + + PanelTextBox txtDb = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("betterquesting.gui.folder")).setAlignment(1); + txtDb.setColor(PresetColor.TEXT_HEADER.getColor()); + cvRight.addPanel(txtDb); + + PanelTextField searchBox = + new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(16, 16, 24, -32), 0), "", + FieldFilterString.INSTANCE); + searchBox.setWatermark("Search..."); + cvRight.addPanel(searchBox); + + cvDirectory = + new CanvasFileDirectory(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 32, 8, 0), 0), curDirectory, + filter) { + @Override + protected boolean addResult(File entry, int index, int width) { + if (!entry.isDirectory()) { + PanelButtonStorage btnAdd = + new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), -1, "", entry); + btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); + btnAdd.setActive(!selList.contains(entry)); + btnAdd.setCallback(value -> { + if (!multiSelect) { selList.clear(); } + selList.add(value); + refreshSelected(); + refreshSearch(); + }); + this.addPanel(btnAdd); + } else { + // Keeps the scrolling region's left side from auto-cropping when no files are present to select. + PanelGeneric pnDummy = new PanelGeneric(new GuiRectangle(0, index * 16, 16, 16, 0), null); + this.addPanel(pnDummy); } + + PanelButtonStorage btnEdit = + new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), -1, + curDirectory == null ? entry.getAbsolutePath() : entry.getName(), entry); + btnEdit.setActive(entry.isDirectory()); + btnEdit.setCallback(value -> { + curDirectory = value; + this.setCurDirectory(curDirectory); + txtTitle.setText(curDirectory == null ? "*" : curDirectory.getAbsolutePath()); + }); + this.addPanel(btnEdit); + + PanelGeneric pnIco = new PanelGeneric(new GuiRectangle(width - 16, index * 16, 16, 16, 0), + entry.isDirectory() ? PresetIcon.ICON_FOLDER_OPEN.getTexture() + : PresetIcon.ICON_FILE.getTexture()); + this.addPanel(pnIco); + + return true; + } }; - btnNew.setIcon(PresetIcon.ICON_DIR_UP.getTexture()); - cvRight.addPanel(btnNew); - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - if(callback != null) callback.setValue(selList.toArray(new File[0])); - mc.displayGuiScreen(this.parent); + cvRight.addPanel(cvDirectory); + + PanelButton selAll = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -24, 16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + if (!multiSelect) { return; } + boolean changed = false; + + for (File file : cvDirectory.getResults()) { + if (!file.isDirectory() && !selList.contains(file)) { + selList.add(file); + changed = true; + } + } + + if (changed) { + cvDirectory.refreshSearch(); + refreshSelected(); } + } + }; + selAll.setActive(multiSelect); + selAll.setTooltip(Collections.singletonList("Select All")); + selAll.setIcon(PresetIcon.ICON_SELECTION.getTexture()); + cvRight.addPanel(selAll); + + searchBox.setCallback(cvDirectory::setSearchFilter); + + PanelVScrollBar scDb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 32, 0, 0), 0)); + cvRight.addPanel(scDb); + cvDirectory.setScrollDriverY(scDb); + + PanelButton btnNew = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + if (curDirectory == null) { return; } + curDirectory = curDirectory.getParentFile(); + cvDirectory.setCurDirectory(curDirectory); + txtTitle.setText(curDirectory == null ? "*" : curDirectory.getAbsolutePath()); + } + }; + btnNew.setIcon(PresetIcon.ICON_DIR_UP.getTexture()); + cvRight.addPanel(btnNew); + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void refreshSelected() + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - cvSelected.resetCanvas(); - - int width = cvSelected.getTransform().getWidth(); - for(int i = 0; i < selList.size(); i++) - { - File f = selList.get(i); - PanelButton btnSel = new PanelButton(new GuiRectangle(0, i * 16, width - 16, 16,0 ), -1, f.getName()); - btnSel.setActive(false); - cvSelected.addPanel(btnSel); - - PanelButtonStorage btnFile = new PanelButtonStorage<>(new GuiRectangle(width - 16, i* 16, 16, 16, 0), -1, "", f); - btnFile.setIcon(PresetIcon.ICON_NEGATIVE.getTexture()); - btnFile.setCallback(value -> { - selList.remove(value); - refreshSelected(); - cvDirectory.refreshSearch(); - }); - cvSelected.addPanel(btnFile); - } + if (callback != null) { callback.setValue(selList.toArray(new File[0])); } + mc.displayGuiScreen(this.parent); + } + } + + private void refreshSelected() { + cvSelected.resetCanvas(); + + int width = cvSelected.getTransform().getWidth(); + for (int i = 0; i < selList.size(); i++) { + File f = selList.get(i); + PanelButton btnSel = new PanelButton(new GuiRectangle(0, i * 16, width - 16, 16, 0), -1, f.getName()); + btnSel.setActive(false); + cvSelected.addPanel(btnSel); + + PanelButtonStorage btnFile = + new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), -1, "", f); + btnFile.setIcon(PresetIcon.ICON_NEGATIVE.getTexture()); + btnFile.setCallback(value -> { + selList.remove(value); + refreshSelected(); + cvDirectory.refreshSearch(); + }); + cvSelected.addPanel(btnFile); } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java b/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java index 2322e522e..0117b51aa 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java @@ -32,140 +32,142 @@ import java.io.File; import java.util.List; -public class GuiImporters extends GuiScreenCanvas implements IPEventListener, ICallback -{ - private PanelTextBox impName; - private CanvasScrolling impDescCV; - private PanelTextBox impDescTX; - private PanelButtonStorage impBtn; - - public GuiImporters(GuiScreen parent) - { - super(parent); +public class GuiImporters extends GuiScreenCanvas implements IPEventListener, ICallback { + private PanelTextBox impName; + private CanvasScrolling impDescCV; + private PanelTextBox impDescTX; + private PanelButtonStorage impBtn; + + public GuiImporters(GuiScreen parent) { + super(parent); + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.importers")).setAlignment( + 1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + // === LEFT SIDE === + + CanvasScrolling cvImports = + new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 24), 0)); + cvBackground.addPanel(cvImports); + + int width = cvImports.getTransform().getWidth(); + List impList = ImporterRegistry.INSTANCE.getImporters(); + + for (int i = 0; i < impList.size(); i++) { + IImporter imp = impList.get(i); + cvImports.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width, 16, 0), 1, + QuestTranslation.translate(imp.getUnlocalisedName()), imp)); } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.importers")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - // === LEFT SIDE === - - CanvasScrolling cvImports = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 24), 0)); - cvBackground.addPanel(cvImports); - - int width = cvImports.getTransform().getWidth(); - List impList = ImporterRegistry.INSTANCE.getImporters(); - - for(int i = 0; i < impList.size(); i++) - { - IImporter imp = impList.get(i); - cvImports.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width, 16, 0), 1, QuestTranslation.translate(imp.getUnlocalisedName()), imp)); - } - - PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); - cvBackground.addPanel(scReq); - scReq.getTransform().setParent(cvImports.getTransform()); - cvImports.setScrollDriverY(scReq); - - // === RIGHT SIDE === - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); - cvBackground.addPanel(cvRight); - - impName = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), "").setAlignment(1).setColor(PresetColor.TEXT_MAIN.getColor()); - cvRight.addPanel(impName); - - impDescCV = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 24), 0)); - cvRight.addPanel(impDescCV); - - PanelVScrollBar scDesc = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); - cvRight.addPanel(scDesc); - scDesc.getTransform().setParent(impDescCV.getTransform()); - impDescCV.setScrollDriverY(scDesc); - - width = impDescCV.getTransform().getWidth(); - impDescTX = new PanelTextBox(new GuiRectangle(0, 0, width, 16, 0), "", true).setColor(PresetColor.TEXT_MAIN.getColor()); - impDescCV.addPanel(impDescTX); - - impBtn = new PanelButtonStorage<>(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(0, -16, 0, 0), 0), 2, QuestTranslation.translate("betterquesting.btn.import"), null); - impBtn.setActive(false); - cvRight.addPanel(impBtn); - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); + + PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); + cvBackground.addPanel(scReq); + scReq.getTransform().setParent(cvImports.getTransform()); + cvImports.setScrollDriverY(scReq); + + // === RIGHT SIDE === + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); + cvBackground.addPanel(cvRight); + + impName = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), "").setAlignment(1) + .setColor( + PresetColor.TEXT_MAIN.getColor()); + cvRight.addPanel(impName); + + impDescCV = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 24), 0)); + cvRight.addPanel(impDescCV); + + PanelVScrollBar scDesc = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); + cvRight.addPanel(scDesc); + scDesc.getTransform().setParent(impDescCV.getTransform()); + impDescCV.setScrollDriverY(scDesc); + + width = impDescCV.getTransform().getWidth(); + impDescTX = + new PanelTextBox(new GuiRectangle(0, 0, width, 16, 0), "", true).setColor(PresetColor.TEXT_MAIN.getColor()); + impDescCV.addPanel(impDescTX); + + impBtn = new PanelButtonStorage<>(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(0, -16, 0, 0), 0), 2, + QuestTranslation.translate("betterquesting.btn.import"), null); + impBtn.setActive(false); + cvRight.addPanel(impBtn); + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1) // Select - { - IImporter imp = ((PanelButtonStorage)btn).getStoredValue(); - impName.setText(QuestTranslation.translate(imp.getUnlocalisedName())); - impDescTX.setText(QuestTranslation.translate(imp.getUnlocalisedDescription())); - impDescCV.refreshScrollBounds(); - impBtn.setStoredValue(imp); - impBtn.setActive(true); - } else if(btn.getButtonID() == 2) // Import - { - lastImport = ((PanelButtonStorage)btn).getStoredValue(); - mc.displayGuiScreen(new GuiFileBrowser(this, this, new File(".").getAbsoluteFile().getParentFile(), lastImport.getFileFilter())); - } - } - - private IImporter lastImport; - - @Override - public void setValue(File[] files) + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1) // Select { - if(files == null || files.length <= 0 || lastImport == null) - { - return; - } - - ImportedQuests questDB = new ImportedQuests(); - IQuestLineDatabase lineDB = new ImportedQuestLines(); - - lastImport.loadFiles(questDB, lineDB, files); - - if(questDB.size() > 0 || lineDB.size() > 0) - { - NetImport.sendImport(questDB, lineDB); - mc.displayGuiScreen(parent); - } + IImporter imp = ((PanelButtonStorage) btn).getStoredValue(); + impName.setText(QuestTranslation.translate(imp.getUnlocalisedName())); + impDescTX.setText(QuestTranslation.translate(imp.getUnlocalisedDescription())); + impDescCV.refreshScrollBounds(); + impBtn.setStoredValue(imp); + impBtn.setActive(true); + } else if (btn.getButtonID() == 2) // Import + { + lastImport = ((PanelButtonStorage) btn).getStoredValue(); + mc.displayGuiScreen( + new GuiFileBrowser(this, this, new File(".").getAbsoluteFile().getParentFile(), lastImport.getFileFilter())); + } + } + + private IImporter lastImport; + + @Override + public void setValue(File[] files) { + if (files == null || files.length == 0 || lastImport == null) { + return; + } + + ImportedQuests questDB = new ImportedQuests(); + IQuestLineDatabase lineDB = new ImportedQuestLines(); + + lastImport.loadFiles(questDB, lineDB, files); + + if (questDB.size() > 0 || lineDB.size() > 0) { + NetImport.sendImport(questDB, lineDB); + mc.displayGuiScreen(parent); } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java index 7f3f91fd2..580c717e0 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java @@ -39,236 +39,240 @@ import java.util.Arrays; import java.util.List; -public class GuiPrerequisiteEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh -{ - private IQuest quest; - private final int questID; - - private CanvasQuestDatabase canvasDB; - private CanvasScrolling canvasPreReq; - - public GuiPrerequisiteEditor(GuiScreen parent, IQuest quest) - { - super(parent); - this.quest = quest; - this.questID = QuestDatabase.INSTANCE.getID(quest); +public class GuiPrerequisiteEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh { + private IQuest quest; + private final int questID; + + private CanvasQuestDatabase canvasDB; + private CanvasScrolling canvasPreReq; + + public GuiPrerequisiteEditor(GuiScreen parent, IQuest quest) { + super(parent); + this.quest = quest; + this.questID = QuestDatabase.INSTANCE.getID(quest); + } + + @Override + public void refreshGui() { + quest = QuestDatabase.INSTANCE.getValue(questID); + + if (quest == null) { + mc.displayGuiScreen(parent); + return; } - - @Override - public void refreshGui() - { - quest = QuestDatabase.INSTANCE.getValue(questID); - - if(quest == null) - { - mc.displayGuiScreen(parent); - return; - } - - canvasDB.refreshSearch(); - refreshReqCanvas(); + + canvasDB.refreshSearch(); + refreshReqCanvas(); + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + "betterquesting.title.pre_requisites")).setAlignment(1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + // === RIGHT SIDE === + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); + cvBackground.addPanel(cvRight); + + PanelTextBox txtDb = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("betterquesting.gui.database")).setAlignment(1) + .setColor( + PresetColor.TEXT_MAIN.getColor()); + cvRight.addPanel(txtDb); + + PanelTextField searchBox = + new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 8, -32), 0), "", + FieldFilterString.INSTANCE); + searchBox.setWatermark("Search..."); + cvRight.addPanel(searchBox); + + canvasDB = new CanvasQuestDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 32, 8, 24), 0)) { + @Override + protected boolean addResult(DBEntry entry, int index, int width) { + PanelButtonStorage> btnAdd = + new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), 2, "", entry); + btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); + btnAdd.setActive(!containsReq(quest, entry.getID())); + this.addPanel(btnAdd); + + PanelButtonStorage> btnEdit = + new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), 1, + QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)), entry); + this.addPanel(btnEdit); + + PanelButtonStorage> btnDel = + new PanelButtonStorage<>(new GuiRectangle(width - 16, index * 16, 16, 16, 0), 4, "", entry); + btnDel.setIcon(PresetIcon.ICON_TRASH.getTexture()); + this.addPanel(btnDel); + + return true; + } + }; + cvRight.addPanel(canvasDB); + + searchBox.setCallback(canvasDB::setSearchFilter); + + PanelVScrollBar scDb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 32, 0, 24), 0)); + cvRight.addPanel(scDb); + canvasDB.setScrollDriverY(scDb); + + PanelButton btnNew = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(0, -16, 0, 0), 0), 5, + QuestTranslation.translate("betterquesting.btn.new")); + cvRight.addPanel(btnNew); + + // === LEFT SIDE === + + CanvasEmpty cvLeft = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 24), 0)); + cvBackground.addPanel(cvLeft); + + PanelTextBox txtQuest = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate( + quest.getProperty(NativeProps.NAME))).setAlignment(1).setColor( + PresetColor.TEXT_MAIN.getColor()); + cvLeft.addPanel(txtQuest); + + canvasPreReq = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); + cvLeft.addPanel(canvasPreReq); + + PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); + cvLeft.addPanel(scReq); + canvasPreReq.setScrollDriverY(scReq); + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + + refreshReqCanvas(); + } + + private void refreshReqCanvas() { + canvasPreReq.resetCanvas(); + int width = canvasPreReq.getTransform().getWidth(); + + List> arrReq = QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements()); + for (int i = 0; i < arrReq.size(); i++) { + PanelButtonStorage> btnEdit = + new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width - 16, 16, 0), 1, + QuestTranslation.translate(arrReq.get(i).getValue().getProperty(NativeProps.NAME)), + arrReq.get(i)); + canvasPreReq.addPanel(btnEdit); + + PanelButtonStorage> btnRem = + new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), 3, "", arrReq.get(i)); + btnRem.setIcon(PresetIcon.ICON_NEGATIVE.getTexture()); + canvasPreReq.addPanel(btnRem); } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.pre_requisites")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - // === RIGHT SIDE === - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); - cvBackground.addPanel(cvRight); - - PanelTextBox txtDb = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.database")).setAlignment(1).setColor(PresetColor.TEXT_MAIN.getColor()); - cvRight.addPanel(txtDb); - - PanelTextField searchBox = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 8, -32), 0), "", FieldFilterString.INSTANCE); - searchBox.setWatermark("Search..."); - cvRight.addPanel(searchBox); - - canvasDB = new CanvasQuestDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 32, 8, 24), 0)) - { - @Override - protected boolean addResult(DBEntry entry, int index, int width) - { - PanelButtonStorage> btnAdd = new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), 2, "", entry); - btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); - btnAdd.setActive(!containsReq(quest, entry.getID())); - this.addPanel(btnAdd); - - PanelButtonStorage> btnEdit = new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), 1, QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)), entry); - this.addPanel(btnEdit); - - PanelButtonStorage> btnDel = new PanelButtonStorage<>(new GuiRectangle(width - 16, index * 16, 16, 16, 0), 4, "", entry); - btnDel.setIcon(PresetIcon.ICON_TRASH.getTexture()); - this.addPanel(btnDel); - - return true; - } - }; - cvRight.addPanel(canvasDB); - - searchBox.setCallback(canvasDB::setSearchFilter); - - PanelVScrollBar scDb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 32, 0, 24), 0)); - cvRight.addPanel(scDb); - canvasDB.setScrollDriverY(scDb); - - PanelButton btnNew = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(0, -16, 0, 0), 0), 5, QuestTranslation.translate("betterquesting.btn.new")); - cvRight.addPanel(btnNew); - - // === LEFT SIDE === - - CanvasEmpty cvLeft = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 24), 0)); - cvBackground.addPanel(cvLeft); - - PanelTextBox txtQuest = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate(quest.getProperty(NativeProps.NAME))).setAlignment(1).setColor(PresetColor.TEXT_MAIN.getColor()); - cvLeft.addPanel(txtQuest); - - canvasPreReq = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); - cvLeft.addPanel(canvasPreReq); - - PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); - cvLeft.addPanel(scReq); - canvasPreReq.setScrollDriverY(scReq); - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); - - refreshReqCanvas(); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void refreshReqCanvas() + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - canvasPreReq.resetCanvas(); - int width = canvasPreReq.getTransform().getWidth(); - - List> arrReq = QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements()); - for(int i = 0; i < arrReq.size(); i++) - { - PanelButtonStorage> btnEdit = new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width - 16, 16, 0), 1, QuestTranslation.translate(arrReq.get(i).getValue().getProperty(NativeProps.NAME)), arrReq.get(i)); - canvasPreReq.addPanel(btnEdit); - - PanelButtonStorage> btnRem = new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), 3, "", arrReq.get(i)); - btnRem.setIcon(PresetIcon.ICON_NEGATIVE.getTexture()); - canvasPreReq.addPanel(btnRem); - } - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Edit Quest - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - mc.displayGuiScreen(new GuiQuest(this, entry.getID())); - } else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Add - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - addReq(quest, entry.getID()); - SendChanges(); - } else if(btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Remove - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - removeReq(quest, entry.getID()); - SendChanges(); - } else if(btn.getButtonID() == 4 && btn instanceof PanelButtonStorage) // Delete - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", new int[]{entry.getID()}); - payload.setInteger("action", 1); - NetQuestEdit.sendEdit(payload); - } else if(btn.getButtonID() == 5) // New - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", -1); - dataList.appendTag(entry); - payload.setTag("data", dataList); - NetQuestEdit.sendEdit(payload); - } - } - - private boolean containsReq(IQuest quest, int id) + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Edit Quest { - for(int reqID : quest.getRequirements()) if(id == reqID) return true; - return false; - } - - private void removeReq(IQuest quest, int id) + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + mc.displayGuiScreen(new GuiQuest(this, entry.getID())); + } else if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Add { - int[] orig = quest.getRequirements(); - if(orig.length <= 0) return; - boolean hasRemoved = false; - int[] rem = new int[orig.length - 1]; - for(int i = 0; i < orig.length; i++) - { - if(!hasRemoved && orig[i] == id) - { - hasRemoved = true; - continue; - } else if(!hasRemoved && i >= rem.length) break; - - rem[!hasRemoved ? i : (i - 1)] = orig[i]; - } - - if(hasRemoved) quest.setRequirements(rem); - } - - private void addReq(IQuest quest, int id) + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + addReq(quest, entry.getID()); + SendChanges(); + } else if (btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Remove { - if(containsReq(quest, id)) return; - int[] orig = quest.getRequirements(); - int[] added = Arrays.copyOf(orig, orig.length + 1); - added[orig.length] = id; - quest.setRequirements(added); + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + removeReq(quest, entry.getID()); + SendChanges(); + } else if (btn.getButtonID() == 4 && btn instanceof PanelButtonStorage) // Delete + { + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", new int[] { entry.getID() }); + payload.setInteger("action", 1); + NetQuestEdit.sendEdit(payload); + } else if (btn.getButtonID() == 5) // New + { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", -1); + dataList.appendTag(entry); + payload.setTag("data", dataList); + NetQuestEdit.sendEdit(payload); + } + } + + private boolean containsReq(IQuest quest, int id) { + for (int reqID : quest.getRequirements()) { if (id == reqID) { return true; } } + return false; + } + + private void removeReq(IQuest quest, int id) { + int[] orig = quest.getRequirements(); + if (orig.length == 0) { return; } + boolean hasRemoved = false; + int[] rem = new int[orig.length - 1]; + for (int i = 0; i < orig.length; i++) { + if (!hasRemoved && orig[i] == id) { + hasRemoved = true; + continue; + } else if (!hasRemoved && i >= rem.length) { break; } + + rem[!hasRemoved ? i : (i - 1)] = orig[i]; } - - private void SendChanges() - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", questID); - entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetQuestEdit.sendEdit(payload); - } + + if (hasRemoved) { quest.setRequirements(rem); } + } + + private void addReq(IQuest quest, int id) { + if (containsReq(quest, id)) { return; } + int[] orig = quest.getRequirements(); + int[] added = Arrays.copyOf(orig, orig.length + 1); + added[orig.length] = id; + quest.setRequirements(added); + } + + private void SendChanges() { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", questID); + entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetQuestEdit.sendEdit(payload); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java index cf283bba1..9e406656c 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java @@ -32,231 +32,234 @@ import net.minecraft.nbt.NBTTagList; import org.lwjgl.input.Keyboard; -public class GuiQuestEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh -{ - private final int questID; - private IQuest quest; - - private PanelTextBox pnTitle; - private PanelTextField flName; - private PanelTextField flDesc; - - private PanelButton btnLogic; - private PanelButton btnVis; - - public GuiQuestEditor(GuiScreen parent, int questID) - { - super(parent); - this.questID = questID; +public class GuiQuestEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh { + private final int questID; + private IQuest quest; + + private PanelTextBox pnTitle; + private PanelTextField flName; + private PanelTextField flDesc; + + private PanelButton btnLogic; + private PanelButton btnVis; + + public GuiQuestEditor(GuiScreen parent, int questID) { + super(parent); + this.questID = questID; + } + + @Override + public void refreshGui() { + quest = QuestDatabase.INSTANCE.getValue(questID); + + if (quest == null) { + mc.displayGuiScreen(this.parent); + } else { + pnTitle.setText(QuestTranslation.translate("betterquesting.title.edit_quest", + QuestTranslation.translate(quest.getProperty(NativeProps.NAME)))); + if (!flName.isFocused()) { flName.setText(quest.getProperty(NativeProps.NAME)); } + if (!flDesc.isFocused()) { flDesc.setText(quest.getProperty(NativeProps.DESC)); } + btnLogic.setText( + QuestTranslation.translate("betterquesting.btn.logic") + ": " + quest.getProperty(NativeProps.LOGIC_QUEST)); + btnVis.setText( + QuestTranslation.translate("betterquesting.btn.show") + ": " + quest.getProperty(NativeProps.VISIBILITY)); } - - @Override - public void refreshGui() - { - quest = QuestDatabase.INSTANCE.getValue(questID); - - if(quest == null) - { - mc.displayGuiScreen(this.parent); - } else - { - pnTitle.setText(QuestTranslation.translate("betterquesting.title.edit_quest", QuestTranslation.translate(quest.getProperty(NativeProps.NAME)))); - if(!flName.isFocused()) flName.setText(quest.getProperty(NativeProps.NAME)); - if(!flDesc.isFocused()) flDesc.setText(quest.getProperty(NativeProps.DESC)); - btnLogic.setText(QuestTranslation.translate("betterquesting.btn.logic") + ": " + quest.getProperty(NativeProps.LOGIC_QUEST)); - btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + quest.getProperty(NativeProps.VISIBILITY)); - } + } + + @Override + public void initPanel() { + super.initPanel(); + + quest = QuestDatabase.INSTANCE.getValue(questID); + + if (quest == null) { + mc.displayGuiScreen(this.parent); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - quest = QuestDatabase.INSTANCE.getValue(questID); - - if(quest == null) - { - mc.displayGuiScreen(this.parent); - return; - } - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - pnTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_quest", QuestTranslation.translate(quest.getProperty(NativeProps.NAME)))).setAlignment(1); - pnTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(pnTitle); - - // === TEXT FIELDS === - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - PanelTextBox pnName = new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -100, -60, 200, 12, 0), QuestTranslation.translate("betterquesting.gui.name")); - pnName.setColor(PresetColor.TEXT_MAIN.getColor()); - cvBackground.addPanel(pnName); - - flName = new PanelTextField<>(new GuiTransform(GuiAlign.MID_CENTER, -100, -48, 200, 16, 0), quest.getProperty(NativeProps.NAME), FieldFilterString.INSTANCE); - flName.setMaxLength(Integer.MAX_VALUE); - cvBackground.addPanel(flName); - - PanelTextBox pnDesc = new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -100, -28, 200, 12, 0), QuestTranslation.translate("betterquesting.gui.description")); - pnDesc.setColor(PresetColor.TEXT_MAIN.getColor()); - cvBackground.addPanel(pnDesc); - - flDesc = new PanelTextField<>(new GuiTransform(GuiAlign.MID_CENTER, -100, -16, 184, 16, 0), quest.getProperty(NativeProps.DESC), FieldFilterString.INSTANCE); - flDesc.setMaxLength(Integer.MAX_VALUE); - cvBackground.addPanel(flDesc); - - // === BUTTONS === - // NOTE: Toggle Main has been removed due to quest frames becoming much more flexible. Can still be toggled in advanced NBT tags. - - PanelButton btnDesc = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 84, -16, 16, 16, 0), 7, "Aa"); - cvBackground.addPanel(btnDesc); - - PanelButton btnTsk = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 16, 100, 16, 0), 1, QuestTranslation.translate("betterquesting.btn.tasks")); - cvBackground.addPanel(btnTsk); - - PanelButton btnRew = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 0, 16, 100, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.rewards")); - cvBackground.addPanel(btnRew); - - PanelButton btnReq = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 32, 100, 16, 0), 3, QuestTranslation.translate("betterquesting.btn.requirements")); - cvBackground.addPanel(btnReq); - - PanelButton btnIco = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 0, 32, 100, 16, 0), 8, QuestTranslation.translate("betterquesting.btn.icon")); - cvBackground.addPanel(btnIco); - - btnVis = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 48, 100, 16, 0), 5, QuestTranslation.translate("betterquesting.btn.show") + ": " + quest.getProperty(NativeProps.VISIBILITY)); - cvBackground.addPanel(btnVis); - - btnLogic = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 0, 48, 100, 16, 0), 6, QuestTranslation.translate("betterquesting.btn.logic") + ": " + quest.getProperty(NativeProps.LOGIC_QUEST)); - cvBackground.addPanel(btnLogic); - - PanelButton btnAdv = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 64, 200, 16, 0), 4, QuestTranslation.translate("betterquesting.btn.advanced")); - cvBackground.addPanel(btnAdv); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + pnTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.edit_quest", QuestTranslation.translate( + quest.getProperty(NativeProps.NAME)))).setAlignment(1); + pnTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(pnTitle); + + // === TEXT FIELDS === + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + PanelTextBox pnName = new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -100, -60, 200, 12, 0), + QuestTranslation.translate("betterquesting.gui.name")); + pnName.setColor(PresetColor.TEXT_MAIN.getColor()); + cvBackground.addPanel(pnName); + + flName = new PanelTextField<>(new GuiTransform(GuiAlign.MID_CENTER, -100, -48, 200, 16, 0), + quest.getProperty(NativeProps.NAME), FieldFilterString.INSTANCE); + flName.setMaxLength(Integer.MAX_VALUE); + cvBackground.addPanel(flName); + + PanelTextBox pnDesc = new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -100, -28, 200, 12, 0), + QuestTranslation.translate("betterquesting.gui.description")); + pnDesc.setColor(PresetColor.TEXT_MAIN.getColor()); + cvBackground.addPanel(pnDesc); + + flDesc = new PanelTextField<>(new GuiTransform(GuiAlign.MID_CENTER, -100, -16, 184, 16, 0), + quest.getProperty(NativeProps.DESC), FieldFilterString.INSTANCE); + flDesc.setMaxLength(Integer.MAX_VALUE); + cvBackground.addPanel(flDesc); + + // === BUTTONS === + // NOTE: Toggle Main has been removed due to quest frames becoming much more flexible. Can still be toggled in advanced NBT tags. + + PanelButton btnDesc = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 84, -16, 16, 16, 0), 7, "Aa"); + cvBackground.addPanel(btnDesc); + + PanelButton btnTsk = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 16, 100, 16, 0), 1, + QuestTranslation.translate("betterquesting.btn.tasks")); + cvBackground.addPanel(btnTsk); + + PanelButton btnRew = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 0, 16, 100, 16, 0), 2, + QuestTranslation.translate("betterquesting.btn.rewards")); + cvBackground.addPanel(btnRew); + + PanelButton btnReq = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 32, 100, 16, 0), 3, + QuestTranslation.translate("betterquesting.btn.requirements")); + cvBackground.addPanel(btnReq); + + PanelButton btnIco = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 0, 32, 100, 16, 0), 8, + QuestTranslation.translate("betterquesting.btn.icon")); + cvBackground.addPanel(btnIco); + + btnVis = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 48, 100, 16, 0), 5, + QuestTranslation.translate("betterquesting.btn.show") + ": " + + quest.getProperty(NativeProps.VISIBILITY)); + cvBackground.addPanel(btnVis); + + btnLogic = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 0, 48, 100, 16, 0), 6, + QuestTranslation.translate("betterquesting.btn.logic") + ": " + + quest.getProperty(NativeProps.LOGIC_QUEST)); + cvBackground.addPanel(btnLogic); + + PanelButton btnAdv = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 64, 200, 16, 0), 4, + QuestTranslation.translate("betterquesting.btn.advanced")); + cvBackground.addPanel(btnAdv); + } + + @Override + public boolean onMouseClick(int mx, int my, int button) { + boolean result = super.onMouseClick(mx, my, button); + boolean flag = false; + + if (!quest.getProperty(NativeProps.NAME).equals(flName.getValue())) { + quest.setProperty(NativeProps.NAME, flName.getValue()); + flag = true; } - - @Override - public boolean onMouseClick(int mx, int my, int button) - { - boolean result = super.onMouseClick(mx, my, button); - boolean flag = false; - - if(!quest.getProperty(NativeProps.NAME).equals(flName.getValue())) - { - quest.setProperty(NativeProps.NAME, flName.getValue()); - flag = true; - } - - if(!quest.getProperty(NativeProps.DESC).equals(flDesc.getValue())) - { - quest.setProperty(NativeProps.DESC, flDesc.getValue()); - flag = true; - } - - if(flag) - { - SendChanges(); - } - - return result; + + if (!quest.getProperty(NativeProps.DESC).equals(flDesc.getValue())) { + quest.setProperty(NativeProps.DESC, flDesc.getValue()); + flag = true; + } + + if (flag) { + SendChanges(); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - switch(btn.getButtonID()) - { - case 0: // Exit - { - mc.displayGuiScreen(this.parent); - break; - } - case 1: // Edit tasks - { - mc.displayGuiScreen(new betterquesting.client.gui2.editors.GuiTaskEditor(this, quest)); - break; - } - case 2: // Edit rewards - { - mc.displayGuiScreen(new betterquesting.client.gui2.editors.GuiRewardEditor(this, quest)); - break; - } - case 3: // Requirements - { - mc.displayGuiScreen(new betterquesting.client.gui2.editors.GuiPrerequisiteEditor(this, quest)); - break; - } - case 4: // Advanced - { - mc.displayGuiScreen(new GuiNbtEditor(this, quest.writeToNBT(new NBTTagCompound()), value -> { - quest.readFromNBT(value); - SendChanges(); - })); - break; - } - case 5: // Visibility - { - EnumQuestVisibility[] visList = EnumQuestVisibility.values(); - EnumQuestVisibility vis = quest.getProperty(NativeProps.VISIBILITY); - vis = visList[(vis.ordinal() + 1)%visList.length]; - quest.setProperty(NativeProps.VISIBILITY, vis); - ((PanelButton)btn).setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + vis); - SendChanges(); - break; - } - case 6: // Logic - { - EnumLogic[] logicList = EnumLogic.values(); - EnumLogic logic = quest.getProperty(NativeProps.LOGIC_QUEST); - logic = logicList[(logic.ordinal() + 1)%logicList.length]; - quest.setProperty(NativeProps.LOGIC_QUEST, logic); - ((PanelButton)btn).setText(QuestTranslation.translate("betterquesting.btn.logic") + ": " + logic); - SendChanges(); - break; - } - case 7: // Description Editor - { - mc.displayGuiScreen(new GuiTextEditor(this, quest.getProperty(NativeProps.DESC), value -> { - quest.setProperty(NativeProps.DESC, value); - SendChanges(); - })); - break; - } - case 8: - { - mc.displayGuiScreen(new GuiItemSelection(this, quest.getProperty(NativeProps.ICON), value -> { - quest.setProperty(NativeProps.ICON, value); - SendChanges(); - })); - } - } + + return result; + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void SendChanges() - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", questID); - entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetQuestEdit.sendEdit(payload); - } + } + + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + switch (btn.getButtonID()) { + case 0: // Exit + { + mc.displayGuiScreen(this.parent); + break; + } + case 1: // Edit tasks + { + mc.displayGuiScreen(new betterquesting.client.gui2.editors.GuiTaskEditor(this, quest)); + break; + } + case 2: // Edit rewards + { + mc.displayGuiScreen(new betterquesting.client.gui2.editors.GuiRewardEditor(this, quest)); + break; + } + case 3: // Requirements + { + mc.displayGuiScreen(new betterquesting.client.gui2.editors.GuiPrerequisiteEditor(this, quest)); + break; + } + case 4: // Advanced + { + mc.displayGuiScreen(new GuiNbtEditor(this, quest.writeToNBT(new NBTTagCompound()), value -> { + quest.readFromNBT(value); + SendChanges(); + })); + break; + } + case 5: // Visibility + { + EnumQuestVisibility[] visList = EnumQuestVisibility.values(); + EnumQuestVisibility vis = quest.getProperty(NativeProps.VISIBILITY); + vis = visList[(vis.ordinal() + 1) % visList.length]; + quest.setProperty(NativeProps.VISIBILITY, vis); + ((PanelButton) btn).setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + vis); + SendChanges(); + break; + } + case 6: // Logic + { + EnumLogic[] logicList = EnumLogic.values(); + EnumLogic logic = quest.getProperty(NativeProps.LOGIC_QUEST); + logic = logicList[(logic.ordinal() + 1) % logicList.length]; + quest.setProperty(NativeProps.LOGIC_QUEST, logic); + ((PanelButton) btn).setText(QuestTranslation.translate("betterquesting.btn.logic") + ": " + logic); + SendChanges(); + break; + } + case 7: // Description Editor + { + mc.displayGuiScreen(new GuiTextEditor(this, quest.getProperty(NativeProps.DESC), value -> { + quest.setProperty(NativeProps.DESC, value); + SendChanges(); + })); + break; + } + case 8: { + mc.displayGuiScreen(new GuiItemSelection(this, quest.getProperty(NativeProps.ICON), value -> { + quest.setProperty(NativeProps.ICON, value); + SendChanges(); + })); + } + } + } + + private void SendChanges() { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", questID); + entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetQuestEdit.sendEdit(payload); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java index 1eb6562bc..c2f08b7a3 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java @@ -44,251 +44,259 @@ import javax.annotation.Nullable; import java.util.List; -public class GuiQuestLineAddRemove extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh -{ - @Nullable - private IQuestLine questLine; - private final int lineID; - - private CanvasQuestDatabase canvasDB; - private CanvasScrolling canvasQL; - - public GuiQuestLineAddRemove(GuiScreen parent, @Nullable IQuestLine questLine) - { - super(parent); - this.questLine = questLine; - this.lineID = QuestLineDatabase.INSTANCE.getID(questLine); +public class GuiQuestLineAddRemove extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh { + @Nullable + private IQuestLine questLine; + private final int lineID; + + private CanvasQuestDatabase canvasDB; + private CanvasScrolling canvasQL; + + public GuiQuestLineAddRemove(GuiScreen parent, @Nullable IQuestLine questLine) { + super(parent); + this.questLine = questLine; + this.lineID = QuestLineDatabase.INSTANCE.getID(questLine); + } + + @Override + public void refreshGui() { + questLine = lineID < 0 ? null : QuestLineDatabase.INSTANCE.getValue(lineID); + canvasDB.refreshSearch(); + if (questLine != null) { refreshQuestList(); } + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.edit_line2", + questLine == null ? "" + : QuestTranslation.translate( + questLine.getUnlocalisedName()))).setAlignment( + 1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + // === LEFT SIDE === + + CanvasEmpty cvLeft = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 24), 8)); + cvBackground.addPanel(cvLeft); + + if (questLine != null) { + PanelTextBox txtQuest = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate(questLine.getUnlocalisedName())).setAlignment( + 1).setColor(PresetColor.TEXT_MAIN.getColor()); + cvLeft.addPanel(txtQuest); } - - @Override - public void refreshGui() - { - questLine = lineID < 0 ? null : QuestLineDatabase.INSTANCE.getValue(lineID); - canvasDB.refreshSearch(); - if(questLine != null) refreshQuestList(); + + canvasQL = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); + cvLeft.addPanel(canvasQL); + + PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); + cvLeft.addPanel(scReq); + canvasQL.setScrollDriverY(scReq); + + // === RIGHT SIDE == + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); + cvBackground.addPanel(cvRight); + + PanelTextBox txtDb = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("betterquesting.gui.database")).setAlignment(1) + .setColor( + PresetColor.TEXT_MAIN.getColor()); + cvRight.addPanel(txtDb); + + PanelTextField searchBox = + new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 8, -32), 0), "", + FieldFilterString.INSTANCE); + searchBox.setWatermark("Search..."); + cvRight.addPanel(searchBox); + + canvasDB = new CanvasQuestDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 32, 8, 24), 0)) { + @Override + protected boolean addResult(DBEntry entry, int index, int width) { + + PanelButtonStorage> btnAdd = + new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), 2, "", entry); + btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); + btnAdd.setActive(questLine != null && questLine.getValue(entry.getID()) == null); + this.addPanel(btnAdd); + + PanelButtonStorage> btnEdit = + new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), 1, + QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)), entry); + this.addPanel(btnEdit); + + PanelButtonStorage> btnDel = + new PanelButtonStorage<>(new GuiRectangle(width - 16, index * 16, 16, 16, 0), 4, "", entry); + btnDel.setIcon(PresetIcon.ICON_TRASH.getTexture()); + this.addPanel(btnDel); + + return true; + } + }; + cvRight.addPanel(canvasDB); + + searchBox.setCallback(canvasDB::setSearchFilter); + + PanelVScrollBar scDb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 32, 0, 24), 0)); + cvRight.addPanel(scDb); + canvasDB.setScrollDriverY(scDb); + + PanelButton btnNew = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(0, -16, 0, 0), 0), 5, + QuestTranslation.translate("betterquesting.btn.new")); + cvRight.addPanel(btnNew); + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + + refreshQuestList(); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @Override - public void initPanel() + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_line2", questLine == null ? "" : QuestTranslation.translate(questLine.getUnlocalisedName()))).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - // === LEFT SIDE === - - CanvasEmpty cvLeft = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 24), 8)); - cvBackground.addPanel(cvLeft); - - if(questLine != null) - { - PanelTextBox txtQuest = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate(questLine.getUnlocalisedName())).setAlignment(1).setColor(PresetColor.TEXT_MAIN.getColor()); - cvLeft.addPanel(txtQuest); - } - - canvasQL = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); - cvLeft.addPanel(canvasQL); - - PanelVScrollBar scReq = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); - cvLeft.addPanel(scReq); - canvasQL.setScrollDriverY(scReq); - - // === RIGHT SIDE == - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); - cvBackground.addPanel(cvRight); - - PanelTextBox txtDb = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.database")).setAlignment(1).setColor(PresetColor.TEXT_MAIN.getColor()); - cvRight.addPanel(txtDb); - - PanelTextField searchBox = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 8, -32), 0), "", FieldFilterString.INSTANCE); - searchBox.setWatermark("Search..."); - cvRight.addPanel(searchBox); - - canvasDB = new CanvasQuestDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 32, 8, 24), 0)) - { - @Override - protected boolean addResult(DBEntry entry, int index, int width) - { - - PanelButtonStorage> btnAdd = new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), 2, "", entry); - btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); - btnAdd.setActive(questLine != null && questLine.getValue(entry.getID()) == null); - this.addPanel(btnAdd); - - PanelButtonStorage> btnEdit = new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), 1, QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)), entry); - this.addPanel(btnEdit); - - PanelButtonStorage> btnDel = new PanelButtonStorage<>(new GuiRectangle(width - 16, index * 16, 16, 16, 0), 4, "", entry); - btnDel.setIcon(PresetIcon.ICON_TRASH.getTexture()); - this.addPanel(btnDel); - - return true; - } - }; - cvRight.addPanel(canvasDB); - - searchBox.setCallback(canvasDB::setSearchFilter); - - PanelVScrollBar scDb = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 32, 0, 24), 0)); - cvRight.addPanel(scDb); - canvasDB.setScrollDriverY(scDb); - - PanelButton btnNew = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(0, -16, 0, 0), 0), 5, QuestTranslation.translate("betterquesting.btn.new")); - cvRight.addPanel(btnNew); - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); - - refreshQuestList(); - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1) // Edit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1) // Edit - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - mc.displayGuiScreen(new GuiQuest(this, entry.getID())); - } else if(btn.getButtonID() == 2) // Add - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - IQuestLineEntry qe = new QuestLineEntry(0, 0); - int x1 = 0; - int y1 = 0; - - topLoop: - while(questLine != null) - { - for(DBEntry qe2 : questLine.getEntries()) - { - int x2 = qe2.getValue().getPosX(); - int y2 = qe2.getValue().getPosY(); - int s2 = Math.max(qe2.getValue().getSizeX(), qe2.getValue().getSizeY()); - - if(x1 >= x2 && x1 < x2 + s2 && y1 >= y2 && y1 < y2 + s2) - { - x1 += s2; - y1 += s2; - continue topLoop; // We're in the way, move over and try again - } - } - - break; - } - - qe.setPosition(x1, y1); - questLine.add(entry.getID(), qe); - SendChanges(); - } else if(btn.getButtonID() == 3 && questLine != null) // Remove - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - questLine.removeID(entry.getID()); - SendChanges(); - } else if(btn.getButtonID() == 4) // Delete - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", new int[]{entry.getID()}); - payload.setInteger("action", 1); - NetQuestEdit.sendEdit(payload); - } else if(btn.getButtonID() == 5) // New - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", -1); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 3); - NetQuestEdit.sendEdit(payload); - } else if(btn.getButtonID() == 6) // Error resolve - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", new int[]{((PanelButtonStorage)btn).getStoredValue()}); - payload.setInteger("action", 1); - NetQuestEdit.sendEdit(payload); - } - } - - private void refreshQuestList() + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + mc.displayGuiScreen(new GuiQuest(this, entry.getID())); + } else if (btn.getButtonID() == 2) // Add { - canvasQL.resetCanvas(); - - if(questLine == null) - { - return; - } - - int width = canvasQL.getTransform().getWidth(); - - List> qles = questLine.getEntries(); - for(int i = 0; i < qles.size(); i++) - { - DBEntry entry = qles.get(i); - - IQuest quest = QuestDatabase.INSTANCE.getValue(entry.getID()); - - if(quest == null) - { - PanelButtonStorage btnErr = new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), 6, "[ERROR]", entry.getID()); - btnErr.setActive(true); - canvasQL.addPanel(btnErr); - continue; - } - - PanelButtonStorage> btnEdit = new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width - 16, 16, 0), 1, QuestTranslation.translate(quest.getProperty(NativeProps.NAME)), new DBEntry<>(entry.getID(), quest)); - canvasQL.addPanel(btnEdit); - - PanelButtonStorage> btnRem = new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), 3, "", new DBEntry<>(entry.getID(), quest)); - btnRem.setIcon(PresetIcon.ICON_NEGATIVE.getTexture()); - canvasQL.addPanel(btnRem); + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + IQuestLineEntry qe = new QuestLineEntry(0, 0); + int x1 = 0; + int y1 = 0; + + topLoop: + while (questLine != null) { + for (DBEntry qe2 : questLine.getEntries()) { + int x2 = qe2.getValue().getPosX(); + int y2 = qe2.getValue().getPosY(); + int s2 = Math.max(qe2.getValue().getSizeX(), qe2.getValue().getSizeY()); + + if (x1 >= x2 && x1 < x2 + s2 && y1 >= y2 && y1 < y2 + s2) { + x1 += s2; + y1 += s2; + continue topLoop; // We're in the way, move over and try again + } } + + break; + } + + qe.setPosition(x1, y1); + questLine.add(entry.getID(), qe); + SendChanges(); + } else if (btn.getButtonID() == 3 && questLine != null) // Remove + { + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + questLine.removeID(entry.getID()); + SendChanges(); + } else if (btn.getButtonID() == 4) // Delete + { + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", new int[] { entry.getID() }); + payload.setInteger("action", 1); + NetQuestEdit.sendEdit(payload); + } else if (btn.getButtonID() == 5) // New + { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", -1); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 3); + NetQuestEdit.sendEdit(payload); + } else if (btn.getButtonID() == 6) // Error resolve + { + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", new int[] { ((PanelButtonStorage) btn).getStoredValue() }); + payload.setInteger("action", 1); + NetQuestEdit.sendEdit(payload); + } + } + + private void refreshQuestList() { + canvasQL.resetCanvas(); + + if (questLine == null) { + return; + } + + int width = canvasQL.getTransform().getWidth(); + + List> qles = questLine.getEntries(); + for (int i = 0; i < qles.size(); i++) { + DBEntry entry = qles.get(i); + + IQuest quest = QuestDatabase.INSTANCE.getValue(entry.getID()); + + if (quest == null) { + PanelButtonStorage btnErr = + new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), 6, "[ERROR]", entry.getID()); + btnErr.setActive(true); + canvasQL.addPanel(btnErr); + continue; + } + + PanelButtonStorage> btnEdit = + new PanelButtonStorage<>(new GuiRectangle(0, i * 16, width - 16, 16, 0), 1, + QuestTranslation.translate(quest.getProperty(NativeProps.NAME)), + new DBEntry<>(entry.getID(), quest)); + canvasQL.addPanel(btnEdit); + + PanelButtonStorage> btnRem = + new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), 3, "", + new DBEntry<>(entry.getID(), quest)); + btnRem.setIcon(PresetIcon.ICON_NEGATIVE.getTexture()); + canvasQL.addPanel(btnRem); } - - private void SendChanges() - { - if(questLine == null) return; - - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("chapterID", lineID); - entry.setTag("config", questLine.writeToNBT(new NBTTagCompound(), null)); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetChapterEdit.sendEdit(payload); - } + } + + private void SendChanges() { + if (questLine == null) { return; } + + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("chapterID", lineID); + entry.setTag("config", questLine.writeToNBT(new NBTTagCompound(), null)); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetChapterEdit.sendEdit(payload); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java index 59426b140..ef469956b 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java @@ -40,337 +40,338 @@ import java.util.List; -public class GuiQuestLinesEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh -{ - private CanvasScrolling lineList; - private PanelTextField tfName; - private PanelTextField tfDesc; - - private PanelButton btnDesign; - private PanelButton btnVis; - private PanelButton btnIcon; - - private IQuestLine selected; - private int selID = -1; - - public GuiQuestLinesEditor(GuiScreen parent) - { - super(parent); +public class GuiQuestLinesEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh { + private CanvasScrolling lineList; + private PanelTextField tfName; + private PanelTextField tfDesc; + + private PanelButton btnDesign; + private PanelButton btnVis; + private PanelButton btnIcon; + + private IQuestLine selected; + private int selID = -1; + + public GuiQuestLinesEditor(GuiScreen parent) { + super(parent); + } + + @Override + public void refreshGui() { + if (selID >= 0) { + selected = QuestLineDatabase.INSTANCE.getValue(selID); + + if (selected == null) { + selID = -1; + btnDesign.setActive(false); + btnIcon.setActive(false); + btnVis.setActive(false); + tfName.setText(""); + tfDesc.setText(""); + } else { + btnDesign.setActive(true); + btnIcon.setActive(true); + btnVis.setActive(true); + btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + + selected.getProperty(NativeProps.VISIBILITY)); + if (!tfName.isFocused()) { tfName.setText(selected.getUnlocalisedName()); } + if (!tfDesc.isFocused()) { tfDesc.setText(selected.getUnlocalisedDescription()); } + } } - - @Override - public void refreshGui() - { - if(selID >= 0) - { - selected = QuestLineDatabase.INSTANCE.getValue(selID); - - if(selected == null) - { - selID = -1; - btnDesign.setActive(false); - btnIcon.setActive(false); - btnVis.setActive(false); - tfName.setText(""); - tfDesc.setText(""); - } else - { - btnDesign.setActive(true); - btnIcon.setActive(true); - btnVis.setActive(true); - btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + selected.getProperty(NativeProps.VISIBILITY)); - if(!tfName.isFocused()) tfName.setText(selected.getUnlocalisedName()); - if(!tfDesc.isFocused()) tfDesc.setText(selected.getUnlocalisedDescription()); - } - } - - reloadList(); + + reloadList(); + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.edit_line1")).setAlignment( + 1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + // Left side + + lineList = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 48), 0)); + cvBackground.addPanel(lineList); + + PanelVScrollBar scList = + new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-16, 32, 8, 48), 0)); + cvBackground.addPanel(scList); + lineList.setScrollDriverY(scList); + + PanelButton btnAdd = + new PanelButton(new GuiTransform(new Vector4f(0F, 1F, 0.25F, 1F), new GuiPadding(16, -40, 0, 24), 0), 1, + QuestTranslation.translate("betterquesting.btn.new")); + cvBackground.addPanel(btnAdd); + + PanelButton btnImport = + new PanelButton(new GuiTransform(new Vector4f(0.25F, 1F, 0.5F, 1F), new GuiPadding(0, -40, 16, 24), 0), 2, + QuestTranslation.translate("betterquesting.btn.import")); + cvBackground.addPanel(btnImport); + + // Right side + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); + cvBackground.addPanel(cvRight); + + PanelTextBox txtName = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 4, 0, -16), 0), + QuestTranslation.translate("betterquesting.gui.name")); + txtName.setColor(PresetColor.TEXT_MAIN.getColor()); + cvRight.addPanel(txtName); + + tfName = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), "", + FieldFilterString.INSTANCE); + cvRight.addPanel(tfName); + + PanelTextBox txtDesc = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 36, 0, -48), 0), + QuestTranslation.translate("betterquesting.gui.description")); + txtDesc.setColor(PresetColor.TEXT_MAIN.getColor()); + cvRight.addPanel(txtDesc); + + tfDesc = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 48, 16, -64), 0), "", + FieldFilterString.INSTANCE); + tfDesc.setMaxLength(Integer.MAX_VALUE); + cvRight.addPanel(tfDesc); + + btnIcon = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 80, 0, -96), 0), -1, + QuestTranslation.translate("betterquesting.btn.icon")) { + @Override + public void onButtonClick() { + if (selected == null) { return; } + mc.displayGuiScreen( + new GuiItemSelection(GuiQuestLinesEditor.this, selected.getProperty(NativeProps.ICON), value -> { + selected.setProperty(NativeProps.ICON, value); + SendChanges(new DBEntry<>(selID, selected)); + })); + } + }; + btnIcon.setActive(selected != null); + cvRight.addPanel(btnIcon); + + btnVis = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 96, 0, -112), 0), -1, + QuestTranslation.translate("betterquesting.btn.show") + ": " + + (selected == null ? EnumQuestVisibility.NORMAL + : selected.getProperty(NativeProps.VISIBILITY))) { + @Override + public void onButtonClick() { + if (selected == null) { return; } + EnumQuestVisibility[] visList = EnumQuestVisibility.values(); + EnumQuestVisibility vis = selected.getProperty(NativeProps.VISIBILITY); + vis = visList[(vis.ordinal() + 1) % visList.length]; + selected.setProperty(NativeProps.VISIBILITY, vis); + this.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + vis); + } + }; + btnVis.setActive(selected != null); + cvRight.addPanel(btnVis); + + PanelButton btnManage = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 112, 0, -128), 0), 3, + QuestTranslation.translate("betterquesting.btn.add_remove_quests")); + cvRight.addPanel(btnManage); + + btnDesign = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 128, 0, -144), 0), 4, + QuestTranslation.translate("betterquesting.btn.designer")); + btnDesign.setActive(selected != null); + cvRight.addPanel(btnDesign); + + PanelButton btnTextEditor = + new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, new GuiPadding(-16, 48, 0, -64), 0), 8, "Aa"); + cvRight.addPanel(btnTextEditor); + + // Dividers + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + + if (selID >= 0) { + selected = QuestLineDatabase.INSTANCE.getValue(selID); + + if (selected == null) { + selID = -1; + btnDesign.setActive(false); + btnIcon.setActive(false); + btnVis.setActive(false); + tfName.setText(""); + tfDesc.setText(""); + } else { + btnDesign.setActive(true); + btnIcon.setActive(true); + btnVis.setActive(true); + btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + + selected.getProperty(NativeProps.VISIBILITY)); + if (!tfName.isFocused()) { tfName.setText(selected.getUnlocalisedName()); } + if (!tfDesc.isFocused()) { tfDesc.setText(selected.getUnlocalisedDescription()); } + } } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_line1")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - // Left side - - lineList = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 48), 0)); - cvBackground.addPanel(lineList); - - PanelVScrollBar scList = new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-16, 32, 8, 48), 0)); - cvBackground.addPanel(scList); - lineList.setScrollDriverY(scList); - - PanelButton btnAdd = new PanelButton(new GuiTransform(new Vector4f(0F, 1F, 0.25F, 1F), new GuiPadding(16, -40, 0, 24), 0), 1, QuestTranslation.translate("betterquesting.btn.new")); - cvBackground.addPanel(btnAdd); - - PanelButton btnImport = new PanelButton(new GuiTransform(new Vector4f(0.25F, 1F, 0.5F, 1F), new GuiPadding(0, -40, 16, 24), 0), 2, QuestTranslation.translate("betterquesting.btn.import")); - cvBackground.addPanel(btnImport); - - // Right side - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 24), 0)); - cvBackground.addPanel(cvRight); - - PanelTextBox txtName = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 4, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.name")); - txtName.setColor(PresetColor.TEXT_MAIN.getColor()); - cvRight.addPanel(txtName); - - tfName = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), "", FieldFilterString.INSTANCE); - cvRight.addPanel(tfName); - - PanelTextBox txtDesc = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 36, 0, -48), 0), QuestTranslation.translate("betterquesting.gui.description")); - txtDesc.setColor(PresetColor.TEXT_MAIN.getColor()); - cvRight.addPanel(txtDesc); - - tfDesc = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 48, 16, -64), 0), "", FieldFilterString.INSTANCE); - tfDesc.setMaxLength(Integer.MAX_VALUE); - cvRight.addPanel(tfDesc); - - btnIcon = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 80, 0, -96), 0), -1, QuestTranslation.translate("betterquesting.btn.icon")) - { - @Override - public void onButtonClick() - { - if(selected == null) return; - mc.displayGuiScreen(new GuiItemSelection(GuiQuestLinesEditor.this, selected.getProperty(NativeProps.ICON), value -> { - selected.setProperty(NativeProps.ICON, value); - SendChanges(new DBEntry<>(selID, selected)); - })); - } - }; - btnIcon.setActive(selected != null); - cvRight.addPanel(btnIcon); - - btnVis = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 96, 0, -112), 0), -1, QuestTranslation.translate("betterquesting.btn.show") + ": " + (selected == null ? EnumQuestVisibility.NORMAL : selected.getProperty(NativeProps.VISIBILITY))) - { - @Override - public void onButtonClick() - { - if(selected == null) return; - EnumQuestVisibility[] visList = EnumQuestVisibility.values(); - EnumQuestVisibility vis = selected.getProperty(NativeProps.VISIBILITY); - vis = visList[(vis.ordinal() + 1)%visList.length]; - selected.setProperty(NativeProps.VISIBILITY, vis); - this.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + vis); - } - }; - btnVis.setActive(selected != null); - cvRight.addPanel(btnVis); - - PanelButton btnManage = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 112, 0, -128), 0), 3, QuestTranslation.translate("betterquesting.btn.add_remove_quests")); - cvRight.addPanel(btnManage); - - btnDesign = new PanelButton(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 128, 0, -144), 0), 4, QuestTranslation.translate("betterquesting.btn.designer")); - btnDesign.setActive(selected != null); - cvRight.addPanel(btnDesign); - - PanelButton btnTextEditor = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, new GuiPadding(-16, 48, 0, -64), 0), 8, "Aa"); - cvRight.addPanel(btnTextEditor); - - // Dividers - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -24, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); - - if(selID >= 0) - { - selected = QuestLineDatabase.INSTANCE.getValue(selID); - - if(selected == null) - { - selID = -1; - btnDesign.setActive(false); - btnIcon.setActive(false); - btnVis.setActive(false); - tfName.setText(""); - tfDesc.setText(""); - } else - { - btnDesign.setActive(true); - btnIcon.setActive(true); - btnVis.setActive(true); - btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + selected.getProperty(NativeProps.VISIBILITY)); - if(!tfName.isFocused()) tfName.setText(selected.getUnlocalisedName()); - if(!tfDesc.isFocused()) tfDesc.setText(selected.getUnlocalisedDescription()); - } - } - - reloadList(); + + reloadList(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (selected != null) { + boolean changed = false; + + if (!tfName.getValue().equals(selected.getUnlocalisedName())) { + selected.setProperty(NativeProps.NAME, tfName.getValue()); + changed = true; + } + + if (!tfDesc.getValue().equals(selected.getUnlocalisedDescription())) { + selected.setProperty(NativeProps.DESC, tfDesc.getValue()); + changed = true; + } + + if (changed) { + SendChanges(new DBEntry<>(selID, selected)); + } } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(selected != null) - { - boolean changed = false; - - if(!tfName.getValue().equals(selected.getUnlocalisedName())) - { - selected.setProperty(NativeProps.NAME, tfName.getValue()); - changed = true; - } - - if(!tfDesc.getValue().equals(selected.getUnlocalisedDescription())) - { - selected.setProperty(NativeProps.DESC, tfDesc.getValue()); - changed = true; - } - - if(changed) - { - SendChanges(new DBEntry<>(selID, selected)); - } - } - - return super.onMouseClick(mx, my, click); + + return super.onMouseClick(mx, my, click); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @Override - public void onPanelEvent(PanelEvent event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1) // New Quest Line { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1) // New Quest Line - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("chapterID", -1); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 3); - NetChapterEdit.sendEdit(payload); - } else if(btn.getButtonID() == 2) // Import - { - mc.displayGuiScreen(new GuiImporters(this)); - } else if(btn.getButtonID() == 3) // Add/Remove Quests - { - mc.displayGuiScreen(new GuiQuestLineAddRemove(this, selected)); - } else if(btn.getButtonID() == 4 && selected != null) // Designer - { - //mc.displayGuiScreen(new GuiQuestLineDesigner(this, selected)); - mc.displayGuiScreen(new GuiDesigner(this, selected)); - } else if(btn.getButtonID() == 5 && btn instanceof PanelButtonStorage) // Select Quest - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - selected = entry.getValue(); - selID = entry.getID(); - tfName.setText(selected.getUnlocalisedName()); - tfDesc.setText(selected.getUnlocalisedDescription()); - btnDesign.setActive(true); - btnIcon.setActive(true); - btnVis.setActive(true); - btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + selected.getProperty(NativeProps.VISIBILITY)); - - reloadList(); - } else if(btn.getButtonID() == 6 && btn instanceof PanelButtonStorage) // Delete Quest - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("chapterIDs", new int[]{entry.getID()}); - payload.setInteger("action", 1); - NetChapterEdit.sendEdit(payload); - } else if(btn.getButtonID() == 7 && btn instanceof PanelButtonStorage) // Move Up - { - DBEntry entry = ((PanelButtonStorage>)btn).getStoredValue(); - int order = QuestLineDatabase.INSTANCE.getOrderIndex(entry.getID()); - if(order > 0) SendReorder(order); - } else if(btn.getButtonID() == 8) // Big Description Editor - { - mc.displayGuiScreen(new GuiTextEditor(this, tfDesc.getRawText(), value -> { - if(selected != null) - { - tfDesc.setText(value); - selected.setProperty(NativeProps.DESC, value); - SendChanges(new DBEntry<>(selID, selected)); - } - })); - } - } - - private void reloadList() + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("chapterID", -1); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 3); + NetChapterEdit.sendEdit(payload); + } else if (btn.getButtonID() == 2) // Import { - lineList.resetCanvas(); - - int w = lineList.getTransform().getWidth(); - int i = 0; - - for(DBEntry entry : QuestLineDatabase.INSTANCE.getSortedEntries()) - { - IQuestLine ql = entry.getValue(); - PanelButtonStorage> tmp = new PanelButtonStorage<>(new GuiRectangle(0, i * 16, w - 32, 16, 0), 5, QuestTranslation.translate(ql.getUnlocalisedName()), entry); - tmp.setActive(entry.getID() != selID); - lineList.addPanel(tmp); - lineList.addPanel(new PanelButtonStorage<>(new GuiRectangle(w - 32, i * 16, 16, 16, 0), 6, "", entry).setIcon(PresetIcon.ICON_TRASH.getTexture())); - PanelButton btnUp = new PanelButtonStorage<>(new GuiRectangle(w - 16, i * 16, 16, 16, 0), 7, "", entry).setIcon(PresetIcon.ICON_UP.getTexture()); - btnUp.setActive(i > 0); - lineList.addPanel(btnUp); - i++; - } - } - - private void SendChanges(DBEntry chapter) - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("chapterID", chapter.getID()); - entry.setTag("config", chapter.getValue().writeToNBT(new NBTTagCompound(), null)); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetChapterEdit.sendEdit(payload); - } - - private void SendReorder(int indexToShift) + mc.displayGuiScreen(new GuiImporters(this)); + } else if (btn.getButtonID() == 3) // Add/Remove Quests + { + mc.displayGuiScreen(new GuiQuestLineAddRemove(this, selected)); + } else if (btn.getButtonID() == 4 && selected != null) // Designer { - if(indexToShift <= 0) return; - List> entries = QuestLineDatabase.INSTANCE.getSortedEntries(); - if(indexToShift >= entries.size()) return; - int[] chapterIDs = new int[entries.size()]; - for(int i = 0; i < entries.size(); i++) - { - chapterIDs[i] = entries.get(i).getID(); + //mc.displayGuiScreen(new GuiQuestLineDesigner(this, selected)); + mc.displayGuiScreen(new GuiDesigner(this, selected)); + } else if (btn.getButtonID() == 5 && btn instanceof PanelButtonStorage) // Select Quest + { + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + selected = entry.getValue(); + selID = entry.getID(); + tfName.setText(selected.getUnlocalisedName()); + tfDesc.setText(selected.getUnlocalisedDescription()); + btnDesign.setActive(true); + btnIcon.setActive(true); + btnVis.setActive(true); + btnVis.setText( + QuestTranslation.translate("betterquesting.btn.show") + ": " + selected.getProperty(NativeProps.VISIBILITY)); + + reloadList(); + } else if (btn.getButtonID() == 6 && btn instanceof PanelButtonStorage) // Delete Quest + { + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("chapterIDs", new int[] { entry.getID() }); + payload.setInteger("action", 1); + NetChapterEdit.sendEdit(payload); + } else if (btn.getButtonID() == 7 && btn instanceof PanelButtonStorage) // Move Up + { + DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); + int order = QuestLineDatabase.INSTANCE.getOrderIndex(entry.getID()); + if (order > 0) { SendReorder(order); } + } else if (btn.getButtonID() == 8) // Big Description Editor + { + mc.displayGuiScreen(new GuiTextEditor(this, tfDesc.getRawText(), value -> { + if (selected != null) { + tfDesc.setText(value); + selected.setProperty(NativeProps.DESC, value); + SendChanges(new DBEntry<>(selID, selected)); } - - int tmp = chapterIDs[indexToShift]; - chapterIDs[indexToShift] = chapterIDs[indexToShift - 1]; - chapterIDs[indexToShift - 1] = tmp; - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("chapterIDs", chapterIDs); - payload.setInteger("action", 2); - NetChapterEdit.sendEdit(payload); + })); } + } + + private void reloadList() { + lineList.resetCanvas(); + + int w = lineList.getTransform().getWidth(); + int i = 0; + + for (DBEntry entry : QuestLineDatabase.INSTANCE.getSortedEntries()) { + IQuestLine ql = entry.getValue(); + PanelButtonStorage> tmp = + new PanelButtonStorage<>(new GuiRectangle(0, i * 16, w - 32, 16, 0), 5, + QuestTranslation.translate(ql.getUnlocalisedName()), entry); + tmp.setActive(entry.getID() != selID); + lineList.addPanel(tmp); + lineList.addPanel(new PanelButtonStorage<>(new GuiRectangle(w - 32, i * 16, 16, 16, 0), 6, "", entry).setIcon( + PresetIcon.ICON_TRASH.getTexture())); + PanelButton btnUp = new PanelButtonStorage<>(new GuiRectangle(w - 16, i * 16, 16, 16, 0), 7, "", entry).setIcon( + PresetIcon.ICON_UP.getTexture()); + btnUp.setActive(i > 0); + lineList.addPanel(btnUp); + i++; + } + } + + private void SendChanges(DBEntry chapter) { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("chapterID", chapter.getID()); + entry.setTag("config", chapter.getValue().writeToNBT(new NBTTagCompound(), null)); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetChapterEdit.sendEdit(payload); + } + + private void SendReorder(int indexToShift) { + if (indexToShift <= 0) { return; } + List> entries = QuestLineDatabase.INSTANCE.getSortedEntries(); + if (indexToShift >= entries.size()) { return; } + int[] chapterIDs = new int[entries.size()]; + for (int i = 0; i < entries.size(); i++) { + chapterIDs[i] = entries.get(i).getID(); + } + + int tmp = chapterIDs[indexToShift]; + chapterIDs[indexToShift] = chapterIDs[indexToShift - 1]; + chapterIDs[indexToShift - 1] = tmp; + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("chapterIDs", chapterIDs); + payload.setInteger("action", 2); + NetChapterEdit.sendEdit(payload); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java index c342fba52..c898586e2 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java @@ -42,185 +42,182 @@ import java.util.Iterator; import java.util.List; -public class GuiRewardEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh -{ - private CanvasScrolling qrList; - - private IQuest quest; - private final int qID; - - public GuiRewardEditor(GuiScreen parent, IQuest quest) - { - super(parent); - - this.quest = quest; - this.qID = QuestDatabase.INSTANCE.getID(quest); +public class GuiRewardEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh { + private CanvasScrolling qrList; + + private IQuest quest; + private final int qID; + + public GuiRewardEditor(GuiScreen parent, IQuest quest) { + super(parent); + + this.quest = quest; + this.qID = QuestDatabase.INSTANCE.getID(quest); + } + + @Override + public void refreshGui() { + quest = QuestDatabase.INSTANCE.getValue(qID); + + if (quest == null) { + mc.displayGuiScreen(this.parent); + return; } - - @Override - public void refreshGui() - { - quest = QuestDatabase.INSTANCE.getValue(qID); - - if(quest == null) - { - mc.displayGuiScreen(this.parent); - return; - } - - refreshRewards(); + + refreshRewards(); + } + + @Override + public void initPanel() { + super.initPanel(); + + if (qID < 0) { + mc.displayGuiScreen(this.parent); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - if(qID < 0) - { - mc.displayGuiScreen(this.parent); - return; - } - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_rewards")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - CanvasSearch, IFactoryData> cvRegSearch = new CanvasSearch, IFactoryData>((new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 48, 24, 32), 0))) - { - @Override - protected Iterator> getIterator() - { - List> list = RewardRegistry.INSTANCE.getAll(); - list.sort(Comparator.comparing(o -> o.getRegistryName().toString().toLowerCase())); - return list.iterator(); - } - - @Override - protected void queryMatches(IFactoryData value, String query, ArrayDeque> results) - { - if(value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) results.add(value); - } - - @Override - protected boolean addResult(IFactoryData entry, int index, int cachedWidth) - { - this.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, entry.getRegistryName().toString(), entry)); - return true; - } + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + "betterquesting.title.edit_rewards")).setAlignment(1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + CanvasSearch, IFactoryData> cvRegSearch = + new CanvasSearch, IFactoryData>( + (new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 48, 24, 32), 0))) { + @Override + protected Iterator> getIterator() { + List> list = RewardRegistry.INSTANCE.getAll(); + list.sort(Comparator.comparing(o -> o.getRegistryName().toString().toLowerCase())); + return list.iterator(); + } + + @Override + protected void queryMatches(IFactoryData value, String query, + ArrayDeque> results) { + if (value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) { results.add(value); } + } + + @Override + protected boolean addResult(IFactoryData entry, int index, int cachedWidth) { + this.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, + entry.getRegistryName().toString(), entry)); + return true; + } }; - cvBackground.addPanel(cvRegSearch); - - PanelVScrollBar scReg = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 48, 16, 32), 0)); - cvBackground.addPanel(scReg); - cvRegSearch.setScrollDriverY(scReg); - - PanelTextField tfSearch = new PanelTextField<>(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(8, 32, 16, -48), 0), "", FieldFilterString.INSTANCE); - tfSearch.setCallback(cvRegSearch::setSearchFilter); - tfSearch.setWatermark("Search..."); - cvBackground.addPanel(tfSearch); - - qrList = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 32), 0)); - cvBackground.addPanel(qrList); - - PanelVScrollBar scRew = new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-16, 32, 8, 32), 0)); - cvBackground.addPanel(scRew); - qrList.setScrollDriverY(scRew); - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); - - refreshRewards(); - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Add - { - IFactoryData fact = ((PanelButtonStorage>)btn).getStoredValue(); - quest.getRewards().add(quest.getRewards().nextID(), fact.createNew()); - - SendChanges(); - } else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Remove - { - IReward reward = ((PanelButtonStorage)btn).getStoredValue(); - - if(quest.getRewards().removeValue(reward)) - { - SendChanges(); - } - } else if(btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Edit - { - IReward reward = ((PanelButtonStorage)btn).getStoredValue(); - GuiScreen editor = reward.getRewardEditor(this, new DBEntry<>(qID, quest)); - - if(editor != null) - { - mc.displayGuiScreen(editor); - } else - { - mc.displayGuiScreen(new GuiNbtEditor(this, reward.writeToNBT(new NBTTagCompound()), value -> { - reward.readFromNBT(value); - SendChanges(); - })); - } - } + cvBackground.addPanel(cvRegSearch); + + PanelVScrollBar scReg = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 48, 16, 32), 0)); + cvBackground.addPanel(scReg); + cvRegSearch.setScrollDriverY(scReg); + + PanelTextField tfSearch = + new PanelTextField<>(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(8, 32, 16, -48), 0), "", + FieldFilterString.INSTANCE); + tfSearch.setCallback(cvRegSearch::setSearchFilter); + tfSearch.setWatermark("Search..."); + cvBackground.addPanel(tfSearch); + + qrList = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 32), 0)); + cvBackground.addPanel(qrList); + + PanelVScrollBar scRew = + new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-16, 32, 8, 32), 0)); + cvBackground.addPanel(scRew); + qrList.setScrollDriverY(scRew); + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + + refreshRewards(); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void refreshRewards() + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - List> dbRew = quest.getRewards().getEntries(); - - qrList.resetCanvas(); - int w = qrList.getTransform().getWidth(); - - for(int i = 0; i < dbRew.size(); i++) - { - IReward reward = dbRew.get(i).getValue(); - qrList.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, w - 16, 16, 0), 3, QuestTranslation.translate(reward.getUnlocalisedName()), reward)); - qrList.addPanel(new PanelButtonStorage<>(new GuiRectangle(w - 16, i * 16, 16, 16, 0), 2, "" + TextFormatting.RED + TextFormatting.BOLD + "x", reward)); - } + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Add + { + IFactoryData fact = + ((PanelButtonStorage>) btn).getStoredValue(); + quest.getRewards().add(quest.getRewards().nextID(), fact.createNew()); + + SendChanges(); + } else if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Remove + { + IReward reward = ((PanelButtonStorage) btn).getStoredValue(); + + if (quest.getRewards().removeValue(reward)) { + SendChanges(); + } + } else if (btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Edit + { + IReward reward = ((PanelButtonStorage) btn).getStoredValue(); + GuiScreen editor = reward.getRewardEditor(this, new DBEntry<>(qID, quest)); + + if (editor != null) { + mc.displayGuiScreen(editor); + } else { + mc.displayGuiScreen(new GuiNbtEditor(this, reward.writeToNBT(new NBTTagCompound()), value -> { + reward.readFromNBT(value); + SendChanges(); + })); + } } - - private void SendChanges() - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", qID); - entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetQuestEdit.sendEdit(payload); - } + } + + private void refreshRewards() { + List> dbRew = quest.getRewards().getEntries(); + + qrList.resetCanvas(); + int w = qrList.getTransform().getWidth(); + + for (int i = 0; i < dbRew.size(); i++) { + IReward reward = dbRew.get(i).getValue(); + qrList.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, w - 16, 16, 0), 3, + QuestTranslation.translate(reward.getUnlocalisedName()), reward)); + qrList.addPanel(new PanelButtonStorage<>(new GuiRectangle(w - 16, i * 16, 16, 16, 0), 2, + "" + TextFormatting.RED + TextFormatting.BOLD + "x", reward)); + } + } + + private void SendChanges() { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", qID); + entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetQuestEdit.sendEdit(payload); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java index ffd17b662..f9d1e2733 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java @@ -42,185 +42,182 @@ import java.util.Iterator; import java.util.List; -public class GuiTaskEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh -{ - private CanvasScrolling qtList; - - private IQuest quest; - private final int qID; - - public GuiTaskEditor(GuiScreen parent, IQuest quest) - { - super(parent); - - this.quest = quest; - this.qID = QuestDatabase.INSTANCE.getID(quest); +public class GuiTaskEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen, INeedsRefresh { + private CanvasScrolling qtList; + + private IQuest quest; + private final int qID; + + public GuiTaskEditor(GuiScreen parent, IQuest quest) { + super(parent); + + this.quest = quest; + this.qID = QuestDatabase.INSTANCE.getID(quest); + } + + @Override + public void refreshGui() { + quest = QuestDatabase.INSTANCE.getValue(qID); + + if (quest == null) { + mc.displayGuiScreen(this.parent); + return; } - - @Override - public void refreshGui() - { - quest = QuestDatabase.INSTANCE.getValue(qID); - - if(quest == null) - { - mc.displayGuiScreen(this.parent); - return; - } - - refreshTasks(); + + refreshTasks(); + } + + @Override + public void initPanel() { + super.initPanel(); + + if (qID < 0) { + mc.displayGuiScreen(this.parent); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - if(qID < 0) - { - mc.displayGuiScreen(this.parent); - return; - } - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_tasks")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - CanvasSearch, IFactoryData> cvRegSearch = new CanvasSearch, IFactoryData>((new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 48, 24, 32), 0))) - { - @Override - protected Iterator> getIterator() - { - List> list = TaskRegistry.INSTANCE.getAll(); - list.sort(Comparator.comparing(o -> o.getRegistryName().toString().toLowerCase())); - return list.iterator(); - } - - @Override - protected void queryMatches(IFactoryData value, String query, ArrayDeque> results) - { - if(value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) results.add(value); - } - - @Override - protected boolean addResult(IFactoryData entry, int index, int cachedWidth) - { - this.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, entry.getRegistryName().toString(), entry)); - return true; - } + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.edit_tasks")).setAlignment( + 1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + CanvasSearch, IFactoryData> cvRegSearch = + new CanvasSearch, IFactoryData>( + (new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 48, 24, 32), 0))) { + @Override + protected Iterator> getIterator() { + List> list = TaskRegistry.INSTANCE.getAll(); + list.sort(Comparator.comparing(o -> o.getRegistryName().toString().toLowerCase())); + return list.iterator(); + } + + @Override + protected void queryMatches(IFactoryData value, String query, + ArrayDeque> results) { + if (value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) { results.add(value); } + } + + @Override + protected boolean addResult(IFactoryData entry, int index, int cachedWidth) { + this.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, + entry.getRegistryName().toString(), entry)); + return true; + } }; - cvBackground.addPanel(cvRegSearch); - - PanelVScrollBar scReg = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 48, 16, 32), 0)); - cvBackground.addPanel(scReg); - cvRegSearch.setScrollDriverY(scReg); - - PanelTextField tfSearch = new PanelTextField<>(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(8, 32, 16, -48), 0), "", FieldFilterString.INSTANCE); - tfSearch.setCallback(cvRegSearch::setSearchFilter); - tfSearch.setWatermark("Search..."); - cvBackground.addPanel(tfSearch); - - qtList = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 32), 0)); - cvBackground.addPanel(qtList); - - PanelVScrollBar scTsk = new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-16, 32, 8, 32), 0)); - cvBackground.addPanel(scTsk); - qtList.setScrollDriverY(scTsk); - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); - - refreshTasks(); - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Add - { - IFactoryData fact = ((PanelButtonStorage>)btn).getStoredValue(); - quest.getTasks().add(quest.getTasks().nextID(), fact.createNew()); - - SendChanges(); - } else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Remove - { - ITask task = ((PanelButtonStorage)btn).getStoredValue(); - - if(quest.getTasks().removeValue(task)) - { - SendChanges(); - } - } else if(btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Edit - { - ITask task = ((PanelButtonStorage)btn).getStoredValue(); - GuiScreen editor = task.getTaskEditor(this, new DBEntry<>(qID, quest)); - - if(editor != null) - { - mc.displayGuiScreen(editor); - } else - { - mc.displayGuiScreen(new GuiNbtEditor(this, task.writeToNBT(new NBTTagCompound()), value -> { - task.readFromNBT(value); - SendChanges(); - })); - } - } + cvBackground.addPanel(cvRegSearch); + + PanelVScrollBar scReg = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 48, 16, 32), 0)); + cvBackground.addPanel(scReg); + cvRegSearch.setScrollDriverY(scReg); + + PanelTextField tfSearch = + new PanelTextField<>(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(8, 32, 16, -48), 0), "", + FieldFilterString.INSTANCE); + tfSearch.setCallback(cvRegSearch::setSearchFilter); + tfSearch.setWatermark("Search..."); + cvBackground.addPanel(tfSearch); + + qtList = new CanvasScrolling(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 16, 32), 0)); + cvBackground.addPanel(qtList); + + PanelVScrollBar scTsk = + new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-16, 32, 8, 32), 0)); + cvBackground.addPanel(scTsk); + qtList.setScrollDriverY(scTsk); + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + + refreshTasks(); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void refreshTasks() + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - List> dbTsk = quest.getTasks().getEntries(); - - qtList.resetCanvas(); - int w = qtList.getTransform().getWidth(); - - for(int i = 0; i < dbTsk.size(); i++) - { - ITask task = dbTsk.get(i).getValue(); - qtList.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, w - 16, 16, 0), 3, QuestTranslation.translate(task.getUnlocalisedName()), task)); - qtList.addPanel(new PanelButtonStorage<>(new GuiRectangle(w - 16, i * 16, 16, 16, 0), 2, "" + TextFormatting.RED + TextFormatting.BOLD + "x", task)); - } + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Add + { + IFactoryData fact = + ((PanelButtonStorage>) btn).getStoredValue(); + quest.getTasks().add(quest.getTasks().nextID(), fact.createNew()); + + SendChanges(); + } else if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Remove + { + ITask task = ((PanelButtonStorage) btn).getStoredValue(); + + if (quest.getTasks().removeValue(task)) { + SendChanges(); + } + } else if (btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Edit + { + ITask task = ((PanelButtonStorage) btn).getStoredValue(); + GuiScreen editor = task.getTaskEditor(this, new DBEntry<>(qID, quest)); + + if (editor != null) { + mc.displayGuiScreen(editor); + } else { + mc.displayGuiScreen(new GuiNbtEditor(this, task.writeToNBT(new NBTTagCompound()), value -> { + task.readFromNBT(value); + SendChanges(); + })); + } } - - private void SendChanges() - { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", qID); - entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetQuestEdit.sendEdit(payload); - } + } + + private void refreshTasks() { + List> dbTsk = quest.getTasks().getEntries(); + + qtList.resetCanvas(); + int w = qtList.getTransform().getWidth(); + + for (int i = 0; i < dbTsk.size(); i++) { + ITask task = dbTsk.get(i).getValue(); + qtList.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, w - 16, 16, 0), 3, + QuestTranslation.translate(task.getUnlocalisedName()), task)); + qtList.addPanel(new PanelButtonStorage<>(new GuiRectangle(w - 16, i * 16, 16, 16, 0), 2, + "" + TextFormatting.RED + TextFormatting.BOLD + "x", task)); + } + } + + private void SendChanges() { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", qID); + entry.setTag("config", quest.writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetQuestEdit.sendEdit(payload); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java index 573b180b0..c285feec7 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java @@ -27,93 +27,92 @@ import net.minecraft.util.text.TextFormatting; import org.lwjgl.input.Keyboard; -public class GuiTextEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen -{ - private final ICallback callback; - private final String textIn; - - private PanelTextField flText; - - public GuiTextEditor(GuiScreen parent, String text, ICallback callback) - { - super(parent); - - textIn = text; - this.callback = callback; - } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_text")).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - flText = new PanelTextField<>(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(124, 32, 24, 32), 0), flText != null ? flText.getRawText() : textIn, FieldFilterString.INSTANCE); - cvBackground.addPanel(flText); - flText.setMaxLength(Integer.MAX_VALUE); - flText.enableWrapping(true); - flText.lockFocus(true); - - CanvasScrolling cvFormatList = new CanvasScrolling(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(16, 32, -116, 32), 0)); - cvBackground.addPanel(cvFormatList); - - TextFormatting[] tfValues = TextFormatting.values(); - for(int i = 0; i < tfValues.length; i++) - { - cvFormatList.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, i * 16, 100, 16), 1, tfValues[i].getFriendlyName(), tfValues[i].toString())); - } - - PanelVScrollBar scFormatScroll = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); - cvBackground.addPanel(scFormatScroll); - scFormatScroll.getTransform().setParent(cvFormatList.getTransform()); - cvFormatList.setScrollDriverY(scFormatScroll); - scFormatScroll.setActive(cvFormatList.getScrollBounds().getHeight() > 0); +public class GuiTextEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen { + private final ICallback callback; + private final String textIn; + + private PanelTextField flText; + + public GuiTextEditor(GuiScreen parent, String text, ICallback callback) { + super(parent); + + textIn = text; + this.callback = callback; + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.edit_text")).setAlignment( + 1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + flText = new PanelTextField<>(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(124, 32, 24, 32), 0), + flText != null ? flText.getRawText() : textIn, FieldFilterString.INSTANCE); + cvBackground.addPanel(flText); + flText.setMaxLength(Integer.MAX_VALUE); + flText.enableWrapping(true); + flText.lockFocus(true); + + CanvasScrolling cvFormatList = + new CanvasScrolling(new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(16, 32, -116, 32), 0)); + cvBackground.addPanel(cvFormatList); + + TextFormatting[] tfValues = TextFormatting.values(); + for (int i = 0; i < tfValues.length; i++) { + cvFormatList.addPanel( + new PanelButtonStorage<>(new GuiRectangle(0, i * 16, 100, 16), 1, tfValues[i].getFriendlyName(), + tfValues[i].toString())); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + PanelVScrollBar scFormatScroll = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); + cvBackground.addPanel(scFormatScroll); + scFormatScroll.getTransform().setParent(cvFormatList.getTransform()); + cvFormatList.setScrollDriverY(scFormatScroll); + scFormatScroll.setActive(cvFormatList.getScrollBounds().getHeight() > 0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) - { - String format = ((PanelButtonStorage)btn).getStoredValue(); - flText.writeText(format); - } + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { + String format = ((PanelButtonStorage) btn).getStoredValue(); + flText.writeText(format); } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - - if(callback != null) - { - callback.setValue(flText.getRawText()); - } + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + + if (callback != null) { + callback.setValue(flText.getRawText()); } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java b/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java index 4eb5933b4..e50fa0f6b 100644 --- a/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java +++ b/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java @@ -18,12 +18,12 @@ import betterquesting.api2.client.gui.panels.IGuiPanel; import betterquesting.api2.client.gui.panels.content.PanelGeneric; import betterquesting.api2.client.gui.panels.content.PanelTextBox; +import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine; import betterquesting.api2.client.gui.themes.presets.PresetColor; import betterquesting.api2.client.gui.themes.presets.PresetIcon; import betterquesting.api2.client.gui.themes.presets.PresetTexture; import betterquesting.api2.client.toolbox.IToolTab; import betterquesting.api2.utils.QuestTranslation; -import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine; import betterquesting.client.toolbox.ToolboxRegistry; import betterquesting.questing.QuestLineDatabase; import net.minecraft.client.gui.GuiScreen; @@ -33,150 +33,148 @@ import java.util.ArrayList; import java.util.List; -public class GuiDesigner extends GuiScreenCanvas implements IVolatileScreen, INeedsRefresh, IPEventListener -{ - // Not final because I hope to support hot swapping in future - private IQuestLine questLine; - private final int lineID; - - private PanelToolController toolController; - private IGuiCanvas cvTray; - - private final List tabList = new ArrayList<>(); - private PanelTextBox tabTitle; - private IGuiPanel lastTabPanel; - private int tabIdx = 0; - - private CanvasQuestLine cvQuest; - - public GuiDesigner(GuiScreen parent, IQuestLine line) - { - super(parent); - this.questLine = line; - this.lineID = QuestLineDatabase.INSTANCE.getID(line); - this.tabList.addAll(ToolboxRegistry.INSTANCE.getAllTabs()); - } - - @Override - public void refreshGui() - { - this.questLine = QuestLineDatabase.INSTANCE.getValue(lineID); - - if(questLine == null) - { - mc.displayGuiScreen(parent); - return; - } - - int sx = cvQuest.getScrollX(); - int sy = cvQuest.getScrollY(); - float z = cvQuest.getZoom(); - cvQuest.setQuestLine(questLine); - cvQuest.setZoom(z); // Always set the scale before attempting to scroll - cvQuest.setScrollX(sx); - cvQuest.setScrollY(sy); - - toolController.refreshCanvas(); +public class GuiDesigner extends GuiScreenCanvas implements IVolatileScreen, INeedsRefresh, IPEventListener { + // Not final because I hope to support hot swapping in future + private IQuestLine questLine; + private final int lineID; + + private PanelToolController toolController; + private IGuiCanvas cvTray; + + private final List tabList = new ArrayList<>(); + private PanelTextBox tabTitle; + private IGuiPanel lastTabPanel; + private int tabIdx = 0; + + private CanvasQuestLine cvQuest; + + public GuiDesigner(GuiScreen parent, IQuestLine line) { + super(parent); + this.questLine = line; + this.lineID = QuestLineDatabase.INSTANCE.getID(line); + this.tabList.addAll(ToolboxRegistry.INSTANCE.getAllTabs()); + } + + @Override + public void refreshGui() { + this.questLine = QuestLineDatabase.INSTANCE.getValue(lineID); + + if (questLine == null) { + mc.displayGuiScreen(parent); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 96, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvTray = new CanvasTextured(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-96, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvTray); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); - - PanelGeneric pnFrame = new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0), PresetTexture.AUX_FRAME_0.getTexture()); - cvBackground.addPanel(pnFrame); - - cvQuest = new CanvasQuestLine(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0), 1); - cvBackground.addPanel(cvQuest); - cvQuest.setQuestLine(questLine); - - PanelButton btnTabLeft = new PanelButton(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0F), new GuiPadding(16, 32, 0, -40), 0), 2, "") - { - @Override - public void onButtonClick() - { - tabIdx--; - refreshToolTab(); - } + + int sx = cvQuest.getScrollX(); + int sy = cvQuest.getScrollY(); + float z = cvQuest.getZoom(); + cvQuest.setQuestLine(questLine); + cvQuest.setZoom(z); // Always set the scale before attempting to scroll + cvQuest.setScrollX(sx); + cvQuest.setScrollY(sy); + + toolController.refreshCanvas(); + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = + new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 96, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvTray = new CanvasTextured(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-96, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvTray); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.done"))); + + PanelGeneric pnFrame = new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0), + PresetTexture.AUX_FRAME_0.getTexture()); + cvBackground.addPanel(pnFrame); + + cvQuest = new CanvasQuestLine(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0), 1); + cvBackground.addPanel(cvQuest); + cvQuest.setQuestLine(questLine); + + PanelButton btnTabLeft = + new PanelButton(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0F), new GuiPadding(16, 32, 0, -40), 0), 2, "") { + @Override + public void onButtonClick() { + tabIdx--; + refreshToolTab(); + } }; - btnTabLeft.setIcon(PresetIcon.ICON_LEFT.getTexture()); - cvTray.addPanel(btnTabLeft); - - PanelButton btnTabRight = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(0, 32, 16, -40), 0), 3, "") - { - @Override - public void onButtonClick() - { - tabIdx++; - refreshToolTab(); - } + btnTabLeft.setIcon(PresetIcon.ICON_LEFT.getTexture()); + cvTray.addPanel(btnTabLeft); + + PanelButton btnTabRight = + new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(0, 32, 16, -40), 0), 3, "") { + @Override + public void onButtonClick() { + tabIdx++; + refreshToolTab(); + } }; - btnTabRight.setIcon(PresetIcon.ICON_RIGHT.getTexture()); - cvTray.addPanel(btnTabRight); - - tabTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(16, 20, 16, -32), 0), "?").setAlignment(1).setColor(PresetColor.TEXT_HEADER.getColor()); - cvTray.addPanel(tabTitle); - - if(toolController != null) - { - cvBackground.addPanel(toolController); - cvQuest.setScrollDriverX(toolController.getScrollX()); - cvQuest.setScrollDriverY(toolController.getScrollY()); - toolController.changeCanvas(cvQuest); - } else - { - toolController = new PanelToolController(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), -1), cvQuest); - cvBackground.addPanel(toolController); - cvQuest.setScrollDriverX(toolController.getScrollX()); - cvQuest.setScrollDriverY(toolController.getScrollY()); - } - - refreshToolTab(); + btnTabRight.setIcon(PresetIcon.ICON_RIGHT.getTexture()); + cvTray.addPanel(btnTabRight); + + tabTitle = + new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(16, 20, 16, -32), 0), "?").setAlignment(1) + .setColor( + PresetColor.TEXT_HEADER.getColor()); + cvTray.addPanel(tabTitle); + + if (toolController != null) { + cvBackground.addPanel(toolController); + cvQuest.setScrollDriverX(toolController.getScrollX()); + cvQuest.setScrollDriverY(toolController.getScrollY()); + toolController.changeCanvas(cvQuest); + } else { + toolController = + new PanelToolController(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), -1), cvQuest); + cvBackground.addPanel(toolController); + cvQuest.setScrollDriverX(toolController.getScrollX()); + cvQuest.setScrollDriverY(toolController.getScrollY()); } - - private void refreshToolTab() - { - if(lastTabPanel != null) cvTray.removePanel(lastTabPanel); - - if(tabList.size() <= 0) return; - if(tabIdx < 0) while(tabIdx < 0) tabIdx += tabList.size(); - tabIdx %= tabList.size(); - - lastTabPanel = tabList.get(tabIdx).getTabGui(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 48, 16, 16), 0), cvQuest, toolController); - tabTitle.setText(QuestTranslation.translate(tabList.get(tabIdx).getUnlocalisedName())); - - if(lastTabPanel != null) cvTray.addPanel(lastTabPanel); + + refreshToolTab(); + } + + private void refreshToolTab() { + if (lastTabPanel != null) { cvTray.removePanel(lastTabPanel); } + + if (tabList.isEmpty()) { return; } + if (tabIdx < 0) { while (tabIdx < 0) { tabIdx += tabList.size(); } } + tabIdx %= tabList.size(); + + lastTabPanel = tabList.get(tabIdx) + .getTabGui(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 48, 16, 16), 0), cvQuest, + toolController); + tabTitle.setText(QuestTranslation.translate(tabList.get(tabIdx).getUnlocalisedName())); + + if (lastTabPanel != null) { cvTray.addPanel(lastTabPanel); } + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - private void onButtonPress(PEventButton event) + } + + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } + mc.displayGuiScreen(this.parent); } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java b/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java index 6d1007d1d..344fc31e9 100644 --- a/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java +++ b/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java @@ -9,13 +9,13 @@ import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.panels.IGuiPanel; import betterquesting.api2.client.gui.panels.content.PanelGeneric; +import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine; import betterquesting.api2.client.gui.resources.colors.GuiColorPulse; import betterquesting.api2.client.gui.resources.colors.IGuiColor; import betterquesting.api2.client.gui.resources.lines.BoxLine; import betterquesting.api2.client.gui.resources.lines.IGuiLine; import betterquesting.api2.client.gui.resources.textures.ColorTexture; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; -import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.NonNullList; import net.minecraft.util.math.MathHelper; @@ -27,309 +27,270 @@ import java.util.List; // Kinda just a poxy panel where tools can be hotswapped out -public class PanelToolController implements IGuiPanel -{ - private CanvasQuestLine questLine; - private final IGuiRect transform; - private boolean enabled = true; - - private final IValueIO scDriverX; - private final IValueIO scDriverY; - - private IToolboxTool activeTool; - - public static final NonNullList selected = NonNullList.create(); - public static final List highlights = new ArrayList<>(); - private GuiRectangle selBounds; - - private IGuiLine selLine = new BoxLine(); - private IGuiColor selCol = new GuiColorPulse(0xFFFFFFFF, 0xFF000000, 2F, 0F); - private IGuiTexture hTex = new ColorTexture(new GuiColorPulse(0x22FFFFFF, 0x77FFFFFF, 2F, 0F)); - - public PanelToolController(IGuiRect rect, CanvasQuestLine questLine) - { - this.transform = rect; - this.questLine = questLine; - - scDriverX = new FloatSimpleIO() - { - @Override - public void writeValue(Float value) - { - if(activeTool != null && !activeTool.clampScrolling()) - { - this.v = value; - } else - { - this.v = MathHelper.clamp(value, 0F, 1F); - } - } - }.setLerp(true, 0.02F); - - scDriverY = new FloatSimpleIO() - { - @Override - public void writeValue(Float value) - { - if(activeTool != null && !activeTool.clampScrolling()) - { - this.v = value; - } else - { - this.v = MathHelper.clamp(value, 0F, 1F); - } - } - }.setLerp(true, 0.02F); - } - - public void setActiveTool(IToolboxTool tool) - { - if(this.activeTool != null) activeTool.disableTool(); - if(tool == null) return; - - activeTool = tool; - tool.initTool(questLine); - } - - public IToolboxTool getActiveTool() - { - return this.activeTool; - } - - public void changeCanvas(@Nonnull CanvasQuestLine canvas) - { - this.questLine = canvas; - refreshCanvas(); - setActiveTool(getActiveTool()); - } - - public void refreshCanvas() - { - List tmp = new ArrayList<>(); - for(PanelButtonQuest b1 : selected) - { - for(PanelButtonQuest b2 : questLine.getQuestButtons()) if(b1.getStoredValue().getID() == b2.getStoredValue().getID()) tmp.add(b2); +public class PanelToolController implements IGuiPanel { + private CanvasQuestLine questLine; + private final IGuiRect transform; + private boolean enabled = true; + + private final IValueIO scDriverX; + private final IValueIO scDriverY; + + private IToolboxTool activeTool; + + public static final NonNullList selected = NonNullList.create(); + public static final List highlights = new ArrayList<>(); + private GuiRectangle selBounds; + + private final IGuiLine selLine = new BoxLine(); + private final IGuiColor selCol = new GuiColorPulse(0xFFFFFFFF, 0xFF000000, 2F, 0F); + private final IGuiTexture hTex = new ColorTexture(new GuiColorPulse(0x22FFFFFF, 0x77FFFFFF, 2F, 0F)); + + public PanelToolController(IGuiRect rect, CanvasQuestLine questLine) { + this.transform = rect; + this.questLine = questLine; + + scDriverX = new FloatSimpleIO() { + @Override + public void writeValue(Float value) { + if (activeTool != null && !activeTool.clampScrolling()) { + this.v = value; + } else { + this.v = MathHelper.clamp(value, 0F, 1F); } - - selected.clear(); - selected.addAll(tmp); - - highlights.clear(); - for(PanelButtonQuest btn : selected) highlights.add(new PanelGeneric(btn.rect, hTex)); - - if(this.activeTool != null) activeTool.refresh(this.questLine); - } - - public CanvasQuestLine getCanvas() - { - return this.getCanvas(); - } - - public IValueIO getScrollX() - { - return this.scDriverX; - } - - public IValueIO getScrollY() - { - return this.scDriverY; - } - - @Override - public IGuiRect getTransform() - { - return transform; - } - - @Override - public void initPanel() - { + } + }.setLerp(true, 0.02F); + + scDriverY = new FloatSimpleIO() { + @Override + public void writeValue(Float value) { + if (activeTool != null && !activeTool.clampScrolling()) { + this.v = value; + } else { + this.v = MathHelper.clamp(value, 0F, 1F); + } + } + }.setLerp(true, 0.02F); + } + + public void setActiveTool(IToolboxTool tool) { + if (this.activeTool != null) { activeTool.disableTool(); } + if (tool == null) { return; } + + activeTool = tool; + tool.initTool(questLine); + } + + public IToolboxTool getActiveTool() { + return this.activeTool; + } + + public void changeCanvas(@Nonnull CanvasQuestLine canvas) { + this.questLine = canvas; + refreshCanvas(); + setActiveTool(getActiveTool()); + } + + public void refreshCanvas() { + List tmp = new ArrayList<>(); + for (PanelButtonQuest b1 : selected) { + for (PanelButtonQuest b2 : questLine.getQuestButtons()) { + if (b1.getStoredValue().getID() == b2.getStoredValue().getID()) { + tmp.add(b2); + } + } } - - @Override - public void setEnabled(boolean state) - { - this.enabled = state; + + selected.clear(); + selected.addAll(tmp); + + highlights.clear(); + for (PanelButtonQuest btn : selected) { + highlights.add(new PanelGeneric(btn.rect, hTex)); } - - @Override - public boolean isEnabled() - { - return enabled; + + if (this.activeTool != null) { + activeTool.refresh(this.questLine); } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - if(!enabled) return; - - if(activeTool != null) - { - float zs = questLine.getZoom(); - int lsx = questLine.getScrollX(); - int lsy = questLine.getScrollY(); - int tx = getTransform().getX(); - int ty = getTransform().getY(); - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - GlStateManager.pushMatrix(); - RenderUtils.startScissor(transform); - - GlStateManager.translate(tx - lsx * zs, ty - lsy * zs, 0F); - GlStateManager.scale(zs, zs, zs); - - if(selBounds != null) - { - selBounds.w = smx - selBounds.x; - selBounds.h = smy - selBounds.y; - - selLine.drawLine(selBounds, selBounds, 2, selCol, partialTick); - } - - for(IGuiPanel pn : highlights) pn.drawPanel(smx, smy, partialTick); - - // Pretending we're on the scrolling canvas (when we're really not) so as not to influence it by hotswapping panels - activeTool.drawCanvas(smx, smy, partialTick); - - RenderUtils.endScissor(); - GlStateManager.popMatrix(); - - activeTool.drawOverlay(mx, my, partialTick); - } + } + + public IValueIO getScrollX() { + return this.scDriverX; + } + + public IValueIO getScrollY() { + return this.scDriverY; + } + + @Override + public IGuiRect getTransform() { + return transform; + } + + @Override + public void initPanel() { + } + + @Override + public void setEnabled(boolean state) { + this.enabled = state; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + if (!enabled) { return; } + + if (activeTool != null) { + float zs = questLine.getZoom(); + int lsx = questLine.getScrollX(); + int lsy = questLine.getScrollY(); + int tx = getTransform().getX(); + int ty = getTransform().getY(); + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + GlStateManager.pushMatrix(); + RenderUtils.startScissor(transform); + + GlStateManager.translate(tx - lsx * zs, ty - lsy * zs, 0F); + GlStateManager.scale(zs, zs, zs); + + if (selBounds != null) { + selBounds.w = smx - selBounds.x; + selBounds.h = smy - selBounds.y; + + selLine.drawLine(selBounds, selBounds, 2, selCol, partialTick); + } + + for (IGuiPanel pn : highlights) { pn.drawPanel(smx, smy, partialTick); } + + // Pretending we're on the scrolling canvas (when we're really not) so as not to influence it by hotswapping panels + activeTool.drawCanvas(smx, smy, partialTick); + + RenderUtils.endScissor(); + GlStateManager.popMatrix(); + + activeTool.drawOverlay(mx, my, partialTick); } - - @Override - public boolean onMouseClick(int mx, int my, int button) - { - if(activeTool != null && this.getTransform().contains(mx, my)) - { - if(activeTool.onMouseClick(mx, my, button)) return true; - if(activeTool.useSelection()) - { - if(button == 1) - { - selBounds = null; - selected.clear(); - highlights.clear(); - activeTool.onSelection(selected); - return true; - } else if(button == 0) - { - float zs = questLine.getZoom(); - int lsx = questLine.getScrollX(); - int lsy = questLine.getScrollY(); - int tx = questLine.getTransform().getX(); - int ty = questLine.getTransform().getY(); - int smx = (int)((mx - tx) / zs) + lsx; - int smy = (int)((my - ty) / zs) + lsy; - - selBounds = new GuiRectangle(smx, smy, 0, 0); - return true; - } - } + } + + @Override + public boolean onMouseClick(int mx, int my, int button) { + if (activeTool != null && this.getTransform().contains(mx, my)) { + if (activeTool.onMouseClick(mx, my, button)) { return true; } + if (activeTool.useSelection()) { + if (button == 1) { + selBounds = null; + selected.clear(); + highlights.clear(); + activeTool.onSelection(selected); + return true; + } else if (button == 0) { + float zs = questLine.getZoom(); + int lsx = questLine.getScrollX(); + int lsy = questLine.getScrollY(); + int tx = questLine.getTransform().getX(); + int ty = questLine.getTransform().getY(); + int smx = (int) ((mx - tx) / zs) + lsx; + int smy = (int) ((my - ty) / zs) + lsy; + + selBounds = new GuiRectangle(smx, smy, 0, 0); + return true; } - - return false; + } } - - @Override - public boolean onMouseRelease(int mx, int my, int button) - { - if(selBounds != null) - { - if(selBounds.w < 0) - { - selBounds.x += selBounds.w; - selBounds.w *= -1; - } - - if(selBounds.h < 0) - { - selBounds.y += selBounds.h; - selBounds.h *= -1; - } - - boolean append = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - boolean subtract = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); - - if(!append && !subtract) selected.clear(); - - for(PanelButtonQuest btn : questLine.getQuestButtons()) - { - if(selBounds.contains(btn.rect.x + btn.rect.w / 2, btn.rect.y + btn.rect.h / 2) || (btn.rect.contains(selBounds.x, selBounds.y) && Math.max(selBounds.w, selBounds.h) < 4)) - { - if(subtract) - { - selected.remove(btn); - continue; - } - if(append && selected.contains(btn)) continue; - selected.add(btn); - } - } - - highlights.clear(); - for(PanelButtonQuest btn : selected) highlights.add(new PanelGeneric(btn.rect, hTex)); - - selBounds = null; - if(activeTool != null) activeTool.onSelection(selected); + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int button) { + if (selBounds != null) { + if (selBounds.w < 0) { + selBounds.x += selBounds.w; + selBounds.w *= -1; + } + + if (selBounds.h < 0) { + selBounds.y += selBounds.h; + selBounds.h *= -1; + } + + boolean append = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + boolean subtract = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); + + if (!append && !subtract) { selected.clear(); } + + for (PanelButtonQuest btn : questLine.getQuestButtons()) { + if (selBounds.contains(btn.rect.x + btn.rect.w / 2, btn.rect.y + btn.rect.h / 2) || + (btn.rect.contains(selBounds.x, selBounds.y) && Math.max(selBounds.w, selBounds.h) < 4)) { + if (subtract) { + selected.remove(btn); + continue; + } + if (append && selected.contains(btn)) { continue; } + selected.add(btn); } - - if(activeTool != null) return activeTool.onMouseRelease(mx, my, button); - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - if(activeTool != null) return activeTool.onMouseScroll(mx, my, scroll); - return false; + } + + highlights.clear(); + for (PanelButtonQuest btn : selected) { highlights.add(new PanelGeneric(btn.rect, hTex)); } + + selBounds = null; + if (activeTool != null) { activeTool.onSelection(selected); } } - - @Override - public boolean onKeyTyped(char c, int keycode) - { - if(activeTool != null) - { - if(activeTool.onKeyPressed(c, keycode)) return true; - if(activeTool.useSelection() && keycode == Keyboard.KEY_A) - { - boolean append = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); - boolean subtract = append && (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)); - - if(subtract) - { - selBounds = null; - selected.clear(); - highlights.clear(); - activeTool.onSelection(selected); - return true; - } else if(append) - { - selected.clear(); - highlights.clear(); - - for(PanelButtonQuest btn : questLine.getQuestButtons()) - { - selected.add(btn); - highlights.add(new PanelGeneric(btn.rect, hTex)); - } - - selBounds = null; - activeTool.onSelection(selected); - return true; - } - } + + if (activeTool != null) { return activeTool.onMouseRelease(mx, my, button); } + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + if (activeTool != null) { return activeTool.onMouseScroll(mx, my, scroll); } + return false; + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + if (activeTool != null) { + if (activeTool.onKeyPressed(c, keycode)) { return true; } + if (activeTool.useSelection() && keycode == Keyboard.KEY_A) { + boolean append = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); + boolean subtract = + append && (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)); + + if (subtract) { + selBounds = null; + selected.clear(); + highlights.clear(); + activeTool.onSelection(selected); + return true; + } else if (append) { + selected.clear(); + highlights.clear(); + + for (PanelButtonQuest btn : questLine.getQuestButtons()) { + selected.add(btn); + highlights.add(new PanelGeneric(btn.rect, hTex)); + } + + selBounds = null; + activeTool.onSelection(selected); + return true; } - return false; - } - - @Override - public List getTooltip(int mx, int my) - { - if(selBounds != null) return Collections.emptyList(); - if(activeTool != null) return activeTool.getTooltip(mx, my); - return null; + } } + return false; + } + + @Override + public List getTooltip(int mx, int my) { + if (selBounds != null) { return Collections.emptyList(); } + if (activeTool != null) { return activeTool.getTooltip(mx, my); } + return null; + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java index e08b6771c..8a81e73b5 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java @@ -5,7 +5,10 @@ import betterquesting.api.misc.ICallback; import betterquesting.api.utils.JsonHelper; import betterquesting.api2.client.gui.GuiScreenCanvas; -import betterquesting.api2.client.gui.controls.*; +import betterquesting.api2.client.gui.controls.IPanelButton; +import betterquesting.api2.client.gui.controls.PanelButton; +import betterquesting.api2.client.gui.controls.PanelButtonStorage; +import betterquesting.api2.client.gui.controls.PanelTextField; import betterquesting.api2.client.gui.controls.filters.FieldFilterString; import betterquesting.api2.client.gui.controls.io.ValueFuncIO; import betterquesting.api2.client.gui.events.IPEventListener; @@ -35,109 +38,110 @@ import net.minecraftforge.fml.common.registry.EntityEntry; import org.lwjgl.input.Keyboard; -public class GuiEntitySelection extends GuiScreenCanvas implements IPEventListener, IVolatileScreen -{ - private final ICallback callback; - private Entity selEntity; - - private PanelEntityPreview pnPreview; - - public GuiEntitySelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) - { - this(parent, JsonHelper.JsonToEntity(tag, Minecraft.getMinecraft().world), callback); - } - - public GuiEntitySelection(GuiScreen parent, Entity entity, ICallback callback) - { - super(parent); - this.selEntity = entity; - this.callback = callback; - } - - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.select_entity")).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - // === RIGHT PANEL === - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); - cvBackground.addPanel(cvRight); - - CanvasEntityDatabase cvDatabase = new CanvasEntityDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0), 1); - cvRight.addPanel(cvDatabase); - - PanelTextField searchBox = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 8, -16), 0), "", FieldFilterString.INSTANCE); - searchBox.setCallback(cvDatabase::setSearchFilter).setWatermark("Search..."); - cvRight.addPanel(searchBox); - - PanelVScrollBar scEdit = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); - cvDatabase.setScrollDriverY(scEdit); - cvRight.addPanel(scEdit); - - // === LEFT PANEL === - - pnPreview = new PanelEntityPreview(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 32), 0), selEntity); - cvBackground.addPanel(pnPreview); - - pnPreview.setRotationDriven(new ValueFuncIO<>(() -> 15F), new ValueFuncIO<>(() -> (float)(Minecraft.getSystemTime()%30000L / 30000D * 360D))); - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } +public class GuiEntitySelection extends GuiScreenCanvas implements IPEventListener, IVolatileScreen { + private final ICallback callback; + private Entity selEntity; + + private PanelEntityPreview pnPreview; + + public GuiEntitySelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) { + this(parent, JsonHelper.JsonToEntity(tag, Minecraft.getMinecraft().world), callback); + } + + public GuiEntitySelection(GuiScreen parent, Entity entity, ICallback callback) { + super(parent); + this.selEntity = entity; + this.callback = callback; + } + + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.done"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + "betterquesting.title.select_entity")).setAlignment(1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + // === RIGHT PANEL === + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); + cvBackground.addPanel(cvRight); + + CanvasEntityDatabase cvDatabase = + new CanvasEntityDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0), 1); + cvRight.addPanel(cvDatabase); + + PanelTextField searchBox = + new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 8, -16), 0), "", + FieldFilterString.INSTANCE); + searchBox.setCallback(cvDatabase::setSearchFilter).setWatermark("Search..."); + cvRight.addPanel(searchBox); + + PanelVScrollBar scEdit = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); + cvDatabase.setScrollDriverY(scEdit); + cvRight.addPanel(scEdit); + + // === LEFT PANEL === + + pnPreview = + new PanelEntityPreview(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 32), 0), selEntity); + cvBackground.addPanel(pnPreview); + + pnPreview.setRotationDriven(new ValueFuncIO<>(() -> 15F), + new ValueFuncIO<>(() -> (float) (Minecraft.getSystemTime() % 30000L / 30000D * 360D))); + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - try - { - if(callback != null) callback.setValue(selEntity); - } catch(Exception e) - { - QuestingAPI.getLogger().error("Unable to return entity selection!", e); - } - - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) - { - Entity e = EntityList.newEntity(((PanelButtonStorage)btn).getStoredValue().getEntityClass(), this.mc.world); - - if(e != null) - { - selEntity = e; - pnPreview.setEntity(selEntity); - } - } + try { + if (callback != null) { callback.setValue(selEntity); } + } catch (Exception e) { + QuestingAPI.getLogger().error("Unable to return entity selection!", e); + } + + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { + Entity e = EntityList.newEntity(((PanelButtonStorage) btn).getStoredValue().getEntityClass(), + this.mc.world); + + if (e != null) { + selEntity = e; + pnPreview.setEntity(selEntity); + } } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java index 5d30b13b2..9aa6c8363 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java @@ -40,168 +40,175 @@ import org.lwjgl.input.Keyboard; import org.lwjgl.util.vector.Vector4f; -public class GuiFluidSelection extends GuiScreenCanvas implements IPEventListener, IVolatileScreen -{ - private final ICallback callback; - private FluidStack itemStack; - - private PanelTextField fieldSize; - private PanelFluidSlot itemPreview; - - public GuiFluidSelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) - { - this(parent, JsonHelper.JsonToFluidStack(tag), callback); - } - - public GuiFluidSelection(GuiScreen parent, FluidStack stack, ICallback callback) +public class GuiFluidSelection extends GuiScreenCanvas implements IPEventListener, IVolatileScreen { + private final ICallback callback; + private FluidStack itemStack; + + private PanelTextField fieldSize; + private PanelFluidSlot itemPreview; + + public GuiFluidSelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) { + this(parent, JsonHelper.JsonToFluidStack(tag), callback); + } + + public GuiFluidSelection(GuiScreen parent, FluidStack stack, ICallback callback) { + super(parent); + this.callback = callback; + this.itemStack = stack; + } + + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.done"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + "betterquesting.title.select_fluid")).setAlignment(1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + // === RIGHT PANEL === + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); + cvBackground.addPanel(cvRight); + + CanvasFluidDatabase cvDatabase = + new CanvasFluidDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0), 1); + cvRight.addPanel(cvDatabase); + + PanelTextField searchBox = + new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 8, -16), 0), "", + FieldFilterString.INSTANCE); + searchBox.setCallback(cvDatabase::setSearchFilter).setWatermark("Search..."); + cvRight.addPanel(searchBox); + + PanelVScrollBar scEdit = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); + cvDatabase.setScrollDriverY(scEdit); + cvRight.addPanel(scEdit); + + // === TOP LEFT PANEL === + + CanvasEmpty cvTopLeft = + new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.4F), new GuiPadding(16, 32, 8, 8), 0)); + cvBackground.addPanel(cvTopLeft); + + PanelTextBox txSelection = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("betterquesting.gui.selection")); + txSelection.setColor(PresetColor.TEXT_MAIN.getColor()); + cvTopLeft.addPanel(txSelection); + + itemPreview = new PanelFluidSlot(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 36, 36, 0), 99, itemStack); + cvTopLeft.addPanel(itemPreview); + + PanelTextBox txMulti = + new PanelTextBox(new GuiTransform(GuiAlign.TOP_LEFT, 36, 20, 16, 12, 0), "x").setAlignment(1); + txMulti.setColor(PresetColor.TEXT_MAIN.getColor()); + cvTopLeft.addPanel(txMulti); + + fieldSize = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 16, 0, -32), 0), + itemStack == null ? "1" : ("" + itemStack.amount), FieldFilterNumber.INT); + cvTopLeft.addPanel(fieldSize); + fieldSize.setCallback(value -> { if (itemStack != null) { itemStack.amount = value; } }); + + // === BOTTOM LEFT PANEL === + + CanvasEmpty cvBottomLeft = + new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0.4F, 0.5F, 1F), new GuiPadding(16, 8, 8, 32), 0)); + cvBackground.addPanel(cvBottomLeft); + + PanelTextBox txInvo = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("container.inventory")); + txInvo.setColor(PresetColor.TEXT_MAIN.getColor()); + cvBottomLeft.addPanel(txInvo); + + IInventory inventory = mc.player.inventory; + + float iScale = + Math.min(cvBottomLeft.getTransform().getWidth() / 162F, (cvBottomLeft.getTransform().getHeight() - 20) / 72F); + int slotSize = (int) Math.floor(18 * iScale); + + for (int i = 0; i < 27; i++) // Main inventory { - super(parent); - this.callback = callback; - this.itemStack = stack; + int x = (i % 9) * slotSize; + int y = (i / 9) * slotSize + 16; + + ItemStack tmp = inventory.getStackInSlot(i + 9); + BigItemStack invoStack = tmp.isEmpty() ? null : new BigItemStack(tmp); + + cvBottomLeft.addPanel( + new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, y, slotSize, slotSize, 0), 2, invoStack, true)); + } - - public void initPanel() + + for (int i = 0; i < 9; i++) // Hotbar { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.select_fluid")).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - // === RIGHT PANEL === - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); - cvBackground.addPanel(cvRight); - - CanvasFluidDatabase cvDatabase = new CanvasFluidDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0), 1); - cvRight.addPanel(cvDatabase); - - PanelTextField searchBox = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 8, -16), 0), "", FieldFilterString.INSTANCE); - searchBox.setCallback(cvDatabase::setSearchFilter).setWatermark("Search..."); - cvRight.addPanel(searchBox); - - PanelVScrollBar scEdit = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); - cvDatabase.setScrollDriverY(scEdit); - cvRight.addPanel(scEdit); - - // === TOP LEFT PANEL === - - CanvasEmpty cvTopLeft = new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.4F), new GuiPadding(16, 32, 8, 8), 0)); - cvBackground.addPanel(cvTopLeft); - - PanelTextBox txSelection = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.selection")); - txSelection.setColor(PresetColor.TEXT_MAIN.getColor()); - cvTopLeft.addPanel(txSelection); - - itemPreview = new PanelFluidSlot(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 36, 36, 0), 99, itemStack); - cvTopLeft.addPanel(itemPreview); - - PanelTextBox txMulti = new PanelTextBox(new GuiTransform(GuiAlign.TOP_LEFT, 36, 20, 16, 12, 0), "x").setAlignment(1); - txMulti.setColor(PresetColor.TEXT_MAIN.getColor()); - cvTopLeft.addPanel(txMulti); - - fieldSize = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 16, 0, -32), 0), itemStack == null ? "1" : ("" + itemStack.amount), FieldFilterNumber.INT); - cvTopLeft.addPanel(fieldSize); - fieldSize.setCallback(value -> { if(itemStack != null) itemStack.amount = value; }); - - // === BOTTOM LEFT PANEL === - - CanvasEmpty cvBottomLeft = new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0.4F, 0.5F, 1F), new GuiPadding(16, 8, 8, 32), 0)); - cvBackground.addPanel(cvBottomLeft); - - PanelTextBox txInvo = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("container.inventory")); - txInvo.setColor(PresetColor.TEXT_MAIN.getColor()); - cvBottomLeft.addPanel(txInvo); - - IInventory inventory = mc.player.inventory; - - float iScale = Math.min(cvBottomLeft.getTransform().getWidth() / 162F, (cvBottomLeft.getTransform().getHeight() - 20) / 72F); - int slotSize = (int)Math.floor(18 * iScale); - - for(int i = 0; i < 27; i++) // Main inventory - { - int x = (i % 9) * slotSize; - int y = (i / 9) * slotSize + 16; - - ItemStack tmp = inventory.getStackInSlot(i + 9); - BigItemStack invoStack = tmp.isEmpty() ? null : new BigItemStack(tmp); - - cvBottomLeft.addPanel(new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, y, slotSize, slotSize, 0), 2, invoStack, true)); - - } - - for(int i = 0; i < 9; i++) // Hotbar - { - int x = (i % 9) * slotSize; - - ItemStack tmp = inventory.getStackInSlot(i); - BigItemStack invoStack = tmp.isEmpty() ? null : new BigItemStack(tmp); - - cvBottomLeft.addPanel(new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, 20 + (3 * slotSize), slotSize, slotSize, 0), 2, invoStack, true)); - } - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); + int x = (i % 9) * slotSize; + + ItemStack tmp = inventory.getStackInSlot(i); + BigItemStack invoStack = tmp.isEmpty() ? null : new BigItemStack(tmp); + + cvBottomLeft.addPanel( + new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, 20 + (3 * slotSize), slotSize, slotSize, 0), 2, + invoStack, true)); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - if(callback != null) - { - callback.setValue(itemStack); - } - - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) - { - FluidStack fluid = ((PanelButtonStorage)btn).getStoredValue(); - - if(fluid != null) - { - itemStack = fluid.copy(); - itemPreview.setStoredValue(itemStack); - fieldSize.setText("" + itemStack.amount); - } - } else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) - { - BigItemStack tmp = ((PanelButtonStorage)btn).getStoredValue(); - FluidStack fluid = tmp == null ? null : FluidUtil.getFluidContained(tmp.getBaseStack()); - - if(fluid != null) - { - itemStack = fluid.copy(); - itemPreview.setStoredValue(itemStack); - fieldSize.setText("" + itemStack.amount); - } - } + if (callback != null) { + callback.setValue(itemStack); + } + + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { + FluidStack fluid = ((PanelButtonStorage) btn).getStoredValue(); + + if (fluid != null) { + itemStack = fluid.copy(); + itemPreview.setStoredValue(itemStack); + fieldSize.setText("" + itemStack.amount); + } + } else if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) { + BigItemStack tmp = ((PanelButtonStorage) btn).getStoredValue(); + FluidStack fluid = tmp == null ? null : FluidUtil.getFluidContained(tmp.getBaseStack()); + + if (fluid != null) { + itemStack = fluid.copy(); + itemPreview.setStoredValue(itemStack); + fieldSize.setText("" + itemStack.amount); + } } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java index 5171049ae..4c77d8adf 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java @@ -40,206 +40,211 @@ import org.lwjgl.util.vector.Vector4f; @SuppressWarnings("WeakerAccess") -public class GuiItemSelection extends GuiScreenCanvas implements IPEventListener, IVolatileScreen -{ - private final ICallback callback; - private BigItemStack itemStack; - - private PanelTextField fieldSize; - private PanelItemSlot itemPreview; - private PanelButtonStorage btnOre; - - public GuiItemSelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) - { - this(parent, JsonHelper.JsonToItemStack(tag), callback); +public class GuiItemSelection extends GuiScreenCanvas implements IPEventListener, IVolatileScreen { + private final ICallback callback; + private BigItemStack itemStack; + + private PanelTextField fieldSize; + private PanelItemSlot itemPreview; + private PanelButtonStorage btnOre; + + public GuiItemSelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) { + this(parent, JsonHelper.JsonToItemStack(tag), callback); + } + + public GuiItemSelection(GuiScreen parent, BigItemStack stack, ICallback callback) { + super(parent); + this.callback = callback; + this.itemStack = stack; + } + + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.done"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + "betterquesting.title.select_item")).setAlignment(1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + // === RIGHT PANEL === + + CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); + cvBackground.addPanel(cvRight); + + CanvasItemDatabase cvDatabase = + new CanvasItemDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0), 1); + cvRight.addPanel(cvDatabase); + + PanelTextField searchBox = + new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 8, -16), 0), "", + FieldFilterString.INSTANCE); + searchBox.setCallback(cvDatabase::setSearchFilter).setWatermark("Search..."); + cvRight.addPanel(searchBox); + + PanelVScrollBar scEdit = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); + cvDatabase.setScrollDriverY(scEdit); + cvRight.addPanel(scEdit); + + // === TOP LEFT PANEL === + + CanvasEmpty cvTopLeft = + new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.4F), new GuiPadding(16, 32, 8, 8), 0)); + cvBackground.addPanel(cvTopLeft); + + PanelTextBox txSelection = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("betterquesting.gui.selection")); + txSelection.setColor(PresetColor.TEXT_MAIN.getColor()); + cvTopLeft.addPanel(txSelection); + + itemPreview = new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 36, 36, 0), 99, itemStack, false, true); + cvTopLeft.addPanel(itemPreview); + + PanelTextBox txMulti = + new PanelTextBox(new GuiTransform(GuiAlign.TOP_LEFT, 36, 20, 16, 12, 0), "x").setAlignment(1); + txMulti.setColor(PresetColor.TEXT_MAIN.getColor()); + cvTopLeft.addPanel(txMulti); + + fieldSize = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 16, 0, -32), 0), + itemStack == null ? "1" : ("" + itemStack.stackSize), FieldFilterNumber.INT); + cvTopLeft.addPanel(fieldSize); + fieldSize.setCallback(value -> { if (itemStack != null) { itemStack.stackSize = value; } }); + + String oreName = "NONE"; + int oreIdx = -1; + if (itemStack != null && !itemStack.getBaseStack().isEmpty() && + !StringUtils.isNullOrEmpty(itemStack.getOreDict())) { + oreName = itemStack.getOreDict(); + int[] oreIds = OreDictionary.getOreIDs(itemStack.getBaseStack()); + for (int i = 0; i < oreIds.length; i++) { + if (OreDictionary.getOreName(oreIds[i]).equalsIgnoreCase(oreName)) { + oreIdx = i; + break; + } + } } - - public GuiItemSelection(GuiScreen parent, BigItemStack stack, ICallback callback) + + btnOre = new PanelButtonStorage<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 36, 24, -52), 0), 2, + "OreDict: " + oreName, oreIdx); + cvTopLeft.addPanel(btnOre); + + PanelButton btnWild = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -16, 36, 16, 16, 0), 3, "*"); + btnWild.setClickAction((b) -> { + if (itemStack != null) { + itemStack.getBaseStack().setItemDamage(OreDictionary.WILDCARD_VALUE); + itemPreview.setStoredValue(itemStack); + } + }); + cvTopLeft.addPanel(btnWild); + + // === BOTTOM LEFT PANEL === + + CanvasEmpty cvBottomLeft = + new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0.4F, 0.5F, 1F), new GuiPadding(16, 8, 8, 32), 0)); + cvBackground.addPanel(cvBottomLeft); + + PanelTextBox txInvo = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate("container.inventory")); + txInvo.setColor(PresetColor.TEXT_MAIN.getColor()); + cvBottomLeft.addPanel(txInvo); + + IInventory inventory = mc.player.inventory; + + float iScale = + Math.min(cvBottomLeft.getTransform().getWidth() / 162F, (cvBottomLeft.getTransform().getHeight() - 20) / 72F); + int slotSize = (int) Math.floor(18 * iScale); + + BigItemStack bigEmpty = new BigItemStack(ItemStack.EMPTY); + for (int i = 0; i < 27; i++) // Main inventory { - super(parent); - this.callback = callback; - this.itemStack = stack; + int x = (i % 9) * slotSize; + int y = (i / 9) * slotSize + 16; + + ItemStack tmp = inventory.getStackInSlot(i + 9); + BigItemStack invoStack = tmp.isEmpty() ? bigEmpty : new BigItemStack(tmp); + + cvBottomLeft.addPanel( + new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, y, slotSize, slotSize, 0), 1, invoStack, true)); + } - - public void initPanel() + + for (int i = 0; i < 9; i++) // Hotbar { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.select_item")).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - // === RIGHT PANEL === - - CanvasEmpty cvRight = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); - cvBackground.addPanel(cvRight); - - CanvasItemDatabase cvDatabase = new CanvasItemDatabase(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0), 1); - cvRight.addPanel(cvDatabase); - - PanelTextField searchBox = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 8, -16), 0), "", FieldFilterString.INSTANCE); - searchBox.setCallback(cvDatabase::setSearchFilter).setWatermark("Search..."); - cvRight.addPanel(searchBox); - - PanelVScrollBar scEdit = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); - cvDatabase.setScrollDriverY(scEdit); - cvRight.addPanel(scEdit); - - // === TOP LEFT PANEL === - - CanvasEmpty cvTopLeft = new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.4F), new GuiPadding(16, 32, 8, 8), 0)); - cvBackground.addPanel(cvTopLeft); - - PanelTextBox txSelection = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.selection")); - txSelection.setColor(PresetColor.TEXT_MAIN.getColor()); - cvTopLeft.addPanel(txSelection); - - itemPreview = new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 36, 36, 0), 99, itemStack, false, true); - cvTopLeft.addPanel(itemPreview); - - PanelTextBox txMulti = new PanelTextBox(new GuiTransform(GuiAlign.TOP_LEFT, 36, 20, 16, 12, 0), "x").setAlignment(1); - txMulti.setColor(PresetColor.TEXT_MAIN.getColor()); - cvTopLeft.addPanel(txMulti); - - fieldSize = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 16, 0, -32), 0), itemStack == null ? "1" : ("" + itemStack.stackSize), FieldFilterNumber.INT); - cvTopLeft.addPanel(fieldSize); - fieldSize.setCallback(value -> { if(itemStack != null) itemStack.stackSize = value; }); - - String oreName = "NONE"; - int oreIdx = -1; - if(itemStack != null && !itemStack.getBaseStack().isEmpty() && !StringUtils.isNullOrEmpty(itemStack.getOreDict())) - { - oreName = itemStack.getOreDict(); - int[] oreIds = OreDictionary.getOreIDs(itemStack.getBaseStack()); - for(int i = 0; i < oreIds.length; i++) - { - if(OreDictionary.getOreName(oreIds[i]).equalsIgnoreCase(oreName)) - { - oreIdx = i; - break; - } - } - } - - btnOre = new PanelButtonStorage<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 36, 24, -52), 0), 2, "OreDict: " + oreName, oreIdx); - cvTopLeft.addPanel(btnOre); - - PanelButton btnWild = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -16, 36, 16, 16, 0), 3, "*"); - btnWild.setClickAction((b) -> { - if(itemStack != null) - { - itemStack.getBaseStack().setItemDamage(OreDictionary.WILDCARD_VALUE); - itemPreview.setStoredValue(itemStack); - } - }); - cvTopLeft.addPanel(btnWild); - - // === BOTTOM LEFT PANEL === - - CanvasEmpty cvBottomLeft = new CanvasEmpty(new GuiTransform(new Vector4f(0F, 0.4F, 0.5F, 1F), new GuiPadding(16, 8, 8, 32), 0)); - cvBackground.addPanel(cvBottomLeft); - - PanelTextBox txInvo = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("container.inventory")); - txInvo.setColor(PresetColor.TEXT_MAIN.getColor()); - cvBottomLeft.addPanel(txInvo); - - IInventory inventory = mc.player.inventory; - - float iScale = Math.min(cvBottomLeft.getTransform().getWidth() / 162F, (cvBottomLeft.getTransform().getHeight() - 20) / 72F); - int slotSize = (int)Math.floor(18 * iScale); - - BigItemStack bigEmpty = new BigItemStack(ItemStack.EMPTY); - for(int i = 0; i < 27; i++) // Main inventory - { - int x = (i % 9) * slotSize; - int y = (i / 9) * slotSize + 16; - - ItemStack tmp = inventory.getStackInSlot(i + 9); - BigItemStack invoStack = tmp.isEmpty() ? bigEmpty : new BigItemStack(tmp); - - cvBottomLeft.addPanel(new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, y, slotSize, slotSize, 0), 1, invoStack, true)); - - } - - for(int i = 0; i < 9; i++) // Hotbar - { - int x = (i % 9) * slotSize; - - ItemStack tmp = inventory.getStackInSlot(i); - BigItemStack invoStack = tmp.isEmpty() ? bigEmpty : new BigItemStack(tmp); - - cvBottomLeft.addPanel(new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, 20 + (3 * slotSize), slotSize, slotSize, 0), 1, invoStack, true)); - } - - // === DIVIDERS === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); + int x = (i % 9) * slotSize; + + ItemStack tmp = inventory.getStackInSlot(i); + BigItemStack invoStack = tmp.isEmpty() ? bigEmpty : new BigItemStack(tmp); + + cvBottomLeft.addPanel( + new PanelItemSlot(new GuiTransform(GuiAlign.TOP_LEFT, x, 20 + (3 * slotSize), slotSize, slotSize, 0), 1, + invoStack, true)); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + // === DIVIDERS === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - if(callback != null) - { - callback.setValue(itemStack); - } - - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) - { - BigItemStack tmp = ((PanelButtonStorage)btn).getStoredValue(); - - if(tmp != null) - { - itemStack = tmp.copy(); - itemPreview.setStoredValue(itemStack); - btnOre.setStoredValue(-1).setText("Ore: NONE"); - fieldSize.setText("" + itemStack.stackSize); - } - } else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage && itemStack != null && !itemStack.getBaseStack().isEmpty()) - { - int[] oreIds = OreDictionary.getOreIDs(itemStack.getBaseStack()); - int idx = ((PanelButtonStorage)btn).getStoredValue(); - idx++; - - if(idx >= oreIds.length || idx < 0) - { - itemStack.setOreDict(""); - ((PanelButtonStorage)btn).setStoredValue(-1).setText("Ore: NONE"); - itemPreview.setStoredValue(itemStack); // Refreshes OD - } else - { - itemStack.setOreDict(OreDictionary.getOreName(oreIds[idx])); - ((PanelButtonStorage)btn).setStoredValue(idx).setText("Ore: " + itemStack.getOreDict()); - itemPreview.setStoredValue(itemStack); // Refreshes OD - } - } + if (callback != null) { + callback.setValue(itemStack); + } + + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { + BigItemStack tmp = ((PanelButtonStorage) btn).getStoredValue(); + + if (tmp != null) { + itemStack = tmp.copy(); + itemPreview.setStoredValue(itemStack); + btnOre.setStoredValue(-1).setText("Ore: NONE"); + fieldSize.setText("" + itemStack.stackSize); + } + } else if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage && itemStack != null && + !itemStack.getBaseStack().isEmpty()) { + int[] oreIds = OreDictionary.getOreIDs(itemStack.getBaseStack()); + int idx = ((PanelButtonStorage) btn).getStoredValue(); + idx++; + + if (idx >= oreIds.length || idx < 0) { + itemStack.setOreDict(""); + ((PanelButtonStorage) btn).setStoredValue(-1).setText("Ore: NONE"); + itemPreview.setStoredValue(itemStack); // Refreshes OD + } else { + itemStack.setOreDict(OreDictionary.getOreName(oreIds[idx])); + ((PanelButtonStorage) btn).setStoredValue(idx).setText("Ore: " + itemStack.getOreDict()); + itemPreview.setStoredValue(itemStack); // Refreshes OD + } } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java index f7cee694e..aa80ddceb 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java @@ -36,194 +36,200 @@ import java.util.ArrayList; import java.util.List; -public class GuiNbtAdd extends GuiScreenCanvas implements IPEventListener, IVolatileScreen -{ - private final NBTBase nbt; - private final int index; - - private PanelTextField flKey; - private final List> options = new ArrayList<>(); - private NBTBase selected = null; - private PanelButton btnConfirm; - //private PanelTextBox txtKey; - - public GuiNbtAdd(GuiScreen parent, NBTTagCompound compoundTag) - { - super(parent); - this.nbt = compoundTag; - this.index = -1; - } - - public GuiNbtAdd(GuiScreen parent, NBTTagList list, int index) - { - super(parent); - this.nbt = list; - this.index = index; - } - - @Override - public void initPanel() +public class GuiNbtAdd extends GuiScreenCanvas implements IPEventListener, IVolatileScreen { + private final NBTBase nbt; + private final int index; + + private PanelTextField flKey; + private final List> options = new ArrayList<>(); + private NBTBase selected = null; + private PanelButton btnConfirm; + //private PanelTextBox txtKey; + + public GuiNbtAdd(GuiScreen parent, NBTTagCompound compoundTag) { + super(parent); + this.nbt = compoundTag; + this.index = -1; + } + + public GuiNbtAdd(GuiScreen parent, NBTTagList list, int index) { + super(parent); + this.nbt = list; + this.index = index; + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 100, 16, 0), 0, + QuestTranslation.translate("gui.cancel"))); + + btnConfirm = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -16, 100, 16, 0), 1, + QuestTranslation.translate("gui.done")); + cvBackground.addPanel(btnConfirm); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.json_add")).setAlignment(1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + if (nbt.getId() == 10) // NBTTagCompound { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 100, 16, 0), 0, QuestTranslation.translate("gui.cancel"))); - - btnConfirm = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -16, 100, 16, 0), 1, QuestTranslation.translate("gui.done")); - cvBackground.addPanel(btnConfirm); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.json_add")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - if(nbt.getId() == 10) // NBTTagCompound - { - btnConfirm.setActive(false); - - PanelTextBox txKeyTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_CENTER, -100, 36, 200, 12, 0), TextFormatting.RED + QuestTranslation.translate("betterquesting.gui.no_key")); - txKeyTitle.setColor(PresetColor.TEXT_MAIN.getColor()); - cvBackground.addPanel(txKeyTitle); - - flKey = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_CENTER, -100, 48, 200, 16, 0), "", FieldFilterString.INSTANCE); - cvBackground.addPanel(flKey); - - flKey.setCallback(value -> { - if(value.isEmpty()) - { - txKeyTitle.setText(TextFormatting.RED + QuestTranslation.translate("betterquesting.gui.no_key")); - } else if(((NBTTagCompound)nbt).hasKey(value)) - { - txKeyTitle.setText(TextFormatting.RED + QuestTranslation.translate("betterquesting.gui.duplicate_key")); - } else - { - txKeyTitle.setText(QuestTranslation.translate("betterquesting.gui.key")); - } - - updateConfirm(); - }); - } - - options.clear(); - - int n = 0; - - // Standard Objects - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n * 16, 100, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.item"), JsonHelper.ItemStackToJson(new BigItemStack(Blocks.STONE), new NBTTagCompound()))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 100, n++ * 16, 92, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.fluid"), JsonHelper.FluidStackToJson(new FluidStack(FluidRegistry.WATER, 1000), new NBTTagCompound()))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.entity"), JsonHelper.EntityToJson(new EntityPig(mc.world), new NBTTagCompound()))); - - // NBT types - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagString.class.getSimpleName(), new NBTTagString(""))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagCompound.class.getSimpleName(), new NBTTagCompound())); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagList.class.getSimpleName(), new NBTTagList())); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagByte.class.getSimpleName(), new NBTTagByte((byte)0))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagShort.class.getSimpleName(), new NBTTagShort((short)0))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagInt.class.getSimpleName(), new NBTTagInt(0))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagLong.class.getSimpleName(), new NBTTagLong(0L))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagFloat.class.getSimpleName(), new NBTTagFloat(0F))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagDouble.class.getSimpleName(), new NBTTagDouble(0D))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagByteArray.class.getSimpleName(), new NBTTagByteArray(new byte[0]))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, NBTTagIntArray.class.getSimpleName(), new NBTTagIntArray(new int[0]))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n * 16, 192, 16, 0), 2, NBTTagLongArray.class.getSimpleName(), new NBTTagLongArray(new long[0]))); - - CanvasScrolling cvOptions = new CanvasScrolling(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-100, 64, -92, 32), 0)); - cvBackground.addPanel(cvOptions); - - for(PanelButtonStorage btn : options) - { - cvOptions.addPanel(btn); + btnConfirm.setActive(false); + + PanelTextBox txKeyTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_CENTER, -100, 36, 200, 12, 0), + TextFormatting.RED + + QuestTranslation.translate("betterquesting.gui.no_key")); + txKeyTitle.setColor(PresetColor.TEXT_MAIN.getColor()); + cvBackground.addPanel(txKeyTitle); + + flKey = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_CENTER, -100, 48, 200, 16, 0), "", + FieldFilterString.INSTANCE); + cvBackground.addPanel(flKey); + + flKey.setCallback(value -> { + if (value.isEmpty()) { + txKeyTitle.setText(TextFormatting.RED + QuestTranslation.translate("betterquesting.gui.no_key")); + } else if (((NBTTagCompound) nbt).hasKey(value)) { + txKeyTitle.setText(TextFormatting.RED + QuestTranslation.translate("betterquesting.gui.duplicate_key")); + } else { + txKeyTitle.setText(QuestTranslation.translate("betterquesting.gui.key")); } - - PanelVScrollBar scOptions = new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(92, 64, -100, 32), 0)); - cvBackground.addPanel(scOptions); - cvOptions.setScrollDriverY(scOptions); + + updateConfirm(); + }); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + options.clear(); + + int n = 0; + + // Standard Objects + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, 0, 100, 16, 0), 2, + QuestTranslation.translate("betterquesting.btn.item"), + JsonHelper.ItemStackToJson(new BigItemStack(Blocks.STONE), + new NBTTagCompound()))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 100, 0, 92, 16, 0), 2, + QuestTranslation.translate("betterquesting.btn.fluid"), + JsonHelper.FluidStackToJson(new FluidStack(FluidRegistry.WATER, 1000), + new NBTTagCompound()))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + QuestTranslation.translate("betterquesting.btn.entity"), + JsonHelper.EntityToJson(new EntityPig(mc.world), new NBTTagCompound()))); + + // NBT types + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagString.class.getSimpleName(), new NBTTagString(""))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagCompound.class.getSimpleName(), new NBTTagCompound())); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagList.class.getSimpleName(), new NBTTagList())); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagByte.class.getSimpleName(), new NBTTagByte((byte) 0))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagShort.class.getSimpleName(), new NBTTagShort((short) 0))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagInt.class.getSimpleName(), new NBTTagInt(0))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagLong.class.getSimpleName(), new NBTTagLong(0L))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagFloat.class.getSimpleName(), new NBTTagFloat(0F))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagDouble.class.getSimpleName(), new NBTTagDouble(0D))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagByteArray.class.getSimpleName(), new NBTTagByteArray(new byte[0]))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n++ * 16, 192, 16, 0), 2, + NBTTagIntArray.class.getSimpleName(), new NBTTagIntArray(new int[0]))); + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 0, n * 16, 192, 16, 0), 2, + NBTTagLongArray.class.getSimpleName(), new NBTTagLongArray(new long[0]))); + + CanvasScrolling cvOptions = + new CanvasScrolling(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(-100, 64, -92, 32), 0)); + cvBackground.addPanel(cvOptions); + + for (PanelButtonStorage btn : options) { + cvOptions.addPanel(btn); } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - switch(btn.getButtonID()) - { - case 0: // Cancel - { - mc.displayGuiScreen(this.parent); - break; - } - case 1: // Confirm - { - if(selected == null) - { - return; - } else if(nbt.getId() == 10) - { - ((NBTTagCompound)nbt).setTag(flKey.getValue(), selected); - } else if(nbt.getId() == 9) - { - NBTTagList l = (NBTTagList)nbt; - - if(index == l.tagCount()) - { - l.appendTag(selected); - } else - { - // Shift entries up manually - for(int n = l.tagCount() - 1; n >= index; n--) - { - l.set(n + 1, l.get(n)); - } - - l.set(index, selected); - } - } - - mc.displayGuiScreen(this.parent); - break; - } - case 2: // Select this - { - selected = ((PanelButtonStorage)btn).getStoredValue(); - - for(PanelButtonStorage b : options) - { - b.setActive(true); - } - - btn.setActive(false); - - updateConfirm(); - break; + + PanelVScrollBar scOptions = + new PanelVScrollBar(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 1F), new GuiPadding(92, 64, -100, 32), 0)); + cvBackground.addPanel(scOptions); + cvOptions.setScrollDriverY(scOptions); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); + } + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + switch (btn.getButtonID()) { + case 0: // Cancel + { + mc.displayGuiScreen(this.parent); + break; + } + case 1: // Confirm + { + if (selected == null) { + return; + } else if (nbt.getId() == 10) { + ((NBTTagCompound) nbt).setTag(flKey.getValue(), selected); + } else if (nbt.getId() == 9) { + NBTTagList l = (NBTTagList) nbt; + + if (index == l.tagCount()) { + l.appendTag(selected); + } else { + // Shift entries up manually + for (int n = l.tagCount() - 1; n >= index; n--) { + l.set(n + 1, l.get(n)); } + + l.set(index, selected); + } } - } - - private void updateConfirm() - { - if(flKey == null) - { - btnConfirm.setActive(selected != null); - } else if(flKey.getValue().isEmpty() || ((NBTTagCompound)nbt).hasKey(flKey.getValue())) - { - btnConfirm.setActive(false); - } else - { - btnConfirm.setActive(selected != null); + + mc.displayGuiScreen(this.parent); + break; + } + case 2: // Select this + { + selected = ((PanelButtonStorage) btn).getStoredValue(); + + for (PanelButtonStorage b : options) { + b.setActive(true); } + + btn.setActive(false); + + updateConfirm(); + break; + } + } + } + + private void updateConfirm() { + if (flKey == null) { + btnConfirm.setActive(selected != null); + } else if (flKey.getValue().isEmpty() || ((NBTTagCompound) nbt).hasKey(flKey.getValue())) { + btnConfirm.setActive(false); + } else { + btnConfirm.setActive(selected != null); } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java index dbfb98fd3..94ae4726e 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java @@ -27,102 +27,101 @@ import net.minecraft.nbt.NBTTagList; import org.lwjgl.input.Keyboard; -public class GuiNbtEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen -{ - private final NBTBase nbt; - private final ICallback comCallback; - private final ICallback lstCallback; - - public GuiNbtEditor(GuiScreen parent, NBTTagCompound tag, ICallback callback) - { - super(parent); - - this.nbt = tag; - this.comCallback = callback; - this.lstCallback = null; - } - - public GuiNbtEditor(GuiScreen parent, NBTTagList tag, ICallback callback) - { - super(parent); - - this.nbt = tag; - this.comCallback = null; - this.lstCallback = callback; - } - - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate(nbt.getId() == 9 ? "betterquesting.title.json_array" : "betterquesting.title.json_object")).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - PanelScrollingNBT pnEdit; - if(nbt.getId() == 10) - { - pnEdit = new PanelScrollingNBT(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 32, 24, 32), 0), (NBTTagCompound)nbt, 1, 2, 3, 4); - } else - { - pnEdit = new PanelScrollingNBT(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 32, 24, 32), 0), (NBTTagList)nbt, 1, 2, 3, 4); - } - cvBackground.addPanel(pnEdit); - - PanelVScrollBar scEdit = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 32, 16, 32), 0)); - cvBackground.addPanel(scEdit); - pnEdit.setScrollDriverY(scEdit); - - // === DECORATIVE LINES === - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_LEFT, 16, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.TOP_RIGHT, -16, 32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), -1); - cvBackground.addPanel(paLine0); - - IGuiRect ls1 = new GuiTransform(GuiAlign.BOTTOM_LEFT, 16, -32, 0, 0, 0); - ls1.setParent(cvBackground.getTransform()); - IGuiRect le1 = new GuiTransform(GuiAlign.BOTTOM_RIGHT, -16, -32, 0, 0, 0); - le1.setParent(cvBackground.getTransform()); - PanelLine paLine1 = new PanelLine(ls1, le1, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), -1); - cvBackground.addPanel(paLine1); +public class GuiNbtEditor extends GuiScreenCanvas implements IPEventListener, IVolatileScreen { + private final NBTBase nbt; + private final ICallback comCallback; + private final ICallback lstCallback; + + public GuiNbtEditor(GuiScreen parent, NBTTagCompound tag, ICallback callback) { + super(parent); + + this.nbt = tag; + this.comCallback = callback; + this.lstCallback = null; + } + + public GuiNbtEditor(GuiScreen parent, NBTTagList tag, ICallback callback) { + super(parent); + + this.nbt = tag; + this.comCallback = null; + this.lstCallback = callback; + } + + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + nbt.getId() == 9 ? "betterquesting.title.json_array" + : "betterquesting.title.json_object")).setAlignment(1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + PanelScrollingNBT pnEdit; + if (nbt.getId() == 10) { + pnEdit = new PanelScrollingNBT(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 32, 24, 32), 0), + (NBTTagCompound) nbt, 1, 2, 3, 4); + } else { + pnEdit = new PanelScrollingNBT(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 32, 24, 32), 0), + (NBTTagList) nbt, 1, 2, 3, 4); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + cvBackground.addPanel(pnEdit); + + PanelVScrollBar scEdit = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-24, 32, 16, 32), 0)); + cvBackground.addPanel(scEdit); + pnEdit.setScrollDriverY(scEdit); + + // === DECORATIVE LINES === + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_LEFT, 16, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.TOP_RIGHT, -16, 32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), -1); + cvBackground.addPanel(paLine0); + + IGuiRect ls1 = new GuiTransform(GuiAlign.BOTTOM_LEFT, 16, -32, 0, 0, 0); + ls1.setParent(cvBackground.getTransform()); + IGuiRect le1 = new GuiTransform(GuiAlign.BOTTOM_RIGHT, -16, -32, 0, 0, 0); + le1.setParent(cvBackground.getTransform()); + PanelLine paLine1 = + new PanelLine(ls1, le1, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), -1); + cvBackground.addPanel(paLine1); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void onButtonPress(PEventButton event) + } + + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - - if(nbt.getId() == 10 && comCallback != null) - { - comCallback.setValue((NBTTagCompound)nbt); - } else if(nbt.getId() == 9 && lstCallback != null) - { - lstCallback.setValue((NBTTagList)nbt); - } - } + mc.displayGuiScreen(this.parent); + + if (nbt.getId() == 10 && comCallback != null) { + comCallback.setValue((NBTTagCompound) nbt); + } else if (nbt.getId() == 9 && lstCallback != null) { + lstCallback.setValue((NBTTagList) nbt); + } } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java index fde202418..bc9e98e32 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java @@ -22,79 +22,80 @@ import net.minecraft.client.gui.GuiScreen; import net.minecraft.nbt.NBTTagCompound; -public class GuiNbtType extends GuiScreenCanvas implements IPEventListener, IVolatileScreen -{ - private final NBTTagCompound tagCompound; - - public GuiNbtType(GuiScreen parent, NBTTagCompound tagCompound) - { - super(parent); - this.tagCompound = tagCompound; - } - - @Override - public void initPanel() - { - super.initPanel(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.json_object")).setAlignment(1); - panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(panTxt); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, -32, 200, 16, 0), 1, QuestTranslation.translate("betterquesting.btn.raw_nbt"))); - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, -16, 200, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.item"))); - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 0, 200, 16, 0), 3, QuestTranslation.translate("betterquesting.btn.fluid"))); - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 16, 200, 16, 0), 4, QuestTranslation.translate("betterquesting.btn.entity"))); - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } +public class GuiNbtType extends GuiScreenCanvas implements IPEventListener, IVolatileScreen { + private final NBTTagCompound tagCompound; + + public GuiNbtType(GuiScreen parent, NBTTagCompound tagCompound) { + super(parent); + this.tagCompound = tagCompound; + } + + @Override + public void initPanel() { + super.initPanel(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.json_object")).setAlignment( + 1); + panTxt.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(panTxt); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, -32, 200, 16, 0), 1, + QuestTranslation.translate("betterquesting.btn.raw_nbt"))); + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, -16, 200, 16, 0), 2, + QuestTranslation.translate("betterquesting.btn.item"))); + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 0, 200, 16, 0), 3, + QuestTranslation.translate("betterquesting.btn.fluid"))); + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, -100, 16, 200, 16, 0), 4, + QuestTranslation.translate("betterquesting.btn.entity"))); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - private void onButtonPress(PEventButton event) - { - IPanelButton btn = event.getButton(); - - switch(btn.getButtonID()) - { - case 0: // Back - { - mc.displayGuiScreen(this.parent); - break; - } - case 1: // Raw NBT - { - mc.displayGuiScreen(new GuiNbtEditor(this.parent, tagCompound, null)); - break; - } - case 2: // Item - { - mc.displayGuiScreen(new GuiItemSelection(this.parent, tagCompound, new NbtItemCallback(tagCompound))); - break; - } - case 3: // Fluid - { - mc.displayGuiScreen(new GuiFluidSelection(this.parent, tagCompound, new NbtFluidCallback(tagCompound))); - break; - } - case 4: // Entity - { - mc.displayGuiScreen(new GuiEntitySelection(this.parent, tagCompound, new NbtEntityCallback(tagCompound))); - break; - } - } + } + + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + switch (btn.getButtonID()) { + case 0: // Back + { + mc.displayGuiScreen(this.parent); + break; + } + case 1: // Raw NBT + { + mc.displayGuiScreen(new GuiNbtEditor(this.parent, tagCompound, null)); + break; + } + case 2: // Item + { + mc.displayGuiScreen(new GuiItemSelection(this.parent, tagCompound, new NbtItemCallback(tagCompound))); + break; + } + case 3: // Fluid + { + mc.displayGuiScreen(new GuiFluidSelection(this.parent, tagCompound, new NbtFluidCallback(tagCompound))); + break; + } + case 4: // Entity + { + mc.displayGuiScreen(new GuiEntitySelection(this.parent, tagCompound, new NbtEntityCallback(tagCompound))); + break; + } } + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java b/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java index 887889c5f..353c4676c 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java @@ -37,50 +37,46 @@ // Self contained editing panel // TODO: Add ability for expansions to register modules for identifying and providing custom editors to various NBT data sets (inventory, tinker tool, magic, etc.) // TODO: This however should not be forced in the event of incorrect identification. Open as... -public class PanelScrollingNBT extends CanvasScrolling implements IPEventListener -{ - private NBTBase nbt; - - private final int btnEdit; - private final int btnAdv; - private final int btnInsert; - private final int btnDelete; - - // TODO: Set a special tag that tells the editor about special serialised objects that should be handled in a special way. - // Considering taglists can't contain extra data there may need a way to pass a special manifest file (via NbtDocs?) - // This tag type should be hidden in by the editor but auto-changed when manually switch to a new type - - private final Stack nbtStack = new Stack<>(); - - public PanelScrollingNBT(IGuiRect rect, NBTTagCompound tag, int btnEdit, int btnAdv, int btnInsert, int btnDelete) - { - this(rect, btnEdit, btnAdv, btnInsert, btnDelete); - - this.setNBT(tag); - } - - public PanelScrollingNBT(IGuiRect rect, NBTTagList tag, int btnEdit, int btnAdv, int btnInsert, int btnDelete) - { - this(rect, btnEdit, btnAdv, btnInsert, btnDelete); - - this.setNBT(tag); - } - - private PanelScrollingNBT(IGuiRect rect, int btnEdit, int btnAdv, int btnInsert, int btnDelete) - { - super(rect); - - this.btnEdit = btnEdit; - this.btnAdv = btnAdv; - this.btnInsert = btnInsert; - this.btnDelete = btnDelete; - - // Listens to its own buttons to update NBT values. The parent screen defines what the IDs are and any furter actions - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - } - - // TODO: Implement this with a proper way of displaying and choosing between options (and setting priority for default) +public class PanelScrollingNBT extends CanvasScrolling implements IPEventListener { + private NBTBase nbt; + + private final int btnEdit; + private final int btnAdv; + private final int btnInsert; + private final int btnDelete; + + // TODO: Set a special tag that tells the editor about special serialised objects that should be handled in a special way. + // Considering taglists can't contain extra data there may need a way to pass a special manifest file (via NbtDocs?) + // This tag type should be hidden in by the editor but auto-changed when manually switch to a new type + + private final Stack nbtStack = new Stack<>(); + + public PanelScrollingNBT(IGuiRect rect, NBTTagCompound tag, int btnEdit, int btnAdv, int btnInsert, int btnDelete) { + this(rect, btnEdit, btnAdv, btnInsert, btnDelete); + + this.setNBT(tag); + } + + public PanelScrollingNBT(IGuiRect rect, NBTTagList tag, int btnEdit, int btnAdv, int btnInsert, int btnDelete) { + this(rect, btnEdit, btnAdv, btnInsert, btnDelete); + + this.setNBT(tag); + } + + private PanelScrollingNBT(IGuiRect rect, int btnEdit, int btnAdv, int btnInsert, int btnDelete) { + super(rect); + + this.btnEdit = btnEdit; + this.btnAdv = btnAdv; + this.btnInsert = btnInsert; + this.btnDelete = btnDelete; + + // Listens to its own buttons to update NBT values. The parent screen defines what the IDs are and any furter actions + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + } + + // TODO: Implement this with a proper way of displaying and choosing between options (and setting priority for default) /*private final List, Consumer>> filterMap = new ArrayList<>(); public void registerHandler(Predicate filter, Consumer action) @@ -103,398 +99,430 @@ public List> getHandler(@Nonnull NBTBase tag) return list; }*/ - - public PanelScrollingNBT setNBT(NBTTagCompound tag) - { - this.nbt = tag; - refreshList(); - return this; - } - - public PanelScrollingNBT setNBT(NBTTagList list) - { - this.nbt = list; - refreshList(); - return this; - } - - @Override - public void initPanel() - { - super.initPanel(); - - this.refreshList(); + + public PanelScrollingNBT setNBT(NBTTagCompound tag) { + this.nbt = tag; + refreshList(); + return this; + } + + public PanelScrollingNBT setNBT(NBTTagList list) { + this.nbt = list; + refreshList(); + return this; + } + + @Override + public void initPanel() { + super.initPanel(); + + this.refreshList(); + } + + @SuppressWarnings("unchecked") + private void refreshList() { + this.resetCanvas(); + + if (this.nbt == null) { + return; } - - @SuppressWarnings("unchecked") - private void refreshList() + + int preSX = getScrollX(); + int preSY = getScrollY(); + int width = getTransform().getWidth(); + int lw = (int) (width / 3F); + int rw = width - lw; // Width on right side (rounds up to account for rounding errors lost on left side) + + if (nbt.getId() == 10) // NBTTagCompound { - this.resetCanvas(); - - if(this.nbt == null) + NBTTagCompound tag = (NBTTagCompound) nbt; + List sortedKeys = new ArrayList<>(tag.getKeySet()); + Collections.sort(sortedKeys); + Iterator keys = sortedKeys.iterator(); + int i = 0; + + while (keys.hasNext()) { + String k = keys.next(); + NBTBase entry = tag.getTag(k); + + PanelTextBox name = new PanelTextBox(new GuiRectangle(0, i * 16 + 4, lw - 8, 12, 0), k).setAlignment(2); + name.setColor(PresetColor.TEXT_MAIN.getColor()); + this.addPanel(name); + + if (entry.getId() == 10) // Object { - return; - } - - int preSX = getScrollX(); - int preSY = getScrollY(); - int width = getTransform().getWidth(); - int lw = (int)(width / 3F); - int rw = width - lw; // Width on right side (rounds up to account for rounding errors lost on left side) - - if(nbt.getId() == 10) // NBTTagCompound + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), btnEdit, + getButtonTitle((NBTTagCompound) entry), k); + this.addPanel(btn); + + btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnAdv, "...", k); + this.addPanel(btn); + } else if (entry.getId() == 9) // List + { + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), btnEdit, "List...", k); + this.addPanel(btn); + } else if (entry.getId() == 8) // Text + { + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), + ((NBTTagString) entry).getString(), + FieldFilterString.INSTANCE); + text.setCallback(new CallbackNBTTagString(tag, k)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnEdit, "Aa", k); + this.addPanel(btn); + } else if (entry.getId() == 1) // Byte/Boolean { - NBTTagCompound tag = (NBTTagCompound)nbt; - List sortedKeys = new ArrayList<>(tag.getKeySet()); - Collections.sort(sortedKeys); - Iterator keys = sortedKeys.iterator(); - int i = 0; - - while(keys.hasNext()) + PanelTextField text = + new PanelTextField<>(new GuiRectangle(lw, i * 16, rw / 2, 16, 0), "" + ((NBTPrimitive) entry).getByte(), + FieldFilterNumber.BYTE); + text.setMaxLength(Integer.MAX_VALUE); // Put callback here + this.addPanel(text); + + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(lw + rw / 2, i * 16, (int) Math.ceil(rw / 2F) - 32, 16, 0), + btnEdit, ((NBTPrimitive) entry).getByte() > 0 ? "true" : "false", k); + this.addPanel(btn); + + text.setMaxLength(Integer.MAX_VALUE).setCallback( + new CallbackMulti<>(new CallbackNBTPrimitive<>(tag, k, Byte.class), + value -> btn.setText(value > 0 ? "true" : "false"))); + btn.setCallback(value -> { + boolean flag = tag.getByte(value) > 0; + tag.setByte(value, flag ? (byte) 0 : (byte) 1); + text.setText(flag ? "0" : "1"); + btn.setText(flag ? "false" : "true"); + }); + } else if (entry.getId() > 1 && entry.getId() < 7) // Number + { + switch (entry.getId()) { + case 2: // Short { - String k = keys.next(); - NBTBase entry = tag.getTag(k); - - PanelTextBox name = new PanelTextBox(new GuiRectangle(0, i * 16 + 4, lw - 8, 12, 0), k).setAlignment(2); - name.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(name); - - if(entry.getId() == 10) // Object - { - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), btnEdit, getButtonTitle((NBTTagCompound)entry), k); - this.addPanel(btn); - - btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnAdv, "...", k); - this.addPanel(btn); - } else if(entry.getId() == 9) // List - { - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), btnEdit, "List...", k); - this.addPanel(btn); - } else if(entry.getId() == 8) // Text - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), "" + ((NBTTagString)entry).getString(), FieldFilterString.INSTANCE); - text.setCallback(new CallbackNBTTagString(tag, k)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnEdit, "Aa", k); - this.addPanel(btn); - } else if(entry.getId() == 1) // Byte/Boolean - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw / 2, 16, 0), "" + ((NBTPrimitive)entry).getByte(), FieldFilterNumber.BYTE); - text.setMaxLength(Integer.MAX_VALUE); // Put callback here - this.addPanel(text); - - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw + rw / 2, i * 16, (int)Math.ceil(rw / 2F) - 32, 16, 0), btnEdit, ((NBTPrimitive)entry).getByte() > 0 ? "true" : "false", k); - this.addPanel(btn); - - text.setMaxLength(Integer.MAX_VALUE).setCallback(new CallbackMulti<>(new CallbackNBTPrimitive<>(tag, k, Byte.class), value -> btn.setText(value > 0 ? "true" : "false"))); - btn.setCallback(value -> { - boolean flag = tag.getByte(value) > 0; - tag.setByte(value, flag ? (byte)0 : (byte)1); - text.setText(flag ? "0" : "1"); - btn.setText(flag ? "false" : "true"); - }); - } else if(entry.getId() > 1 && entry.getId() < 7) // Number - { - switch(entry.getId()) - { - case 2: // Short - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getShort(), FieldFilterNumber.SHORT); - text.setCallback(new CallbackNBTPrimitive<>(tag, k, Short.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 3: // Integer - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getInt(), FieldFilterNumber.INT); - text.setCallback(new CallbackNBTPrimitive<>(tag, k, Integer.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 4: // Long - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getLong(), FieldFilterNumber.LONG); - text.setCallback(new CallbackNBTPrimitive<>(tag, k, Long.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 5: // Float - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getFloat(), FieldFilterNumber.FLOAT); - text.setCallback(new CallbackNBTPrimitive<>(tag, k, Float.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 6: // Double - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getDouble(), FieldFilterNumber.DOUBLE); - text.setCallback(new CallbackNBTPrimitive<>(tag, k, Double.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - } - } else - { - PanelTextBox err = new PanelTextBox(new GuiRectangle(lw, i * 16 + 4, rw - 48, 12, 0), entry.getClass().getSimpleName() + " Not Supported Yet").setAlignment(1); - err.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(err); - } - - PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", k); - btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); - - PanelButtonStorage btnD = new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), btnDelete, "x", k); - btnD.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 0, 0, 255), new GuiColorStatic(255, 0, 0, 255)); - this.addPanel(btnD); - - i++; + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getShort(), + FieldFilterNumber.SHORT); + text.setCallback(new CallbackNBTPrimitive<>(tag, k, Short.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; } - - this.addPanel(new PanelGeneric(new GuiRectangle(0, i * 16, width - 32, 16, 0), null)); // Keeps the list from auto resizing - - PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", ""); - btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); - } else if(nbt.getId() == 9) // NBTTagList - { - NBTTagList list = (NBTTagList)nbt; - - int i = 0; - - for(; i < list.tagCount(); i++) + case 3: // Integer { - NBTBase entry = list.get(i); - - PanelTextBox name = new PanelTextBox(new GuiRectangle(0, i * 16 + 4, lw - 8, 16, 0), "#" + i).setAlignment(2); - name.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(name); - - if(entry.getId() == 10) // Object - { - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), btnEdit, getButtonTitle((NBTTagCompound)entry), i); - this.addPanel(btn); - - btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnAdv, "...", i); - this.addPanel(btn); - } else if(entry.getId() == 9) // List - { - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), btnEdit, "List...", i); - this.addPanel(btn); - } else if(entry.getId() == 8) // Text - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), "" + ((NBTTagString)entry).getString(), FieldFilterString.INSTANCE); - text.setCallback(new CallbackNBTTagString(list, i)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnEdit, "Aa", i); - this.addPanel(btn); - } else if(entry.getId() == 1) // Byte/Boolean - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw / 2, 16, 0), "" + ((NBTPrimitive)entry).getByte(), FieldFilterNumber.BYTE); - this.addPanel(text); - - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw + rw / 2, i * 16, (int)Math.ceil(rw / 2F) - 32, 16, 0), btnEdit, ((NBTPrimitive)entry).getByte() > 0 ? "true" : "false", i); - this.addPanel(btn); - - text.setMaxLength(Integer.MAX_VALUE).setCallback(new CallbackMulti<>(new CallbackNBTPrimitive<>(list, i, Byte.class), value -> btn.setText(value > 0 ? "true" : "false"))); - btn.setCallback(value -> { - boolean flag = ((NBTTagByte)list.get(value)).getByte() > 0; - list.set(value, new NBTTagByte(flag ? (byte)0 : (byte)1)); - text.setText(flag ? "0" : "1"); - btn.setText(flag ? "false" : "true"); - }); - } else if(entry.getId() > 1 && entry.getId() < 7) // Number - { - switch(entry.getId()) - { - case 2: // Short - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getShort(), FieldFilterNumber.SHORT); - text.setCallback(new CallbackNBTPrimitive<>(list, i, Short.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 3: // Integer - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getInt(), FieldFilterNumber.INT); - text.setCallback(new CallbackNBTPrimitive<>(list, i, Integer.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 4: // Long - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getLong(), FieldFilterNumber.LONG); - text.setCallback(new CallbackNBTPrimitive<>(list, i, Long.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 5: // Float - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getFloat(), FieldFilterNumber.FLOAT); - text.setCallback(new CallbackNBTPrimitive<>(list, i, Float.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - case 6: // Double - { - PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), "" + ((NBTPrimitive)entry).getDouble(), FieldFilterNumber.DOUBLE); - text.setCallback(new CallbackNBTPrimitive<>(list, i, Double.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); - break; - } - } - } else - { - PanelTextBox err = new PanelTextBox(new GuiRectangle(lw, i * 16 + 4, rw - 48, 12, 0), entry.getClass().getSimpleName() + " Not Supported Yet").setAlignment(1); - err.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(err); - } - - PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", i); - btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); - - PanelButtonStorage btnD = new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), btnDelete, "x", i); - btnD.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 0, 0, 255), new GuiColorStatic(255, 0, 0, 255)); - this.addPanel(btnD); + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getInt(), + FieldFilterNumber.INT); + text.setCallback(new CallbackNBTPrimitive<>(tag, k, Integer.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; } - - this.addPanel(new PanelGeneric(new GuiRectangle(0, i * 16, width - 32, 16, 0), null)); // Keeps the list from auto resizing - - PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", i); - btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); - } - - this.setScrollX(preSX); - this.setScrollY(preSY); - } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); + case 4: // Long + { + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getLong(), + FieldFilterNumber.LONG); + text.setCallback(new CallbackNBTPrimitive<>(tag, k, Long.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; + } + case 5: // Float + { + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getFloat(), + FieldFilterNumber.FLOAT); + text.setCallback(new CallbackNBTPrimitive<>(tag, k, Float.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; + } + case 6: // Double + { + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getDouble(), + FieldFilterNumber.DOUBLE); + text.setCallback(new CallbackNBTPrimitive<>(tag, k, Double.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; + } + } + } else { + PanelTextBox err = new PanelTextBox(new GuiRectangle(lw, i * 16 + 4, rw - 48, 12, 0), + entry.getClass().getSimpleName() + " Not Supported Yet").setAlignment(1); + err.setColor(PresetColor.TEXT_MAIN.getColor()); + this.addPanel(err); } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + + PanelButtonStorage btnI = + new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", k); + btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), + new GuiColorStatic(0, 255, 0, 255)); + this.addPanel(btnI); + + PanelButtonStorage btnD = + new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), btnDelete, "x", k); + btnD.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 0, 0, 255), + new GuiColorStatic(255, 0, 0, 255)); + this.addPanel(btnD); + + i++; + } + + this.addPanel( + new PanelGeneric(new GuiRectangle(0, i * 16, width - 32, 16, 0), null)); // Keeps the list from auto resizing + + PanelButtonStorage btnI = + new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", ""); + btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), + new GuiColorStatic(0, 255, 0, 255)); + this.addPanel(btnI); + } else if (nbt.getId() == 9) // NBTTagList { - if(nbt == null) - { - return; - } - - IPanelButton btn = event.getButton(); - NBTBase entry; - - if(!(btn.getButtonID() == btnEdit || btn.getButtonID() == btnAdv || btn.getButtonID() == btnInsert || btn.getButtonID() == btnDelete)) + NBTTagList list = (NBTTagList) nbt; + + int i = 0; + + for (; i < list.tagCount(); i++) { + NBTBase entry = list.get(i); + + PanelTextBox name = new PanelTextBox(new GuiRectangle(0, i * 16 + 4, lw - 8, 16, 0), "#" + i).setAlignment(2); + name.setColor(PresetColor.TEXT_MAIN.getColor()); + this.addPanel(name); + + if (entry.getId() == 10) // Object { - return; - } - - if(nbt.getId() == 10) + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), btnEdit, + getButtonTitle((NBTTagCompound) entry), i); + this.addPanel(btn); + + btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnAdv, "...", i); + this.addPanel(btn); + } else if (entry.getId() == 9) // List { - entry = ((NBTTagCompound)nbt).getTag(((PanelButtonStorage)btn).getStoredValue()); - } else if(nbt.getId() == 9) + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), btnEdit, "List...", i); + this.addPanel(btn); + } else if (entry.getId() == 8) // Text { - entry = ((NBTTagList)nbt).get(((PanelButtonStorage)btn).getStoredValue()); - } else + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), + ((NBTTagString) entry).getString(), + FieldFilterString.INSTANCE); + text.setCallback(new CallbackNBTTagString(list, i)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnEdit, "Aa", i); + this.addPanel(btn); + } else if (entry.getId() == 1) // Byte/Boolean { - throw new RuntimeException("Invalid NBT tag type!"); - } - - if(btn.getButtonID() == btnEdit) // Context dependent action/toggle + PanelTextField text = + new PanelTextField<>(new GuiRectangle(lw, i * 16, rw / 2, 16, 0), "" + ((NBTPrimitive) entry).getByte(), + FieldFilterNumber.BYTE); + this.addPanel(text); + + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(lw + rw / 2, i * 16, (int) Math.ceil(rw / 2F) - 32, 16, 0), + btnEdit, ((NBTPrimitive) entry).getByte() > 0 ? "true" : "false", i); + this.addPanel(btn); + + text.setMaxLength(Integer.MAX_VALUE).setCallback( + new CallbackMulti<>(new CallbackNBTPrimitive<>(list, i, Byte.class), + value -> btn.setText(value > 0 ? "true" : "false"))); + btn.setCallback(value -> { + boolean flag = ((NBTTagByte) list.get(value)).getByte() > 0; + list.set(value, new NBTTagByte(flag ? (byte) 0 : (byte) 1)); + text.setText(flag ? "0" : "1"); + btn.setText(flag ? "false" : "true"); + }); + } else if (entry.getId() > 1 && entry.getId() < 7) // Number { - if(entry.getId() == 10) // Object editor - { - NBTTagCompound tag = (NBTTagCompound)entry; - - if(JsonHelper.isItem(tag)) - { - mc.displayGuiScreen(new GuiItemSelection(mc.currentScreen, tag, new NbtItemCallback(tag))); - } else if(JsonHelper.isFluid(tag)) - { - mc.displayGuiScreen(new GuiFluidSelection(mc.currentScreen, tag, new NbtFluidCallback(tag))); - } else if(JsonHelper.isEntity(tag)) - { - mc.displayGuiScreen(new GuiEntitySelection(mc.currentScreen, tag, new NbtEntityCallback(tag))); - } else - { - mc.displayGuiScreen(new GuiNbtEditor(mc.currentScreen, tag, null)); - } - } else if(entry.getId() == 9) // List editor - { - mc.displayGuiScreen(new GuiNbtEditor(mc.currentScreen, (NBTTagList)entry, null)); - } else if(entry.getId() == 8) // Text editor + switch (entry.getId()) { + case 2: // Short { - if(nbt.getId() == 10) - { - mc.displayGuiScreen(new GuiTextEditor(mc.currentScreen, ((NBTTagString)entry).getString(), new CallbackNBTTagString((NBTTagCompound)nbt, ((PanelButtonStorage)btn).getStoredValue()))); - } else if(nbt.getId() == 9) - { - mc.displayGuiScreen(new GuiTextEditor(mc.currentScreen, ((NBTTagString)entry).getString(), new CallbackNBTTagString((NBTTagList)nbt, ((PanelButtonStorage)btn).getStoredValue()))); - } - } else if(entry.getId() == 7 || entry.getId() == 11 || entry.getId() == 12) // Byte/Integer/Long array - { - // TODO: Add supportted editors for Byte, Integer and Long Arrays - throw new UnsupportedOperationException("NBTTagByteArray, NBTTagIntArray and NBTTagLongArray are not currently supported yet"); + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getShort(), + FieldFilterNumber.SHORT); + text.setCallback(new CallbackNBTPrimitive<>(list, i, Short.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; } - } else if(btn.getButtonID() == btnAdv) // Open advanced editor (on supported types) - { - if(entry.getId() == 10) + case 3: // Integer { - mc.displayGuiScreen(new GuiNbtType(mc.currentScreen, (NBTTagCompound)entry)); - } else if(entry.getId() == 9) // Not currently available but will be when context list editors (enchantments/inventories/etc) are available - { - // TODO: Replace with context based list editors - mc.displayGuiScreen(new GuiNbtEditor(mc.currentScreen, (NBTTagList)entry, null)); + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getInt(), + FieldFilterNumber.INT); + text.setCallback(new CallbackNBTPrimitive<>(list, i, Integer.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; } - } else if(btn.getButtonID() == btnInsert) - { - if(nbt.getId() == 10) + case 4: // Long { - mc.displayGuiScreen(new GuiNbtAdd(mc.currentScreen, (NBTTagCompound)nbt)); - } else if(nbt.getId() == 9) - { - mc.displayGuiScreen(new GuiNbtAdd(mc.currentScreen, (NBTTagList)nbt, ((PanelButtonStorage)btn).getStoredValue())); + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getLong(), + FieldFilterNumber.LONG); + text.setCallback(new CallbackNBTPrimitive<>(list, i, Long.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; } - } else if(btn.getButtonID() == btnDelete) - { - if(nbt.getId() == 10) + case 5: // Float { - ((NBTTagCompound)nbt).removeTag(((PanelButtonStorage)btn).getStoredValue()); - refreshList(); - } else if(nbt.getId() == 9) + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getFloat(), + FieldFilterNumber.FLOAT); + text.setCallback(new CallbackNBTPrimitive<>(list, i, Float.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; + } + case 6: // Double { - ((NBTTagList)nbt).removeTag(((PanelButtonStorage)btn).getStoredValue()); - refreshList(); + PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), + "" + ((NBTPrimitive) entry).getDouble(), + FieldFilterNumber.DOUBLE); + text.setCallback(new CallbackNBTPrimitive<>(list, i, Double.class)).setMaxLength(Integer.MAX_VALUE); + this.addPanel(text); + break; } + } + } else { + PanelTextBox err = new PanelTextBox(new GuiRectangle(lw, i * 16 + 4, rw - 48, 12, 0), + entry.getClass().getSimpleName() + " Not Supported Yet").setAlignment(1); + err.setColor(PresetColor.TEXT_MAIN.getColor()); + this.addPanel(err); } + + PanelButtonStorage btnI = + new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", i); + btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), + new GuiColorStatic(0, 255, 0, 255)); + this.addPanel(btnI); + + PanelButtonStorage btnD = + new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), btnDelete, "x", i); + btnD.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 0, 0, 255), + new GuiColorStatic(255, 0, 0, 255)); + this.addPanel(btnD); + } + + this.addPanel( + new PanelGeneric(new GuiRectangle(0, i * 16, width - 32, 16, 0), null)); // Keeps the list from auto resizing + + PanelButtonStorage btnI = + new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", i); + btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), + new GuiColorStatic(0, 255, 0, 255)); + this.addPanel(btnI); } - - private final Minecraft mc = Minecraft.getMinecraft(); - - private String getButtonTitle(NBTTagCompound tag) + + this.setScrollX(preSX); + this.setScrollY(preSY); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); + } + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + if (nbt == null) { + return; + } + + IPanelButton btn = event.getButton(); + NBTBase entry; + + if (!(btn.getButtonID() == btnEdit || btn.getButtonID() == btnAdv || btn.getButtonID() == btnInsert || + btn.getButtonID() == btnDelete)) { + return; + } + + if (nbt.getId() == 10) { + entry = ((NBTTagCompound) nbt).getTag(((PanelButtonStorage) btn).getStoredValue()); + } else if (nbt.getId() == 9) { + entry = ((NBTTagList) nbt).get(((PanelButtonStorage) btn).getStoredValue()); + } else { + throw new RuntimeException("Invalid NBT tag type!"); + } + + if (btn.getButtonID() == btnEdit) // Context dependent action/toggle { - if(JsonHelper.isItem(tag)) - { - BigItemStack stack = JsonHelper.JsonToItemStack(tag); - return QuestTranslation.translate("betterquesting.btn.item") + ": " + stack.getBaseStack().getDisplayName(); - } else if(JsonHelper.isFluid(tag)) - { - FluidStack fluid = JsonHelper.JsonToFluidStack(tag); - return QuestTranslation.translate("betterquesting.btn.fluid") + ": " + fluid.getLocalizedName(); - } else if(JsonHelper.isEntity(tag)) - { - Entity entity = JsonHelper.JsonToEntity(tag, this.mc.world); - return QuestTranslation.translate("betterquesting.btn.entity") + ": " + entity.getName(); + if (entry.getId() == 10) // Object editor + { + NBTTagCompound tag = (NBTTagCompound) entry; + + if (JsonHelper.isItem(tag)) { + mc.displayGuiScreen(new GuiItemSelection(mc.currentScreen, tag, new NbtItemCallback(tag))); + } else if (JsonHelper.isFluid(tag)) { + mc.displayGuiScreen(new GuiFluidSelection(mc.currentScreen, tag, new NbtFluidCallback(tag))); + } else if (JsonHelper.isEntity(tag)) { + mc.displayGuiScreen(new GuiEntitySelection(mc.currentScreen, tag, new NbtEntityCallback(tag))); + } else { + mc.displayGuiScreen(new GuiNbtEditor(mc.currentScreen, tag, null)); } - - return "Object..."; + } else if (entry.getId() == 9) // List editor + { + mc.displayGuiScreen(new GuiNbtEditor(mc.currentScreen, (NBTTagList) entry, null)); + } else if (entry.getId() == 8) // Text editor + { + if (nbt.getId() == 10) { + mc.displayGuiScreen(new GuiTextEditor(mc.currentScreen, ((NBTTagString) entry).getString(), + new CallbackNBTTagString((NBTTagCompound) nbt, + ((PanelButtonStorage) btn).getStoredValue()))); + } else if (nbt.getId() == 9) { + mc.displayGuiScreen(new GuiTextEditor(mc.currentScreen, ((NBTTagString) entry).getString(), + new CallbackNBTTagString((NBTTagList) nbt, + ((PanelButtonStorage) btn).getStoredValue()))); + } + } else if (entry.getId() == 7 || entry.getId() == 11 || entry.getId() == 12) // Byte/Integer/Long array + { + // TODO: Add supportted editors for Byte, Integer and Long Arrays + throw new UnsupportedOperationException( + "NBTTagByteArray, NBTTagIntArray and NBTTagLongArray are not currently supported yet"); + } + } else if (btn.getButtonID() == btnAdv) // Open advanced editor (on supported types) + { + if (entry.getId() == 10) { + mc.displayGuiScreen(new GuiNbtType(mc.currentScreen, (NBTTagCompound) entry)); + } else if (entry.getId() == + 9) // Not currently available but will be when context list editors (enchantments/inventories/etc) are available + { + // TODO: Replace with context based list editors + mc.displayGuiScreen(new GuiNbtEditor(mc.currentScreen, (NBTTagList) entry, null)); + } + } else if (btn.getButtonID() == btnInsert) { + if (nbt.getId() == 10) { + mc.displayGuiScreen(new GuiNbtAdd(mc.currentScreen, (NBTTagCompound) nbt)); + } else if (nbt.getId() == 9) { + mc.displayGuiScreen( + new GuiNbtAdd(mc.currentScreen, (NBTTagList) nbt, ((PanelButtonStorage) btn).getStoredValue())); + } + } else if (btn.getButtonID() == btnDelete) { + if (nbt.getId() == 10) { + ((NBTTagCompound) nbt).removeTag(((PanelButtonStorage) btn).getStoredValue()); + refreshList(); + } else if (nbt.getId() == 9) { + ((NBTTagList) nbt).removeTag(((PanelButtonStorage) btn).getStoredValue()); + refreshList(); + } } + } + + private final Minecraft mc = Minecraft.getMinecraft(); + + private String getButtonTitle(NBTTagCompound tag) { + if (JsonHelper.isItem(tag)) { + BigItemStack stack = JsonHelper.JsonToItemStack(tag); + return QuestTranslation.translate("betterquesting.btn.item") + ": " + stack.getBaseStack().getDisplayName(); + } else if (JsonHelper.isFluid(tag)) { + FluidStack fluid = JsonHelper.JsonToFluidStack(tag); + return QuestTranslation.translate("betterquesting.btn.fluid") + ": " + fluid.getLocalizedName(); + } else if (JsonHelper.isEntity(tag)) { + Entity entity = JsonHelper.JsonToEntity(tag, this.mc.world); + return QuestTranslation.translate("betterquesting.btn.entity") + ": " + entity.getName(); + } + + return "Object..."; + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtEntityCallback.java b/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtEntityCallback.java index 7baa7851e..6ae861b30 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtEntityCallback.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtEntityCallback.java @@ -1,34 +1,29 @@ package betterquesting.client.gui2.editors.nbt.callback; +import betterquesting.api.misc.ICallback; +import betterquesting.api.utils.JsonHelper; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.passive.EntityPig; import net.minecraft.nbt.NBTTagCompound; -import betterquesting.api.misc.ICallback; -import betterquesting.api.utils.JsonHelper; -public class NbtEntityCallback implements ICallback -{ - private final NBTTagCompound json; - - public NbtEntityCallback(NBTTagCompound json) - { - this.json = json; - } - - public void setValue(Entity entity) - { - Entity baseEntity; - - if(entity != null) - { - baseEntity = entity; - } else - { - baseEntity = new EntityPig(Minecraft.getMinecraft().world); - } - - JsonHelper.ClearCompoundTag(json); - JsonHelper.EntityToJson(baseEntity, json); - } +public class NbtEntityCallback implements ICallback { + private final NBTTagCompound json; + + public NbtEntityCallback(NBTTagCompound json) { + this.json = json; + } + + public void setValue(Entity entity) { + Entity baseEntity; + + if (entity != null) { + baseEntity = entity; + } else { + baseEntity = new EntityPig(Minecraft.getMinecraft().world); + } + + JsonHelper.ClearCompoundTag(json); + JsonHelper.EntityToJson(baseEntity, json); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtFluidCallback.java b/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtFluidCallback.java index 9d42a7242..ddfeaaa2f 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtFluidCallback.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtFluidCallback.java @@ -1,33 +1,28 @@ package betterquesting.client.gui2.editors.nbt.callback; +import betterquesting.api.misc.ICallback; +import betterquesting.api.utils.JsonHelper; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import betterquesting.api.misc.ICallback; -import betterquesting.api.utils.JsonHelper; -public class NbtFluidCallback implements ICallback -{ - private final NBTTagCompound json; - - public NbtFluidCallback(NBTTagCompound json) - { - this.json = json; - } - - public void setValue(FluidStack stack) - { - FluidStack baseStack; - - if(stack != null) - { - baseStack = stack; - } else - { - baseStack = new FluidStack(FluidRegistry.WATER, 1000); - } - - JsonHelper.ClearCompoundTag(json); - JsonHelper.FluidStackToJson(baseStack, json); - } +public class NbtFluidCallback implements ICallback { + private final NBTTagCompound json; + + public NbtFluidCallback(NBTTagCompound json) { + this.json = json; + } + + public void setValue(FluidStack stack) { + FluidStack baseStack; + + if (stack != null) { + baseStack = stack; + } else { + baseStack = new FluidStack(FluidRegistry.WATER, 1000); + } + + JsonHelper.ClearCompoundTag(json); + JsonHelper.FluidStackToJson(baseStack, json); + } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtItemCallback.java b/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtItemCallback.java index ace609685..a523c8b55 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtItemCallback.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/callback/NbtItemCallback.java @@ -1,33 +1,28 @@ package betterquesting.client.gui2.editors.nbt.callback; -import net.minecraft.init.Blocks; -import net.minecraft.nbt.NBTTagCompound; import betterquesting.api.misc.ICallback; import betterquesting.api.utils.BigItemStack; import betterquesting.api.utils.JsonHelper; +import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; + +public class NbtItemCallback implements ICallback { + private final NBTTagCompound json; + + public NbtItemCallback(NBTTagCompound json) { + this.json = json; + } + + public void setValue(BigItemStack stack) { + BigItemStack baseStack; + + if (stack != null) { + baseStack = stack; + } else { + baseStack = new BigItemStack(Blocks.STONE); + } -public class NbtItemCallback implements ICallback -{ - private final NBTTagCompound json; - - public NbtItemCallback(NBTTagCompound json) - { - this.json = json; - } - - public void setValue(BigItemStack stack) - { - BigItemStack baseStack; - - if(stack != null) - { - baseStack = stack; - } else - { - baseStack = new BigItemStack(Blocks.STONE); - } - - JsonHelper.ClearCompoundTag(json); - JsonHelper.ItemStackToJson(baseStack, json); - } + JsonHelper.ClearCompoundTag(json); + JsonHelper.ItemStackToJson(baseStack, json); + } } diff --git a/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java b/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java index 7a06a3711..5afc3bf99 100644 --- a/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java +++ b/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java @@ -1,164 +1,188 @@ package betterquesting.client.gui2.inventory; import betterquesting.blocks.TileSubmitStation; +import betterquesting.misc.Util; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.ItemHandlerHelper; +import net.minecraftforge.items.SlotItemHandler; -public class ContainerSubmitStation extends Container -{ - private TileSubmitStation tile; - - public ContainerSubmitStation(InventoryPlayer inventory, TileSubmitStation tile) - { - this.tile = tile; - - this.addSlotToContainer(new Slot(tile, 0, 0, 0) - { - @Override - public boolean isItemValid(ItemStack stack) - { - return inventory.isItemValidForSlot(0, stack); - } - }); - - this.addSlotToContainer(new Slot(tile, 1, 0, 0) - { - @Override - public boolean isItemValid(ItemStack stack) - { - return false; - } - }); - - for (int i = 0; i < 3; ++i) - { - for (int j = 0; j < 9; ++j) - { - this.addSlotToContainer(new Slot(inventory, j + i * 9 + 9, j * 18, i * 18)); - } - } +import javax.annotation.Nonnull; + +public class ContainerSubmitStation extends Container { + public final TileSubmitStation tile; + private final InventoryPlayer player; + + public ContainerSubmitStation(InventoryPlayer player, TileSubmitStation tile) { + this.tile = tile; + this.player = player; + + IItemHandler handler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); + addSlotToContainer(new SlotItemHandler(handler, 0, 0, 0)); + addSlotToContainer(new SlotItemHandler(handler, 1, 0, 0)); + + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.addSlotToContainer(new Slot(player, j + i * 9 + 9, j * 18, i * 18)); + } + } + + for (int i = 0; i < 9; ++i) { + this.addSlotToContainer(new Slot(player, i, i * 18, 58)); + } + } + + @Override + public void detectAndSendChanges() { + if (player.player instanceof EntityPlayerMP) { + boolean old = ((EntityPlayerMP) player.player).isChangingQuantityOnly; + ((EntityPlayerMP) player.player).isChangingQuantityOnly = false; + super.detectAndSendChanges(); + ((EntityPlayerMP) player.player).isChangingQuantityOnly = old; + } else { + super.detectAndSendChanges(); + } + } + + public void moveInventorySlots(int x, int y) { + int idx = 2; + + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + Slot s = inventorySlots.get(idx); + s.xPos = j * 18 + x; + s.yPos = i * 18 + y; + idx++; + } + } + + for (int i = 0; i < 9; ++i) { + Slot s = inventorySlots.get(idx); + s.xPos = i * 18 + x; + s.yPos = 58 + y; + idx++; + } + } + + @Override + protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean reverseDirection) { + boolean flag = false; + Iterable range = Util.closedOpenRange(startIndex, endIndex, reverseDirection); + + if (stack.isStackable()) { + for (int i : range) { + Slot slot = this.inventorySlots.get(i); + ItemStack slotStack = slot.getStack(); - for (int i = 0; i < 9; ++i) - { - this.addSlotToContainer(new Slot(inventory, i, i * 18, 58)); + if (ItemHandlerHelper.canItemStacksStack(stack, slotStack)) { + int total = slotStack.getCount() + stack.getCount(); + int maxSize = Math.min(stack.getMaxStackSize(), slot.getItemStackLimit(stack)); + if (total <= maxSize) { + stack.setCount(0); + slotStack.setCount(total); + slot.onSlotChanged(); + flag = true; + } else if (slotStack.getCount() < maxSize) { + stack.shrink(maxSize - slotStack.getCount()); + slotStack.setCount(maxSize); + slot.onSlotChanged(); + flag = true; + } } - } - - public void moveInventorySlots(int x, int y) - { - int idx = 2; - - for (int i = 0; i < 3; ++i) - { - for (int j = 0; j < 9; ++j) - { - Slot s = inventorySlots.get(idx); - s.xPos = j * 18 + x; - s.yPos = i * 18 + y; - idx++; - } + } + } + + for (int i : range) { + Slot slot = this.inventorySlots.get(i); + ItemStack slotStack = slot.getStack(); + + if (slotStack.isEmpty() && slot.isItemValid(stack)) { + int maxSize = Math.min(slot.getItemStackLimit(stack), stack.getMaxStackSize()); + slot.putStack(stack.splitStack(Math.min(maxSize, stack.getCount()))); + slot.onSlotChanged(); + flag = true; + break; + } + } + + return flag; + } + + /** + * Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that. + */ + @Nonnull + @Override + public ItemStack transferStackInSlot(@Nonnull EntityPlayer player, int idx) { + if (idx < 0) { + return ItemStack.EMPTY; + } + + ItemStack itemstack = ItemStack.EMPTY; + Slot slot = this.inventorySlots.get(idx); + + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (idx == 0) { + if (!this.mergeItemStack(itemstack1, 1, 37, true)) { + return ItemStack.EMPTY; } - for (int i = 0; i < 9; ++i) - { - Slot s = inventorySlots.get(idx); - s.xPos = i * 18 + x; - s.yPos = 58 + y; - idx++; + slot.onSlotChange(itemstack1, itemstack); + } else if (slot.isItemValid(itemstack1)) { + if (!this.mergeItemStack(itemstack1, 0, 1, false)) { + return ItemStack.EMPTY; + } + } else if (idx < 28) { + if (!this.mergeItemStack(itemstack1, 28, 37, false)) { + return ItemStack.EMPTY; } - } - - /** - * Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that. - */ - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int idx) - { - if(idx < 0) return ItemStack.EMPTY; - - ItemStack itemstack = ItemStack.EMPTY; - Slot slot = this.inventorySlots.get(idx); - - if (slot != null && slot.getHasStack()) - { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (idx == 0) - { - if (!this.mergeItemStack(itemstack1, 1, 37, true)) - { - return ItemStack.EMPTY; - } - - slot.onSlotChange(itemstack1, itemstack); - } - else if (slot.isItemValid(itemstack1)) - { - if (!this.mergeItemStack(itemstack1, 0, 1, false)) - { - return ItemStack.EMPTY; - } - } - else if (idx < 28) - { - if (!this.mergeItemStack(itemstack1, 28, 37, false)) - { - return ItemStack.EMPTY; - } - } - else if (idx < 37) - { - if (!this.mergeItemStack(itemstack1, 1, 28, false)) - { - return ItemStack.EMPTY; - } - } - else if (!this.mergeItemStack(itemstack1, 1, 37, false)) - { - return ItemStack.EMPTY; - } - - if (itemstack1.isEmpty()) - { - slot.putStack(ItemStack.EMPTY); - } - else - { - slot.onSlotChanged(); - } - - if (itemstack1.getCount() == itemstack.getCount()) - { - return ItemStack.EMPTY; - } - - slot.onTake(player, itemstack1); + } else if (idx < 37) { + if (!this.mergeItemStack(itemstack1, 1, 28, false)) { + return ItemStack.EMPTY; } + } else if (!this.mergeItemStack(itemstack1, 1, 37, false)) { + return ItemStack.EMPTY; + } + + if (itemstack1.isEmpty()) { + slot.putStack(ItemStack.EMPTY); + } else { + slot.onSlotChanged(); + } + + if (itemstack1.getCount() == itemstack.getCount()) { + return ItemStack.EMPTY; + } - return itemstack; + slot.onTake(player, itemstack1); } - - public void moveSubmitSlot(int x, int y) - { - Slot s = inventorySlots.get(0); - s.xPos = x; - s.yPos = y; - } - - public void moveReturnSlot(int x, int y) - { - Slot s = inventorySlots.get(1); - s.xPos = x; - s.yPos = y; - } - - @Override - public boolean canInteractWith(EntityPlayer player) - { - return tile.isUsableByPlayer(player); - } + + return itemstack; + } + + public void moveSubmitSlot(int x, int y) { + Slot s = inventorySlots.get(0); + s.xPos = x; + s.yPos = y; + } + + public void moveReturnSlot(int x, int y) { + Slot s = inventorySlots.get(1); + s.xPos = x; + s.yPos = y; + } + + @Override + public boolean canInteractWith(@Nonnull EntityPlayer player) { + return tile.isUsableByPlayer(player); + } } diff --git a/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java b/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java index e03edb2fd..fdd647b54 100644 --- a/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java +++ b/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java @@ -4,6 +4,7 @@ import betterquesting.api.client.gui.misc.INeedsRefresh; import betterquesting.api.properties.NativeProps; import betterquesting.api.questing.IQuest; +import betterquesting.api.questing.tasks.IEnergyTask; import betterquesting.api.questing.tasks.IFluidTask; import betterquesting.api.questing.tasks.IItemTask; import betterquesting.api.questing.tasks.ITask; @@ -35,290 +36,272 @@ import org.lwjgl.input.Keyboard; import org.lwjgl.util.vector.Vector4f; -import java.util.Iterator; import java.util.List; -public class GuiSubmitStation extends GuiContainerCanvas implements INeedsRefresh -{ - private final ContainerSubmitStation ssContainer; - private final TileSubmitStation tile; - - private final NonNullList> quests = NonNullList.create(); - private final NonNullList> tasks = NonNullList.create(); - - private IGuiCanvas cvBackground; - - private IPanelButton btnSet; - private IPanelButton btnRem; - private IPanelButton btnQstLeft; - private IPanelButton btnQstRight; - private IPanelButton btnTskLeft; - private IPanelButton btnTskRight; - - private PanelTextBox txtQstTitle; - private PanelTextBox txtTskTitle; - - private IGuiPanel taskPanel; - - private int selQuest = 0; - private int selTask = 0; - - public GuiSubmitStation(GuiScreen parent, InventoryPlayer playerInvo, TileSubmitStation submitStation) - { - super(parent, new ContainerSubmitStation(playerInvo, submitStation)); - this.ssContainer = (ContainerSubmitStation)this.inventorySlots; - this.tile = submitStation; - } - - @Override - public void refreshGui() - { - quests.clear(); - QuestCache qc = mc.player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if(qc != null) quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); - filterQuests(); - +public class GuiSubmitStation extends GuiContainerCanvas implements INeedsRefresh { + private final ContainerSubmitStation ssContainer; + private final TileSubmitStation tile; + + private final NonNullList> quests = NonNullList.create(); + private final NonNullList> tasks = NonNullList.create(); + + private IGuiCanvas cvBackground; + + private IPanelButton btnSet; + private IPanelButton btnRem; + private IPanelButton btnQstLeft; + private IPanelButton btnQstRight; + private IPanelButton btnTskLeft; + private IPanelButton btnTskRight; + + private PanelTextBox txtQstTitle; + private PanelTextBox txtTskTitle; + + private IGuiPanel taskPanel; + + private int selQuest = 0; + private int selTask = 0; + + public GuiSubmitStation(GuiScreen parent, InventoryPlayer playerInvo, TileSubmitStation submitStation) { + super(parent, new ContainerSubmitStation(playerInvo, submitStation)); + this.ssContainer = (ContainerSubmitStation) this.inventorySlots; + this.tile = submitStation; + } + + @Override + public void refreshGui() { + quests.clear(); + QuestCache qc = mc.player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc != null) { quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); } + filterQuests(); + + refreshTaskPanel(); + } + + @Override + public void initPanel() { + super.initPanel(); + + Keyboard.enableRepeatEvents(true); + + quests.clear(); + taskPanel = null; + QuestCache qc = mc.player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc != null) { quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); } + filterQuests(); + + // Background panel + cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + PanelTextBox txtTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate( + "betterquesting.title.submit_station")).setAlignment(1); + txtTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txtTitle); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), -1, + QuestTranslation.translate("gui.done")).setClickAction( + (b) -> mc.displayGuiScreen(parent))); + + btnQstLeft = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 0F), 8, 32, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + selQuest--; refreshTaskPanel(); - } - - @Override - public void initPanel() - { - super.initPanel(); - - Keyboard.enableRepeatEvents(true); - - quests.clear(); - taskPanel = null; - QuestCache qc = mc.player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if(qc != null) quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); - filterQuests(); - - // Background panel - cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - PanelTextBox txtTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.submit_station")).setAlignment(1); - txtTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txtTitle); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), -1, QuestTranslation.translate("gui.done")).setClickAction((b) -> mc.displayGuiScreen(parent))); - - btnQstLeft = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 0F), 8, 32, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - selQuest--; - refreshTaskPanel(); - } - }; - ((PanelButton)btnQstLeft).setIcon(PresetIcon.ICON_LEFT.getTexture()); - cvBackground.addPanel(btnQstLeft); - - btnQstRight = new PanelButton(new GuiTransform(new Vector4f(1F, 0F, 1F, 0F), -32, 32, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - selQuest++; - refreshTaskPanel(); - } - }; - ((PanelButton)btnQstRight).setIcon(PresetIcon.ICON_RIGHT.getTexture()); - cvBackground.addPanel(btnQstRight); - - btnTskLeft = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 0F), 8, 48, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - selTask--; - refreshTaskPanel(); - } - }; - ((PanelButton)btnTskLeft).setIcon(PresetIcon.ICON_LEFT.getTexture()); - cvBackground.addPanel(btnTskLeft); - - btnTskRight = new PanelButton(new GuiTransform(new Vector4f(1F, 0F, 1F, 0F), -32, 48, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - selTask++; - refreshTaskPanel(); - } - }; - ((PanelButton)btnTskRight).setIcon(PresetIcon.ICON_RIGHT.getTexture()); - cvBackground.addPanel(btnTskRight); - - btnSet = new PanelButton(new GuiTransform(new Vector4f(0.75F, 0F, 0.75F, 0F), -16, 64, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - DBEntry selQuestEntry = quests.get(selQuest); - DBEntry selTaskEntry = tasks.get(selTask); - tile.setupTask(QuestingAPI.getQuestingUUID(mc.player), selQuestEntry.getValue(), selTaskEntry.getValue()); - NetStationEdit.setupStation(tile.getPos(), selQuestEntry.getID(), selTaskEntry.getID()); - refreshTaskPanel(); - } - }; - ((PanelButton)btnSet).setIcon(PresetIcon.ICON_TICK.getTexture(), new GuiColorStatic(0xFF00FF00), 0); - cvBackground.addPanel(btnSet); - - btnRem = new PanelButton(new GuiTransform(new Vector4f(0.75F, 0F, 0.75F, 0F), 0, 64, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - tile.reset(); - NetStationEdit.resetStation(tile.getPos()); - refreshTaskPanel(); - } - }; - ((PanelButton)btnRem).setIcon(PresetIcon.ICON_CROSS.getTexture(), new GuiColorStatic(0xFFFF0000), 0); - cvBackground.addPanel(btnRem); - - txtQstTitle = new PanelTextBox(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(24, 36, 32, -48), 0), ""); - txtQstTitle.setColor(PresetColor.TEXT_MAIN.getColor()).setAlignment(1); - cvBackground.addPanel(txtQstTitle); - - txtTskTitle = new PanelTextBox(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(24, 52, 32, -64), 0), ""); - txtTskTitle.setColor(PresetColor.TEXT_MAIN.getColor()).setAlignment(1); - cvBackground.addPanel(txtTskTitle); - - setInventoryPosition((xSize - 64)/4 + 16 - 81, (ySize - 64)/2 + 16 - 49); + } + }; + ((PanelButton) btnQstLeft).setIcon(PresetIcon.ICON_LEFT.getTexture()); + cvBackground.addPanel(btnQstLeft); + + btnQstRight = new PanelButton(new GuiTransform(new Vector4f(1F, 0F, 1F, 0F), -32, 32, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + selQuest++; + refreshTaskPanel(); + } + }; + ((PanelButton) btnQstRight).setIcon(PresetIcon.ICON_RIGHT.getTexture()); + cvBackground.addPanel(btnQstRight); + + btnTskLeft = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 0.5F, 0F), 8, 48, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + selTask--; + refreshTaskPanel(); + } + }; + ((PanelButton) btnTskLeft).setIcon(PresetIcon.ICON_LEFT.getTexture()); + cvBackground.addPanel(btnTskLeft); + + btnTskRight = new PanelButton(new GuiTransform(new Vector4f(1F, 0F, 1F, 0F), -32, 48, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + selTask++; + refreshTaskPanel(); + } + }; + ((PanelButton) btnTskRight).setIcon(PresetIcon.ICON_RIGHT.getTexture()); + cvBackground.addPanel(btnTskRight); + + btnSet = new PanelButton(new GuiTransform(new Vector4f(0.75F, 0F, 0.75F, 0F), -16, 64, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + DBEntry selQuestEntry = quests.get(selQuest); + DBEntry selTaskEntry = tasks.get(selTask); + tile.setupTask(QuestingAPI.getQuestingUUID(mc.player), selQuestEntry.getID(), selTaskEntry.getID()); + NetStationEdit.setupStation(tile.getPos(), + selQuestEntry.getID(), + selTaskEntry.getID(), + (byte) ssContainer.windowId); + refreshTaskPanel(); + } + }; + ((PanelButton) btnSet).setIcon(PresetIcon.ICON_TICK.getTexture(), new GuiColorStatic(0xFF00FF00), 0); + cvBackground.addPanel(btnSet); + + btnRem = new PanelButton(new GuiTransform(new Vector4f(0.75F, 0F, 0.75F, 0F), 0, 64, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + tile.reset(); + NetStationEdit.resetStation(tile.getPos(), (byte) ssContainer.windowId); refreshTaskPanel(); + } + }; + ((PanelButton) btnRem).setIcon(PresetIcon.ICON_CROSS.getTexture(), new GuiColorStatic(0xFFFF0000), 0); + cvBackground.addPanel(btnRem); + + txtQstTitle = + new PanelTextBox(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(24, 36, 32, -48), 0), ""); + txtQstTitle.setColor(PresetColor.TEXT_MAIN.getColor()).setAlignment(1); + cvBackground.addPanel(txtQstTitle); + + txtTskTitle = + new PanelTextBox(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0F), new GuiPadding(24, 52, 32, -64), 0), ""); + txtTskTitle.setColor(PresetColor.TEXT_MAIN.getColor()).setAlignment(1); + cvBackground.addPanel(txtTskTitle); + + setInventoryPosition((xSize - 64) / 4 + 16 - 81, (ySize - 64) / 2 + 16 - 49); + refreshTaskPanel(); + } + + private void setInventoryPosition(int x, int y) { + // OLD SCHOOL GUI MATH + // Move the slots into place manually (coordinates are already relative to the parent transform) + ssContainer.moveInventorySlots(x + 17, y + 39); + ssContainer.moveSubmitSlot(x + 71, y + 17); + ssContainer.moveReturnSlot(x + 107, y + 17); + + for (int i = 0; i < 36; i++) { + int j = i % 9 * 18; + int k = i / 9 * 18; + if (i >= 27) { k += 4; } + + this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + j, y + k + 22, 18, 18, -1), + PresetTexture.ITEM_FRAME.getTexture())); } - - private void setInventoryPosition(int x, int y) - { - // OLD SCHOOL GUI MATH - // Move the slots into place manually (coordinates are already relative to the parent transform) - ssContainer.moveInventorySlots(x + 17, y + 39); - ssContainer.moveSubmitSlot(x + 71, y + 17); - ssContainer.moveReturnSlot(x + 107, y + 17); - - for(int i = 0; i < 36; i++) - { - int j = i%9 * 18; - int k = i/9 * 18; - if(i >= 27) k += 4; - - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + j, y + k + 22, 18, 18, -1), PresetTexture.ITEM_FRAME.getTexture())); + + this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 54, y, 18, 18, -1), + PresetTexture.ITEM_FRAME.getTexture())); + this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 72, y, 18, 18, -1), + PresetIcon.ICON_RIGHT.getTexture())); + this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 90, y, 18, 18, -1), + PresetTexture.ITEM_FRAME.getTexture())); + } + + private void filterQuests() { + quests.removeIf(q -> { + boolean shouldDelete = true; + + for (DBEntry tsk : q.getValue().getTasks().getEntries()) { + if (tsk.getValue() instanceof IItemTask || + tsk.getValue() instanceof IFluidTask || + tsk.getValue() instanceof IEnergyTask) { + shouldDelete = false; + break; } - - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 54, y, 18, 18, -1), PresetTexture.ITEM_FRAME.getTexture())); - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 72, y, 18, 18, -1), PresetIcon.ICON_RIGHT.getTexture())); - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 90, y, 18, 18, -1), PresetTexture.ITEM_FRAME.getTexture())); - } - - private void filterQuests() - { - Iterator> iter = quests.iterator(); - - while(iter.hasNext()) - { - DBEntry entry = iter.next(); - - boolean valid = false; - - for(DBEntry tsk : entry.getValue().getTasks().getEntries()) - { - if(tsk.getValue() instanceof IItemTask || tsk.getValue() instanceof IFluidTask) - { - valid = true; - break; - } - } - - if(!valid) iter.remove(); + } + + return shouldDelete; + }); + } + + private void refreshTaskPanel() { + if (taskPanel != null) { cvBackground.removePanel(taskPanel); } + + if (tile.isSetup()) { + DBEntry qdbe = null; + + for (int i = 0; i < quests.size(); i++) { + DBEntry entry = quests.get(i); + if (entry.getID() == tile.questID) { + selQuest = i; + qdbe = entry; + break; } - } - - private void refreshTaskPanel() - { - if(taskPanel != null) cvBackground.removePanel(taskPanel); - - if(tile.isSetup()) - { - DBEntry qdbe = null; - - for(int i = 0; i < quests.size(); i++) - { - DBEntry entry = quests.get(i); - if(entry.getID() == tile.questID) - { - selQuest = i; - qdbe = entry; - break; - } - } - - if(qdbe != null) - { - List> tmpTasks = qdbe.getValue().getTasks().getEntries(); - for(int i = 0; i < tmpTasks.size(); i++) - { - if(tmpTasks.get(i).getID() == tile.taskID) - { - selTask = i; - break; - } - } - } - - btnRem.setActive(true); - btnSet.setActive(false); - - btnQstLeft.setActive(false); - btnQstRight.setActive(false); - btnTskLeft.setActive(false); - btnTskRight.setActive(false); - } else - { - btnRem.setActive(false); - btnSet.setActive(false); - - btnQstLeft.setActive(true); - btnQstRight.setActive(true); - btnTskLeft.setActive(true); - btnTskRight.setActive(true); + } + + if (qdbe != null) { + List> tmpTasks = qdbe.getValue().getTasks().getEntries(); + for (int i = 0; i < tmpTasks.size(); i++) { + if (tmpTasks.get(i).getID() == tile.taskID) { + selTask = i; + break; + } } - - if(quests.size() <= 0) - { - selQuest = -1; - selTask = -1; - txtQstTitle.setText(""); - txtTskTitle.setText(""); - return; - } else selQuest = lazyPosMod(selQuest, quests.size()); - - DBEntry entry = quests.get(selQuest); - txtQstTitle.setText(QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME))); - - tasks.clear(); - tasks.addAll(entry.getValue().getTasks().getEntries()); - - if(tasks.size() <= 0) - { - selTask = -1; - txtTskTitle.setText(""); - return; - } else selTask = lazyPosMod(selTask, tasks.size()); - - DBEntry curTask = tasks.get(selTask); - txtTskTitle.setText(QuestTranslation.translate(curTask.getValue().getUnlocalisedName())); - btnSet.setActive(!tile.isSetup() && (curTask.getValue() instanceof IItemTask || curTask.getValue() instanceof IFluidTask)); - - taskPanel = curTask.getValue().getTaskGui(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 88, 16, 24), 0), entry); - if(taskPanel != null) cvBackground.addPanel(taskPanel); + } + + btnRem.setActive(true); + btnSet.setActive(false); + + btnQstLeft.setActive(false); + btnQstRight.setActive(false); + btnTskLeft.setActive(false); + btnTskRight.setActive(false); + } else { + btnRem.setActive(false); + btnSet.setActive(false); + + btnQstLeft.setActive(true); + btnQstRight.setActive(true); + btnTskLeft.setActive(true); + btnTskRight.setActive(true); } - - private int lazyPosMod(int a, int b) - { - return ((a % b) + b) % b; + + if (quests.isEmpty()) { + selQuest = -1; + selTask = -1; + txtQstTitle.setText(""); + txtTskTitle.setText(""); + return; + } else { selQuest = lazyPosMod(selQuest, quests.size()); } + + DBEntry entry = quests.get(selQuest); + txtQstTitle.setText(QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME))); + + tasks.clear(); + tasks.addAll(entry.getValue().getTasks().getEntries()); + + if (tasks.isEmpty()) { + selTask = -1; + txtTskTitle.setText(""); + return; + } else { + selTask = lazyPosMod(selTask, tasks.size()); } + + ITask curTask = tasks.get(selTask).getValue(); + txtTskTitle.setText(QuestTranslation.translate(curTask.getUnlocalisedName())); + btnSet.setActive(!tile.isSetup() && (curTask instanceof IItemTask || + curTask instanceof IFluidTask || + curTask instanceof IEnergyTask)); + + taskPanel = curTask.getTaskGui(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 88, 16, 24), 0), entry); + if (taskPanel != null) { cvBackground.addPanel(taskPanel); } + } + + private int lazyPosMod(int a, int b) { + return ((a % b) + b) % b; + } } diff --git a/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java b/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java index a5e368cb5..dd9325349 100644 --- a/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java +++ b/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java @@ -49,170 +49,178 @@ import java.util.Map.Entry; import java.util.UUID; -public class GuiPartyCreate extends GuiScreenCanvas implements IPEventListener, INeedsRefresh -{ - private PanelTextField flName; - private CanvasScrolling invitePanel; - private PanelVScrollBar inviteScroll; - private UUID playerID; - - public GuiPartyCreate(GuiScreen parent) - { - super(parent); +public class GuiPartyCreate extends GuiScreenCanvas implements IPEventListener, INeedsRefresh { + private PanelTextField flName; + private CanvasScrolling invitePanel; + private PanelVScrollBar inviteScroll; + private UUID playerID; + + public GuiPartyCreate(GuiScreen parent) { + super(parent); + } + + @Override + public void refreshGui() { + DBEntry curParty = PartyManager.INSTANCE.getParty(playerID); + + if (curParty != null) { + mc.displayGuiScreen(new GuiPartyManage(parent)); + return; } - - @Override - public void refreshGui() - { - DBEntry curParty = PartyManager.INSTANCE.getParty(playerID); - - if(curParty != null) - { - mc.displayGuiScreen(new GuiPartyManage(parent)); - return; - } - - refreshInvites(); + + refreshInvites(); + } + + @Override + public void initPanel() { + super.initPanel(); + + playerID = QuestingAPI.getQuestingUUID(mc.player); + + DBEntry curParty = PartyManager.INSTANCE.getParty(playerID); + + if (curParty != null) { + mc.displayGuiScreen(new GuiPartyManage(parent)); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - playerID = QuestingAPI.getQuestingUUID(mc.player); - - DBEntry curParty = PartyManager.INSTANCE.getParty(playerID); - - if(curParty != null) - { - mc.displayGuiScreen(new GuiPartyManage(parent)); - return; - } - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.party_none")).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - CanvasEmpty cvLeftHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 32), 0)); - cvBackground.addPanel(cvLeftHalf); - - PanelPlayerPortrait pnPortrait = new PanelPlayerPortrait(new GuiTransform(GuiAlign.TOP_CENTER, -32, 0, 64, 64, 0), mc.player).setDepth(-16F); - cvLeftHalf.addPanel(pnPortrait); - - cvLeftHalf.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_CENTER, 16, 48, 24, 24, 0), new ItemTexture(new BigItemStack(BetterQuesting.extraLife, LifeDatabase.INSTANCE.getLives(QuestingAPI.getQuestingUUID(mc.player))), true, true).setDepth(32F))); - - PanelTextBox txName = new PanelTextBox(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(16, -44, 16, 28), 0), QuestTranslation.translate("betterquesting.gui.name")); - txName.setColor(PresetColor.TEXT_HEADER.getColor()); - cvLeftHalf.addPanel(txName); - - flName = new PanelTextField<>(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(16, -32, 16, 16), 0), "New Party", FieldFilterString.INSTANCE); - cvLeftHalf.addPanel(flName); - - PanelButton btnCreate = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(16, -16, 16, 0), 0), 1, QuestTranslation.translate("betterquesting.btn.party_new")); - cvLeftHalf.addPanel(btnCreate); - - CanvasEmpty cvRightHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); - cvBackground.addPanel(cvRightHalf); - - invitePanel = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); - cvRightHalf.addPanel(invitePanel); - - inviteScroll = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); - cvRightHalf.addPanel(inviteScroll); - invitePanel.setScrollDriverY(inviteScroll); - - PanelTextBox txInvite = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.party_invites")).setAlignment(1); - txInvite.setColor(PresetColor.TEXT_HEADER.getColor()); - cvRightHalf.addPanel(txInvite); - - refreshInvites(); - - // Divider - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.party_none")).setAlignment( + 1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + CanvasEmpty cvLeftHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 32, 8, 32), 0)); + cvBackground.addPanel(cvLeftHalf); + + PanelPlayerPortrait pnPortrait = + new PanelPlayerPortrait(new GuiTransform(GuiAlign.TOP_CENTER, -32, 0, 64, 64, 0), mc.player).setDepth(-16F); + cvLeftHalf.addPanel(pnPortrait); + + cvLeftHalf.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_CENTER, 16, 48, 24, 24, 0), new ItemTexture( + new BigItemStack(BetterQuesting.extraLife, + LifeDatabase.INSTANCE.getLives(QuestingAPI.getQuestingUUID(mc.player))), true, true).setDepth( + 32F))); + + PanelTextBox txName = new PanelTextBox(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(16, -44, 16, 28), 0), + QuestTranslation.translate("betterquesting.gui.name")); + txName.setColor(PresetColor.TEXT_HEADER.getColor()); + cvLeftHalf.addPanel(txName); + + flName = + new PanelTextField<>(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(16, -32, 16, 16), 0), "New Party", + FieldFilterString.INSTANCE); + cvLeftHalf.addPanel(flName); + + PanelButton btnCreate = + new PanelButton(new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(16, -16, 16, 0), 0), 1, + QuestTranslation.translate("betterquesting.btn.party_new")); + cvLeftHalf.addPanel(btnCreate); + + CanvasEmpty cvRightHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); + cvBackground.addPanel(cvRightHalf); + + invitePanel = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); + cvRightHalf.addPanel(invitePanel); + + inviteScroll = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 16, 0, 0), 0)); + cvRightHalf.addPanel(inviteScroll); + invitePanel.setScrollDriverY(inviteScroll); + + PanelTextBox txInvite = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate( + "betterquesting.gui.party_invites")).setAlignment(1); + txInvite.setColor(PresetColor.TEXT_HEADER.getColor()); + cvRightHalf.addPanel(txInvite); + + refreshInvites(); + + // Divider + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @Override - public void onPanelEvent(PanelEvent event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } - } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1) // Create { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1) // Create - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 0); - payload.setString("name", flName.getRawText()); - NetPartyAction.sendAction(payload); - } else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Join - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 4); - payload.setInteger("partyID", ((PanelButtonStorage)btn).getStoredValue()); - NetPartyAction.sendAction(payload); - } - } - - private void refreshInvites() + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 0); + payload.setString("name", flName.getRawText()); + NetPartyAction.sendAction(payload); + } else if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Join { - invitePanel.resetCanvas(); - int cvWidth = invitePanel.getTransform().getWidth(); - List> invites = PartyInvitations.INSTANCE.getPartyInvites(playerID); - int elSize = RenderUtils.getStringWidth("...", mc.fontRenderer); - - for(int i = 0; i < invites.size(); i++) - { - int pid = invites.get(i).getKey(); - if(pid < 0) continue; - long exp = invites.get(i).getValue(); - IParty party = PartyManager.INSTANCE.getValue(pid); - - PanelButtonStorage btnJoin = new PanelButtonStorage<>(new GuiRectangle(cvWidth - 50, i * 24, 50, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.party_join"), pid); - invitePanel.addPanel(btnJoin); - - String pName = party == null ? "Unknown (" + pid + ")" : party.getProperties().getProperty(NativeProps.NAME); - if(RenderUtils.getStringWidth(pName, mc.fontRenderer) > cvWidth - 58) - { - pName = mc.fontRenderer.trimStringToWidth(pName, cvWidth - 58 - elSize) + "..."; - } - - PanelTextBox txPartyName = new PanelTextBox(new GuiRectangle(0, i * 24 + 4, cvWidth - 58, 12, 0), pName); - txPartyName.setColor(PresetColor.TEXT_MAIN.getColor()); - invitePanel.addPanel(txPartyName); - - PanelHBarFill flExpiry = new PanelHBarFill(new GuiRectangle(0, i * 24 + 16, cvWidth, 8)); - ValueFuncIO expFunc = new ValueFuncIO<>(() -> (float)((exp - System.currentTimeMillis()) / 300000D)); - flExpiry.setFillDriver(expFunc); - flExpiry.setFillColor(new GuiColorTransition(new GuiColorStatic(0xFF00FF00), new GuiColorPulse(0xFFFF0000, 0xFFC00000, 1F, 0F)).setupBlending(false, 0.2F).setBlendDriver(expFunc)); - invitePanel.addPanel(flExpiry); - } - - inviteScroll.setActive(invitePanel.getScrollBounds().getHeight() > 0); + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 4); + payload.setInteger("partyID", ((PanelButtonStorage) btn).getStoredValue()); + NetPartyAction.sendAction(payload); + } + } + + private void refreshInvites() { + invitePanel.resetCanvas(); + int cvWidth = invitePanel.getTransform().getWidth(); + List> invites = PartyInvitations.INSTANCE.getPartyInvites(playerID); + int elSize = RenderUtils.getStringWidth("...", mc.fontRenderer); + + for (int i = 0; i < invites.size(); i++) { + int pid = invites.get(i).getKey(); + if (pid < 0) { continue; } + long exp = invites.get(i).getValue(); + IParty party = PartyManager.INSTANCE.getValue(pid); + + PanelButtonStorage btnJoin = + new PanelButtonStorage<>(new GuiRectangle(cvWidth - 50, i * 24, 50, 16, 0), 2, + QuestTranslation.translate("betterquesting.btn.party_join"), pid); + invitePanel.addPanel(btnJoin); + + String pName = party == null ? "Unknown (" + pid + ")" : party.getProperties().getProperty(NativeProps.NAME); + if (RenderUtils.getStringWidth(pName, mc.fontRenderer) > cvWidth - 58) { + pName = mc.fontRenderer.trimStringToWidth(pName, cvWidth - 58 - elSize) + "..."; + } + + PanelTextBox txPartyName = new PanelTextBox(new GuiRectangle(0, i * 24 + 4, cvWidth - 58, 12, 0), pName); + txPartyName.setColor(PresetColor.TEXT_MAIN.getColor()); + invitePanel.addPanel(txPartyName); + + PanelHBarFill flExpiry = new PanelHBarFill(new GuiRectangle(0, i * 24 + 16, cvWidth, 8)); + ValueFuncIO expFunc = new ValueFuncIO<>(() -> (float) ((exp - System.currentTimeMillis()) / 300000D)); + flExpiry.setFillDriver(expFunc); + flExpiry.setFillColor(new GuiColorTransition(new GuiColorStatic(0xFF00FF00), + new GuiColorPulse(0xFFFF0000, 0xFFC00000, 1F, 0F)).setupBlending( + false, 0.2F).setBlendDriver(expFunc)); + invitePanel.addPanel(flExpiry); } + + inviteScroll.setActive(invitePanel.getScrollBounds().getHeight() > 0); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java b/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java index d38dfd4b9..7fecfef8e 100644 --- a/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java +++ b/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java @@ -38,120 +38,123 @@ import java.util.UUID; // TODO: Make this use a proper scrolling search for big servers -public class GuiPartyInvite extends GuiScreenCanvas implements IPEventListener -{ - private IParty party; - private int partyID; - private PanelTextField flName; - - public GuiPartyInvite(GuiScreen parent) - { - super(parent); +public class GuiPartyInvite extends GuiScreenCanvas implements IPEventListener { + private IParty party; + private int partyID; + private PanelTextField flName; + + public GuiPartyInvite(GuiScreen parent) { + super(parent); + } + + @Override + public void initPanel() { + super.initPanel(); + + UUID playerID = QuestingAPI.getQuestingUUID(mc.player); + DBEntry tmp = PartyManager.INSTANCE.getParty(playerID); + + if (tmp == null) { + mc.displayGuiScreen(parent); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - UUID playerID = QuestingAPI.getQuestingUUID(mc.player); - DBEntry tmp = PartyManager.INSTANCE.getParty(playerID); - - if(tmp == null) - { - mc.displayGuiScreen(parent); - return; - } - - party = tmp.getValue(); - partyID = tmp.getID(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.party_invite", party.getProperties().getProperty(NativeProps.NAME))).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - flName = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(32, 32, 72, -48), 0), "", FieldFilterString.INSTANCE); - flName.setMaxLength(16); - flName.setWatermark("Username"); - cvBackground.addPanel(flName); - - PanelButton btnInvite = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, new GuiPadding(-72, 32, 32, -48), 0), 1, QuestTranslation.translate("betterquesting.btn.party_invite")); - cvBackground.addPanel(btnInvite); - - CanvasScrolling cvNameList = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(32, 64, 40, 32), 0)); - cvBackground.addPanel(cvNameList); - - PanelVScrollBar scNameScroll = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); - cvBackground.addPanel(scNameScroll); - scNameScroll.getTransform().setParent(cvNameList.getTransform()); - cvNameList.setScrollDriverY(scNameScroll); - - int listWidth = cvBackground.getTransform().getWidth() - 64; - int nameSize = RenderUtils.getStringWidth("________________", fontRenderer); - int columnNum = listWidth/nameSize; - - List nameList = new ArrayList<>(); - mc.player.connection.getPlayerInfoMap().forEach((info) -> nameList.add(info.getGameProfile().getName())); - - nameList.removeIf((entry) -> { - UUID memID = NameCache.INSTANCE.getUUID(entry); - return memID != null && party.getStatus(memID) != null; - }); - - for(int i = 0; i < nameList.size(); i++) - { - int x1 = i % columnNum; - int y1 = i / columnNum; - String name = nameList.get(i); - PanelButtonStorage btnName = new PanelButtonStorage<>(new GuiRectangle(x1 * nameSize, y1 * 16, nameSize, 16), 2, name, name); - cvNameList.addPanel(btnName); - } - - scNameScroll.setActive(cvNameList.getScrollBounds().getHeight() > 0); + + party = tmp.getValue(); + partyID = tmp.getID(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.party_invite", + party.getProperties().getProperty( + NativeProps.NAME))).setAlignment(1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + flName = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(32, 32, 72, -48), 0), "", + FieldFilterString.INSTANCE); + flName.setMaxLength(16); + flName.setWatermark("Username"); + cvBackground.addPanel(flName); + + PanelButton btnInvite = + new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, new GuiPadding(-72, 32, 32, -48), 0), 1, + QuestTranslation.translate("betterquesting.btn.party_invite")); + cvBackground.addPanel(btnInvite); + + CanvasScrolling cvNameList = + new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(32, 64, 40, 32), 0)); + cvBackground.addPanel(cvNameList); + + PanelVScrollBar scNameScroll = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); + cvBackground.addPanel(scNameScroll); + scNameScroll.getTransform().setParent(cvNameList.getTransform()); + cvNameList.setScrollDriverY(scNameScroll); + + int listWidth = cvBackground.getTransform().getWidth() - 64; + int nameSize = RenderUtils.getStringWidth("________________", fontRenderer); + int columnNum = listWidth / nameSize; + + List nameList = new ArrayList<>(); + mc.player.connection.getPlayerInfoMap().forEach((info) -> nameList.add(info.getGameProfile().getName())); + + nameList.removeIf((entry) -> { + UUID memID = NameCache.INSTANCE.getUUID(entry); + return memID != null && party.getStatus(memID) != null; + }); + + for (int i = 0; i < nameList.size(); i++) { + int x1 = i % columnNum; + int y1 = i / columnNum; + String name = nameList.get(i); + PanelButtonStorage btnName = + new PanelButtonStorage<>(new GuiRectangle(x1 * nameSize, y1 * 16, nameSize, 16), 2, name, name); + cvNameList.addPanel(btnName); } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + scNameScroll.setActive(cvNameList.getScrollBounds().getHeight() > 0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit + { + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 1 && !flName.getRawText().isEmpty()) // Manual Invite + { + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 3); + payload.setInteger("partyID", partyID); + payload.setString("username", flName.getRawText()); + payload.setLong("expiry", 300000L); // 5 minutes in milliseconds + NetPartyAction.sendAction(payload); + } else if (btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Invite { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 1 && flName.getRawText().length() > 0) // Manual Invite - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 3); - payload.setInteger("partyID", partyID); - payload.setString("username", flName.getRawText()); - payload.setLong("expiry", 300000L); // 5 minutes in milliseconds - NetPartyAction.sendAction(payload); - } else if(btn.getButtonID() == 2 && btn instanceof PanelButtonStorage) // Invite - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 3); - payload.setInteger("partyID", partyID); - payload.setString("username", ((PanelButtonStorage)btn).getStoredValue()); - payload.setLong("expiry", 300000L); // 5 minutes in milliseconds - NetPartyAction.sendAction(payload); - } + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 3); + payload.setInteger("partyID", partyID); + payload.setString("username", ((PanelButtonStorage) btn).getStoredValue()); + payload.setLong("expiry", 300000L); // 5 minutes in milliseconds + NetPartyAction.sendAction(payload); } + } } diff --git a/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java b/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java index 0947ef942..a5074fb96 100644 --- a/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java +++ b/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java @@ -46,209 +46,220 @@ import java.util.List; import java.util.UUID; -public class GuiPartyManage extends GuiScreenCanvas implements IPEventListener, INeedsRefresh -{ - private IParty party; - private int partyID = -1; - private PanelTextField flName; - private PanelVScrollBar scUserList; - - public GuiPartyManage(GuiScreen parent) - { - super(parent); +public class GuiPartyManage extends GuiScreenCanvas implements IPEventListener, INeedsRefresh { + private IParty party; + private int partyID = -1; + private PanelTextField flName; + private PanelVScrollBar scUserList; + + public GuiPartyManage(GuiScreen parent) { + super(parent); + } + + @Override + public void refreshGui() { + UUID playerID = QuestingAPI.getQuestingUUID(mc.player); + + DBEntry tmp = PartyManager.INSTANCE.getParty(playerID); + + if (tmp == null) { + mc.displayGuiScreen(new GuiPartyCreate(parent)); + return; } - - @Override - public void refreshGui() - { - UUID playerID = QuestingAPI.getQuestingUUID(mc.player); - - DBEntry tmp = PartyManager.INSTANCE.getParty(playerID); - - if(tmp == null) - { - mc.displayGuiScreen(new GuiPartyCreate(parent)); - return; - } - - party = tmp.getValue(); - partyID = tmp.getID(); - - if(!flName.isFocused()) flName.setText(party.getProperties().getProperty(NativeProps.NAME)); - - initPanel(); + + party = tmp.getValue(); + partyID = tmp.getID(); + + if (!flName.isFocused()) { flName.setText(party.getProperties().getProperty(NativeProps.NAME)); } + + initPanel(); + } + + @Override + public void initPanel() { + super.initPanel(); + + UUID playerID = QuestingAPI.getQuestingUUID(mc.player); + + DBEntry tmp = PartyManager.INSTANCE.getParty(playerID); + + if (tmp == null) { + mc.displayGuiScreen(new GuiPartyCreate(parent)); + return; } - - @Override - public void initPanel() - { - super.initPanel(); - - UUID playerID = QuestingAPI.getQuestingUUID(mc.player); - - DBEntry tmp = PartyManager.INSTANCE.getParty(playerID); - - if(tmp == null) - { - mc.displayGuiScreen(new GuiPartyCreate(parent)); - return; - } - - party = tmp.getValue(); - partyID = tmp.getID(); - - PEventBroadcaster.INSTANCE.register(this, PEventButton.class); - Keyboard.enableRepeatEvents(true); - - // 0 = INVITE, 1 = MEMBER, 2 = ADMIN, 3 = OWNER/OP - EnumPartyStatus status = NameCache.INSTANCE.isOP(playerID) ? EnumPartyStatus.OWNER : party.getStatus(playerID); - if(status == null) status = EnumPartyStatus.MEMBER; // Fallback (potentially exploitable I know) - - // Background panel - CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); - - cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); - - PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.party", party.getProperties().getProperty(NativeProps.NAME))).setAlignment(1); - txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); - cvBackground.addPanel(txTitle); - - // Left side - - CanvasEmpty cvLeftHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 64, 8, 64), 0)); - cvBackground.addPanel(cvLeftHalf); - - PanelButtonStorage btnLeave = new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, -75, 32, 70, 16, 0), 3, QuestTranslation.translate("betterquesting.btn.party_leave"), mc.player.getGameProfile().getName()); - cvLeftHalf.addPanel(btnLeave); - - PanelButton btnInvite = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 5, 32, 70, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.party_invite")); - cvLeftHalf.addPanel(btnInvite); - btnInvite.setActive(status.ordinal() >= EnumPartyStatus.ADMIN.ordinal()); - - if(flName == null) flName = new PanelTextField<>(new GuiTransform(GuiAlign.MID_CENTER, -75, -32, 134, 16, 0), party.getProperties().getProperty(NativeProps.NAME), FieldFilterString.INSTANCE); - cvLeftHalf.addPanel(flName); - flName.setActive(status.ordinal() >= EnumPartyStatus.OWNER.ordinal()); - - PanelButton btnSetName = new PanelButton(new GuiTransform(GuiAlign.RIGHT_EDGE, 0, 0, 16, 16, 0), 4, ""); - cvLeftHalf.addPanel(btnSetName); - btnSetName.getTransform().setParent(flName.getTransform()); - btnSetName.setIcon(PresetIcon.ICON_REFRESH.getTexture()); - btnSetName.setActive(status.ordinal() >= EnumPartyStatus.OWNER.ordinal()); - - PanelTextBox txName = new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -75, -48, 134, 16, 0), QuestTranslation.translate("betterquesting.gui.name")); - txName.setColor(PresetColor.TEXT_HEADER.getColor()); - cvLeftHalf.addPanel(txName); - - // Right side - - CanvasEmpty cvRightHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); - cvBackground.addPanel(cvRightHalf); - - PanelTextBox txInvite = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), QuestTranslation.translate("betterquesting.gui.party_members")).setAlignment(1); - txInvite.setColor(PresetColor.TEXT_HEADER.getColor()); - cvRightHalf.addPanel(txInvite); - - CanvasScrolling cvUserList = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); - cvRightHalf.addPanel(cvUserList); - - if(scUserList == null) scUserList = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); - cvRightHalf.addPanel(scUserList); - scUserList.getTransform().setParent(cvUserList.getTransform()); - cvUserList.setScrollDriverY(scUserList); - - List partyMemList = party.getMembers(); - int elSize = RenderUtils.getStringWidth("...", fontRenderer); - int cvWidth = cvUserList.getTransform().getWidth(); - boolean hardcore = QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); - ItemTexture txHeart = new ItemTexture(new BigItemStack(BetterQuesting.extraLife)); - - for(int i = 0; i < partyMemList.size(); i++) - { - UUID mid = partyMemList.get(i); - String mName = NameCache.INSTANCE.getName(mid); - - if(RenderUtils.getStringWidth(mName, fontRenderer) > cvWidth - 58) - { - mName = mc.fontRenderer.trimStringToWidth(mName, cvWidth - 58 - elSize) + "..."; - } - - PanelPlayerPortrait pnPortrait = new PanelPlayerPortrait(new GuiRectangle(0, i * 32, 32, 32, 0), mid, mName); - cvUserList.addPanel(pnPortrait); - - PanelTextBox txMemName = new PanelTextBox(new GuiRectangle(32, i * 32 + 4, cvWidth - 32, 12, 0), mName); - txMemName.setColor(PresetColor.TEXT_MAIN.getColor()); - cvUserList.addPanel(txMemName); - - PanelButtonStorage btnKick = new PanelButtonStorage<>(new GuiRectangle(cvWidth - 32, i * 32, 32, 32, 0), 3, QuestTranslation.translate("betterquesting.btn.party_kick"), mName); - cvUserList.addPanel(btnKick); - - PanelGeneric pnItem = new PanelGeneric(new GuiRectangle(32, i * 32 + 16, 16, 16, 0), txHeart); - cvUserList.addPanel(pnItem); - - String lifeCount; - - if(hardcore) - { - lifeCount = " x " + LifeDatabase.INSTANCE.getLives(mid); - } else - { - lifeCount = " x \u221E"; - } - - PanelTextBox txLives = new PanelTextBox(new GuiRectangle(48, i * 32 + 20, cvWidth - 48 - 32, 12, 0), lifeCount); - txLives.setColor(PresetColor.TEXT_MAIN.getColor()); - cvUserList.addPanel(txLives); - } - - scUserList.setActive(cvUserList.getScrollBounds().getHeight() > 0); - - // Divider - - IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); - ls0.setParent(cvBackground.getTransform()); - IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); - le0.setParent(cvBackground.getTransform()); - PanelLine paLine0 = new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); - cvBackground.addPanel(paLine0); + + party = tmp.getValue(); + partyID = tmp.getID(); + + PEventBroadcaster.INSTANCE.register(this, PEventButton.class); + Keyboard.enableRepeatEvents(true); + + // 0 = INVITE, 1 = MEMBER, 2 = ADMIN, 3 = OWNER/OP + EnumPartyStatus status = NameCache.INSTANCE.isOP(playerID) ? EnumPartyStatus.OWNER : party.getStatus(playerID); + if (status == null) { + status = EnumPartyStatus.MEMBER; // Fallback (potentially exploitable I know) } - - @Override - public void onPanelEvent(PanelEvent event) - { - if(event instanceof PEventButton) - { - onButtonPress((PEventButton)event); - } + + // Background panel + CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvBackground); + + cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, + QuestTranslation.translate("gui.back"))); + + PanelTextBox txTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), + QuestTranslation.translate("betterquesting.title.party", + party.getProperties().getProperty( + NativeProps.NAME))).setAlignment(1); + txTitle.setColor(PresetColor.TEXT_HEADER.getColor()); + cvBackground.addPanel(txTitle); + + // Left side + + CanvasEmpty cvLeftHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(16, 64, 8, 64), 0)); + cvBackground.addPanel(cvLeftHalf); + + PanelButtonStorage btnLeave = + new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, -75, 32, 70, 16, 0), 3, + QuestTranslation.translate("betterquesting.btn.party_leave"), + mc.player.getGameProfile().getName()); + cvLeftHalf.addPanel(btnLeave); + + PanelButton btnInvite = new PanelButton(new GuiTransform(GuiAlign.MID_CENTER, 5, 32, 70, 16, 0), 2, + QuestTranslation.translate("betterquesting.btn.party_invite")); + cvLeftHalf.addPanel(btnInvite); + btnInvite.setActive(status.ordinal() >= EnumPartyStatus.ADMIN.ordinal()); + + if (flName == null) { + flName = new PanelTextField<>(new GuiTransform(GuiAlign.MID_CENTER, -75, -32, 134, 16, 0), + party.getProperties().getProperty(NativeProps.NAME), + FieldFilterString.INSTANCE); } - - @SuppressWarnings("unchecked") - private void onButtonPress(PEventButton event) + cvLeftHalf.addPanel(flName); + flName.setActive(status.ordinal() >= EnumPartyStatus.OWNER.ordinal()); + + PanelButton btnSetName = new PanelButton(new GuiTransform(GuiAlign.RIGHT_EDGE, 0, 0, 16, 16, 0), 4, ""); + cvLeftHalf.addPanel(btnSetName); + btnSetName.getTransform().setParent(flName.getTransform()); + btnSetName.setIcon(PresetIcon.ICON_REFRESH.getTexture()); + btnSetName.setActive(status.ordinal() >= EnumPartyStatus.OWNER.ordinal()); + + PanelTextBox txName = new PanelTextBox(new GuiTransform(GuiAlign.MID_CENTER, -75, -48, 134, 16, 0), + QuestTranslation.translate("betterquesting.gui.name")); + txName.setColor(PresetColor.TEXT_HEADER.getColor()); + cvLeftHalf.addPanel(txName); + + // Right side + + CanvasEmpty cvRightHalf = new CanvasEmpty(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 32, 16, 32), 0)); + cvBackground.addPanel(cvRightHalf); + + PanelTextBox txInvite = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 0, 0, -16), 0), + QuestTranslation.translate( + "betterquesting.gui.party_members")).setAlignment(1); + txInvite.setColor(PresetColor.TEXT_HEADER.getColor()); + cvRightHalf.addPanel(txInvite); + + CanvasScrolling cvUserList = + new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 16, 8, 0), 0)); + cvRightHalf.addPanel(cvUserList); + + if (scUserList == null) { + scUserList = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(0, 0, -8, 0), 0)); + } + cvRightHalf.addPanel(scUserList); + scUserList.getTransform().setParent(cvUserList.getTransform()); + cvUserList.setScrollDriverY(scUserList); + + List partyMemList = party.getMembers(); + int elSize = RenderUtils.getStringWidth("...", fontRenderer); + int cvWidth = cvUserList.getTransform().getWidth(); + boolean hardcore = QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); + ItemTexture txHeart = new ItemTexture(new BigItemStack(BetterQuesting.extraLife)); + + for (int i = 0; i < partyMemList.size(); i++) { + UUID mid = partyMemList.get(i); + String mName = NameCache.INSTANCE.getName(mid); + + if (RenderUtils.getStringWidth(mName, fontRenderer) > cvWidth - 58) { + mName = mc.fontRenderer.trimStringToWidth(mName, cvWidth - 58 - elSize) + "..."; + } + + PanelPlayerPortrait pnPortrait = new PanelPlayerPortrait(new GuiRectangle(0, i * 32, 32, 32, 0), mid, mName); + cvUserList.addPanel(pnPortrait); + + PanelTextBox txMemName = new PanelTextBox(new GuiRectangle(32, i * 32 + 4, cvWidth - 32, 12, 0), mName); + txMemName.setColor(PresetColor.TEXT_MAIN.getColor()); + cvUserList.addPanel(txMemName); + + PanelButtonStorage btnKick = + new PanelButtonStorage<>(new GuiRectangle(cvWidth - 32, i * 32, 32, 32, 0), 3, + QuestTranslation.translate("betterquesting.btn.party_kick"), mName); + cvUserList.addPanel(btnKick); + + PanelGeneric pnItem = new PanelGeneric(new GuiRectangle(32, i * 32 + 16, 16, 16, 0), txHeart); + cvUserList.addPanel(pnItem); + + String lifeCount; + + if (hardcore) { + lifeCount = " x " + LifeDatabase.INSTANCE.getLives(mid); + } else { + lifeCount = " x ∞"; + } + + PanelTextBox txLives = new PanelTextBox(new GuiRectangle(48, i * 32 + 20, cvWidth - 48 - 32, 12, 0), lifeCount); + txLives.setColor(PresetColor.TEXT_MAIN.getColor()); + cvUserList.addPanel(txLives); + } + + scUserList.setActive(cvUserList.getScrollBounds().getHeight() > 0); + + // Divider + + IGuiRect ls0 = new GuiTransform(GuiAlign.TOP_CENTER, 0, 32, 0, 0, 0); + ls0.setParent(cvBackground.getTransform()); + IGuiRect le0 = new GuiTransform(GuiAlign.BOTTOM_CENTER, 0, -32, 0, 0, 0); + le0.setParent(cvBackground.getTransform()); + PanelLine paLine0 = + new PanelLine(ls0, le0, PresetLine.GUI_DIVIDER.getLine(), 1, PresetColor.GUI_DIVIDER.getColor(), 1); + cvBackground.addPanel(paLine0); + } + + @Override + public void onPanelEvent(PanelEvent event) { + if (event instanceof PEventButton) { + onButtonPress((PEventButton) event); + } + } + + @SuppressWarnings("unchecked") + private void onButtonPress(PEventButton event) { + IPanelButton btn = event.getButton(); + + if (btn.getButtonID() == 0) // Exit + { + mc.displayGuiScreen(this.parent); + } else if (btn.getButtonID() == 2) // Invite + { + mc.displayGuiScreen(new GuiPartyInvite(this)); + } else if (btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Kick/Leave + { + String id = ((PanelButtonStorage) btn).getStoredValue(); + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 5); + payload.setInteger("partyID", partyID); + payload.setString("username", id); + NetPartyAction.sendAction(payload); + } else if (btn.getButtonID() == 4) // Change name { - IPanelButton btn = event.getButton(); - - if(btn.getButtonID() == 0) // Exit - { - mc.displayGuiScreen(this.parent); - } else if(btn.getButtonID() == 2) // Invite - { - mc.displayGuiScreen(new GuiPartyInvite(this)); - } else if(btn.getButtonID() == 3 && btn instanceof PanelButtonStorage) // Kick/Leave - { - String id = ((PanelButtonStorage)btn).getStoredValue(); - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 5); - payload.setInteger("partyID", partyID); - payload.setString("username", id); - NetPartyAction.sendAction(payload); - } else if(btn.getButtonID() == 4) // Change name - { - party.getProperties().setProperty(NativeProps.NAME, flName.getRawText()); - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 2); - payload.setInteger("partyID", partyID); - payload.setTag("data", party.writeProperties(new NBTTagCompound())); - NetPartyAction.sendAction(payload); - } + party.getProperties().setProperty(NativeProps.NAME, flName.getRawText()); + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 2); + payload.setInteger("partyID", partyID); + payload.setTag("data", party.writeProperties(new NBTTagCompound())); + NetPartyAction.sendAction(payload); } + } } diff --git a/src/main/java/betterquesting/client/gui3/GuiStatus.java b/src/main/java/betterquesting/client/gui3/GuiStatus.java index 3655eadeb..6c320552d 100644 --- a/src/main/java/betterquesting/client/gui3/GuiStatus.java +++ b/src/main/java/betterquesting/client/gui3/GuiStatus.java @@ -16,93 +16,102 @@ import net.minecraft.client.gui.GuiScreen; import org.lwjgl.util.vector.Vector4f; -public class GuiStatus extends GuiScreenCanvas -{ - public GuiStatus(GuiScreen parent) - { - super(parent); - } - - @Override - public void initPanel() - { - super.initPanel(); - - // === BACKGROUND PANEL === - CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(bgCan); - - CanvasHoverTray cvHover = new CanvasHoverTray(new GuiTransform(GuiAlign.MID_CENTER, 16, 16, 16, 16, 0), new GuiTransform(GuiAlign.MID_CENTER, 16, 16, 64, 64, 5), PresetTexture.PANEL_DARK.getTexture()); - bgCan.addPanel(cvHover); - cvHover.getCanvasClosed().addPanel(new PanelGeneric(new GuiTransform(), PresetIcon.ICON_CROSS.getTexture())); - cvHover.getCanvasOpen().addPanel(new PanelGeneric(new GuiTransform(), PresetIcon.ICON_TICK.getTexture())); - - // === SIDE BAR === - - CanvasTextured bgSideBar = new CanvasTextured(new GuiTransform(new Vector4f(0F, 0F, 0.2F, 1F), new GuiPadding(8, 24, 4, 24), 0), PresetTexture.PANEL_INNER.getTexture()); - bgCan.addPanel(bgSideBar); - - CanvasScrolling cvBtnList = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 8, 0), 0)); - bgSideBar.addPanel(cvBtnList); - - PanelVScrollBar scBtnList = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 0, 0, 0), 0)); - bgSideBar.addPanel(scBtnList); - cvBtnList.setScrollDriverY(scBtnList); - - int lw = cvBtnList.getTransform().getWidth(); - int i = 0; - - PanelButton btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Status"); - cvBtnList.addPanel(btnEntry); - - btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Equip"); - cvBtnList.addPanel(btnEntry); - - btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Quests"); - cvBtnList.addPanel(btnEntry); - - btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Guild"); - cvBtnList.addPanel(btnEntry); - - btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Trade"); - cvBtnList.addPanel(btnEntry); - - // === QUICK BAR === (Settings, Party, Inbox, Theme) - - CanvasTextured bgQuickBar = new CanvasTextured(new GuiTransform(new Vector4f(0F, 1F, 0.2F, 1F), new GuiPadding(8, -24, 4, 8), 0), PresetTexture.PANEL_INNER.getTexture()); - bgCan.addPanel(bgQuickBar); - - PanelButton btnSettings = new PanelButton(new GuiTransform(new Vector4f(0F, 0F, 0.25F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); - btnSettings.setIcon(PresetIcon.ICON_GEAR.getTexture()); - bgQuickBar.addPanel(btnSettings); - - PanelButton btnParty = new PanelButton(new GuiTransform(new Vector4f(0.25F, 0F, 0.5F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); - btnParty.setIcon(PresetIcon.ICON_PARTY.getTexture()); - bgQuickBar.addPanel(btnParty); - - PanelButton btnInbox = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 0.75F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); - btnInbox.setIcon(PresetIcon.ICON_NOTICE.getTexture()); - bgQuickBar.addPanel(btnInbox); - - PanelButton btnTheme = new PanelButton(new GuiTransform(new Vector4f(0.75F, 0F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); - btnTheme.setIcon(PresetIcon.ICON_THEME.getTexture()); - bgQuickBar.addPanel(btnTheme); - - // === OUTER CHARACTER PANEL === - - //CanvasTextured bgChar = new CanvasTextured(new GuiTransform(new Vector4f(0.2F, 0F, 1F, 1F), new GuiPadding(4, 24, 8, 48), 0), PresetTexture.PANEL_INNER.getTexture()); - //bgCan.addPanel(bgChar); - - // === CHARACTER PREVIEW === - - //PanelEntityPreview pvChar = new PanelEntityPreview(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(0, 0, 4, 8), 0), mc.player); - //bgChar.addPanel(pvChar); - //pvChar.setRotationFixed(-15F, 0F); - - // === EQUIPMENT SLOTS === - - // === LEVEL + XP BAR === - - // === STAT LIST === - } +public class GuiStatus extends GuiScreenCanvas { + public GuiStatus(GuiScreen parent) { + super(parent); + } + + @Override + public void initPanel() { + super.initPanel(); + + // === BACKGROUND PANEL === + CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(bgCan); + + CanvasHoverTray cvHover = new CanvasHoverTray(new GuiTransform(GuiAlign.MID_CENTER, 16, 16, 16, 16, 0), + new GuiTransform(GuiAlign.MID_CENTER, 16, 16, 64, 64, 5), + PresetTexture.PANEL_DARK.getTexture()); + bgCan.addPanel(cvHover); + cvHover.getCanvasClosed().addPanel(new PanelGeneric(new GuiTransform(), PresetIcon.ICON_CROSS.getTexture())); + cvHover.getCanvasOpen().addPanel(new PanelGeneric(new GuiTransform(), PresetIcon.ICON_TICK.getTexture())); + + // === SIDE BAR === + + CanvasTextured bgSideBar = + new CanvasTextured(new GuiTransform(new Vector4f(0F, 0F, 0.2F, 1F), new GuiPadding(8, 24, 4, 24), 0), + PresetTexture.PANEL_INNER.getTexture()); + bgCan.addPanel(bgSideBar); + + CanvasScrolling cvBtnList = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 8, 0), 0)); + bgSideBar.addPanel(cvBtnList); + + PanelVScrollBar scBtnList = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 0, 0, 0), 0)); + bgSideBar.addPanel(scBtnList); + cvBtnList.setScrollDriverY(scBtnList); + + int lw = cvBtnList.getTransform().getWidth(); + int i = 0; + + PanelButton btnEntry = new PanelButton(new GuiRectangle(0, 0, lw, 16, 0), 0, "Status"); + cvBtnList.addPanel(btnEntry); + + btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Equip"); + cvBtnList.addPanel(btnEntry); + + btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Quests"); + cvBtnList.addPanel(btnEntry); + + btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Guild"); + cvBtnList.addPanel(btnEntry); + + btnEntry = new PanelButton(new GuiRectangle(0, i++ * 24, lw, 16, 0), 0, "Trade"); + cvBtnList.addPanel(btnEntry); + + // === QUICK BAR === (Settings, Party, Inbox, Theme) + + CanvasTextured bgQuickBar = + new CanvasTextured(new GuiTransform(new Vector4f(0F, 1F, 0.2F, 1F), new GuiPadding(8, -24, 4, 8), 0), + PresetTexture.PANEL_INNER.getTexture()); + bgCan.addPanel(bgQuickBar); + + PanelButton btnSettings = + new PanelButton(new GuiTransform(new Vector4f(0F, 0F, 0.25F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); + btnSettings.setIcon(PresetIcon.ICON_GEAR.getTexture()); + bgQuickBar.addPanel(btnSettings); + + PanelButton btnParty = + new PanelButton(new GuiTransform(new Vector4f(0.25F, 0F, 0.5F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); + btnParty.setIcon(PresetIcon.ICON_PARTY.getTexture()); + bgQuickBar.addPanel(btnParty); + + PanelButton btnInbox = + new PanelButton(new GuiTransform(new Vector4f(0.5F, 0F, 0.75F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); + btnInbox.setIcon(PresetIcon.ICON_NOTICE.getTexture()); + bgQuickBar.addPanel(btnInbox); + + PanelButton btnTheme = + new PanelButton(new GuiTransform(new Vector4f(0.75F, 0F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), 0, ""); + btnTheme.setIcon(PresetIcon.ICON_THEME.getTexture()); + bgQuickBar.addPanel(btnTheme); + + // === OUTER CHARACTER PANEL === + + //CanvasTextured bgChar = new CanvasTextured(new GuiTransform(new Vector4f(0.2F, 0F, 1F, 1F), new GuiPadding(4, 24, 8, 48), 0), PresetTexture.PANEL_INNER.getTexture()); + //bgCan.addPanel(bgChar); + + // === CHARACTER PREVIEW === + + //PanelEntityPreview pvChar = new PanelEntityPreview(new GuiTransform(GuiAlign.HALF_LEFT, new GuiPadding(0, 0, 4, 8), 0), mc.player); + //bgChar.addPanel(pvChar); + //pvChar.setRotationFixed(-15F, 0F); + + // === EQUIPMENT SLOTS === + + // === LEVEL + XP BAR === + + // === STAT LIST === + } } diff --git a/src/main/java/betterquesting/client/importers/ImportedQuestLines.java b/src/main/java/betterquesting/client/importers/ImportedQuestLines.java index c94a41468..6255a8ecc 100644 --- a/src/main/java/betterquesting/client/importers/ImportedQuestLines.java +++ b/src/main/java/betterquesting/client/importers/ImportedQuestLines.java @@ -14,119 +14,100 @@ import java.util.HashMap; import java.util.List; -public class ImportedQuestLines extends SimpleDatabase implements IQuestLineDatabase -{ - private final List lineOrder = new ArrayList<>(); - private final QuestLineSorter SORTER = new QuestLineSorter(this); - - @Override - public int getOrderIndex(int lineID) - { - synchronized(lineOrder) - { - if(getValue(lineID) == null) - { - return -1; - } else if(!lineOrder.contains(lineID)) - { - lineOrder.add(lineID); - } - - return lineOrder.indexOf(lineID); - } - } - - @Override - public void setOrderIndex(int lineID, int index) - { - synchronized(lineOrder) - { - lineOrder.remove((Integer)lineID); - lineOrder.add(index, lineID); - } - } - - @Override - public List> getSortedEntries() - { - List> ary = new ArrayList<>(getEntries()); - ary.sort(SORTER); - return ary; - } - - @Override - public NBTTagList writeToNBT(NBTTagList json, List subset) - { - for(DBEntry entry : getEntries()) - { - if(subset != null && !subset.contains(entry.getID())) continue; - NBTTagCompound jObj = entry.getValue().writeToNBT(new NBTTagCompound(), null); - jObj.setInteger("lineID", entry.getID()); - jObj.setInteger("order", getOrderIndex(entry.getID())); - json.appendTag(jObj); - } - - return json; - } - - @Override - public void readFromNBT(NBTTagList json, boolean merge) - { - if(!merge) reset(); - - List unassigned = new ArrayList<>(); - HashMap orderMap = new HashMap<>(); - - for(int i = 0; i < json.tagCount(); i++) - { - NBTTagCompound jql = json.getCompoundTagAt(i); - - int id = jql.hasKey("lineID", 99) ? jql.getInteger("lineID") : -1; - int order = jql.hasKey("order", 99) ? jql.getInteger("order") : -1; - QuestLine line = new QuestLine(); - line.readFromNBT(jql, merge); - - if(id >= 0) - { - add(id, line); - } else - { - unassigned.add(line); - } - - if(order >= 0) - { - orderMap.put(order, id); - } - } - - // Legacy support ONLY - for(IQuestLine q : unassigned) add(nextID(), q); - - List orderKeys = new ArrayList<>(orderMap.keySet()); - Collections.sort(orderKeys); - - synchronized(lineOrder) - { - lineOrder.clear(); - for(int o : orderKeys) lineOrder.add(orderMap.get(o)); - } - } - - @Override - public void removeQuest(int questID) - { - for(DBEntry ql : getEntries()) - { - ql.getValue().removeID(questID); - } - } - - @Override - public IQuestLine createNew(int id) - { - QuestLine ql = new QuestLine(); - add(id, ql); - return ql; - } +public class ImportedQuestLines extends SimpleDatabase implements IQuestLineDatabase { + private final List lineOrder = new ArrayList<>(); + private final QuestLineSorter SORTER = new QuestLineSorter(this); + + @Override + public int getOrderIndex(int lineID) { + synchronized (lineOrder) { + if (getValue(lineID) == null) { + return -1; + } else if (!lineOrder.contains(lineID)) { + lineOrder.add(lineID); + } + + return lineOrder.indexOf(lineID); + } + } + + @Override + public void setOrderIndex(int lineID, int index) { + synchronized (lineOrder) { + lineOrder.remove((Integer) lineID); + lineOrder.add(index, lineID); + } + } + + @Override + public List> getSortedEntries() { + List> ary = new ArrayList<>(getEntries()); + ary.sort(SORTER); + return ary; + } + + @Override + public NBTTagList writeToNBT(NBTTagList json, List subset) { + for (DBEntry entry : getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { continue; } + NBTTagCompound jObj = entry.getValue().writeToNBT(new NBTTagCompound(), null); + jObj.setInteger("lineID", entry.getID()); + jObj.setInteger("order", getOrderIndex(entry.getID())); + json.appendTag(jObj); + } + + return json; + } + + @Override + public void readFromNBT(NBTTagList json, boolean merge) { + if (!merge) { reset(); } + + List unassigned = new ArrayList<>(); + HashMap orderMap = new HashMap<>(); + + for (int i = 0; i < json.tagCount(); i++) { + NBTTagCompound jql = json.getCompoundTagAt(i); + + int id = jql.hasKey("lineID", 99) ? jql.getInteger("lineID") : -1; + int order = jql.hasKey("order", 99) ? jql.getInteger("order") : -1; + QuestLine line = new QuestLine(); + line.readFromNBT(jql, merge); + + if (id >= 0) { + add(id, line); + } else { + unassigned.add(line); + } + + if (order >= 0) { + orderMap.put(order, id); + } + } + + // Legacy support ONLY + for (IQuestLine q : unassigned) { add(nextID(), q); } + + List orderKeys = new ArrayList<>(orderMap.keySet()); + Collections.sort(orderKeys); + + synchronized (lineOrder) { + lineOrder.clear(); + for (int o : orderKeys) { lineOrder.add(orderMap.get(o)); } + } + } + + @Override + public void removeQuest(int questID) { + for (DBEntry ql : getEntries()) { + ql.getValue().removeID(questID); + } + } + + @Override + public IQuestLine createNew(int id) { + QuestLine ql = new QuestLine(); + add(id, ql); + return ql; + } } diff --git a/src/main/java/betterquesting/client/importers/ImportedQuests.java b/src/main/java/betterquesting/client/importers/ImportedQuests.java index 1817a9764..ca90c82a0 100644 --- a/src/main/java/betterquesting/client/importers/ImportedQuests.java +++ b/src/main/java/betterquesting/client/importers/ImportedQuests.java @@ -14,74 +14,63 @@ import java.util.List; import java.util.UUID; -public class ImportedQuests extends SimpleDatabase implements IQuestDatabase -{ - @Override - public IQuest createNew(int id) - { - return this.add(id, new QuestInstance()).getValue(); - } - - @Override - public List> bulkLookup(int... ids) - { - if(ids == null || ids.length <= 0) return Collections.emptyList(); - - List> values = new ArrayList<>(); - - synchronized(this) - { - for(int i : ids) - { - IQuest v = getValue(i); - if(v != null) values.add(new DBEntry<>(i, v)); - } - } - - return values; +public class ImportedQuests extends SimpleDatabase implements IQuestDatabase { + @Override + public IQuest createNew(int id) { + return this.add(id, new QuestInstance()).getValue(); + } + + @Override + public List> bulkLookup(int... ids) { + if (ids == null || ids.length == 0) { return Collections.emptyList(); } + + List> values = new ArrayList<>(); + + synchronized (this) { + for (int i : ids) { + IQuest v = getValue(i); + if (v != null) { values.add(new DBEntry<>(i, v)); } + } } - - @Override - public NBTTagList writeToNBT(NBTTagList nbt, List subset) - { - for(DBEntry entry : this.getEntries()) - { - if(subset != null && !subset.contains(entry.getID())) continue; - NBTTagCompound jq = new NBTTagCompound(); - entry.getValue().writeToNBT(jq); - jq.setInteger("questID", entry.getID()); - nbt.appendTag(jq); - } - - return nbt; - } - - @Override - public void readFromNBT(NBTTagList nbt, boolean merge) - { - if(!merge) this.reset(); - - for(int i = 0; i < nbt.tagCount(); i++) - { - NBTTagCompound qTag = nbt.getCompoundTagAt(i); - - int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; - if(qID < 0) continue; - - IQuest quest = getValue(qID); - quest = quest != null? quest : this.createNew(qID); - quest.readFromNBT(qTag); - } - } - - @Override - public NBTTagList writeProgressToNBT(NBTTagList nbt, @Nullable List users) - { - return nbt; + + return values; + } + + @Override + public NBTTagList writeToNBT(NBTTagList nbt, List subset) { + for (DBEntry entry : this.getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { continue; } + NBTTagCompound jq = new NBTTagCompound(); + entry.getValue().writeToNBT(jq); + jq.setInteger("questID", entry.getID()); + nbt.appendTag(jq); } - - @Override - public void readProgressFromNBT(NBTTagList nbt, boolean merge) - { + + return nbt; + } + + @Override + public void readFromNBT(NBTTagList nbt, boolean merge) { + if (!merge) { this.reset(); } + + for (int i = 0; i < nbt.tagCount(); i++) { + NBTTagCompound qTag = nbt.getCompoundTagAt(i); + + int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; + if (qID < 0) { continue; } + + IQuest quest = getValue(qID); + quest = quest != null ? quest : this.createNew(qID); + quest.readFromNBT(qTag); } + } + + @Override + public NBTTagList writeProgressToNBT(NBTTagList nbt, @Nullable List users) { + return nbt; + } + + @Override + public void readProgressFromNBT(NBTTagList nbt, boolean merge) { + } } diff --git a/src/main/java/betterquesting/client/importers/ImporterRegistry.java b/src/main/java/betterquesting/client/importers/ImporterRegistry.java index f35c8d94b..80385c7e9 100644 --- a/src/main/java/betterquesting/client/importers/ImporterRegistry.java +++ b/src/main/java/betterquesting/client/importers/ImporterRegistry.java @@ -6,31 +6,26 @@ import java.util.ArrayList; import java.util.List; -public final class ImporterRegistry implements IImportRegistry -{ - public static final ImporterRegistry INSTANCE = new ImporterRegistry(); - - private final List importers = new ArrayList<>(); - - @Override - public void registerImporter(IImporter imp) - { - if(imp == null) - { - throw new NullPointerException("Tried to register null quest importer"); - } - - if(importers.contains(imp)) - { - throw new IllegalArgumentException("Unable to register duplicate quest importer"); - } - - importers.add(imp); - } - - @Override - public List getImporters() - { - return importers; - } +public final class ImporterRegistry implements IImportRegistry { + public static final ImporterRegistry INSTANCE = new ImporterRegistry(); + + private final List importers = new ArrayList<>(); + + @Override + public void registerImporter(IImporter imp) { + if (imp == null) { + throw new NullPointerException("Tried to register null quest importer"); + } + + if (importers.contains(imp)) { + throw new IllegalArgumentException("Unable to register duplicate quest importer"); + } + + importers.add(imp); + } + + @Override + public List getImporters() { + return importers; + } } diff --git a/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java b/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java index c1610c310..b5054b878 100644 --- a/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java +++ b/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java @@ -1,29 +1,26 @@ package betterquesting.client.renderer; +import betterquesting.api.placeholders.EntityPlaceholder; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.item.EntityItem; import net.minecraft.util.ResourceLocation; -import betterquesting.api.placeholders.EntityPlaceholder; -public class EntityPlaceholderRenderer extends Render -{ - protected EntityPlaceholderRenderer(RenderManager renderManager) - { - super(renderManager); - } +import javax.annotation.Nonnull; + +public class EntityPlaceholderRenderer extends Render { + protected EntityPlaceholderRenderer(RenderManager renderManager) { + super(renderManager); + } - @Override - public void doRender(EntityPlaceholder entity, double x, double y, double z, float yaw, float partialTick) - { - EntityItem item = entity.GetItemEntity(); - this.renderManager.renderEntity(item, x, y + 1D, z, yaw, partialTick, false); - } + @Override + public void doRender(EntityPlaceholder entity, double x, double y, double z, float yaw, float partialTick) { + EntityItem item = entity.GetItemEntity(); + this.renderManager.renderEntity(item, x, y + 1D, z, yaw, partialTick, false); + } - @Override - protected ResourceLocation getEntityTexture(EntityPlaceholder entity) - { - return null; - } - + @Override + protected ResourceLocation getEntityTexture(@Nonnull EntityPlaceholder entity) { + return null; + } } diff --git a/src/main/java/betterquesting/client/renderer/PlaceholderRenderFactory.java b/src/main/java/betterquesting/client/renderer/PlaceholderRenderFactory.java index 09b4a4cf1..e358c6c37 100644 --- a/src/main/java/betterquesting/client/renderer/PlaceholderRenderFactory.java +++ b/src/main/java/betterquesting/client/renderer/PlaceholderRenderFactory.java @@ -1,17 +1,15 @@ package betterquesting.client.renderer; +import betterquesting.api.placeholders.EntityPlaceholder; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraftforge.fml.client.registry.IRenderFactory; -import betterquesting.api.placeholders.EntityPlaceholder; -public class PlaceholderRenderFactory implements IRenderFactory -{ +public class PlaceholderRenderFactory implements IRenderFactory { + + @Override + public Render createRenderFor(RenderManager manager) { + return new EntityPlaceholderRenderer(manager); + } - @Override - public Render createRenderFor(RenderManager manager) - { - return new EntityPlaceholderRenderer(manager); - } - } diff --git a/src/main/java/betterquesting/client/themes/ResourceRegistry.java b/src/main/java/betterquesting/client/themes/ResourceRegistry.java index 0752ee194..0190e3601 100644 --- a/src/main/java/betterquesting/client/themes/ResourceRegistry.java +++ b/src/main/java/betterquesting/client/themes/ResourceRegistry.java @@ -10,58 +10,53 @@ import betterquesting.api2.client.gui.resources.lines.IGuiLine; import betterquesting.api2.client.gui.resources.textures.IGuiTexture; import betterquesting.api2.client.gui.themes.IResourceReg; -import betterquesting.api2.registry.*; +import betterquesting.api2.registry.FunctionRegistry; +import betterquesting.api2.registry.IFactoryData; import com.google.gson.JsonObject; -public class ResourceRegistry implements IResourceReg -{ - public static final ResourceRegistry INSTANCE = new ResourceRegistry(); - - private final FunctionRegistry TEX_REG = new FunctionRegistry<>(); - private final FunctionRegistry COL_REG = new FunctionRegistry<>(); - private final FunctionRegistry LIN_REG = new FunctionRegistry<>(); - - public ResourceRegistry() - { - // NOTE: Only going to cover the basics here. Advanced GUI elements would be better suited to code based themes - lazyRegister(TEX_REG, FactorySimpleTexture.INSTANCE, new JsonObject()); - lazyRegister(TEX_REG, FactorySlicedTexture.INSTANCE, new JsonObject()); - lazyRegister(TEX_REG, FactoryLayeredTexture.INSTANCE, new JsonObject()); - lazyRegister(TEX_REG, FactoryColorTexture.INSTANCE, new JsonObject()); - lazyRegister(TEX_REG, FactoryEmptyTexture.INSTANCE, new JsonObject()); - lazyRegister(TEX_REG, FactoryPolyTextureR.INSTANCE, new JsonObject()); - lazyRegister(TEX_REG, FactoryPolyTextureC.INSTANCE, new JsonObject()); - - lazyRegister(COL_REG, FactoryColorStatic.INSTANCE, new JsonObject()); - lazyRegister(COL_REG, FactoryColorSequence.INSTANCE, new JsonObject()); - lazyRegister(COL_REG, FactoryColorPulse.INSTANCE, new JsonObject()); - - lazyRegister(LIN_REG, FactorySimpleLine.INSTANCE, new JsonObject()); - lazyRegister(LIN_REG, FactoryLineTaxiCab.INSTANCE, new JsonObject()); - } - - private void lazyRegister(FunctionRegistry reg, IFactoryData factory, E template) - { - reg.register(factory.getRegistryName(), factory::loadFromData, template); - } - - @Override - public FunctionRegistry getTexReg() - { - return TEX_REG; - } - - @Override - public FunctionRegistry getColorReg() - { - return COL_REG; - } - - @Override - public FunctionRegistry getLineReg() - { - return LIN_REG; - } - - // TODO: Sounds? +public class ResourceRegistry implements IResourceReg { + public static final ResourceRegistry INSTANCE = new ResourceRegistry(); + + private final FunctionRegistry TEX_REG = new FunctionRegistry<>(); + private final FunctionRegistry COL_REG = new FunctionRegistry<>(); + private final FunctionRegistry LIN_REG = new FunctionRegistry<>(); + + public ResourceRegistry() { + // NOTE: Only going to cover the basics here. Advanced GUI elements would be better suited to code based themes + lazyRegister(TEX_REG, FactorySimpleTexture.INSTANCE, new JsonObject()); + lazyRegister(TEX_REG, FactorySlicedTexture.INSTANCE, new JsonObject()); + lazyRegister(TEX_REG, FactoryLayeredTexture.INSTANCE, new JsonObject()); + lazyRegister(TEX_REG, FactoryColorTexture.INSTANCE, new JsonObject()); + lazyRegister(TEX_REG, FactoryEmptyTexture.INSTANCE, new JsonObject()); + lazyRegister(TEX_REG, FactoryPolyTextureR.INSTANCE, new JsonObject()); + lazyRegister(TEX_REG, FactoryPolyTextureC.INSTANCE, new JsonObject()); + + lazyRegister(COL_REG, FactoryColorStatic.INSTANCE, new JsonObject()); + lazyRegister(COL_REG, FactoryColorSequence.INSTANCE, new JsonObject()); + lazyRegister(COL_REG, FactoryColorPulse.INSTANCE, new JsonObject()); + + lazyRegister(LIN_REG, FactorySimpleLine.INSTANCE, new JsonObject()); + lazyRegister(LIN_REG, FactoryLineTaxiCab.INSTANCE, new JsonObject()); + } + + private void lazyRegister(FunctionRegistry reg, IFactoryData factory, E template) { + reg.register(factory.getRegistryName(), factory::loadFromData, template); + } + + @Override + public FunctionRegistry getTexReg() { + return TEX_REG; + } + + @Override + public FunctionRegistry getColorReg() { + return COL_REG; + } + + @Override + public FunctionRegistry getLineReg() { + return LIN_REG; + } + + // TODO: Sounds? } diff --git a/src/main/java/betterquesting/client/themes/ResourceTheme.java b/src/main/java/betterquesting/client/themes/ResourceTheme.java index 030042dc9..7e2b42f5c 100644 --- a/src/main/java/betterquesting/client/themes/ResourceTheme.java +++ b/src/main/java/betterquesting/client/themes/ResourceTheme.java @@ -17,173 +17,151 @@ import java.util.Map.Entry; import java.util.function.Function; -public class ResourceTheme implements IGuiTheme -{ - private final ResourceLocation ID; - private final String dispName; - - private IGuiTheme parentTheme; - private ResourceLocation parentID; - private boolean cached = false; - - private final HashMap TEX_MAP = new HashMap<>(); - private final HashMap COLOR_MAP = new HashMap<>(); - private final HashMap LINE_MAP = new HashMap<>(); - - public ResourceTheme(ResourceLocation parentID, ResourceLocation id, String dispName) - { - this.ID = id; - this.dispName = dispName; - this.parentID = parentID; - } - - public void loadFromJson(JsonObject jThm) - { - JsonObject jsonTextureRoot = JsonHelper.GetObject(jThm, "textures"); - for(Entry entry : jsonTextureRoot.entrySet()) - { - if(!entry.getValue().isJsonObject()) continue; - JsonObject joTex = entry.getValue().getAsJsonObject(); - - ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joTex, "textureType", "")); - IGuiTexture gTex = ResourceRegistry.INSTANCE.getTexReg().createNew(typeID, joTex); - - if(gTex == null) - { - BetterQuesting.logger.error("Failed to load texture type " + typeID + " for theme " + ID); - continue; - } - - this.setTexture(new ResourceLocation(entry.getKey()), gTex); - } - - JsonObject jsonColourRoot = JsonHelper.GetObject(jThm, "colors"); - for(Entry entry : jsonColourRoot.entrySet()) - { - if(!(entry.getValue() instanceof JsonObject)) continue; - JsonObject joCol = entry.getValue().getAsJsonObject(); - - ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joCol, "colorType", "")); - IGuiColor gCol = ResourceRegistry.INSTANCE.getColorReg().createNew(typeID, joCol); - - if(gCol == null) - { - BetterQuesting.logger.error("Failed to load color type " + typeID + " for theme " + ID); - continue; - } - - this.setColor(new ResourceLocation(entry.getKey()), gCol); - } - - JsonObject jsonLinesRoot = JsonHelper.GetObject(jThm, "lines"); - for(Entry entry : jsonLinesRoot.entrySet()) - { - if(!(entry.getValue() instanceof JsonObject)) continue; - JsonObject joLine = entry.getValue().getAsJsonObject(); - - ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joLine, "lineType", "")); - IGuiLine gLine = ResourceRegistry.INSTANCE.getLineReg().createNew(typeID, joLine); - - if(gLine == null) - { - BetterQuesting.logger.error("Failed to load line type " + typeID + " for theme " + ID); - continue; - } - - this.setLine(new ResourceLocation(entry.getKey()), gLine); - } - } - - private IGuiTheme getParent() - { - if(cached) return parentTheme; - - IGuiTheme parent = ThemeRegistry.INSTANCE.getTheme(parentID); - IGuiTheme checking = parent; - while(checking != null) - { - if(checking instanceof ResourceTheme) - { - if(((ResourceTheme)checking).parentTheme == this) - { - BetterQuesting.logger.error("Circular reference in resource theme " + ID); - this.parentTheme = null; - cached = true; - return null; - } - checking = ((ResourceTheme)checking).parentTheme; - continue; - } - break; - } - - this.parentTheme = parent; - cached = true; - - return this.parentTheme; - } - - public void setTexture(ResourceLocation key, IGuiTexture texture) - { - if(key == null) return; - TEX_MAP.put(key, texture); // Could actually use null here to override the parent - } - - public void setColor(ResourceLocation key, IGuiColor color) - { - if(key == null) return; - COLOR_MAP.put(key, color); // Could actually use null here to override the parent - } - - public void setLine(ResourceLocation key, IGuiLine line) - { - if(key == null) return; - LINE_MAP.put(key, line); // Could actually use null here to override the parent - } - - @Override - public String getName() - { - return dispName; - } - - @Override - public ResourceLocation getID() - { - return ID; - } - - @Override - public IGuiTexture getTexture(ResourceLocation key) - { - IGuiTexture value = TEX_MAP.get(key); - if(value != null) return value; - if(getParent() != null) return getParent().getTexture(key); - return null; +public class ResourceTheme implements IGuiTheme { + private final ResourceLocation ID; + private final String dispName; + + private IGuiTheme parentTheme; + private final ResourceLocation parentID; + private boolean cached = false; + + private final HashMap TEX_MAP = new HashMap<>(); + private final HashMap COLOR_MAP = new HashMap<>(); + private final HashMap LINE_MAP = new HashMap<>(); + + public ResourceTheme(ResourceLocation parentID, ResourceLocation id, String dispName) { + this.ID = id; + this.dispName = dispName; + this.parentID = parentID; + } + + public void loadFromJson(JsonObject jThm) { + JsonObject jsonTextureRoot = JsonHelper.GetObject(jThm, "textures"); + for (Entry entry : jsonTextureRoot.entrySet()) { + if (!entry.getValue().isJsonObject()) { continue; } + JsonObject joTex = entry.getValue().getAsJsonObject(); + + ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joTex, "textureType", "")); + IGuiTexture gTex = ResourceRegistry.INSTANCE.getTexReg().createNew(typeID, joTex); + + if (gTex == null) { + BetterQuesting.logger.error("Failed to load texture type " + typeID + " for theme " + ID); + continue; + } + + this.setTexture(new ResourceLocation(entry.getKey()), gTex); } - - @Override - public IGuiLine getLine(ResourceLocation key) - { - IGuiLine value = LINE_MAP.get(key); - if(value != null) return value; - if(getParent() != null) return getParent().getLine(key); - return null; + + JsonObject jsonColourRoot = JsonHelper.GetObject(jThm, "colors"); + for (Entry entry : jsonColourRoot.entrySet()) { + if (!(entry.getValue() instanceof JsonObject)) { continue; } + JsonObject joCol = entry.getValue().getAsJsonObject(); + + ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joCol, "colorType", "")); + IGuiColor gCol = ResourceRegistry.INSTANCE.getColorReg().createNew(typeID, joCol); + + if (gCol == null) { + BetterQuesting.logger.error("Failed to load color type " + typeID + " for theme " + ID); + continue; + } + + this.setColor(new ResourceLocation(entry.getKey()), gCol); } - - @Override - public IGuiColor getColor(ResourceLocation key) - { - IGuiColor value = COLOR_MAP.get(key); - if(value != null) return value; - if(getParent() != null) return getParent().getColor(key); - return null; + + JsonObject jsonLinesRoot = JsonHelper.GetObject(jThm, "lines"); + for (Entry entry : jsonLinesRoot.entrySet()) { + if (!(entry.getValue() instanceof JsonObject)) { continue; } + JsonObject joLine = entry.getValue().getAsJsonObject(); + + ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joLine, "lineType", "")); + IGuiLine gLine = ResourceRegistry.INSTANCE.getLineReg().createNew(typeID, joLine); + + if (gLine == null) { + BetterQuesting.logger.error("Failed to load line type " + typeID + " for theme " + ID); + continue; + } + + this.setLine(new ResourceLocation(entry.getKey()), gLine); } - - @Nullable - @Override - public Function getGui(GuiKey key) - { - return null; + } + + private IGuiTheme getParent() { + if (cached) { return parentTheme; } + + IGuiTheme parent = ThemeRegistry.INSTANCE.getTheme(parentID); + IGuiTheme checking = parent; + while (checking != null) { + if (checking instanceof ResourceTheme) { + if (((ResourceTheme) checking).parentTheme == this) { + BetterQuesting.logger.error("Circular reference in resource theme " + ID); + this.parentTheme = null; + cached = true; + return null; + } + checking = ((ResourceTheme) checking).parentTheme; + continue; + } + break; } + + this.parentTheme = parent; + cached = true; + + return this.parentTheme; + } + + public void setTexture(ResourceLocation key, IGuiTexture texture) { + if (key == null) { return; } + TEX_MAP.put(key, texture); // Could actually use null here to override the parent + } + + public void setColor(ResourceLocation key, IGuiColor color) { + if (key == null) { return; } + COLOR_MAP.put(key, color); // Could actually use null here to override the parent + } + + public void setLine(ResourceLocation key, IGuiLine line) { + if (key == null) { return; } + LINE_MAP.put(key, line); // Could actually use null here to override the parent + } + + @Override + public String getName() { + return dispName; + } + + @Override + public ResourceLocation getID() { + return ID; + } + + @Override + public IGuiTexture getTexture(ResourceLocation key) { + IGuiTexture value = TEX_MAP.get(key); + if (value != null) { return value; } + if (getParent() != null) { return getParent().getTexture(key); } + return null; + } + + @Override + public IGuiLine getLine(ResourceLocation key) { + IGuiLine value = LINE_MAP.get(key); + if (value != null) { return value; } + if (getParent() != null) { return getParent().getLine(key); } + return null; + } + + @Override + public IGuiColor getColor(ResourceLocation key) { + IGuiColor value = COLOR_MAP.get(key); + if (value != null) { return value; } + if (getParent() != null) { return getParent().getColor(key); } + return null; + } + + @Nullable + @Override + public Function getGui(GuiKey key) { + return null; + } } diff --git a/src/main/java/betterquesting/client/themes/ThemeRegistry.java b/src/main/java/betterquesting/client/themes/ThemeRegistry.java index c9bc31f06..08d286661 100644 --- a/src/main/java/betterquesting/client/themes/ThemeRegistry.java +++ b/src/main/java/betterquesting/client/themes/ThemeRegistry.java @@ -1,5 +1,6 @@ package betterquesting.client.themes; +import betterquesting.api.misc.ICallback; import betterquesting.api.storage.BQ_Settings; import betterquesting.api.utils.JsonHelper; import betterquesting.api2.client.gui.misc.GuiPadding; @@ -41,323 +42,289 @@ import java.util.List; import java.util.function.Function; -public class ThemeRegistry implements IThemeRegistry -{ - public static final ThemeRegistry INSTANCE = new ThemeRegistry(); - - private static final IGuiTexture NULL_TEXTURE = new SlicedTexture(PresetTexture.TX_NULL, new GuiRectangle(0,0,32,32), new GuiPadding(8,8,8,8)); - private static final IGuiLine NULL_LINE = new SimpleLine(); - private static final IGuiColor NULL_COLOR = new GuiColorStatic(0xFF000000); - - private final HashMap defTextures = new HashMap<>(); - private final HashMap defLines = new HashMap<>(); - private final HashMap defColors = new HashMap<>(); - private final HashMap, Function> defGuis = new HashMap<>(); - - private final HashMap themes = new HashMap<>(); - private final List loadedThemes = new ArrayList<>(); - - private final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - private IGuiTheme activeTheme = null; - - private boolean setup = false; - - public ThemeRegistry() - { - PresetTexture.registerTextures(this); - PresetIcon.registerIcons(this); - PresetLine.registerLines(this); - PresetColor.registerColors(this); - - setDefaultGui(PresetGUIs.HOME, arg -> new GuiHome(arg.parent)); - - setDefaultGui(PresetGUIs.EDIT_NBT, arg -> - { - if(arg.value instanceof NBTTagCompound) - { - //noinspection unchecked - return new GuiNbtEditor(arg.parent, (NBTTagCompound)arg.value, arg.callback); - } else if(arg.value instanceof NBTTagList) - { - //noinspection unchecked - return new GuiNbtEditor(arg.parent, (NBTTagList)arg.value, arg.callback); - } else - { - return null; - } - }); - - setDefaultGui(PresetGUIs.EDIT_ITEM, arg -> new GuiItemSelection(arg.parent, arg.value, arg.callback)); - setDefaultGui(PresetGUIs.EDIT_FLUID, arg -> new GuiFluidSelection(arg.parent, arg.value, arg.callback)); - setDefaultGui(PresetGUIs.EDIT_ENTITY, arg -> new GuiEntitySelection(arg.parent, arg.value, arg.callback)); - setDefaultGui(PresetGUIs.EDIT_TEXT, arg -> new GuiTextEditor(arg.parent, arg.value, arg.callback)); - setDefaultGui(PresetGUIs.FILE_EXPLORE, arg -> new GuiFileBrowser(arg.parent, arg.callback, arg.root, arg.filter).allowMultiSelect(arg.multiSelect)); - } - - @Override - public void registerTheme(IGuiTheme theme) - { - if(theme == null || theme.getID() == null) - { - throw new NullPointerException("Cannot register null theme"); - } else if(themes.containsKey(theme.getID())) - { - //throw new IllegalArgumentException("Cannot register duplicate theme: " + theme.getID()); - } - - themes.put(theme.getID(), theme); - - if(activeTheme == null) setup = false; // A theme was registered that could possibly resolve the currently configured theme - } - - /** - * Sets the default fallback texture. Only use if you're defining your own custom texture ID - */ - @Override - public void setDefaultTexture(ResourceLocation key, IGuiTexture tex) - { - if(key == null || tex == null) - { - throw new NullPointerException("Tried to register a default theme texture with one or more NULL arguments"); - } - - defTextures.put(key, tex); - } - - /** - * Sets the default fallback texture. Only use if you're defining your own custom texture ID - */ - @Override - public void setDefaultLine(ResourceLocation key, IGuiLine line) - { - if(key == null || line == null) - { - throw new NullPointerException("Tried to register a default theme line with one or more NULL arguments"); - } - - defLines.put(key, line); - } - - /** - * Sets the default fallback texture. Only use if you're defining your own custom texture ID - */ - @Override - public void setDefaultColor(ResourceLocation key, IGuiColor color) - { - if(key == null || color == null) - { - throw new NullPointerException("Tried to register default theme colour with one or more NULL arguments"); - } - - defColors.put(key, color); - } - - @Override - public void setDefaultGui(GuiKey key, Function func) +public class ThemeRegistry implements IThemeRegistry { + public static final ThemeRegistry INSTANCE = new ThemeRegistry(); + + private static final IGuiTexture NULL_TEXTURE = + new SlicedTexture(PresetTexture.TX_NULL, new GuiRectangle(0, 0, 32, 32), new GuiPadding(8, 8, 8, 8)); + private static final IGuiLine NULL_LINE = new SimpleLine(); + private static final IGuiColor NULL_COLOR = new GuiColorStatic(0xFF000000); + + private final HashMap defTextures = new HashMap<>(); + private final HashMap defLines = new HashMap<>(); + private final HashMap defColors = new HashMap<>(); + private final HashMap, Function> defGuis = new HashMap<>(); + + private final HashMap themes = new HashMap<>(); + private final List loadedThemes = new ArrayList<>(); + + private final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + private IGuiTheme activeTheme = null; + + private boolean setup = false; + + public ThemeRegistry() { + PresetTexture.registerTextures(this); + PresetIcon.registerIcons(this); + PresetLine.registerLines(this); + PresetColor.registerColors(this); + + setDefaultGui(PresetGUIs.HOME, arg -> new GuiHome(arg.parent)); + + setDefaultGui(PresetGUIs.EDIT_NBT, arg -> { - if(key == null || func == null) - { - throw new NullPointerException("Tried to register a default gui with one or more NULL arguments"); - } - - defGuis.put(key, func); + if (arg.value instanceof NBTTagCompound) { + //noinspection unchecked + return new GuiNbtEditor(arg.parent, (NBTTagCompound) arg.value, (ICallback) arg.callback); + } else if (arg.value instanceof NBTTagList) { + //noinspection unchecked + return new GuiNbtEditor(arg.parent, (NBTTagList) arg.value, (ICallback) arg.callback); + } else { + return null; + } + }); + + setDefaultGui(PresetGUIs.EDIT_ITEM, arg -> new GuiItemSelection(arg.parent, arg.value, arg.callback)); + setDefaultGui(PresetGUIs.EDIT_FLUID, arg -> new GuiFluidSelection(arg.parent, arg.value, arg.callback)); + setDefaultGui(PresetGUIs.EDIT_ENTITY, arg -> new GuiEntitySelection(arg.parent, arg.value, arg.callback)); + setDefaultGui(PresetGUIs.EDIT_TEXT, arg -> new GuiTextEditor(arg.parent, arg.value, arg.callback)); + setDefaultGui(PresetGUIs.FILE_EXPLORE, + arg -> new GuiFileBrowser(arg.parent, arg.callback, arg.root, arg.filter).allowMultiSelect( + arg.multiSelect)); + } + + @Override + public void registerTheme(IGuiTheme theme) { + if (theme == null || theme.getID() == null) { + throw new NullPointerException("Cannot register null theme"); + } else if (themes.containsKey(theme.getID())) { + //throw new IllegalArgumentException("Cannot register duplicate theme: " + theme.getID()); } - - @Override - public void setTheme(ResourceLocation id) - { - setTheme(themes.get(id), id); - } - - @Override - public IGuiTheme getTheme(ResourceLocation key) - { - if(key == null) return null; - return themes.get(key); + + themes.put(theme.getID(), theme); + + if (activeTheme == null) { + setup = false; // A theme was registered that could possibly resolve the currently configured theme } - - private void setTheme(IGuiTheme theme, ResourceLocation id) - { - this.activeTheme = theme; - - BQ_Settings.curTheme = id == null ? "" : id.toString(); - - if(ConfigHandler.config != null) - { - ConfigHandler.config.get(Configuration.CATEGORY_GENERAL, "Theme", "").set(BQ_Settings.curTheme); - ConfigHandler.config.save(); - } else - { - BetterQuesting.logger.log(Level.WARN, "Unable to save theme setting"); - } - } - - @Override - public IGuiTheme getCurrentTheme() - { - if(!setup && this.activeTheme == null) - { - this.activeTheme = this.getTheme(new ResourceLocation(BQ_Settings.curTheme)); - setup = true; - } - - return this.activeTheme; - } - - @Override - public void loadResourceThemes() - { - loadedThemes.forEach(themes::remove); - loadedThemes.clear(); - - IResourceManager resManager = Minecraft.getMinecraft().getResourceManager(); - - for(String domain : resManager.getResourceDomains()) - { - ResourceLocation res = new ResourceLocation(domain, "bq_themes.json"); - List list; - - try - { - list = resManager.getAllResources(res); - } catch (Exception e) { continue; } // Not going to log errors everytime the file isn't found - - for(IResource iresource : list) - { - try(InputStreamReader isr = new InputStreamReader(iresource.getInputStream(), StandardCharsets.UTF_8)) - { - JsonArray jAry = GSON.fromJson(isr, JsonArray.class); - isr.close(); - - for(int i = 0; i < jAry.size(); i++) - { - JsonElement je = jAry.get(i); - - if(!(je instanceof JsonObject)) - { - BetterQuesting.logger.log(Level.WARN, "Invalid theme entry at index " + i + " in " + iresource.getResourceLocation()); - continue; - } - - JsonObject jThm = je.getAsJsonObject(); - - if(jThm.has("themeType")) - { - BetterQuesting.logger.warn("Deprecated legacy theme entry " + i + " in " + iresource.getResourceLocation()); - BetterQuesting.logger.warn("Please convert this to the new format"); - continue; - } - - ResourceLocation parentID = !jThm.has("themeParent") ? null : new ResourceLocation(JsonHelper.GetString(jThm, "themeParent", "minecraft:null")); - String themeName = JsonHelper.GetString(jThm, "themeName", "Unnamed Theme"); - String idRaw = JsonHelper.GetString(jThm, "themeID", themeName); - idRaw = idRaw.toLowerCase().trim().replaceAll(" ", "_"); - if(!idRaw.contains(":")) idRaw = domain + ":" + idRaw; - ResourceLocation themeId = new ResourceLocation(idRaw); - - int n = 0; - while(themes.containsKey(themeId)) themeId = new ResourceLocation(domain, idRaw + n++); - - ResourceTheme resTheme; - - try - { - resTheme = new ResourceTheme(parentID, themeId, themeName); - } catch(Exception e) - { - BetterQuesting.logger.error("Failed to load theme entry " + i + " in " + iresource.getResourceLocation(), e); - continue; - } - - resTheme.loadFromJson(jThm); - themes.put(resTheme.getID(), resTheme); - loadedThemes.add(resTheme.getID()); - } - } catch (Exception e) - { - BetterQuesting.logger.error("Error reading bq_themes.json from " + iresource.getResourceLocation(), e); - } - } - } + } + + /** + * Sets the default fallback texture. Only use if you're defining your own custom texture ID + */ + @Override + public void setDefaultTexture(ResourceLocation key, IGuiTexture tex) { + if (key == null || tex == null) { + throw new NullPointerException("Tried to register a default theme texture with one or more NULL arguments"); } - - @Override - public IGuiTexture getTexture(ResourceLocation key) - { - if(key == null) return NULL_TEXTURE; - - IGuiTexture tex = null; - - if(getCurrentTheme() != null) tex = activeTheme.getTexture(key); - if(tex == null) tex = defTextures.get(key); - return tex == null? NULL_TEXTURE : tex; - } - - @Override - public IGuiLine getLine(ResourceLocation key) - { - if(key == null) return NULL_LINE; - - IGuiLine line = null; - - if(getCurrentTheme() != null) line = activeTheme.getLine(key); - if(line == null) line = defLines.get(key); - return line == null? NULL_LINE : line; - } - - @Override - public IGuiColor getColor(ResourceLocation key) - { - if(key == null) return NULL_COLOR; - - IGuiColor color = null; - - if(getCurrentTheme() != null) color = activeTheme.getColor(key); - if(color == null) color = defColors.get(key); - return color == null? NULL_COLOR : color; - } - - @Override - @SuppressWarnings("unchecked") - public GuiScreen getGui(GuiKey key, T args) - { - if(key == null) return null; - - Function func = null; - - if(getCurrentTheme() != null) func = activeTheme.getGui(key); - if(func == null) func = (Function)defGuis.get(key); - - return func == null ? null : func.apply(args); + + defTextures.put(key, tex); + } + + /** + * Sets the default fallback texture. Only use if you're defining your own custom texture ID + */ + @Override + public void setDefaultLine(ResourceLocation key, IGuiLine line) { + if (key == null || line == null) { + throw new NullPointerException("Tried to register a default theme line with one or more NULL arguments"); } - - @Override - public List getAllThemes() - { - return new ArrayList<>(themes.values()); - } - - @Override - public ResourceLocation[] getKnownTextures() - { - return defTextures.keySet().toArray(new ResourceLocation[0]); + + defLines.put(key, line); + } + + /** + * Sets the default fallback texture. Only use if you're defining your own custom texture ID + */ + @Override + public void setDefaultColor(ResourceLocation key, IGuiColor color) { + if (key == null || color == null) { + throw new NullPointerException("Tried to register default theme colour with one or more NULL arguments"); } - - @Override - public ResourceLocation[] getKnownColors() - { - return defColors.keySet().toArray(new ResourceLocation[0]); + + defColors.put(key, color); + } + + @Override + public void setDefaultGui(GuiKey key, Function func) { + if (key == null || func == null) { + throw new NullPointerException("Tried to register a default gui with one or more NULL arguments"); } - - @Override - public ResourceLocation[] getKnownLines() - { - return defLines.keySet().toArray(new ResourceLocation[0]); + + defGuis.put(key, func); + } + + @Override + public void setTheme(ResourceLocation id) { + setTheme(themes.get(id), id); + } + + @Override + public IGuiTheme getTheme(ResourceLocation key) { + if (key == null) { return null; } + return themes.get(key); + } + + private void setTheme(IGuiTheme theme, ResourceLocation id) { + this.activeTheme = theme; + + BQ_Settings.curTheme = id == null ? "" : id.toString(); + + if (ConfigHandler.config != null) { + ConfigHandler.config.get(Configuration.CATEGORY_GENERAL, "Theme", "").set(BQ_Settings.curTheme); + ConfigHandler.config.save(); + } else { + BetterQuesting.logger.log(Level.WARN, "Unable to save theme setting"); } - - @Override - public GuiKey[] getKnownGuis() - { - return defGuis.keySet().toArray(new GuiKey[0]); + } + + @Override + public IGuiTheme getCurrentTheme() { + if (!setup && this.activeTheme == null) { + this.activeTheme = this.getTheme(new ResourceLocation(BQ_Settings.curTheme)); + setup = true; } + + return this.activeTheme; + } + + @Override + public void loadResourceThemes() { + loadedThemes.forEach(themes::remove); + loadedThemes.clear(); + + IResourceManager resManager = Minecraft.getMinecraft().getResourceManager(); + + for (String domain : resManager.getResourceDomains()) { + ResourceLocation res = new ResourceLocation(domain, "bq_themes.json"); + List list; + + try { + list = resManager.getAllResources(res); + } catch (Exception e) { continue; } // Not going to log errors everytime the file isn't found + + for (IResource iresource : list) { + try (InputStreamReader isr = new InputStreamReader(iresource.getInputStream(), StandardCharsets.UTF_8)) { + JsonArray jAry = GSON.fromJson(isr, JsonArray.class); + isr.close(); + + for (int i = 0; i < jAry.size(); i++) { + JsonElement je = jAry.get(i); + + if (!(je instanceof JsonObject)) { + BetterQuesting.logger.log(Level.WARN, + "Invalid theme entry at index " + i + " in " + iresource.getResourceLocation()); + continue; + } + + JsonObject jThm = je.getAsJsonObject(); + + if (jThm.has("themeType")) { + BetterQuesting.logger.warn( + "Deprecated legacy theme entry " + i + " in " + iresource.getResourceLocation()); + BetterQuesting.logger.warn("Please convert this to the new format"); + continue; + } + + ResourceLocation parentID = !jThm.has("themeParent") ? null : new ResourceLocation( + JsonHelper.GetString(jThm, "themeParent", "minecraft:null")); + String themeName = JsonHelper.GetString(jThm, "themeName", "Unnamed Theme"); + String idRaw = JsonHelper.GetString(jThm, "themeID", themeName); + idRaw = idRaw.toLowerCase().trim().replaceAll(" ", "_"); + if (!idRaw.contains(":")) { idRaw = domain + ":" + idRaw; } + ResourceLocation themeId = new ResourceLocation(idRaw); + + int n = 0; + while (themes.containsKey(themeId)) { themeId = new ResourceLocation(domain, idRaw + n++); } + + ResourceTheme resTheme; + + try { + resTheme = new ResourceTheme(parentID, themeId, themeName); + } catch (Exception e) { + BetterQuesting.logger.error("Failed to load theme entry " + i + " in " + iresource.getResourceLocation(), + e); + continue; + } + + resTheme.loadFromJson(jThm); + themes.put(resTheme.getID(), resTheme); + loadedThemes.add(resTheme.getID()); + } + } catch (Exception e) { + BetterQuesting.logger.error("Error reading bq_themes.json from " + iresource.getResourceLocation(), e); + } + } + } + } + + @Override + public IGuiTexture getTexture(ResourceLocation key) { + if (key == null) { return NULL_TEXTURE; } + + IGuiTexture tex = null; + + if (getCurrentTheme() != null) { tex = activeTheme.getTexture(key); } + if (tex == null) { tex = defTextures.get(key); } + return tex == null ? NULL_TEXTURE : tex; + } + + @Override + public IGuiLine getLine(ResourceLocation key) { + if (key == null) { return NULL_LINE; } + + IGuiLine line = null; + + if (getCurrentTheme() != null) { line = activeTheme.getLine(key); } + if (line == null) { line = defLines.get(key); } + return line == null ? NULL_LINE : line; + } + + @Override + public IGuiColor getColor(ResourceLocation key) { + if (key == null) { return NULL_COLOR; } + + IGuiColor color = null; + + if (getCurrentTheme() != null) { color = activeTheme.getColor(key); } + if (color == null) { color = defColors.get(key); } + return color == null ? NULL_COLOR : color; + } + + @Override + @SuppressWarnings("unchecked") + public GuiScreen getGui(GuiKey key, T args) { + if (key == null) { return null; } + + Function func = null; + + if (getCurrentTheme() != null) { func = activeTheme.getGui(key); } + if (func == null) { func = (Function) defGuis.get(key); } + + return func == null ? null : func.apply(args); + } + + @Override + public List getAllThemes() { + return new ArrayList<>(themes.values()); + } + + @Override + public ResourceLocation[] getKnownTextures() { + return defTextures.keySet().toArray(new ResourceLocation[0]); + } + + @Override + public ResourceLocation[] getKnownColors() { + return defColors.keySet().toArray(new ResourceLocation[0]); + } + + @Override + public ResourceLocation[] getKnownLines() { + return defLines.keySet().toArray(new ResourceLocation[0]); + } + + @Override + public GuiKey[] getKnownGuis() { + return defGuis.keySet().toArray(new GuiKey[0]); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/client/toolbox/PanelTabMain.java b/src/main/java/betterquesting/client/toolbox/PanelTabMain.java index 338d8de85..8437ae5c6 100644 --- a/src/main/java/betterquesting/client/toolbox/PanelTabMain.java +++ b/src/main/java/betterquesting/client/toolbox/PanelTabMain.java @@ -25,119 +25,140 @@ import java.util.ArrayList; import java.util.List; -public class PanelTabMain extends CanvasEmpty -{ - private final CanvasQuestLine cvQuestLine; - private final PanelToolController toolController; - - private static final List toolEntries = new ArrayList<>(); - - public PanelTabMain(IGuiRect rect, CanvasQuestLine cvQuestLine, PanelToolController toolController) - { - super(rect); - this.cvQuestLine = cvQuestLine; - this.toolController = toolController; - } - - @Override - public void initPanel() - { - super.initPanel(); - - int w = getTransform().getWidth(); - - IGuiColor tCol = new GuiColorStatic(0xFF000000); - this.addPanel(new PanelButton(new GuiRectangle(0, 0, w / 2, 16, 0), -1, "" + ToolboxTabMain.INSTANCE.getSnapValue()) - { - @Override - public void onButtonClick() - { - ToolboxTabMain.INSTANCE.toggleSnap(); - this.setText("" + ToolboxTabMain.INSTANCE.getSnapValue()); - } - }.setIcon(PresetIcon.ICON_GRID.getTexture()).setTextShadow(false).setTextHighlight(tCol, tCol, tCol).setTooltip(makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.snap.name"), QuestTranslation.translate("betterquesting.toolbox.tool.snap.desc")))); - - this.addPanel(new PanelButton(new GuiRectangle(w / 2, 0, w / 2, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - Minecraft mc = Minecraft.getMinecraft(); - mc.displayGuiScreen(new GuiNbtEditor(mc.currentScreen, cvQuestLine.getQuestLine().writeToNBT(new NBTTagCompound(), null), value -> { - NBTTagCompound payload = new NBTTagCompound(); - NBTTagList dataList = new NBTTagList(); - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("chapterID", QuestLineDatabase.INSTANCE.getID(cvQuestLine.getQuestLine())); - entry.setTag("config", value); - dataList.appendTag(entry); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetChapterEdit.sendEdit(payload); - })); - } - }.setIcon(PresetIcon.ICON_PROPS.getTexture()).setTooltip(makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.raw.name"), QuestTranslation.translate("betterquesting.toolbox.tool.raw.desc")))); - - final List> toolBtns = new ArrayList<>(); - - for(int i = 0; i < toolEntries.size(); i++) - { - ToolEntry entry = toolEntries.get(i); - int x = (i % 2) * (w / 2); - int y = (i / 2) * 16 + 24; - PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(x, y, w / 2, 16, 0), -1, "", entry.tool); - btn.setActive(toolController.getActiveTool() != entry.tool); - btn.setIcon(entry.tex).setTooltip(entry.tt); - btn.setCallback(value -> { - toolController.setActiveTool(value); - toolBtns.forEach(b -> b.setActive(true)); - btn.setActive(false); - }); - toolBtns.add(btn); - this.addPanel(btn); - - if(entry.tool instanceof ToolboxToolOpen && toolController.getActiveTool() == null) - { - toolController.setActiveTool(entry.tool); - btn.setActive(false); - } - } - } - - private static List makeToolTip(String title, String desc) - { - List list = new ArrayList<>(); - list.add(title); - list.addAll(Minecraft.getMinecraft().fontRenderer.listFormattedStringToWidth(TextFormatting.GRAY + desc, 128)); - return list; - } - - private static class ToolEntry - { - private final IToolboxTool tool; - private final IGuiTexture tex; - private final List tt; - - private ToolEntry(IToolboxTool tool, IGuiTexture tex, List tt) - { - this.tool = tool; - this.tex = tex; - this.tt = tt; - } +public class PanelTabMain extends CanvasEmpty { + private final CanvasQuestLine cvQuestLine; + private final PanelToolController toolController; + + private static final List toolEntries = new ArrayList<>(); + + public PanelTabMain(IGuiRect rect, CanvasQuestLine cvQuestLine, PanelToolController toolController) { + super(rect); + this.cvQuestLine = cvQuestLine; + this.toolController = toolController; + } + + @Override + public void initPanel() { + super.initPanel(); + + int w = getTransform().getWidth(); + + IGuiColor tCol = new GuiColorStatic(0xFF000000); + this.addPanel( + new PanelButton(new GuiRectangle(0, 0, w / 2, 16, 0), -1, "" + ToolboxTabMain.INSTANCE.getSnapValue()) { + @Override + public void onButtonClick() { + ToolboxTabMain.INSTANCE.toggleSnap(); + this.setText("" + ToolboxTabMain.INSTANCE.getSnapValue()); + } + }.setIcon(PresetIcon.ICON_GRID.getTexture()).setTextShadow(false).setTextHighlight(tCol, tCol, tCol).setTooltip( + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.snap.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.snap.desc")))); + + this.addPanel(new PanelButton(new GuiRectangle(w / 2, 0, w / 2, 16, 0), -1, "") { + @Override + public void onButtonClick() { + Minecraft mc = Minecraft.getMinecraft(); + mc.displayGuiScreen( + new GuiNbtEditor(mc.currentScreen, cvQuestLine.getQuestLine().writeToNBT(new NBTTagCompound(), null), + value -> { + NBTTagCompound payload = new NBTTagCompound(); + NBTTagList dataList = new NBTTagList(); + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("chapterID", + QuestLineDatabase.INSTANCE.getID(cvQuestLine.getQuestLine())); + entry.setTag("config", value); + dataList.appendTag(entry); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetChapterEdit.sendEdit(payload); + })); + } + }.setIcon(PresetIcon.ICON_PROPS.getTexture()).setTooltip( + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.raw.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.raw.desc")))); + + final List> toolBtns = new ArrayList<>(); + + for (int i = 0; i < toolEntries.size(); i++) { + ToolEntry entry = toolEntries.get(i); + int x = (i % 2) * (w / 2); + int y = (i / 2) * 16 + 24; + PanelButtonStorage btn = + new PanelButtonStorage<>(new GuiRectangle(x, y, w / 2, 16, 0), -1, "", entry.tool); + btn.setActive(toolController.getActiveTool() != entry.tool); + btn.setIcon(entry.tex).setTooltip(entry.tt); + btn.setCallback(value -> { + toolController.setActiveTool(value); + toolBtns.forEach(b -> b.setActive(true)); + btn.setActive(false); + }); + toolBtns.add(btn); + this.addPanel(btn); + + if (entry.tool instanceof ToolboxToolOpen && toolController.getActiveTool() == null) { + toolController.setActiveTool(entry.tool); + btn.setActive(false); + } } - - static - { - toolEntries.add(new ToolEntry(new ToolboxToolOpen(), PresetIcon.ICON_CURSOR.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.open.name"), QuestTranslation.translate("betterquesting.toolbox.tool.open.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolNew(), PresetIcon.ICON_NEW.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.new.name"), QuestTranslation.translate("betterquesting.toolbox.tool.new.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolGrab(), PresetIcon.ICON_GRAB.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.grab.name"), QuestTranslation.translate("betterquesting.toolbox.tool.grab.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolLink(), PresetIcon.ICON_LINK.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.link.name"), QuestTranslation.translate("betterquesting.toolbox.tool.link.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolCopy(), PresetIcon.ICON_COPY.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.copy.name"), QuestTranslation.translate("betterquesting.toolbox.tool.copy.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolScale(), PresetIcon.ICON_SCALE.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.scale.name"), QuestTranslation.translate("betterquesting.toolbox.tool.scale.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolDelete(), PresetIcon.ICON_TRASH.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.delete.name"), QuestTranslation.translate("betterquesting.toolbox.tool.delete.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolRemove(), PresetIcon.ICON_NEGATIVE.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.remove.name"), QuestTranslation.translate("betterquesting.toolbox.tool.remove.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolComplete(), PresetIcon.ICON_TICK.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.complete.name"), QuestTranslation.translate("betterquesting.toolbox.tool.complete.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolReset(), PresetIcon.ICON_REFRESH.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.reset.name"), QuestTranslation.translate("betterquesting.toolbox.tool.reset.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolIcon(), PresetIcon.ICON_ITEM.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.icon.name"), QuestTranslation.translate("betterquesting.toolbox.tool.icon.desc")))); - toolEntries.add(new ToolEntry(new ToolboxToolFrame(), PresetIcon.ICON_NOTICE.getTexture(), makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.frame.name"), QuestTranslation.translate("betterquesting.toolbox.tool.frame.desc")))); + } + + private static List makeToolTip(String title, String desc) { + List list = new ArrayList<>(); + list.add(title); + list.addAll(Minecraft.getMinecraft().fontRenderer.listFormattedStringToWidth(TextFormatting.GRAY + desc, 128)); + return list; + } + + private static class ToolEntry { + private final IToolboxTool tool; + private final IGuiTexture tex; + private final List tt; + + private ToolEntry(IToolboxTool tool, IGuiTexture tex, List tt) { + this.tool = tool; + this.tex = tex; + this.tt = tt; } + } + + static { + toolEntries.add(new ToolEntry(new ToolboxToolOpen(), PresetIcon.ICON_CURSOR.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.open.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.open.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolNew(), PresetIcon.ICON_NEW.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.new.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.new.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolGrab(), PresetIcon.ICON_GRAB.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.grab.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.grab.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolLink(), PresetIcon.ICON_LINK.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.link.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.link.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolCopy(), PresetIcon.ICON_COPY.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.copy.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.copy.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolScale(), PresetIcon.ICON_SCALE.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.scale.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.scale.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolDelete(), PresetIcon.ICON_TRASH.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.delete.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.delete.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolRemove(), PresetIcon.ICON_NEGATIVE.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.remove.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.remove.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolComplete(), PresetIcon.ICON_TICK.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.complete.name"), + QuestTranslation.translate( + "betterquesting.toolbox.tool.complete.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolReset(), PresetIcon.ICON_REFRESH.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.reset.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.reset.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolIcon(), PresetIcon.ICON_ITEM.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.icon.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.icon.desc")))); + toolEntries.add(new ToolEntry(new ToolboxToolFrame(), PresetIcon.ICON_NOTICE.getTexture(), + makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.frame.name"), + QuestTranslation.translate("betterquesting.toolbox.tool.frame.desc")))); + } } diff --git a/src/main/java/betterquesting/client/toolbox/ToolboxRegistry.java b/src/main/java/betterquesting/client/toolbox/ToolboxRegistry.java index 64f04c68d..345cdfc18 100644 --- a/src/main/java/betterquesting/client/toolbox/ToolboxRegistry.java +++ b/src/main/java/betterquesting/client/toolbox/ToolboxRegistry.java @@ -7,35 +7,29 @@ import java.util.Collection; import java.util.HashMap; -public class ToolboxRegistry implements IToolRegistry -{ - public static final ToolboxRegistry INSTANCE = new ToolboxRegistry(); - - private final HashMap toolTabs = new HashMap<>(); - - @Override - public void registerToolTab(ResourceLocation tabID, IToolTab tab) - { - if(tabID == null || tab == null) - { - throw new NullPointerException("Tried to register null tab or null ID"); - } else if(toolTabs.containsKey(tabID)) - { - throw new IllegalArgumentException("Cannot register duplicate tab ID: " + tabID); - } - - toolTabs.put(tabID, tab); - } - - @Override - public IToolTab getTabByID(ResourceLocation tabID) - { - return toolTabs.get(tabID); +public class ToolboxRegistry implements IToolRegistry { + public static final ToolboxRegistry INSTANCE = new ToolboxRegistry(); + + private final HashMap toolTabs = new HashMap<>(); + + @Override + public void registerToolTab(ResourceLocation tabID, IToolTab tab) { + if (tabID == null || tab == null) { + throw new NullPointerException("Tried to register null tab or null ID"); + } else if (toolTabs.containsKey(tabID)) { + throw new IllegalArgumentException("Cannot register duplicate tab ID: " + tabID); } - - @Override - public Collection getAllTabs() - { - return toolTabs.values(); - } + + toolTabs.put(tabID, tab); + } + + @Override + public IToolTab getTabByID(ResourceLocation tabID) { + return toolTabs.get(tabID); + } + + @Override + public Collection getAllTabs() { + return toolTabs.values(); + } } diff --git a/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java b/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java index a39d549e8..d338ae2f3 100644 --- a/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java +++ b/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java @@ -3,110 +3,97 @@ import betterquesting.api2.client.gui.misc.GuiRectangle; import betterquesting.api2.client.gui.misc.IGuiRect; import betterquesting.api2.client.gui.panels.IGuiPanel; +import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine; import betterquesting.api2.client.gui.resources.colors.IGuiColor; import betterquesting.api2.client.gui.resources.lines.IGuiLine; import betterquesting.api2.client.gui.themes.presets.PresetColor; import betterquesting.api2.client.gui.themes.presets.PresetLine; import betterquesting.api2.client.toolbox.IToolTab; -import betterquesting.api2.client.gui.panels.lists.CanvasQuestLine; import betterquesting.client.gui2.editors.designer.PanelToolController; -public class ToolboxTabMain implements IToolTab -{ - public static final ToolboxTabMain INSTANCE = new ToolboxTabMain(); - - private int dragSnap = 4; - private int[] snaps = new int[]{1,4,6,8,12,16,24,32}; - - @Override - public String getUnlocalisedName() - { - return "betterquesting.toolbox.tab.main"; - } - - @Override - public IGuiPanel getTabGui(IGuiRect rect, CanvasQuestLine cvQuestLine, PanelToolController toolController) - { - return new PanelTabMain(rect, cvQuestLine, toolController); - } - - public void toggleSnap() - { - dragSnap = (dragSnap + 1)%snaps.length; - } - - public int getSnapValue() - { - return snaps[dragSnap%snaps.length]; - } - - public int getSnapIndex() - { - return dragSnap; - } - - public void drawGrid(CanvasQuestLine ui) - { - if(getSnapValue() <= 1) return; - - float zs = ui.getZoom(); - int snap = getSnapValue(); - - float offX = -ui.getScrollX(); - offX = ((offX % snap + snap) % snap) * zs; - int midX = Math.floorDiv(-ui.getScrollX(), snap); - - float offY = -ui.getScrollY(); - offY = ((offY % snap + snap) % snap) * zs; - int midY = Math.floorDiv(-ui.getScrollY(), snap); - - int x = ui.getTransform().getX(); - int y = ui.getTransform().getY(); - int width = ui.getTransform().getWidth(); - int height = ui.getTransform().getHeight(); - int divX = (int)Math.ceil((width - offX) / (zs * snap)); - int divY = (int)Math.ceil((height - offY) / (zs * snap)); - - IGuiColor gMinor = PresetColor.GRID_MINOR.getColor(); - IGuiColor gMajor = PresetColor.GRID_MAJOR.getColor(); - IGuiLine lMinor = PresetLine.GRID_MINOR.getLine(); - IGuiLine lMajor = PresetLine.GRID_MAJOR.getLine(); - - GuiRectangle p1 = new GuiRectangle(0, 0, 0, 0); - GuiRectangle p2 = new GuiRectangle(0, 0, 0, 0); - - p1.y = y; - p2.y = y + height; - - for(int i = 0; i < divX; i++) - { - int lx = x + (int)(i * snap * zs + offX); - p1.x = lx; - p2.x = lx; - if(i == midX) - { - lMajor.drawLine(p1, p2, 2, gMajor, 1F); - } else - { - lMinor.drawLine(p1, p2, 1, gMinor, 1F); - } - } - - p1.x = x; - p2.x = x + width; - - for(int j = 0; j < divY; j++) - { - int ly = y + (int)(j * snap * zs + offY); - p1.y = ly; - p2.y = ly; - if(j == midY) - { - lMajor.drawLine(p1, p2, 2, gMajor, 1F); - } else - { - lMinor.drawLine(p1, p2, 1, gMinor, 1F); - } - } - } +public class ToolboxTabMain implements IToolTab { + public static final ToolboxTabMain INSTANCE = new ToolboxTabMain(); + + private int dragSnap = 4; + private final int[] snaps = new int[] { 1, 4, 6, 8, 12, 16, 24, 32 }; + + @Override + public String getUnlocalisedName() { + return "betterquesting.toolbox.tab.main"; + } + + @Override + public IGuiPanel getTabGui(IGuiRect rect, CanvasQuestLine cvQuestLine, PanelToolController toolController) { + return new PanelTabMain(rect, cvQuestLine, toolController); + } + + public void toggleSnap() { + dragSnap = (dragSnap + 1) % snaps.length; + } + + public int getSnapValue() { + return snaps[dragSnap % snaps.length]; + } + + public int getSnapIndex() { + return dragSnap; + } + + public void drawGrid(CanvasQuestLine ui) { + if (getSnapValue() <= 1) { return; } + + float zs = ui.getZoom(); + int snap = getSnapValue(); + + float offX = -ui.getScrollX(); + offX = ((offX % snap + snap) % snap) * zs; + int midX = Math.floorDiv(-ui.getScrollX(), snap); + + float offY = -ui.getScrollY(); + offY = ((offY % snap + snap) % snap) * zs; + int midY = Math.floorDiv(-ui.getScrollY(), snap); + + int x = ui.getTransform().getX(); + int y = ui.getTransform().getY(); + int width = ui.getTransform().getWidth(); + int height = ui.getTransform().getHeight(); + int divX = (int) Math.ceil((width - offX) / (zs * snap)); + int divY = (int) Math.ceil((height - offY) / (zs * snap)); + + IGuiColor gMinor = PresetColor.GRID_MINOR.getColor(); + IGuiColor gMajor = PresetColor.GRID_MAJOR.getColor(); + IGuiLine lMinor = PresetLine.GRID_MINOR.getLine(); + IGuiLine lMajor = PresetLine.GRID_MAJOR.getLine(); + + GuiRectangle p1 = new GuiRectangle(0, 0, 0, 0); + GuiRectangle p2 = new GuiRectangle(0, 0, 0, 0); + + p1.y = y; + p2.y = y + height; + + for (int i = 0; i < divX; i++) { + int lx = x + (int) (i * snap * zs + offX); + p1.x = lx; + p2.x = lx; + if (i == midX) { + lMajor.drawLine(p1, p2, 2, gMajor, 1F); + } else { + lMinor.drawLine(p1, p2, 1, gMinor, 1F); + } + } + + p1.x = x; + p2.x = x + width; + + for (int j = 0; j < divY; j++) { + int ly = y + (int) (j * snap * zs + offY); + p1.y = ly; + p2.y = ly; + if (j == midY) { + lMajor.drawLine(p1, p2, 2, gMajor, 1F); + } else { + lMinor.drawLine(p1, p2, 1, gMinor, 1F); + } + } + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java index 3d45109bd..56646f2a4 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java @@ -12,117 +12,102 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolComplete implements IToolboxTool -{ - private CanvasQuestLine gui = null; - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - } - - @Override - public void disableTool() - { - } - - @Override - public void refresh(CanvasQuestLine gui) - { - } - - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) return false; - - PanelButtonQuest btn = gui.getButtonAt(mx, my); - - if(btn == null) return false; - if(PanelToolController.selected.size() > 0 && !PanelToolController.selected.contains(btn)) return false; - - List btnList = PanelToolController.selected.size() > 0 ? PanelToolController.selected : Collections.singletonList(btn); - int[] questIDs = new int[btnList.size()]; - - for(int i = 0; i < btnList.size(); i++) - { - questIDs[i] = btnList.get(i).getStoredValue().getID(); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", questIDs); - payload.setBoolean("state", true); - payload.setInteger("action", 2); - NetQuestEdit.sendEdit(payload); - - return true; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } +public class ToolboxToolComplete implements IToolboxTool { + private CanvasQuestLine gui = null; + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + } + + @Override + public void disableTool() { + } + + @Override + public void refresh(CanvasQuestLine gui) { + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { return false; } + + PanelButtonQuest btn = gui.getButtonAt(mx, my); + + if (btn == null) { return false; } + if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { return false; } - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - if(PanelToolController.selected.size() <= 0 || key != Keyboard.KEY_RETURN) return false; - - List btnList = PanelToolController.selected; - int[] questIDs = new int[btnList.size()]; - - for(int i = 0; i < btnList.size(); i++) - { - questIDs[i] = btnList.get(i).getStoredValue().getID(); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", questIDs); - payload.setBoolean("state", true); - payload.setInteger("action", 2); - NetQuestEdit.sendEdit(payload); - - return true; - } - - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public void onSelection(NonNullList buttons) - { + List btnList = PanelToolController.selected.isEmpty() ? Collections.singletonList(btn) + : PanelToolController.selected; + int[] questIDs = new int[btnList.size()]; + + for (int i = 0; i < btnList.size(); i++) { + questIDs[i] = btnList.get(i).getStoredValue().getID(); } - - @Override - public boolean useSelection() - { - return true; + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", questIDs); + payload.setBoolean("state", true); + payload.setInteger("action", 2); + NetQuestEdit.sendEdit(payload); + + return true; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + + List btnList = PanelToolController.selected; + int[] questIDs = new int[btnList.size()]; + + for (int i = 0; i < btnList.size(); i++) { + questIDs[i] = btnList.get(i).getStoredValue().getID(); } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", questIDs); + payload.setBoolean("state", true); + payload.setInteger("action", 2); + NetQuestEdit.sendEdit(payload); + + return true; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return true; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java index d298ef12b..30b8b5a5c 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java @@ -20,254 +20,228 @@ import java.util.*; -public class ToolboxToolCopy implements IToolboxTool -{ - private CanvasQuestLine gui = null; - - private final NonNullList grabList = NonNullList.create(); - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - grabList.clear(); - } - - @Override - public void disableTool() - { - grabList.clear(); - } - - @Override - public void refresh(CanvasQuestLine gui) - { - if(grabList.size() <= 0) return; - - List tmp = new ArrayList<>(); - - for(GrabEntry grab : grabList) - { - for(PanelButtonQuest btn : PanelToolController.selected) - { - if(btn.getStoredValue().getID() == grab.btn.getStoredValue().getID()) - { - tmp.add(new GrabEntry(btn, grab.offX, grab.offY)); - break; - } - } +public class ToolboxToolCopy implements IToolboxTool { + private CanvasQuestLine gui = null; + + private final NonNullList grabList = NonNullList.create(); + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + grabList.clear(); + } + + @Override + public void disableTool() { + grabList.clear(); + } + + @Override + public void refresh(CanvasQuestLine gui) { + if (grabList.isEmpty()) { return; } + + List tmp = new ArrayList<>(); + + for (GrabEntry grab : grabList) { + for (PanelButtonQuest btn : PanelToolController.selected) { + if (btn.getStoredValue().getID() == grab.btn.getStoredValue().getID()) { + tmp.add(new GrabEntry(btn, grab.offX, grab.offY)); + break; } - - grabList.clear(); - grabList.addAll(tmp); + } } - - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - if(grabList.size() <= 0) return; - - int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); - int dx = mx; - int dy = my; - dx = ((dx%snap) + snap)%snap; - dy = ((dy%snap) + snap)%snap; - dx = mx - dx; - dy = my - dy; - - for(GrabEntry grab : grabList) - { - grab.btn.rect.x = dx + grab.offX; - grab.btn.rect.y = dy + grab.offY; - grab.btn.drawPanel(dx, dy, partialTick); - } - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - if(grabList.size() > 0) ToolboxTabMain.INSTANCE.drawGrid(gui); + + grabList.clear(); + grabList.addAll(tmp); + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + if (grabList.isEmpty()) { return; } + + int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); + int dx = mx; + int dy = my; + dx = ((dx % snap) + snap) % snap; + dy = ((dy % snap) + snap) % snap; + dx = mx - dx; + dy = my - dy; + + for (GrabEntry grab : grabList) { + grab.btn.rect.x = dx + grab.offX; + grab.btn.rect.y = dy + grab.offY; + grab.btn.drawPanel(dx, dy, partialTick); } - - @Override - public List getTooltip(int mx, int my) - { - return grabList.size() <= 0 ? null : Collections.emptyList(); + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + if (!grabList.isEmpty()) { ToolboxTabMain.INSTANCE.drawGrid(gui); } + } + + @Override + public List getTooltip(int mx, int my) { + return grabList.isEmpty() ? null : Collections.emptyList(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click == 1 && !grabList.isEmpty()) { + grabList.clear(); + return true; + } else if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click == 1 && grabList.size() > 0) - { - grabList.clear(); - return true; - } else if(click != 0 || !gui.getTransform().contains(mx, my)) - { - return false; - } - - if(grabList.size() <= 0) - { - PanelButtonQuest btnClicked = gui.getButtonAt(mx, my); - - if(btnClicked != null) // Pickup the group or the single one if none are selected - { - if(PanelToolController.selected.size() > 0) - { - if(!PanelToolController.selected.contains(btnClicked)) return false; - - for(PanelButtonQuest btn : PanelToolController.selected) - { - GuiRectangle rect = new GuiRectangle(btn.rect); - grabList.add(new GrabEntry(new PanelButtonQuest(rect, -1, "", btn.getStoredValue()), rect.x - btnClicked.rect.x, rect.y - btnClicked.rect.y)); - } - } else - { - grabList.add(new GrabEntry(new PanelButtonQuest(new GuiRectangle(btnClicked.rect), -1, "", btnClicked.getStoredValue()), 0, 0)); - } - - return true; - } - - return false; - } - - // Pre-sync - IQuestLine qLine = gui.getQuestLine(); - int lID = QuestLineDatabase.INSTANCE.getID(qLine); - - int[] nextIDs = getNextIDs(grabList.size()); - HashMap remappedIDs = new HashMap<>(); - - for(int i = 0; i < grabList.size(); i++) remappedIDs.put(grabList.get(i).btn.getStoredValue().getID(), nextIDs[i]); - - NBTTagList qdList = new NBTTagList(); - - for(int i = 0; i < grabList.size(); i++) - { - GrabEntry grab = grabList.get(i); - IQuest quest = grab.btn.getStoredValue().getValue(); - int qID = nextIDs[i]; - - if(qLine.getValue(qID) == null) qLine.add(qID, new QuestLineEntry(grab.btn.rect.x, grab.btn.rect.y, grab.btn.rect.w, grab.btn.rect.h)); - - NBTTagCompound questTags = quest.writeToNBT(new NBTTagCompound()); - - int[] oldIDs = Arrays.copyOf(quest.getRequirements(), quest.getRequirements().length); - - for(int n = 0; n < oldIDs.length; n++) - { - if(remappedIDs.containsKey(oldIDs[n])) - { - oldIDs[n] = remappedIDs.get(oldIDs[n]); - } - } - - // We can't tamper with the original so we change it in NBT post-write - questTags.setIntArray("preRequisites", oldIDs); - - NBTTagCompound tagEntry = new NBTTagCompound(); - tagEntry.setInteger("questID", qID); - tagEntry.setTag("config", questTags); - qdList.appendTag(tagEntry); - } - - grabList.clear(); - - // Send new quests - NBTTagCompound quPayload = new NBTTagCompound(); - quPayload.setTag("data", qdList); - quPayload.setInteger("action", 3); - NetQuestEdit.sendEdit(quPayload); - - // Send quest line edits - NBTTagCompound chPayload = new NBTTagCompound(); - NBTTagList cdList = new NBTTagList(); - NBTTagCompound tagEntry = new NBTTagCompound(); - tagEntry.setInteger("chapterID", lID); - tagEntry.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); - cdList.appendTag(tagEntry); - chPayload.setTag("data", cdList); - chPayload.setInteger("action", 0); - NetChapterEdit.sendEdit(chPayload); - - return true; - } - - private int[] getNextIDs(int num) - { - List> listDB = QuestDatabase.INSTANCE.getEntries(); - int[] nxtIDs = new int[num]; - - if(listDB.size() <= 0 || listDB.get(listDB.size() - 1).getID() == listDB.size() - 1) - { - for(int i = 0; i < num; i++) nxtIDs[i] = listDB.size() + i; - return nxtIDs; - } - - int n1 = 0; - int n2 = 0; - for(int i = 0; i < num; i++) - { - while(n2 < listDB.size() && listDB.get(n2).getID() == n1) - { - n1++; - n2++; - } - - nxtIDs[i] = n1++; + + if (grabList.isEmpty()) { + PanelButtonQuest btnClicked = gui.getButtonAt(mx, my); + + if (btnClicked != null) // Pickup the group or the single one if none are selected + { + if (!PanelToolController.selected.isEmpty()) { + if (!PanelToolController.selected.contains(btnClicked)) { return false; } + + for (PanelButtonQuest btn : PanelToolController.selected) { + GuiRectangle rect = new GuiRectangle(btn.rect); + grabList.add( + new GrabEntry(new PanelButtonQuest(rect, -1, "", btn.getStoredValue()), rect.x - btnClicked.rect.x, + rect.y - btnClicked.rect.y)); + } + } else { + grabList.add(new GrabEntry( + new PanelButtonQuest(new GuiRectangle(btnClicked.rect), -1, "", btnClicked.getStoredValue()), 0, 0)); } - - return nxtIDs; + + return true; + } + + return false; + } + + // Pre-sync + IQuestLine qLine = gui.getQuestLine(); + int lID = QuestLineDatabase.INSTANCE.getID(qLine); + + int[] nextIDs = getNextIDs(grabList.size()); + HashMap remappedIDs = new HashMap<>(); + + for (int i = 0; i < grabList.size(); i++) { + remappedIDs.put(grabList.get(i).btn.getStoredValue().getID(), nextIDs[i]); } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; + + NBTTagList qdList = new NBTTagList(); + + for (int i = 0; i < grabList.size(); i++) { + GrabEntry grab = grabList.get(i); + IQuest quest = grab.btn.getStoredValue().getValue(); + int qID = nextIDs[i]; + + if (qLine.getValue(qID) == null) { + qLine.add(qID, new QuestLineEntry(grab.btn.rect.x, grab.btn.rect.y, grab.btn.rect.w, grab.btn.rect.h)); + } + + NBTTagCompound questTags = quest.writeToNBT(new NBTTagCompound()); + + int[] oldIDs = Arrays.copyOf(quest.getRequirements(), quest.getRequirements().length); + + for (int n = 0; n < oldIDs.length; n++) { + if (remappedIDs.containsKey(oldIDs[n])) { + oldIDs[n] = remappedIDs.get(oldIDs[n]); + } + } + + // We can't tamper with the original so we change it in NBT post-write + questTags.setIntArray("preRequisites", oldIDs); + + NBTTagCompound tagEntry = new NBTTagCompound(); + tagEntry.setInteger("questID", qID); + tagEntry.setTag("config", questTags); + qdList.appendTag(tagEntry); } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int keyCode) - { - return grabList.size() > 0; - } - - @Override - public boolean clampScrolling() - { - return grabList.size() <= 0; - } - - @Override - public void onSelection(NonNullList buttons) - { + + grabList.clear(); + + // Send new quests + NBTTagCompound quPayload = new NBTTagCompound(); + quPayload.setTag("data", qdList); + quPayload.setInteger("action", 3); + NetQuestEdit.sendEdit(quPayload); + + // Send quest line edits + NBTTagCompound chPayload = new NBTTagCompound(); + NBTTagList cdList = new NBTTagList(); + NBTTagCompound tagEntry = new NBTTagCompound(); + tagEntry.setInteger("chapterID", lID); + tagEntry.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); + cdList.appendTag(tagEntry); + chPayload.setTag("data", cdList); + chPayload.setInteger("action", 0); + NetChapterEdit.sendEdit(chPayload); + + return true; + } + + private int[] getNextIDs(int num) { + List> listDB = QuestDatabase.INSTANCE.getEntries(); + int[] nxtIDs = new int[num]; + + if (listDB.isEmpty() || listDB.get(listDB.size() - 1).getID() == listDB.size() - 1) { + for (int i = 0; i < num; i++) { nxtIDs[i] = listDB.size() + i; } + return nxtIDs; } - - @Override - public boolean useSelection() - { - return grabList.size() <= 0; + + int n1 = 0; + int n2 = 0; + for (int i = 0; i < num; i++) { + while (n2 < listDB.size() && listDB.get(n2).getID() == n1) { + n1++; + n2++; + } + + nxtIDs[i] = n1++; } - - private class GrabEntry - { - private final PanelButtonQuest btn; - private final int offX; - private final int offY; - - private GrabEntry(PanelButtonQuest btn, int offX, int offY) - { - this.btn = btn; - this.offX = offX; - this.offY = offY; - } + + return nxtIDs; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int keyCode) { + return !grabList.isEmpty(); + } + + @Override + public boolean clampScrolling() { + return grabList.isEmpty(); + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return grabList.isEmpty(); + } + + private static class GrabEntry { + private final PanelButtonQuest btn; + private final int offX; + private final int offY; + + private GrabEntry(PanelButtonQuest btn, int offX, int offY) { + this.btn = btn; + this.offX = offX; + this.offY = offY; } + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java index 149bfdb29..8ef4cebbc 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java @@ -12,115 +12,106 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolDelete implements IToolboxTool -{ - private CanvasQuestLine gui; - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - } - - @Override - public void disableTool() - { - } - - @Override - public void refresh(CanvasQuestLine gui) - { - } +public class ToolboxToolDelete implements IToolboxTool { + private CanvasQuestLine gui; + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + } + + @Override + public void disableTool() { + } + + @Override + public void refresh(CanvasQuestLine gui) { + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + } - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; } - - @Override - public List getTooltip(int mx, int my) - { - return null; + + PanelButtonQuest btn = gui.getButtonAt(mx, my); + + if (btn == null) { + return false; } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) return false; - - PanelButtonQuest btn = gui.getButtonAt(mx, my); - - if(btn == null) return false; - if(PanelToolController.selected.size() > 0 && !PanelToolController.selected.contains(btn)) return false; - - List btnList = PanelToolController.selected.size() > 0 ? PanelToolController.selected : Collections.singletonList(btn); - int[] questIDs = new int[btnList.size()]; - - for(int i = 0; i < btnList.size(); i++) - { - questIDs[i] = btnList.get(i).getStoredValue().getID(); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", questIDs); - payload.setInteger("action", 1); - NetQuestEdit.sendEdit(payload); - - return true; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; + if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { + return false; } - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - if(PanelToolController.selected.size() <= 0 || key != Keyboard.KEY_RETURN) return false; - - List btnList = PanelToolController.selected; - int[] questIDs = new int[btnList.size()]; - - for(int i = 0; i < btnList.size(); i++) - { - questIDs[i] = btnList.get(i).getStoredValue().getID(); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", questIDs); - payload.setInteger("action", 1); - NetQuestEdit.sendEdit(payload); - - return true; - } - - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public void onSelection(NonNullList buttons) - { + List btnList = PanelToolController.selected.isEmpty() ? Collections.singletonList(btn) + : PanelToolController.selected; + int[] questIDs = new int[btnList.size()]; + + for (int i = 0; i < btnList.size(); i++) { + questIDs[i] = btnList.get(i).getStoredValue().getID(); } - - @Override - public boolean useSelection() - { - return true; + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", questIDs); + payload.setInteger("action", 1); + NetQuestEdit.sendEdit(payload); + + return true; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + + List btnList = PanelToolController.selected; + int[] questIDs = new int[btnList.size()]; + + for (int i = 0; i < btnList.size(); i++) { + questIDs[i] = btnList.get(i).getStoredValue().getID(); } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", questIDs); + payload.setInteger("action", 1); + NetQuestEdit.sendEdit(payload); + + return true; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return true; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java index 345722880..6e1086ac2 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java @@ -14,117 +14,102 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolFrame implements IToolboxTool -{ - private CanvasQuestLine gui; - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - } - - @Override - public void refresh(CanvasQuestLine gui) - { - - } - - @Override - public void disableTool() - { - - } - - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - - } - - @Override - public void onSelection(NonNullList buttons) - { - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) return false; - - PanelButtonQuest btn = gui.getButtonAt(mx, my); - - if(btn == null) return false; - if(PanelToolController.selected.size() > 0 && !PanelToolController.selected.contains(btn)) return false; - - List btnList = PanelToolController.selected.size() > 0 ? PanelToolController.selected : Collections.singletonList(btn); - changeFrame(btnList); - return true; - } - - private void changeFrame(List btnList) - { - boolean state = !btnList.get(0).getStoredValue().getValue().getProperty(NativeProps.MAIN); - - NBTTagList dataList = new NBTTagList(); - for(PanelButtonQuest btn : btnList) - { - btn.getStoredValue().getValue().setProperty(NativeProps.MAIN, state); - - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", btn.getStoredValue().getID()); - entry.setTag("config", btn.getStoredValue().getValue().writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetQuestEdit.sendEdit(payload); - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - if(PanelToolController.selected.size() <= 0 || key != Keyboard.KEY_RETURN) return false; - - changeFrame(PanelToolController.selected); - return true; - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } - - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public boolean useSelection() - { - return true; +public class ToolboxToolFrame implements IToolboxTool { + private CanvasQuestLine gui; + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + } + + @Override + public void refresh(CanvasQuestLine gui) { + + } + + @Override + public void disableTool() { + + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { return false; } + + PanelButtonQuest btn = gui.getButtonAt(mx, my); + + if (btn == null) { return false; } + if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { return false; } + + List btnList = PanelToolController.selected.isEmpty() ? Collections.singletonList(btn) + : PanelToolController.selected; + changeFrame(btnList); + return true; + } + + private void changeFrame(List btnList) { + boolean state = !btnList.get(0).getStoredValue().getValue().getProperty(NativeProps.MAIN); + + NBTTagList dataList = new NBTTagList(); + for (PanelButtonQuest btn : btnList) { + btn.getStoredValue().getValue().setProperty(NativeProps.MAIN, state); + + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", btn.getStoredValue().getID()); + entry.setTag("config", btn.getStoredValue().getValue().writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetQuestEdit.sendEdit(payload); + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + + changeFrame(PanelToolController.selected); + return true; + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public boolean useSelection() { + return true; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java index 31fffc5bf..2a417a274 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java @@ -17,221 +17,191 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolGrab implements IToolboxTool -{ - private CanvasQuestLine gui; - - private final NonNullList grabList = NonNullList.create(); - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - grabList.clear(); - } - - @Override - public void disableTool() - { - for(GrabEntry grab : grabList) - { - IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); - - if(qle != null) - { - grab.btn.rect.x = qle.getPosX(); - grab.btn.rect.y = qle.getPosY(); - } - } - - grabList.clear(); - } - - @Override - public void refresh(CanvasQuestLine gui) - { - if(grabList.size() <= 0) return; - - List tmp = new ArrayList<>(); - - for(GrabEntry grab : grabList) - { - for(PanelButtonQuest btn : PanelToolController.selected) - { - if(btn.getStoredValue().getID() == grab.btn.getStoredValue().getID()) - { - tmp.add(new GrabEntry(btn, grab.offX, grab.offY)); - break; - } - } - } - - grabList.clear(); - grabList.addAll(tmp); +public class ToolboxToolGrab implements IToolboxTool { + private CanvasQuestLine gui; + + private final NonNullList grabList = NonNullList.create(); + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + grabList.clear(); + } + + @Override + public void disableTool() { + for (GrabEntry grab : grabList) { + IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); + + if (qle != null) { + grab.btn.rect.x = qle.getPosX(); + grab.btn.rect.y = qle.getPosY(); + } } - - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - if(grabList.size() <= 0) return; - - int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); - int dx = mx; - int dy = my; - dx = ((dx%snap) + snap)%snap; - dy = ((dy%snap) + snap)%snap; - dx = mx - dx; - dy = my - dy; - - for(GrabEntry grab : grabList) - { - grab.btn.rect.x = dx + grab.offX; - grab.btn.rect.y = dy + grab.offY; + + grabList.clear(); + } + + @Override + public void refresh(CanvasQuestLine gui) { + if (grabList.isEmpty()) { return; } + + List tmp = new ArrayList<>(); + + for (GrabEntry grab : grabList) { + for (PanelButtonQuest btn : PanelToolController.selected) { + if (btn.getStoredValue().getID() == grab.btn.getStoredValue().getID()) { + tmp.add(new GrabEntry(btn, grab.offX, grab.offY)); + break; } - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - ToolboxTabMain.INSTANCE.drawGrid(gui); + } } - - @Override - public List getTooltip(int mx, int my) - { - if(grabList.size() <= 0) return null; - - for(GrabEntry grab : grabList) - { - if(grab.offX == 0 && grab.offY == 0) - { - List list = new ArrayList<>(); - list.add("X: " + grab.btn.rect.x); - list.add("Y: " + grab.btn.rect.y); - return list; - } - } - - return Collections.emptyList(); + + grabList.clear(); + grabList.addAll(tmp); + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + if (grabList.isEmpty()) { return; } + + int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); + int dx = mx; + int dy = my; + dx = ((dx % snap) + snap) % snap; + dy = ((dy % snap) + snap) % snap; + dx = mx - dx; + dy = my - dy; + + for (GrabEntry grab : grabList) { + grab.btn.rect.x = dx + grab.offX; + grab.btn.rect.y = dy + grab.offY; } - - @Override - public void onSelection(NonNullList buttons) - { + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + ToolboxTabMain.INSTANCE.drawGrid(gui); + } + + @Override + public List getTooltip(int mx, int my) { + if (grabList.isEmpty()) { return null; } + + for (GrabEntry grab : grabList) { + if (grab.offX == 0 && grab.offY == 0) { + List list = new ArrayList<>(); + list.add("X: " + grab.btn.rect.x); + list.add("Y: " + grab.btn.rect.y); + return list; + } } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click == 1 && grabList.size() > 0) // Reset tool - { - for(GrabEntry grab : grabList) - { - IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); - - if(qle != null) - { - grab.btn.rect.x = qle.getPosX(); - grab.btn.rect.y = qle.getPosY(); - } - } - - grabList.clear(); - return true; - } else if(click != 0 || !gui.getTransform().contains(mx, my)) // Not a click we're listening for - { - return false; - } - - if(grabList.size() > 0) // Apply positioning - { - IQuestLine qLine = gui.getQuestLine(); - int lID = QuestLineDatabase.INSTANCE.getID(qLine); - for(GrabEntry grab : grabList) - { - IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); - if(qle != null) qle.setPosition(grab.btn.rect.x, grab.btn.rect.y); - } - - // Send quest line edits - NBTTagCompound chPayload = new NBTTagCompound(); - NBTTagList cdList = new NBTTagList(); - NBTTagCompound tagEntry = new NBTTagCompound(); - tagEntry.setInteger("chapterID", lID); - tagEntry.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); - cdList.appendTag(tagEntry); - chPayload.setTag("data", cdList); - chPayload.setInteger("action", 0); - NetChapterEdit.sendEdit(chPayload); - - grabList.clear(); - return true; - } - - PanelButtonQuest btnClicked = gui.getButtonAt(mx, my); - - if(btnClicked != null) // Pickup the group or the single one if none are selected - { - if(PanelToolController.selected.size() > 0) - { - if(!PanelToolController.selected.contains(btnClicked)) return false; - - for(PanelButtonQuest btn : PanelToolController.selected) - { - grabList.add(new GrabEntry(btn, btn.rect.x - btnClicked.rect.x, btn.rect.y - btnClicked.rect.y)); - } - } else - { - grabList.add(new GrabEntry(btnClicked, 0, 0)); - } - - return true; + + return Collections.emptyList(); + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click == 1 && !grabList.isEmpty()) // Reset tool + { + for (GrabEntry grab : grabList) { + IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); + + if (qle != null) { + grab.btn.rect.x = qle.getPosX(); + grab.btn.rect.y = qle.getPosY(); } - - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) + } + + grabList.clear(); + return true; + } else if (click != 0 || !gui.getTransform().contains(mx, my)) // Not a click we're listening for { - return false; + return false; } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int keyCode) - { - return grabList.size() > 0; - } - - @Override - public boolean clampScrolling() - { - return grabList.size() <= 0; - } - - @Override - public boolean useSelection() + + if (!grabList.isEmpty()) // Apply positioning { - return grabList.size() <= 0; + IQuestLine qLine = gui.getQuestLine(); + int lID = QuestLineDatabase.INSTANCE.getID(qLine); + for (GrabEntry grab : grabList) { + IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); + if (qle != null) { qle.setPosition(grab.btn.rect.x, grab.btn.rect.y); } + } + + // Send quest line edits + NBTTagCompound chPayload = new NBTTagCompound(); + NBTTagList cdList = new NBTTagList(); + NBTTagCompound tagEntry = new NBTTagCompound(); + tagEntry.setInteger("chapterID", lID); + tagEntry.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); + cdList.appendTag(tagEntry); + chPayload.setTag("data", cdList); + chPayload.setInteger("action", 0); + NetChapterEdit.sendEdit(chPayload); + + grabList.clear(); + return true; } - - private class GrabEntry + + PanelButtonQuest btnClicked = gui.getButtonAt(mx, my); + + if (btnClicked != null) // Pickup the group or the single one if none are selected { - private final PanelButtonQuest btn; - private final int offX; - private final int offY; - - private GrabEntry(PanelButtonQuest btn, int offX, int offY) - { - this.btn = btn; - this.offX = offX; - this.offY = offY; + if (!PanelToolController.selected.isEmpty()) { + if (!PanelToolController.selected.contains(btnClicked)) { return false; } + + for (PanelButtonQuest btn : PanelToolController.selected) { + grabList.add(new GrabEntry(btn, btn.rect.x - btnClicked.rect.x, btn.rect.y - btnClicked.rect.y)); } + } else { + grabList.add(new GrabEntry(btnClicked, 0, 0)); + } + + return true; + } + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int keyCode) { + return !grabList.isEmpty(); + } + + @Override + public boolean clampScrolling() { + return grabList.isEmpty(); + } + + @Override + public boolean useSelection() { + return grabList.isEmpty(); + } + + private static class GrabEntry { + private final PanelButtonQuest btn; + private final int offX; + private final int offY; + + private GrabEntry(PanelButtonQuest btn, int offX, int offY) { + this.btn = btn; + this.offX = offX; + this.offY = offY; } + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java index 942830914..b9e26883f 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java @@ -17,113 +17,105 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolIcon implements IToolboxTool -{ - private CanvasQuestLine gui; - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - } - - @Override - public void disableTool() - { - } - - @Override - public void refresh(CanvasQuestLine gui) - { - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) return false; - - PanelButtonQuest btn = gui.getButtonAt(mx, my); - - if(btn == null) return false; - if(PanelToolController.selected.size() > 0 && !PanelToolController.selected.contains(btn)) return false; - - List btnList = PanelToolController.selected.size() > 0 ? PanelToolController.selected : Collections.singletonList(btn); - changeIcon(btnList, btn.getStoredValue().getValue().getProperty(NativeProps.ICON)); - return true; - } - - private void changeIcon(List list, BigItemStack refItem) - { - Minecraft mc = Minecraft.getMinecraft(); - mc.displayGuiScreen(new GuiItemSelection(mc.currentScreen, refItem, value -> { - NBTTagList dataList = new NBTTagList(); - for(PanelButtonQuest b : list) - { - b.getStoredValue().getValue().setProperty(NativeProps.ICON, value); - - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", b.getStoredValue().getID()); - entry.setTag("config", b.getStoredValue().getValue().writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetQuestEdit.sendEdit(payload); - })); - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - if(PanelToolController.selected.size() <= 0 || key != Keyboard.KEY_RETURN) return false; - changeIcon(PanelToolController.selected, PanelToolController.selected.get(0).getStoredValue().getValue().getProperty(NativeProps.ICON)); - return true; - } - - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - } - - @Override - public List getTooltip(int mx, int my) - { - return null; +public class ToolboxToolIcon implements IToolboxTool { + private CanvasQuestLine gui; + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + } + + @Override + public void disableTool() { + } + + @Override + public void refresh(CanvasQuestLine gui) { + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; } - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public void onSelection(NonNullList buttons) - { + PanelButtonQuest btn = gui.getButtonAt(mx, my); + + if (btn == null) { + return false; } - - @Override - public boolean useSelection() - { - return true; + if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { + return false; } + + List btnList = PanelToolController.selected.isEmpty() ? Collections.singletonList(btn) + : PanelToolController.selected; + changeIcon(btnList, btn.getStoredValue().getValue().getProperty(NativeProps.ICON)); + return true; + } + + private void changeIcon(List list, BigItemStack refItem) { + Minecraft mc = Minecraft.getMinecraft(); + mc.displayGuiScreen(new GuiItemSelection(mc.currentScreen, refItem, value -> { + NBTTagList dataList = new NBTTagList(); + for (PanelButtonQuest b : list) { + b.getStoredValue().getValue().setProperty(NativeProps.ICON, value); + + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", b.getStoredValue().getID()); + entry.setTag("config", b.getStoredValue().getValue().writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); + } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetQuestEdit.sendEdit(payload); + })); + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + changeIcon(PanelToolController.selected, + PanelToolController.selected.get(0).getStoredValue().getValue().getProperty(NativeProps.ICON)); + return true; + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return true; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java index ac3ef2e82..d01a333d5 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java @@ -17,220 +17,191 @@ import java.util.Arrays; import java.util.List; -public class ToolboxToolLink implements IToolboxTool -{ - private CanvasQuestLine gui; - private final NonNullList linking = NonNullList.create(); - private final GuiRectangle mouseRect = new GuiRectangle(0, 0, 0, 0); - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - linking.clear(); - } - - @Override - public void disableTool() - { - linking.clear(); - } - - @Override - public void refresh(CanvasQuestLine gui) - { - if(linking.size() <= 0) return; - - List tmp = new ArrayList<>(); - - for(PanelButtonQuest b1 : linking) - { - for(PanelButtonQuest b2 : gui.getQuestButtons()) if(b1.getStoredValue().getID() == b2.getStoredValue().getID()) tmp.add(b2); - } - - linking.clear(); - linking.addAll(tmp); - } - - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - if(linking.size() <= 0) return; - - mouseRect.x = mx; - mouseRect.y = my; - - for(PanelButtonQuest btn : linking) - { - PresetLine.QUEST_COMPLETE.getLine().drawLine(btn.rect, mouseRect, 2, PresetColor.QUEST_LINE_COMPLETE.getColor(), partialTick); - } - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click == 1 && linking.size() > 0) - { - linking.clear(); - return true; - } else if(click != 0 || !gui.getTransform().contains(mx, my)) - { - return false; - } - - if(linking.size() <= 0) - { - PanelButtonQuest btn = gui.getButtonAt(mx, my); - if(btn == null) return false; - - if(PanelToolController.selected.size() > 0) - { - if(!PanelToolController.selected.contains(btn)) return false; - linking.addAll(PanelToolController.selected); - return true; - } - - linking.add(btn); - return true; - } else - { - PanelButtonQuest b2 = gui.getButtonAt(mx, my); - - if(b2 == null) return false; - linking.remove(b2); - - if(linking.size() > 0) - { - IQuest q2 = b2.getStoredValue().getValue(); - boolean mod2 = false; - - NBTTagList dataList = new NBTTagList(); - - for(PanelButtonQuest b1 : linking) - { - IQuest q1 = b1.getStoredValue().getValue(); - boolean mod1 = false; - - // Don't have to worry about the lines anymore. The panel is getting refereshed anyway - if(!containsReq(q2, b1.getStoredValue().getID()) && !containsReq(q1, b2.getStoredValue().getID())) - { - mod2 = addReq(q2, b1.getStoredValue().getID()) || mod2; - } else - { - mod2 = removeReq(q2, b1.getStoredValue().getID()) || mod2; - mod1 = removeReq(q1, b2.getStoredValue().getID()); - } - - if(mod1) - { - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", b1.getStoredValue().getID()); - entry.setTag("config", b1.getStoredValue().getValue().writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - } - } - - if(mod2) - { - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("questID", b2.getStoredValue().getID()); - entry.setTag("config", q2.writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", dataList); - payload.setInteger("action", 0); - NetQuestEdit.sendEdit(payload); - - linking.clear(); - return true; - } - - return false; - } - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int keyCode) - { - return false; - } - - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public void onSelection(NonNullList buttons) - { +public class ToolboxToolLink implements IToolboxTool { + private CanvasQuestLine gui; + private final NonNullList linking = NonNullList.create(); + private final GuiRectangle mouseRect = new GuiRectangle(0, 0, 0, 0); + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + linking.clear(); + } + + @Override + public void disableTool() { + linking.clear(); + } + + @Override + public void refresh(CanvasQuestLine gui) { + if (linking.isEmpty()) { return; } + + List tmp = new ArrayList<>(); + + for (PanelButtonQuest b1 : linking) { + for (PanelButtonQuest b2 : gui.getQuestButtons()) { + if (b1.getStoredValue().getID() == b2.getStoredValue().getID()) { tmp.add(b2); } + } } - - @Override - public boolean useSelection() - { - return linking.size() <= 0; + + linking.clear(); + linking.addAll(tmp); + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + if (linking.isEmpty()) { return; } + + mouseRect.x = mx; + mouseRect.y = my; + + for (PanelButtonQuest btn : linking) { + PresetLine.QUEST_COMPLETE.getLine().drawLine(btn.rect, mouseRect, 2, PresetColor.QUEST_LINE_COMPLETE.getColor(), + partialTick); } - - private boolean containsReq(IQuest quest, int id) - { - for(int reqID : quest.getRequirements()) if(id == reqID) return true; - return false; + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click == 1 && !linking.isEmpty()) { + linking.clear(); + return true; + } else if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; } - - private boolean removeReq(IQuest quest, int id) - { - int[] orig = quest.getRequirements(); - if(orig.length <= 0) return false; - boolean hasRemoved = false; - int[] rem = new int[orig.length - 1]; - for(int i = 0; i < orig.length; i++) - { - if(!hasRemoved && orig[i] == id) - { - hasRemoved = true; - continue; - } else if(!hasRemoved && i >= rem.length) break; - - rem[!hasRemoved ? i : (i - 1)] = orig[i]; + + if (linking.isEmpty()) { + PanelButtonQuest btn = gui.getButtonAt(mx, my); + if (btn == null) { return false; } + + if (!PanelToolController.selected.isEmpty()) { + if (!PanelToolController.selected.contains(btn)) { return false; } + linking.addAll(PanelToolController.selected); + return true; + } + + linking.add(btn); + return true; + } else { + PanelButtonQuest b2 = gui.getButtonAt(mx, my); + + if (b2 == null) { return false; } + linking.remove(b2); + + if (!linking.isEmpty()) { + IQuest q2 = b2.getStoredValue().getValue(); + boolean mod2 = false; + + NBTTagList dataList = new NBTTagList(); + + for (PanelButtonQuest b1 : linking) { + IQuest q1 = b1.getStoredValue().getValue(); + boolean mod1 = false; + + // Don't have to worry about the lines anymore. The panel is getting refereshed anyway + if (!containsReq(q2, b1.getStoredValue().getID()) && !containsReq(q1, b2.getStoredValue().getID())) { + mod2 = addReq(q2, b1.getStoredValue().getID()) || mod2; + } else { + mod2 = removeReq(q2, b1.getStoredValue().getID()) || mod2; + mod1 = removeReq(q1, b2.getStoredValue().getID()); + } + + if (mod1) { + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", b1.getStoredValue().getID()); + entry.setTag("config", b1.getStoredValue().getValue().writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); + } } - - if(hasRemoved) quest.setRequirements(rem); - return hasRemoved; - } - - private boolean addReq(IQuest quest, int id) - { - if(containsReq(quest, id)) return false; - int[] orig = quest.getRequirements(); - int[] added = Arrays.copyOf(orig, orig.length + 1); - added[orig.length] = id; - quest.setRequirements(added); + + if (mod2) { + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("questID", b2.getStoredValue().getID()); + entry.setTag("config", q2.writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); + } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", dataList); + payload.setInteger("action", 0); + NetQuestEdit.sendEdit(payload); + + linking.clear(); return true; + } + + return false; } + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int keyCode) { + return false; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return linking.isEmpty(); + } + + private boolean containsReq(IQuest quest, int id) { + for (int reqID : quest.getRequirements()) { if (id == reqID) { return true; } } + return false; + } + + private boolean removeReq(IQuest quest, int id) { + int[] orig = quest.getRequirements(); + if (orig.length == 0) { return false; } + boolean hasRemoved = false; + int[] rem = new int[orig.length - 1]; + for (int i = 0; i < orig.length; i++) { + if (!hasRemoved && orig[i] == id) { + hasRemoved = true; + continue; + } else if (!hasRemoved && i >= rem.length) { break; } + + rem[!hasRemoved ? i : (i - 1)] = orig[i]; + } + + if (hasRemoved) { quest.setRequirements(rem); } + return hasRemoved; + } + + private boolean addReq(IQuest quest, int id) { + if (containsReq(quest, id)) { return false; } + int[] orig = quest.getRequirements(); + int[] added = Arrays.copyOf(orig, orig.length + 1); + added[orig.length] = id; + quest.setRequirements(added); + return true; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java index 9c3ef56d1..f1e262db4 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java @@ -19,142 +19,124 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolNew implements IToolboxTool -{ - private CanvasQuestLine gui = null; - private PanelButtonQuest nQuest; - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - - nQuest = new PanelButtonQuest(new GuiRectangle(0, 0, 24, 24), -1, "", null); - } - - @Override - public void refresh(CanvasQuestLine gui) - { - } - - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - if(nQuest == null) - { - return; - } - - int snap = ToolboxTabMain.INSTANCE.getSnapValue(); - int modX = ((mx%snap) + snap)%snap; - int modY = ((my%snap) + snap)%snap; - mx -= modX; - my -= modY; - - nQuest.rect.x = mx; - nQuest.rect.y = my; - nQuest.drawPanel(mx, my, partialTick); // TODO: Draw relative - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - ToolboxTabMain.INSTANCE.drawGrid(gui); - } - - @Override - public List getTooltip(int mx, int my) - { - return Collections.emptyList(); - } - - @Override - public void disableTool() - { - if(nQuest != null) nQuest = null; - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) - { - return false; - } - - // Pre-sync - IQuestLine qLine = gui.getQuestLine(); - int qID = QuestDatabase.INSTANCE.nextID(); - int lID = QuestLineDatabase.INSTANCE.getID(qLine); - IQuestLineEntry qe = qLine.getValue(qID);//new QuestLineEntry(mx, my, 24); - - - if(qe == null) - { - qe = new QuestLineEntry(nQuest.rect.x, nQuest.rect.y, 24, 24); - qLine.add(qID, qe); - } else - { - qe.setPosition(nQuest.rect.x, nQuest.rect.y); - qe.setSize(24, 24); - } - - // Sync Quest - NBTTagCompound quPayload = new NBTTagCompound(); - NBTTagList qdList = new NBTTagList(); - NBTTagCompound qTag = new NBTTagCompound(); - qTag.setInteger("questID", qID); - qdList.appendTag(qTag); - quPayload.setTag("data", qdList); - quPayload.setInteger("action", 3); - NetQuestEdit.sendEdit(quPayload); - - // Sync Line - NBTTagCompound chPayload = new NBTTagCompound(); - NBTTagList cdList = new NBTTagList(); - NBTTagCompound cTag = new NBTTagCompound(); - cTag.setInteger("chapterID", lID); - cTag.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); - cdList.appendTag(cTag); - chPayload.setTag("data", cdList); - chPayload.setInteger("action", 0); - NetChapterEdit.sendEdit(chPayload); - - return true; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; +public class ToolboxToolNew implements IToolboxTool { + private CanvasQuestLine gui = null; + private PanelButtonQuest nQuest; + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + + nQuest = new PanelButtonQuest(new GuiRectangle(0, 0, 24, 24), -1, "", null); + } + + @Override + public void refresh(CanvasQuestLine gui) { + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + if (nQuest == null) { + return; } - - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int keyCode) - { - return false; - } - - @Override - public boolean clampScrolling() - { - return false; - } - - @Override - public void onSelection(NonNullList buttons) - { + + int snap = ToolboxTabMain.INSTANCE.getSnapValue(); + int modX = ((mx % snap) + snap) % snap; + int modY = ((my % snap) + snap) % snap; + mx -= modX; + my -= modY; + + nQuest.rect.x = mx; + nQuest.rect.y = my; + nQuest.drawPanel(mx, my, partialTick); // TODO: Draw relative + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + ToolboxTabMain.INSTANCE.drawGrid(gui); + } + + @Override + public List getTooltip(int mx, int my) { + return Collections.emptyList(); + } + + @Override + public void disableTool() { + if (nQuest != null) { nQuest = null; } + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; } - - @Override - public boolean useSelection() - { - return false; + + // Pre-sync + IQuestLine qLine = gui.getQuestLine(); + int qID = QuestDatabase.INSTANCE.nextID(); + int lID = QuestLineDatabase.INSTANCE.getID(qLine); + IQuestLineEntry qe = qLine.getValue(qID);//new QuestLineEntry(mx, my, 24); + + + if (qe == null) { + qe = new QuestLineEntry(nQuest.rect.x, nQuest.rect.y, 24, 24); + qLine.add(qID, qe); + } else { + qe.setPosition(nQuest.rect.x, nQuest.rect.y); + qe.setSize(24, 24); } + + // Sync Quest + NBTTagCompound quPayload = new NBTTagCompound(); + NBTTagList qdList = new NBTTagList(); + NBTTagCompound qTag = new NBTTagCompound(); + qTag.setInteger("questID", qID); + qdList.appendTag(qTag); + quPayload.setTag("data", qdList); + quPayload.setInteger("action", 3); + NetQuestEdit.sendEdit(quPayload); + + // Sync Line + NBTTagCompound chPayload = new NBTTagCompound(); + NBTTagList cdList = new NBTTagList(); + NBTTagCompound cTag = new NBTTagCompound(); + cTag.setInteger("chapterID", lID); + cTag.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); + cdList.appendTag(cTag); + chPayload.setTag("data", cdList); + chPayload.setInteger("action", 0); + NetChapterEdit.sendEdit(chPayload); + + return true; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int keyCode) { + return false; + } + + @Override + public boolean clampScrolling() { + return false; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return false; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java index fb9ed17c8..cb8a31dd8 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java @@ -9,95 +9,79 @@ import java.util.List; -public class ToolboxToolOpen implements IToolboxTool -{ - private CanvasQuestLine gui; - - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - } - - @Override - public void disableTool() - { - } - - @Override - public void refresh(CanvasQuestLine gui) - { - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) - { - return false; - } - - PanelButtonQuest btn = gui.getButtonAt(mx, my); - - if(btn != null) - { - int qID = btn.getStoredValue().getID(); - - Minecraft mc = Minecraft.getMinecraft(); - mc.displayGuiScreen(new GuiQuest(mc.currentScreen, qID)); - return true; - } - - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } +public class ToolboxToolOpen implements IToolboxTool { + private CanvasQuestLine gui; - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - } - - @Override - public List getTooltip(int mx, int my) - { - return null; - } + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + } + + @Override + public void disableTool() { + } - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - return false; - } - - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public void onSelection(NonNullList buttons) - { + @Override + public void refresh(CanvasQuestLine gui) { + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; } - - @Override - public boolean useSelection() - { - return false; + + PanelButtonQuest btn = gui.getButtonAt(mx, my); + + if (btn != null) { + int qID = btn.getStoredValue().getID(); + + Minecraft mc = Minecraft.getMinecraft(); + mc.displayGuiScreen(new GuiQuest(mc.currentScreen, qID)); + return true; } + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + return false; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return false; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java index 0e2e02ab6..9afa3e19c 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java @@ -14,131 +14,112 @@ import java.util.List; -public class ToolboxToolRemove implements IToolboxTool -{ - private CanvasQuestLine gui; - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - } - - @Override - public void disableTool() - { - } - - @Override - public void refresh(CanvasQuestLine gui) - { - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) - { - return false; - } - - IQuestLine line = gui.getQuestLine(); - PanelButtonQuest btn = gui.getButtonAt(mx, my); - - if(line != null && btn != null) - { - if(PanelToolController.selected.size() > 0) - { - if(!PanelToolController.selected.contains(btn)) return false; - for(PanelButtonQuest b : PanelToolController.selected) line.removeID(b.getStoredValue().getID()); - } else - { - int qID = btn.getStoredValue().getID(); - line.removeID(qID); - } - - // Sync Line - NBTTagCompound chPayload = new NBTTagCompound(); - NBTTagList cdList = new NBTTagList(); - NBTTagCompound cTag = new NBTTagCompound(); - cTag.setInteger("chapterID", QuestLineDatabase.INSTANCE.getID(line)); - cTag.setTag("config", line.writeToNBT(new NBTTagCompound(), null)); - cdList.appendTag(cTag); - chPayload.setTag("data", cdList); - chPayload.setInteger("action", 0); - NetChapterEdit.sendEdit(chPayload); - return true; - } - - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } +public class ToolboxToolRemove implements IToolboxTool { + private CanvasQuestLine gui; - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - } - - @Override - public List getTooltip(int mx, int my) - { - return null; + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + } + + @Override + public void disableTool() { + } + + @Override + public void refresh(CanvasQuestLine gui) { + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; } - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - if(PanelToolController.selected.size() > 0 && key == Keyboard.KEY_RETURN) - { - IQuestLine line = gui.getQuestLine(); - for(PanelButtonQuest b : PanelToolController.selected) line.removeID(b.getStoredValue().getID()); - - // Sync Line - NBTTagCompound chPayload = new NBTTagCompound(); - NBTTagList cdList = new NBTTagList(); - NBTTagCompound cTag = new NBTTagCompound(); - cTag.setInteger("chapterID", QuestLineDatabase.INSTANCE.getID(line)); - cTag.setTag("config", line.writeToNBT(new NBTTagCompound(), null)); - cdList.appendTag(cTag); - chPayload.setTag("data", cdList); - chPayload.setInteger("action", 0); - NetChapterEdit.sendEdit(chPayload); - return true; - } - - return false; - } - - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public void onSelection(NonNullList buttons) - { + IQuestLine line = gui.getQuestLine(); + PanelButtonQuest btn = gui.getButtonAt(mx, my); + + if (line != null && btn != null) { + if (!PanelToolController.selected.isEmpty()) { + if (!PanelToolController.selected.contains(btn)) { return false; } + for (PanelButtonQuest b : PanelToolController.selected) { line.removeID(b.getStoredValue().getID()); } + } else { + int qID = btn.getStoredValue().getID(); + line.removeID(qID); + } + + // Sync Line + NBTTagCompound chPayload = new NBTTagCompound(); + NBTTagList cdList = new NBTTagList(); + NBTTagCompound cTag = new NBTTagCompound(); + cTag.setInteger("chapterID", QuestLineDatabase.INSTANCE.getID(line)); + cTag.setTag("config", line.writeToNBT(new NBTTagCompound(), null)); + cdList.appendTag(cTag); + chPayload.setTag("data", cdList); + chPayload.setInteger("action", 0); + NetChapterEdit.sendEdit(chPayload); + return true; } - - @Override - public boolean useSelection() - { - return true; + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + if (!PanelToolController.selected.isEmpty() && key == Keyboard.KEY_RETURN) { + IQuestLine line = gui.getQuestLine(); + for (PanelButtonQuest b : PanelToolController.selected) { line.removeID(b.getStoredValue().getID()); } + + // Sync Line + NBTTagCompound chPayload = new NBTTagCompound(); + NBTTagList cdList = new NBTTagList(); + NBTTagCompound cTag = new NBTTagCompound(); + cTag.setInteger("chapterID", QuestLineDatabase.INSTANCE.getID(line)); + cTag.setTag("config", line.writeToNBT(new NBTTagCompound(), null)); + cdList.appendTag(cTag); + chPayload.setTag("data", cdList); + chPayload.setInteger("action", 0); + NetChapterEdit.sendEdit(chPayload); + return true; } + + return false; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return true; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java index a6b299383..1962a5312 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java @@ -12,117 +12,106 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolReset implements IToolboxTool -{ - private CanvasQuestLine gui; - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - } - - @Override - public void disableTool() - { - } - - @Override - public void refresh(CanvasQuestLine gui) - { - } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click != 0 || !gui.getTransform().contains(mx, my)) return false; - - PanelButtonQuest btn = gui.getButtonAt(mx, my); - - if(btn == null) return false; - if(PanelToolController.selected.size() > 0 && !PanelToolController.selected.contains(btn)) return false; - - List btnList = PanelToolController.selected.size() > 0 ? PanelToolController.selected : Collections.singletonList(btn); - int[] questIDs = new int[btnList.size()]; - - for(int i = 0; i < btnList.size(); i++) - { - questIDs[i] = btnList.get(i).getStoredValue().getID(); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", questIDs); - payload.setBoolean("state", false); - payload.setInteger("action", 2); - NetQuestEdit.sendEdit(payload); - - return true; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; - } +public class ToolboxToolReset implements IToolboxTool { + private CanvasQuestLine gui; + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + } + + @Override + public void disableTool() { + } + + @Override + public void refresh(CanvasQuestLine gui) { + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click != 0 || !gui.getTransform().contains(mx, my)) { return false; } - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { + PanelButtonQuest btn = gui.getButtonAt(mx, my); + + if (btn == null) { + return false; } - - @Override - public List getTooltip(int mx, int my) - { - return null; + if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { + return false; } - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - if(PanelToolController.selected.size() <= 0 || key != Keyboard.KEY_RETURN) return false; - - List btnList = PanelToolController.selected; - int[] questIDs = new int[btnList.size()]; - - for(int i = 0; i < btnList.size(); i++) - { - questIDs[i] = btnList.get(i).getStoredValue().getID(); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", questIDs); - payload.setBoolean("state", false); - payload.setInteger("action", 2); - NetQuestEdit.sendEdit(payload); - - return true; - } - - @Override - public boolean clampScrolling() - { - return true; - } - - @Override - public void onSelection(NonNullList buttons) - { + List btnList = !PanelToolController.selected.isEmpty() ? PanelToolController.selected + : Collections.singletonList(btn); + int[] questIDs = new int[btnList.size()]; + + for (int i = 0; i < btnList.size(); i++) { + questIDs[i] = btnList.get(i).getStoredValue().getID(); } - - @Override - public boolean useSelection() - { - return true; + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", questIDs); + payload.setBoolean("state", false); + payload.setInteger("action", 2); + NetQuestEdit.sendEdit(payload); + + return true; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + } + + @Override + public void drawOverlay(int mx, int my, float partialTick) { + } + + @Override + public List getTooltip(int mx, int my) { + return null; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + + List btnList = PanelToolController.selected; + int[] questIDs = new int[btnList.size()]; + + for (int i = 0; i < btnList.size(); i++) { + questIDs[i] = btnList.get(i).getStoredValue().getID(); } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", questIDs); + payload.setBoolean("state", false); + payload.setInteger("action", 2); + NetQuestEdit.sendEdit(payload); + + return true; + } + + @Override + public boolean clampScrolling() { + return true; + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return true; + } } diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java index 4eb20f7cd..d9abbabc8 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java @@ -24,269 +24,234 @@ import java.util.Collections; import java.util.List; -public class ToolboxToolScale implements IToolboxTool -{ - private CanvasQuestLine gui; - - private final NonNullList grabList = NonNullList.create(); - private final GuiRectangle scaleBounds = new GuiRectangle(0, 0, 0, 0); - private IGuiLine selLine = new BoxLine(); - private IGuiColor selCol = new GuiColorPulse(0xFFFFFFFF, 0xFF000000, 2F, 0F); - - @Override - public void initTool(CanvasQuestLine gui) - { - this.gui = gui; - grabList.clear(); - } - - @Override - public void disableTool() - { - if(grabList.size() > 0) - { - for(GrabEntry grab : grabList) - { - IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); - - if(qle != null) - { - grab.btn.rect.x = qle.getPosX(); - grab.btn.rect.y = qle.getPosY(); - grab.btn.rect.w = qle.getSizeX(); - grab.btn.rect.h = qle.getSizeY(); - } - } - - grabList.clear(); - } - } - - @Override - public void refresh(CanvasQuestLine gui) - { - List tmp = new ArrayList<>(); - - for(GrabEntry grab : grabList) - { - for(PanelButtonQuest btn : PanelToolController.selected) - { - if(btn.getStoredValue().getID() == grab.btn.getStoredValue().getID()) - { - tmp.add(new GrabEntry(btn, grab.anchor)); - break; - } - } +public class ToolboxToolScale implements IToolboxTool { + private CanvasQuestLine gui; + + private final NonNullList grabList = NonNullList.create(); + private final GuiRectangle scaleBounds = new GuiRectangle(0, 0, 0, 0); + private final IGuiLine selLine = new BoxLine(); + private final IGuiColor selCol = new GuiColorPulse(0xFFFFFFFF, 0xFF000000, 2F, 0F); + + @Override + public void initTool(CanvasQuestLine gui) { + this.gui = gui; + grabList.clear(); + } + + @Override + public void disableTool() { + if (!grabList.isEmpty()) { + for (GrabEntry grab : grabList) { + IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); + + if (qle != null) { + grab.btn.rect.x = qle.getPosX(); + grab.btn.rect.y = qle.getPosY(); + grab.btn.rect.w = qle.getSizeX(); + grab.btn.rect.h = qle.getSizeY(); } - - grabList.clear(); - grabList.addAll(tmp); - } + } - @Override - public void drawCanvas(int mx, int my, float partialTick) - { - if(grabList.size() > 0) - { - int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); - int dx = mx + snap/2; - int dy = my + snap/2; - dx = ((dx%snap) + snap)%snap; - dy = ((dy%snap) + snap)%snap; - dx = (mx + snap/2) - dx; - dy = (my + snap/2) - dy; - - scaleBounds.w = dx - scaleBounds.x; - scaleBounds.h = dy - scaleBounds.y; - - boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - for(GrabEntry grab : grabList) - { - grab.btn.rect.w = Math.max(1, Math.round(scaleBounds.w * grab.anchor.z)); - grab.btn.rect.h = Math.max(1, Math.round(scaleBounds.h * grab.anchor.w)); - - if(shift) // Probably could be implemented better but I'm just going to leave it as now - { - grab.btn.rect.x = grab.sx - grab.btn.rect.w/2; - grab.btn.rect.y = grab.sy - grab.btn.rect.h/2; - } else - { - grab.btn.rect.x = scaleBounds.x + Math.round(scaleBounds.w * grab.anchor.x); - grab.btn.rect.y = scaleBounds.y + Math.round(scaleBounds.h * grab.anchor.y); - } - } - - if(grabList.size() > 1 && !shift) - { - selLine.drawLine(scaleBounds, scaleBounds, 2, selCol, partialTick); - } - } - } - - @Override - public void drawOverlay(int mx, int my, float partialTick) - { - if(grabList.size() > 0) ToolboxTabMain.INSTANCE.drawGrid(gui); + grabList.clear(); } - - @Override - public List getTooltip(int mx, int my) - { - return grabList.size() <= 0 ? null : Collections.emptyList(); + } + + @Override + public void refresh(CanvasQuestLine gui) { + List tmp = new ArrayList<>(); + + for (GrabEntry grab : grabList) { + for (PanelButtonQuest btn : PanelToolController.selected) { + if (btn.getStoredValue().getID() == grab.btn.getStoredValue().getID()) { + tmp.add(new GrabEntry(btn, grab.anchor)); + break; + } + } } - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(click == 1 && grabList.size() > 0) - { - for(GrabEntry grab : grabList) - { - IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); - - if(qle != null) - { - grab.btn.rect.x = qle.getPosX(); - grab.btn.rect.y = qle.getPosY(); - grab.btn.rect.w = qle.getSizeX(); - grab.btn.rect.h = qle.getSizeY(); - } - } - - grabList.clear(); - return true; - } else if(click != 0 || !gui.getTransform().contains(mx, my)) - { - return false; - } - - if(grabList.size() > 0) - { - IQuestLine qLine = gui.getQuestLine(); - int lID = QuestLineDatabase.INSTANCE.getID(qLine); - for(GrabEntry grab : grabList) - { - IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); - if(qle != null) - { - qle.setPosition(grab.btn.rect.x, grab.btn.rect.y); - qle.setSize(grab.btn.rect.w, grab.btn.rect.h); - } - } - - // Send quest line edits - NBTTagCompound chPayload = new NBTTagCompound(); - NBTTagList cdList = new NBTTagList(); - NBTTagCompound tagEntry = new NBTTagCompound(); - tagEntry.setInteger("chapterID", lID); - tagEntry.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); - cdList.appendTag(tagEntry); - chPayload.setTag("data", cdList); - chPayload.setInteger("action", 0); - NetChapterEdit.sendEdit(chPayload); - - grabList.clear(); - return true; - } - - PanelButtonQuest btnClicked = gui.getButtonAt(mx, my); - - if(btnClicked != null) // Pickup the group or the single one if none are selected + grabList.clear(); + grabList.addAll(tmp); + } + + @Override + public void drawCanvas(int mx, int my, float partialTick) { + if (!grabList.isEmpty()) { + int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); + int dx = mx + snap / 2; + int dy = my + snap / 2; + dx = ((dx % snap) + snap) % snap; + dy = ((dy % snap) + snap) % snap; + dx = (mx + snap / 2) - dx; + dy = (my + snap / 2) - dy; + + scaleBounds.w = dx - scaleBounds.x; + scaleBounds.h = dy - scaleBounds.y; + + boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + for (GrabEntry grab : grabList) { + grab.btn.rect.w = Math.max(1, Math.round(scaleBounds.w * grab.anchor.z)); + grab.btn.rect.h = Math.max(1, Math.round(scaleBounds.h * grab.anchor.w)); + + if (shift) // Probably could be implemented better but I'm just going to leave it as now { - if(PanelToolController.selected.size() > 0) - { - if(!PanelToolController.selected.contains(btnClicked)) return false; - - boolean first = true; - for(PanelButtonQuest btn : PanelToolController.selected) - { - if(first) - { - scaleBounds.x = btn.rect.x; - scaleBounds.y = btn.rect.y; - scaleBounds.w = btn.rect.w; - scaleBounds.h = btn.rect.h; - first = false; - } else - { - scaleBounds.x = Math.min(scaleBounds.x, btn.rect.x); - scaleBounds.y = Math.min(scaleBounds.y, btn.rect.y); - scaleBounds.w = Math.max(scaleBounds.x + scaleBounds.w, btn.rect.x + btn.rect.w) - scaleBounds.x; - scaleBounds.h = Math.max(scaleBounds.y + scaleBounds.h, btn.rect.y + btn.rect.h) - scaleBounds.y; - } - } - - for(PanelButtonQuest btn : PanelToolController.selected) - { - float x = (btn.rect.x - scaleBounds.x) / (float)scaleBounds.w; - float y = (btn.rect.y - scaleBounds.y) / (float)scaleBounds.h; - float w = btn.rect.w / (float)scaleBounds.w; - float h = btn.rect.h / (float)scaleBounds.h; - grabList.add(new GrabEntry(btn, new Vector4f(x, y, w, h))); - } - } else - { - scaleBounds.x = btnClicked.rect.x; - scaleBounds.y = btnClicked.rect.y; - scaleBounds.w = btnClicked.rect.w; - scaleBounds.h = btnClicked.rect.h; - grabList.add(new GrabEntry(btnClicked, new Vector4f(0F, 0F, 1F, 1F))); - } - - return true; + grab.btn.rect.x = grab.sx - grab.btn.rect.w / 2; + grab.btn.rect.y = grab.sy - grab.btn.rect.h / 2; + } else { + grab.btn.rect.x = scaleBounds.x + Math.round(scaleBounds.w * grab.anchor.x); + grab.btn.rect.y = scaleBounds.y + Math.round(scaleBounds.h * grab.anchor.y); } - - return false; - } - - @Override - public boolean onMouseRelease(int mx, int my, int click) - { - return false; + } + + if (grabList.size() > 1 && !shift) { + selLine.drawLine(scaleBounds, scaleBounds, 2, selCol, partialTick); + } } + } - @Override - public boolean onMouseScroll(int mx, int my, int scroll) - { - return false; - } - - @Override - public boolean onKeyPressed(char c, int key) - { - return grabList.size() > 0; - } - - @Override - public boolean clampScrolling() - { - return grabList.size() <= 0; - } - - @Override - public void onSelection(NonNullList buttons) - { + @Override + public void drawOverlay(int mx, int my, float partialTick) { + if (!grabList.isEmpty()) { + ToolboxTabMain.INSTANCE.drawGrid(gui); } - - @Override - public boolean useSelection() - { - return grabList.size() <= 0; + } + + @Override + public List getTooltip(int mx, int my) { + return grabList.isEmpty() ? null : Collections.emptyList(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (click == 1 && !grabList.isEmpty()) { + for (GrabEntry grab : grabList) { + IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); + + if (qle != null) { + grab.btn.rect.x = qle.getPosX(); + grab.btn.rect.y = qle.getPosY(); + grab.btn.rect.w = qle.getSizeX(); + grab.btn.rect.h = qle.getSizeY(); + } + } + + grabList.clear(); + return true; + } else if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; + } + + if (!grabList.isEmpty()) { + IQuestLine qLine = gui.getQuestLine(); + int lID = QuestLineDatabase.INSTANCE.getID(qLine); + for (GrabEntry grab : grabList) { + IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); + if (qle != null) { + qle.setPosition(grab.btn.rect.x, grab.btn.rect.y); + qle.setSize(grab.btn.rect.w, grab.btn.rect.h); + } + } + + // Send quest line edits + NBTTagCompound chPayload = new NBTTagCompound(); + NBTTagList cdList = new NBTTagList(); + NBTTagCompound tagEntry = new NBTTagCompound(); + tagEntry.setInteger("chapterID", lID); + tagEntry.setTag("config", qLine.writeToNBT(new NBTTagCompound(), null)); + cdList.appendTag(tagEntry); + chPayload.setTag("data", cdList); + chPayload.setInteger("action", 0); + NetChapterEdit.sendEdit(chPayload); + + grabList.clear(); + return true; } - - private class GrabEntry + + PanelButtonQuest btnClicked = gui.getButtonAt(mx, my); + + if (btnClicked != null) // Pickup the group or the single one if none are selected { - private final PanelButtonQuest btn; - private final Vector4f anchor; - private final int sx; - private final int sy; - - private GrabEntry(PanelButtonQuest btn, Vector4f anchor) - { - this.btn = btn; - this.anchor = anchor; - this.sx = btn.rect.x + btn.rect.w/2; - this.sy = btn.rect.y + btn.rect.h/2; + if (!PanelToolController.selected.isEmpty()) { + if (!PanelToolController.selected.contains(btnClicked)) { + return false; + } + + boolean first = true; + for (PanelButtonQuest btn : PanelToolController.selected) { + if (first) { + scaleBounds.x = btn.rect.x; + scaleBounds.y = btn.rect.y; + scaleBounds.w = btn.rect.w; + scaleBounds.h = btn.rect.h; + first = false; + } else { + scaleBounds.x = Math.min(scaleBounds.x, btn.rect.x); + scaleBounds.y = Math.min(scaleBounds.y, btn.rect.y); + scaleBounds.w = Math.max(scaleBounds.x + scaleBounds.w, btn.rect.x + btn.rect.w) - scaleBounds.x; + scaleBounds.h = Math.max(scaleBounds.y + scaleBounds.h, btn.rect.y + btn.rect.h) - scaleBounds.y; + } + } + + for (PanelButtonQuest btn : PanelToolController.selected) { + float x = (btn.rect.x - scaleBounds.x) / (float) scaleBounds.w; + float y = (btn.rect.y - scaleBounds.y) / (float) scaleBounds.h; + float w = btn.rect.w / (float) scaleBounds.w; + float h = btn.rect.h / (float) scaleBounds.h; + grabList.add(new GrabEntry(btn, new Vector4f(x, y, w, h))); } + } else { + scaleBounds.x = btnClicked.rect.x; + scaleBounds.y = btnClicked.rect.y; + scaleBounds.w = btnClicked.rect.w; + scaleBounds.h = btnClicked.rect.h; + grabList.add(new GrabEntry(btnClicked, new Vector4f(0F, 0F, 1F, 1F))); + } + + return true; + } + + return false; + } + + @Override + public boolean onMouseRelease(int mx, int my, int click) { + return false; + } + + @Override + public boolean onMouseScroll(int mx, int my, int scroll) { + return false; + } + + @Override + public boolean onKeyPressed(char c, int key) { + return !grabList.isEmpty(); + } + + @Override + public boolean clampScrolling() { + return grabList.isEmpty(); + } + + @Override + public void onSelection(NonNullList buttons) { + } + + @Override + public boolean useSelection() { + return grabList.isEmpty(); + } + + private static class GrabEntry { + private final PanelButtonQuest btn; + private final Vector4f anchor; + private final int sx; + private final int sy; + + private GrabEntry(PanelButtonQuest btn, Vector4f anchor) { + this.btn = btn; + this.anchor = anchor; + this.sx = btn.rect.x + btn.rect.w / 2; + this.sy = btn.rect.y + btn.rect.h / 2; } + } } diff --git a/src/main/java/betterquesting/client/ui_builder/CanvasBuilderUtil.java b/src/main/java/betterquesting/client/ui_builder/CanvasBuilderUtil.java deleted file mode 100644 index 52063528a..000000000 --- a/src/main/java/betterquesting/client/ui_builder/CanvasBuilderUtil.java +++ /dev/null @@ -1,5 +0,0 @@ -package betterquesting.client.ui_builder; - -public class CanvasBuilderUtil -{ -} diff --git a/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java b/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java index e780fe63e..3cff42cfb 100644 --- a/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java +++ b/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java @@ -16,112 +16,104 @@ import java.util.ArrayList; import java.util.List; -public class ComponentPanel implements INBTSaveLoad -{ - // Purely for organisational purposes - public String refName = "New Panel"; - public String panelType = "betterquesting:canvas_empty"; - - // Usually these two are the same but not always - public int cvParentID = -1; // ID of the canvas we're contained within - public int tfParentID = -1; // ID of the transform we're positioned relative to - - private NBTTagCompound transTag = new NBTTagCompound(); - private NBTTagCompound panelData = new NBTTagCompound(); - - // When these are passed off to the GUI context, make sure it's stated whether it's in-editor or not - // (only content and navigation need setting up otherwise the GUI might actually edit things before intended use) - private final List scripts = new ArrayList<>(); - - public ComponentPanel() - { - setTransform(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0)); - } - - public ComponentPanel(GuiTransform transform) - { - setTransform(transform); - } - - public void setTransform(GuiTransform transform) - { - Vector4f anchor = transform.getAnchor(); - transTag.setFloat("anchor_left", anchor.x); - transTag.setFloat("anchor_top", anchor.y); - transTag.setFloat("anchor_right", anchor.z); - transTag.setFloat("anchor_bottom", anchor.w); - - GuiPadding padding = transform.getPadding(); - transTag.setInteger("pad_left", padding.l); - transTag.setInteger("pad_top", padding.t); - transTag.setInteger("pad_right", padding.r); - transTag.setInteger("pad_bottom", padding.b); - - transTag.setInteger("depth", transform.getDepth()); - } - - public NBTTagCompound getTransformTag() - { - return transTag; - } - - public NBTTagCompound getPanelData() - { - return panelData; - } - - public void setPanelData(@Nonnull NBTTagCompound tag) - { - this.panelData = tag; - } - - public IGuiPanel build() - { - Vector4f anchor = new Vector4f(transTag.getFloat("anchor_left"), transTag.getFloat("anchor_top"), transTag.getFloat("anchor_right"), transTag.getFloat("anchor_bottom")); - GuiPadding padding = new GuiPadding(transTag.getInteger("pad_left"), transTag.getInteger("pad_top"), transTag.getInteger("pad_right"), transTag.getInteger("pad_bottom")); - GuiTransform transform = new GuiTransform(anchor, padding, transTag.getInteger("depth")); - - ResourceLocation res = StringUtils.isNullOrEmpty(panelType) ? new ResourceLocation("betterquesting:canvas_empty") : new ResourceLocation(panelType); - return ComponentRegistry.INSTANCE.createNew(res, transform, panelData); - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) - { - nbt.setString("ref_name", refName); - nbt.setString("panel_type", panelType); - - nbt.setInteger("cv_parent", cvParentID); - nbt.setInteger("tf_parent", tfParentID); - - nbt.setTag("transform", transTag.copy()); - nbt.setTag("panel_data", panelData.copy()); - - NBTTagList sList = new NBTTagList(); - scripts.forEach((str) -> sList.appendTag(new NBTTagString(str))); - nbt.setTag("script_hooks", sList); - - return nbt; - } - - @Override - public void readFromNBT(NBTTagCompound nbt) - { - refName = nbt.getString("ref_name"); - panelType = nbt.getString("panel_type"); - - cvParentID = nbt.getInteger("cv_parent"); - tfParentID = nbt.getInteger("tf_parent"); - - // Location of the panel - transTag = nbt.getCompoundTag("transform").copy(); - panelData = nbt.getCompoundTag("panel_data").copy(); - - scripts.clear(); - NBTTagList sList = nbt.getTagList("script_hooks", 8); - for(int i = 0; i < sList.tagCount(); i++) - { - scripts.add(sList.getStringTagAt(i)); - } +public class ComponentPanel implements INBTSaveLoad { + // Purely for organisational purposes + public String refName = "New Panel"; + public String panelType = "betterquesting:canvas_empty"; + + // Usually these two are the same but not always + public int cvParentID = -1; // ID of the canvas we're contained within + public int tfParentID = -1; // ID of the transform we're positioned relative to + + private NBTTagCompound transTag = new NBTTagCompound(); + private NBTTagCompound panelData = new NBTTagCompound(); + + // When these are passed off to the GUI context, make sure it's stated whether it's in-editor or not + // (only content and navigation need setting up otherwise the GUI might actually edit things before intended use) + private final List scripts = new ArrayList<>(); + + public ComponentPanel() { + setTransform(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0)); + } + + public ComponentPanel(GuiTransform transform) { + setTransform(transform); + } + + public void setTransform(GuiTransform transform) { + Vector4f anchor = transform.getAnchor(); + transTag.setFloat("anchor_left", anchor.x); + transTag.setFloat("anchor_top", anchor.y); + transTag.setFloat("anchor_right", anchor.z); + transTag.setFloat("anchor_bottom", anchor.w); + + GuiPadding padding = transform.getPadding(); + transTag.setInteger("pad_left", padding.l); + transTag.setInteger("pad_top", padding.t); + transTag.setInteger("pad_right", padding.r); + transTag.setInteger("pad_bottom", padding.b); + + transTag.setInteger("depth", transform.getDepth()); + } + + public NBTTagCompound getTransformTag() { + return transTag; + } + + public NBTTagCompound getPanelData() { + return panelData; + } + + public void setPanelData(@Nonnull NBTTagCompound tag) { + this.panelData = tag; + } + + public IGuiPanel build() { + Vector4f anchor = new Vector4f(transTag.getFloat("anchor_left"), transTag.getFloat("anchor_top"), + transTag.getFloat("anchor_right"), transTag.getFloat("anchor_bottom")); + GuiPadding padding = new GuiPadding(transTag.getInteger("pad_left"), transTag.getInteger("pad_top"), + transTag.getInteger("pad_right"), transTag.getInteger("pad_bottom")); + GuiTransform transform = new GuiTransform(anchor, padding, transTag.getInteger("depth")); + + ResourceLocation res = StringUtils.isNullOrEmpty(panelType) ? new ResourceLocation("betterquesting:canvas_empty") + : new ResourceLocation(panelType); + return ComponentRegistry.INSTANCE.createNew(res, transform, panelData); + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + nbt.setString("ref_name", refName); + nbt.setString("panel_type", panelType); + + nbt.setInteger("cv_parent", cvParentID); + nbt.setInteger("tf_parent", tfParentID); + + nbt.setTag("transform", transTag.copy()); + nbt.setTag("panel_data", panelData.copy()); + + NBTTagList sList = new NBTTagList(); + scripts.forEach((str) -> sList.appendTag(new NBTTagString(str))); + nbt.setTag("script_hooks", sList); + + return nbt; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + refName = nbt.getString("ref_name"); + panelType = nbt.getString("panel_type"); + + cvParentID = nbt.getInteger("cv_parent"); + tfParentID = nbt.getInteger("tf_parent"); + + // Location of the panel + transTag = nbt.getCompoundTag("transform").copy(); + panelData = nbt.getCompoundTag("panel_data").copy(); + + scripts.clear(); + NBTTagList sList = nbt.getTagList("script_hooks", 8); + for (int i = 0; i < sList.tagCount(); i++) { + scripts.add(sList.getStringTagAt(i)); } + } } diff --git a/src/main/java/betterquesting/client/ui_builder/ComponentRegistry.java b/src/main/java/betterquesting/client/ui_builder/ComponentRegistry.java index 0603069db..d839de08e 100644 --- a/src/main/java/betterquesting/client/ui_builder/ComponentRegistry.java +++ b/src/main/java/betterquesting/client/ui_builder/ComponentRegistry.java @@ -16,58 +16,56 @@ import java.util.List; import java.util.function.BiFunction; -public class ComponentRegistry -{ - public static final ComponentRegistry INSTANCE = new ComponentRegistry(); - - private final HashMap> REG_MAP = new HashMap<>(); - private final HashMap TEMPLATE_TAGS = new HashMap<>(); - - public ComponentRegistry() - { - init(); - } - - public void register(@Nonnull ResourceLocation idname, @Nonnull BiFunction factory, @Nonnull NBTTagCompound template) - { - if(REG_MAP.containsKey(idname)) - { - throw new IllegalArgumentException("Tried to register duplicate GUI component ID"); - } - - REG_MAP.put(idname, factory); - TEMPLATE_TAGS.put(idname, template); - } - - @Nonnull - public IGuiPanel createNew(@Nonnull ResourceLocation idName, @Nonnull IGuiRect rect, @Nullable NBTTagCompound tag) - { - BiFunction factory = REG_MAP.get(idName); - if(factory == null) return new CanvasTextured(rect, ThemeRegistry.INSTANCE.getTexture(null)); // TODO: Return placeholder panel - IGuiPanel pan = factory.apply(rect, tag); - //if(tag != null) pan.readFromNBT(tag); - return pan; - } - - @Nonnull - public NBTTagCompound getTemplateTag(@Nonnull ResourceLocation idName) - { - NBTTagCompound tag = TEMPLATE_TAGS.get(idName); - return tag == null ? new NBTTagCompound() : tag.copy(); - } - - public List getRegisteredIDs() - { - return new ArrayList<>(REG_MAP.keySet()); +public class ComponentRegistry { + public static final ComponentRegistry INSTANCE = new ComponentRegistry(); + + private final HashMap> REG_MAP = new HashMap<>(); + private final HashMap TEMPLATE_TAGS = new HashMap<>(); + + public ComponentRegistry() { + init(); + } + + public void register(@Nonnull ResourceLocation idname, + @Nonnull BiFunction factory, + @Nonnull NBTTagCompound template) { + if (REG_MAP.containsKey(idname)) { + throw new IllegalArgumentException("Tried to register duplicate GUI component ID"); } - - private void init() - { - //register(new ResourceLocation("betterquesting", "canvas_empty"), CanvasEmpty::new, new NBTTagCompound()); - - NBTTagCompound refTag = new NBTTagCompound(); - //refTag.setString("texture", PresetTexture.PANEL_MAIN.getKey().toString()); - register(new ResourceLocation("betterquesting", "canvas_textured"), (rect, tag) -> new CanvasTextured(rect, PresetTexture.PANEL_MAIN.getTexture()), refTag); - register(new ResourceLocation("betterquesting", "panel_button"), (rect, tag) -> {return new PanelButton(rect, -1, "New Button");}, refTag); + + REG_MAP.put(idname, factory); + TEMPLATE_TAGS.put(idname, template); + } + + @Nonnull + public IGuiPanel createNew(@Nonnull ResourceLocation idName, @Nonnull IGuiRect rect, @Nullable NBTTagCompound tag) { + BiFunction factory = REG_MAP.get(idName); + if (factory == null) { + return new CanvasTextured(rect, ThemeRegistry.INSTANCE.getTexture(null)); // TODO: Return placeholder panel } + IGuiPanel pan = factory.apply(rect, tag); + //if(tag != null) pan.readFromNBT(tag); + return pan; + } + + @Nonnull + public NBTTagCompound getTemplateTag(@Nonnull ResourceLocation idName) { + NBTTagCompound tag = TEMPLATE_TAGS.get(idName); + return tag == null ? new NBTTagCompound() : tag.copy(); + } + + public List getRegisteredIDs() { + return new ArrayList<>(REG_MAP.keySet()); + } + + private void init() { + //register(new ResourceLocation("betterquesting", "canvas_empty"), CanvasEmpty::new, new NBTTagCompound()); + + NBTTagCompound refTag = new NBTTagCompound(); + //refTag.setString("texture", PresetTexture.PANEL_MAIN.getKey().toString()); + register(new ResourceLocation("betterquesting", "canvas_textured"), + (rect, tag) -> new CanvasTextured(rect, PresetTexture.PANEL_MAIN.getTexture()), refTag); + register(new ResourceLocation("betterquesting", "panel_button"), + (rect, tag) -> new PanelButton(rect, -1, "New Button"), refTag); + } } diff --git a/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java b/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java index dd9a203d1..0feb1b652 100644 --- a/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java +++ b/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java @@ -6,7 +6,10 @@ import betterquesting.api2.client.gui.controls.PanelButton; import betterquesting.api2.client.gui.controls.PanelButtonStorage; import betterquesting.api2.client.gui.misc.*; -import betterquesting.api2.client.gui.panels.*; +import betterquesting.api2.client.gui.panels.CanvasEmpty; +import betterquesting.api2.client.gui.panels.CanvasTextured; +import betterquesting.api2.client.gui.panels.IGuiCanvas; +import betterquesting.api2.client.gui.panels.IGuiPanel; import betterquesting.api2.client.gui.panels.bars.PanelVScrollBar; import betterquesting.api2.client.gui.panels.lists.CanvasScrolling; import betterquesting.api2.client.gui.resources.colors.GuiColorStatic; @@ -30,822 +33,749 @@ import javax.annotation.Nonnull; import java.util.*; -public class GuiBuilderMain extends GuiScreenCanvas implements IVolatileScreen -{ - // Database of panel components given unique IDs - // We can deal with the save/load here without having to make an entire class for this - private final SimpleDatabase COM_DB = new SimpleDatabase<>(); - // GUI panel representations of components. IDs should line up with COM_DB - private final SimpleDatabase PANEL_DB = new SimpleDatabase<>(); - - private CanvasEmpty cvPreview; - private IGuiCanvas cvPropTray; // Also doubles as the palette tray - private PanelButton btnTrayToggle; - - private ResourceLocation paletteSel = null; - - private int toolMode = 0; - // 0 = NONE (operate the preview panels as-is) - // 1 = SELECT (highlight panels to edit/delete) - // 2 = CREATE (Places a new panel on to the first panel under the mouse or which-ever is selected) - // 3 = RESIZE (Drag edges of the panels to change the anchors and/or padding dimensions) - // 4 = RE-ANCHOR (Move the panel to a new canvas parent. Ctrl moves only the transform parenting) - // 5 = DELETE (Deletes the panel under the mouse and all of its children. Transform parents are reset to -1) - - private int selectedID = -1; - private IGuiPanel selPn = null; - - private int dragID = -1; // Which panel are we dragging from - private int dragType = -1; // What kind of drag are we performing - - // TODO: Add context information about what this GUI is being built for - public GuiBuilderMain(GuiScreen parent) - { - super(parent); - - // We're using the entire screen including areas normally reserved for margins to make space for tools - this.useMargins(false); - this.useDefaultBG(true); - } - - @Override - public void initPanel() - { - super.initPanel(); - - // The normal area with margins will now be the inner preview so we recalculate margins for that here - int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); - int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); - GuiTransform pvTransform = new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(marginX, marginY, marginX, marginY), 0); - - cvPreview = new CanvasEmpty(pvTransform); - this.addPanel(cvPreview); - - // === PROPERTY TRAY === - - cvPropTray = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 1F), new GuiPadding(0, 32, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvPropTray); - cvPropTray.setEnabled(false); - - btnTrayToggle = new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.5F, 1F), -16, -16, 16, 16, 0), -1, "").setIcon(PresetIcon.ICON_UP.getTexture()); - btnTrayToggle.setClickAction((btn) -> { - if(cvPropTray.isEnabled()) - { - closeTray(); - } else if(selectedID >= 0 && !(toolMode == 0 || toolMode == 2)) - { - ComponentPanel com = COM_DB.getValue(selectedID); - // TODO: Add a callback here so the component can read in changes - if(com != null) openTrayNBT(com.writeToNBT(new NBTTagCompound())); - } else if(toolMode == 3) - { - openTrayPalette(); - } - }); - this.addPanel(btnTrayToggle); - - // === EXIT CORNER === - - PanelButton btnExit = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -16, 0, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - mc.displayGuiScreen(parent); - } - }.setIcon(PresetIcon.ICON_CROSS.getTexture()); - this.addPanel(btnExit); - - // === SAVE - LOAD - REFRESH === - - PanelButton btnSave = new PanelButton(new GuiRectangle(0, 0, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - // Deal with this later - } - }.setIcon(PresetIcon.ICON_TICK.getTexture()); - this.addPanel(btnSave); - - PanelButton btnLoad = new PanelButton(new GuiRectangle(16, 0, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - // Deal with this later - } - }.setIcon(PresetIcon.ICON_FOLDER_OPEN.getTexture()); - this.addPanel(btnLoad); - - PanelButton btnRefresh = new PanelButton(new GuiRectangle(32, 0, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - refreshComponents(); - } - }.setIcon(PresetIcon.ICON_REFRESH.getTexture()); - this.addPanel(btnRefresh); - - // === TOOL ROW === - - final List toolBtns = new ArrayList<>(); - - PanelButton btnCursor = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 0, -16, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); - toolMode = 0; - } - }.setIcon(PresetIcon.ICON_CURSOR.getTexture()); - btnCursor.setActive(toolMode != 0); - this.addPanel(btnCursor); - toolBtns.add(btnCursor); - - PanelButton btnProp = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 16, -16, 16, 16, 0), -1, "") +public class GuiBuilderMain extends GuiScreenCanvas implements IVolatileScreen { + // Database of panel components given unique IDs + // We can deal with the save/load here without having to make an entire class for this + private final SimpleDatabase COM_DB = new SimpleDatabase<>(); + // GUI panel representations of components. IDs should line up with COM_DB + private final SimpleDatabase PANEL_DB = new SimpleDatabase<>(); + + private CanvasEmpty cvPreview; + private IGuiCanvas cvPropTray; // Also doubles as the palette tray + private PanelButton btnTrayToggle; + + private ResourceLocation paletteSel = null; + + private int toolMode = 0; + // 0 = NONE (operate the preview panels as-is) + // 1 = SELECT (highlight panels to edit/delete) + // 2 = CREATE (Places a new panel on to the first panel under the mouse or which-ever is selected) + // 3 = RESIZE (Drag edges of the panels to change the anchors and/or padding dimensions) + // 4 = RE-ANCHOR (Move the panel to a new canvas parent. Ctrl moves only the transform parenting) + // 5 = DELETE (Deletes the panel under the mouse and all of its children. Transform parents are reset to -1) + + private int selectedID = -1; + private IGuiPanel selPn = null; + + private int dragID = -1; // Which panel are we dragging from + private int dragType = -1; // What kind of drag are we performing + + // TODO: Add context information about what this GUI is being built for + public GuiBuilderMain(GuiScreen parent) { + super(parent); + + // We're using the entire screen including areas normally reserved for margins to make space for tools + this.useMargins(false); + this.useDefaultBG(true); + } + + @Override + public void initPanel() { + super.initPanel(); + + // The normal area with margins will now be the inner preview so we recalculate margins for that here + int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); + int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); + GuiTransform pvTransform = + new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(marginX, marginY, marginX, marginY), 0); + + cvPreview = new CanvasEmpty(pvTransform); + this.addPanel(cvPreview); + + // === PROPERTY TRAY === + + cvPropTray = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 1F), new GuiPadding(0, 32, 0, 0), 0), + PresetTexture.PANEL_MAIN.getTexture()); + this.addPanel(cvPropTray); + cvPropTray.setEnabled(false); + + btnTrayToggle = + new PanelButton(new GuiTransform(new Vector4f(0.5F, 1F, 0.5F, 1F), -16, -16, 16, 16, 0), -1, "").setIcon( + PresetIcon.ICON_UP.getTexture()); + btnTrayToggle.setClickAction((btn) -> { + if (cvPropTray.isEnabled()) { + closeTray(); + } else if (selectedID >= 0 && !(toolMode == 0 || toolMode == 2)) { + ComponentPanel com = COM_DB.getValue(selectedID); + // TODO: Add a callback here so the component can read in changes + if (com != null) { openTrayNBT(com.writeToNBT(new NBTTagCompound())); } + } else if (toolMode == 3) { + openTrayPalette(); + } + }); + this.addPanel(btnTrayToggle); + + // === EXIT CORNER === + + PanelButton btnExit = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -16, 0, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + mc.displayGuiScreen(parent); + } + }.setIcon(PresetIcon.ICON_CROSS.getTexture()); + this.addPanel(btnExit); + + // === SAVE - LOAD - REFRESH === + + PanelButton btnSave = new PanelButton(new GuiRectangle(0, 0, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + // Deal with this later + } + }.setIcon(PresetIcon.ICON_TICK.getTexture()); + this.addPanel(btnSave); + + PanelButton btnLoad = new PanelButton(new GuiRectangle(16, 0, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + // Deal with this later + } + }.setIcon(PresetIcon.ICON_FOLDER_OPEN.getTexture()); + this.addPanel(btnLoad); + + PanelButton btnRefresh = new PanelButton(new GuiRectangle(32, 0, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + refreshComponents(); + } + }.setIcon(PresetIcon.ICON_REFRESH.getTexture()); + this.addPanel(btnRefresh); + + // === TOOL ROW === + + final List toolBtns = new ArrayList<>(); + + PanelButton btnCursor = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 0, -16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + toolBtns.forEach((btn) -> btn.setActive(true)); + this.setActive(false); + toolMode = 0; + } + }.setIcon(PresetIcon.ICON_CURSOR.getTexture()); + btnCursor.setActive(toolMode != 0); + this.addPanel(btnCursor); + toolBtns.add(btnCursor); + + PanelButton btnProp = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 16, -16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + toolBtns.forEach((btn) -> btn.setActive(true)); + this.setActive(false); + toolMode = 1; + } + }.setIcon(PresetIcon.ICON_PROPS.getTexture()); + btnProp.setActive(toolMode != 1); + this.addPanel(btnProp); + toolBtns.add(btnProp); + + // Adds a new panel based on where the user clicked (we can re-parent thing later so we don't need pre-selection functionality) + PanelButton btnAdd = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 32, -16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + toolBtns.forEach((btn) -> btn.setActive(true)); + this.setActive(false); + toolMode = 2; + + openTrayPalette(); + } + }.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); + btnAdd.setActive(toolMode != 2); + this.addPanel(btnAdd); + toolBtns.add(btnAdd); + + // Changes the canvas parent + PanelButton btnSize = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 48, -16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + toolBtns.forEach((btn) -> btn.setActive(true)); + this.setActive(false); + toolMode = 3; + } + }.setIcon(PresetIcon.ICON_SCALE.getTexture()); + btnSize.setActive(toolMode != 3); + this.addPanel(btnSize); + toolBtns.add(btnSize); + + // Edit the transform bounds + // TODO: Add a CTRL alternate mode to move the transform parent only (doesn't need a whole new button) + PanelButton btnLink = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 64, -16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + toolBtns.forEach((btn) -> btn.setActive(true)); + this.setActive(false); + toolMode = 4; + } + }.setIcon(PresetIcon.ICON_LINK.getTexture()); + btnLink.setActive(toolMode != 4); + this.addPanel(btnLink); + toolBtns.add(btnLink); + + // Delete the panel and its children + PanelButton btnDel = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 80, -16, 16, 16, 0), -1, "") { + @Override + public void onButtonClick() { + toolBtns.forEach((btn) -> btn.setActive(true)); + this.setActive(false); + toolMode = 5; + } + }.setIcon(PresetIcon.ICON_TRASH.getTexture()); + btnDel.setActive(toolMode != 5); + this.addPanel(btnDel); + toolBtns.add(btnDel); + + refreshComponents(); + } + + @Override + public void drawPanel(int mx, int my, float partialTick) { + super.drawPanel(mx, my, partialTick); + + int cmx = MathHelper.clamp(mx, cvPreview.getTransform().getX(), + cvPreview.getTransform().getX() + cvPreview.getTransform().getWidth()); + int cmy = MathHelper.clamp(my, cvPreview.getTransform().getY(), + cvPreview.getTransform().getY() + cvPreview.getTransform().getHeight()); + + // === DRAG ACTIONS === + + if (dragID >= 0) { + if (toolMode == 3 && selPn != null && dragType > 0) { + ComponentPanel com = COM_DB.getValue(selectedID); + + if ((dragType & 16) == 16 && selPn.getTransform() instanceof GuiTransform) // Editing anchor { - @Override - public void onButtonClick() - { - toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); - toolMode = 1; + GuiTransform trans = (GuiTransform) selPn.getTransform(); + int dx = cmx - trans.getParent().getX(); + int dy = cmy - trans.getParent().getY(); + int width = trans.getParent().getWidth(); + int height = trans.getParent().getHeight(); + boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + // Edge Bit Map = R L B T + if ((dragType & 1) == 1 && height > 0) { + trans.getAnchor().y = dy / (float) height; + if (shift) { + trans.getAnchor().y += 0.025F; + trans.getAnchor().y -= trans.getAnchor().y % 0.05F; } - }.setIcon(PresetIcon.ICON_PROPS.getTexture()); - btnProp.setActive(toolMode != 1); - this.addPanel(btnProp); - toolBtns.add(btnProp); - - // Adds a new panel based on where the user clicked (we can re-parent thing later so we don't need pre-selection functionality) - PanelButton btnAdd = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 32, -16, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); - toolMode = 2; - - openTrayPalette(); + } + + if ((dragType & 2) == 2 && height > 0) { + trans.getAnchor().w = dy / (float) height; + if (shift) { + trans.getAnchor().w += 0.025F; + trans.getAnchor().w -= trans.getAnchor().w % 0.05F; } - }.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); - btnAdd.setActive(toolMode != 2); - this.addPanel(btnAdd); - toolBtns.add(btnAdd); - - // Changes the canvas parent - PanelButton btnSize = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 48, -16, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); - toolMode = 3; + } + + if ((dragType & 4) == 4 && width > 0) { + trans.getAnchor().x = dx / (float) width; + if (shift) { + trans.getAnchor().x += 0.025F; + trans.getAnchor().x -= trans.getAnchor().x % 0.05F; } - }.setIcon(PresetIcon.ICON_SCALE.getTexture()); - btnSize.setActive(toolMode != 3); - this.addPanel(btnSize); - toolBtns.add(btnSize); - - // Edit the transform bounds - // TODO: Add a CTRL alternate mode to move the transform parent only (doesn't need a whole new button) - PanelButton btnLink = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 64, -16, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); - toolMode = 4; + } + + if ((dragType & 8) == 8 && width > 0) { + trans.getAnchor().z = dx / (float) width; + if (shift) { + trans.getAnchor().z += 0.025F; + trans.getAnchor().z -= trans.getAnchor().z % 0.05F; } - }.setIcon(PresetIcon.ICON_LINK.getTexture()); - btnLink.setActive(toolMode != 4); - this.addPanel(btnLink); - toolBtns.add(btnLink); - - // Delete the panel and its children - PanelButton btnDel = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 80, -16, 16, 16, 0), -1, "") - { - @Override - public void onButtonClick() - { - toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); - toolMode = 5; + } + + if (com != null) { com.setTransform(trans); } + } else if ((dragType & 16) == 0 && selPn.getTransform() instanceof GuiTransform) { + // TODO: Make this work for GuiRectangle (or just deprecate that class entirely... but legacy support uhg) + GuiTransform trans = (GuiTransform) selPn.getTransform(); + int width = MathHelper.ceil(trans.getParent().getWidth() * (trans.getAnchor().z - trans.getAnchor().x)); + int height = MathHelper.ceil(trans.getParent().getHeight() * (trans.getAnchor().w - trans.getAnchor().y)); + int dx = + cmx - (trans.getParent().getX() + MathHelper.ceil(trans.getParent().getWidth() * trans.getAnchor().x)); + int dy = + cmy - (trans.getParent().getY() + MathHelper.ceil(trans.getParent().getHeight() * trans.getAnchor().y)); + boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + // Edge Bit Map = R L B T + if ((dragType & 1) == 1) { + trans.getPadding().t = dy; + if (shift) { + trans.getPadding().t += 4; + trans.getPadding().t -= trans.getPadding().t % 8; } - }.setIcon(PresetIcon.ICON_TRASH.getTexture()); - btnDel.setActive(toolMode != 5); - this.addPanel(btnDel); - toolBtns.add(btnDel); - - refreshComponents(); - } - - @Override - public void drawPanel(int mx, int my, float partialTick) - { - super.drawPanel(mx, my, partialTick); - - int cmx = MathHelper.clamp(mx, cvPreview.getTransform().getX(), cvPreview.getTransform().getX() + cvPreview.getTransform().getWidth()); - int cmy = MathHelper.clamp(my, cvPreview.getTransform().getY(), cvPreview.getTransform().getY() + cvPreview.getTransform().getHeight()); - - // === DRAG ACTIONS === - - if(dragID >= 0) - { - if(toolMode == 3 && selPn != null && dragType > 0) - { - ComponentPanel com = COM_DB.getValue(selectedID); - - if((dragType & 16) == 16 && selPn.getTransform() instanceof GuiTransform) // Editing anchor - { - GuiTransform trans = (GuiTransform)selPn.getTransform(); - int dx = cmx - trans.getParent().getX(); - int dy = cmy - trans.getParent().getY(); - int width = trans.getParent().getWidth(); - int height = trans.getParent().getHeight(); - boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - - // Edge Bit Map = R L B T - if((dragType & 1) == 1 && height > 0) - { - trans.getAnchor().y = dy / (float)height; - if(shift) - { - trans.getAnchor().y += 0.025F; - trans.getAnchor().y -= trans.getAnchor().y % 0.05F; - } - } - - if((dragType & 2) == 2 && height > 0) - { - trans.getAnchor().w = dy / (float)height; - if(shift) - { - trans.getAnchor().w += 0.025F; - trans.getAnchor().w -= trans.getAnchor().w % 0.05F; - } - } - - if((dragType & 4) == 4 && width > 0) - { - trans.getAnchor().x = dx / (float)width; - if(shift) - { - trans.getAnchor().x += 0.025F; - trans.getAnchor().x -= trans.getAnchor().x % 0.05F; - } - } - - if((dragType & 8) == 8 && width > 0) - { - trans.getAnchor().z = dx / (float)width; - if(shift) - { - trans.getAnchor().z += 0.025F; - trans.getAnchor().z -= trans.getAnchor().z % 0.05F; - } - } - - if(com != null) com.setTransform(trans); - } else if((dragType & 16) == 0 && selPn.getTransform() instanceof GuiTransform) - { - // TODO: Make this work for GuiRectangle (or just deprecate that class entirely... but legacy support uhg) - GuiTransform trans = (GuiTransform)selPn.getTransform(); - int width = MathHelper.ceil(trans.getParent().getWidth() * (trans.getAnchor().z - trans.getAnchor().x)); - int height = MathHelper.ceil(trans.getParent().getHeight() * (trans.getAnchor().w - trans.getAnchor().y)); - int dx = cmx - (trans.getParent().getX() + MathHelper.ceil(trans.getParent().getWidth() * trans.getAnchor().x)); - int dy = cmy - (trans.getParent().getY() + MathHelper.ceil(trans.getParent().getHeight() * trans.getAnchor().y)); - boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - - // Edge Bit Map = R L B T - if((dragType & 1) == 1) - { - trans.getPadding().t = dy; - if(shift) - { - trans.getPadding().t += 4; - trans.getPadding().t -= trans.getPadding().t % 8; - } - } - - if((dragType & 2) == 2) - { - trans.getPadding().b = height - dy; - if(shift) - { - trans.getPadding().b += 4; - trans.getPadding().b -= trans.getPadding().b % 8; - } - } - - if((dragType & 4) == 4) - { - trans.getPadding().l = dx; - if(shift) - { - trans.getPadding().l += 4; - trans.getPadding().l -= trans.getPadding().l % 8; - } - } - - if((dragType & 8) == 8) - { - trans.getPadding().r = width - dx; - if(shift) - { - trans.getPadding().r += 4; - trans.getPadding().r -= trans.getPadding().r % 8; - } - } - - if(com != null) com.setTransform(trans); - } + } + + if ((dragType & 2) == 2) { + trans.getPadding().b = height - dy; + if (shift) { + trans.getPadding().b += 4; + trans.getPadding().b -= trans.getPadding().b % 8; } - - if(!Mouse.isButtonDown(0)) - { - if(dragID >= 0) refreshComponents(); - dragID = -1; - dragType = -1; + } + + if ((dragType & 4) == 4) { + trans.getPadding().l = dx; + if (shift) { + trans.getPadding().l += 4; + trans.getPadding().l -= trans.getPadding().l % 8; } - } - - // === HOVER ACTIONS === - - if(toolMode == 2 && cvPreview.getTransform().contains(mx, my)) - { - IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); - if(topPanel == null) topPanel = cvPreview; - - IGuiRect drawBounds; - - int edge = getNearbyEdges(topPanel.getTransform(), mx, my, 16, true); - - if(edge > 0) - { - drawBounds = PRE_TF_EDGE.get(edge); - drawBounds.setParent(topPanel.getTransform()); - } else - { - int segment = getSegmentSlice(topPanel.getTransform(), mx, my); - drawBounds = PRE_TF_SEG[segment]; - drawBounds.setParent(topPanel.getTransform()); + } + + if ((dragType & 8) == 8) { + trans.getPadding().r = width - dx; + if (shift) { + trans.getPadding().r += 4; + trans.getPadding().r -= trans.getPadding().r % 8; } - - drawTransformBounds(drawBounds, false); - } else if((toolMode == 1 || toolMode == 3) && selPn != null) - { - drawTransformBounds(selPn.getTransform(), false); - } - } - - private final GuiTransform refBounds = new GuiTransform(); - - // I don't think I need to theme these. Not hard to change later if necessary - private BoxLine boxLine = new BoxLine(); - private IGuiColor parCol = new GuiColorStatic(0xFFFF0000); - private IGuiColor ancCol = new GuiColorStatic(0xFFFFFF00); - private IGuiColor boundsCol = new GuiColorStatic(0xFF0000FF); - - private void drawTransformBounds(@Nonnull IGuiRect rect, boolean showNumbers) - { - if(rect.getParent() != null) boxLine.drawLine(rect.getParent(), rect.getParent(), 2, parCol, 1F); - boxLine.drawLine(rect, rect, 2, boundsCol, 1F); - - if(rect.getParent() == null) return; - - int midX = rect.getX() + rect.getWidth() / 2; - int midY = rect.getY() + rect.getHeight() / 2; - - int x1 = rect.getParent().getX(); - int x2 = rect.getX(); - int x3 = x2 + rect.getWidth(); - int x4 = rect.getParent().getX() + rect.getParent().getWidth(); - int ax1 = x1; - int ax2 = x4; - - int y1 = rect.getParent().getY(); - int y2 = rect.getY(); - int y3 = y2 + rect.getHeight(); - int y4 = rect.getParent().getY() + rect.getParent().getHeight(); - int ay1 = y1; - int ay2 = y4; - - if(rect instanceof GuiTransform) - { - GuiTransform trans = (GuiTransform)rect; - ax1 = x1 + MathHelper.floor(trans.getParent().getWidth() * trans.getAnchor().x); - ax2 = x1 + MathHelper.floor(trans.getParent().getWidth() * trans.getAnchor().z); - - ay1 = y1 + MathHelper.floor(trans.getParent().getHeight() * trans.getAnchor().y); - ay2 = y1 + MathHelper.floor(trans.getParent().getHeight() * trans.getAnchor().w); - - // X axis line - drawSimpleLine(x1, midY, ax1, midY, 2, ancCol); - drawSimpleLine(ax2, midY, x4, midY, 2, ancCol); - - // X axis cross bar - drawSimpleLine(ax1, midY - 8, ax1, midY + 8, 2, ancCol); - drawSimpleLine(ax2, midY - 8, ax2, midY + 8, 2, ancCol); - - // Y axis line - drawSimpleLine(midX, y1, midX, ay1, 2, ancCol); - drawSimpleLine(midX, ay2, midX, y4, 2, ancCol); - - // Y axis cross bar - drawSimpleLine(midX - 8, ay1, midX + 8, ay1, 2, ancCol); - drawSimpleLine(midX - 8, ay2, midX + 8, ay2, 2, ancCol); + } + + if (com != null) { com.setTransform(trans); } } - - drawSimpleLine(ax1, midY, x2, midY, 2, parCol); - drawSimpleLine(x3, midY, ax2, midY, 2, parCol); - - drawSimpleLine(midX, ay1, midX, y2, 2, parCol); - drawSimpleLine(midX, y3, midX, ay2, 2, parCol); + } + + if (!Mouse.isButtonDown(0)) { + if (dragID >= 0) { refreshComponents(); } + dragID = -1; + dragType = -1; + } } - - private void drawSimpleLine(int x1, int y1, int x2, int y2, int width, IGuiColor color) - { - GlStateManager.pushMatrix(); - - GlStateManager.disableTexture2D(); - color.applyGlColor(); - GL11.glLineWidth(width); - - GL11.glBegin(GL11.GL_LINES); - GL11.glVertex2f(x1, y1); - GL11.glVertex2f(x2, y2); - GL11.glEnd(); - - GL11.glLineWidth(1F); - GlStateManager.enableTexture2D(); - GlStateManager.color(1F, 1F, 1F, 1F); - - GlStateManager.popMatrix(); + + // === HOVER ACTIONS === + + if (toolMode == 2 && cvPreview.getTransform().contains(mx, my)) { + IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); + if (topPanel == null) { topPanel = cvPreview; } + + IGuiRect drawBounds; + + int edge = getNearbyEdges(topPanel.getTransform(), mx, my, 16, true); + + if (edge > 0) { + drawBounds = PRE_TF_EDGE.get(edge); + drawBounds.setParent(topPanel.getTransform()); + } else { + int segment = getSegmentSlice(topPanel.getTransform(), mx, my); + drawBounds = PRE_TF_SEG[segment]; + drawBounds.setParent(topPanel.getTransform()); + } + + drawTransformBounds(drawBounds, false); + } else if ((toolMode == 1 || toolMode == 3) && selPn != null) { + drawTransformBounds(selPn.getTransform(), false); } - - @Override - public boolean onMouseClick(int mx, int my, int click) - { - if(toolMode == 0 || !cvPreview.getTransform().contains(mx, my)) return super.onMouseClick(mx, my, click); - - if(toolMode == 1) - { - if(click == 0 ) - { - IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); // Has a bit of give in it so tiny panels can still be grabbed - selectedID = PANEL_DB.getID(topPanel); - if(selectedID >= 0) selPn = topPanel; - } else if(click == 1) - { - selPn = null; - selectedID = -1; - } - } else if(toolMode == 2 && click == 0 && paletteSel != null) // Create - { - IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); - if(topPanel == null) topPanel = cvPreview; - - GuiTransform drawBounds; - - int edge = getNearbyEdges(topPanel.getTransform(), mx, my, 16, true); - - if(edge > 0) - { - drawBounds = PRE_TF_EDGE.get(edge); - drawBounds.setParent(topPanel.getTransform()); - } else - { - int segment = getSegmentSlice(topPanel.getTransform(), mx, my); - drawBounds = PRE_TF_SEG[segment]; - drawBounds.setParent(topPanel.getTransform()); - } - - drawBounds = drawBounds.copy(); - if(topPanel == cvPreview) - { - drawBounds.getPadding().setPadding(0, 0, 0, 0); - } else - { - drawBounds.getPadding().setPadding(8, 8, 8, 8); - } - - ComponentPanel com = new ComponentPanel(drawBounds); - COM_DB.add(COM_DB.nextID(), com); - - com.panelType = paletteSel.toString(); - //com.setPanelData(ComponentRegistry.INSTANCE.getTemplateNbt(paletteSel)); - - int id = PANEL_DB.getID(topPanel); - selectedID = id; // Quick select this new panel - com.cvParentID = id; - - refreshComponents(); - - selPn = PANEL_DB.getValue(id); - } else if(toolMode == 3 && cvPreview.getChildren().size() > 0) // Resize - { - if(click == 0 && selPn == null) - { - IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); // Has a bit of give in it so tiny panels can still be grabbed - selectedID = PANEL_DB.getID(topPanel); - if(selectedID >= 0) selPn = topPanel; - } else if(click == 0) - { - int edgePad = getNearbyEdges(selPn.getTransform(), mx, my, 4, true); - int edgePar = 0; - - if(edgePad <= 0 && selPn.getTransform() instanceof GuiTransform) - { - // We want a version of the transform without the padding but still keeping anchor offsets (because that's what we're grabbing - GuiTransform temp = new GuiTransform(((GuiTransform)selPn.getTransform()).getAnchor(), new GuiPadding(0, 0, 0, 0), 0); - temp.setParent(selPn.getTransform().getParent()); - edgePar = selPn.getTransform().getParent() == null ? 0 : getNearbyEdges(temp, mx, my, 4, false); - } - - if(edgePad > 0) - { - dragID = selectedID; - dragType = edgePad; - } else if(edgePar > 0) - { - dragID = selectedID; - dragType = edgePar | 16; // Offset indicates anchor adjustments - } - } else if(click == 1) - { - selPn = null; - selectedID = -1; - } - } else if(toolMode == 5 && cvPreview.getTransform().contains(mx, my)) // Delete - { - IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); - int topID = topPanel == null ? -1 : PANEL_DB.getID(topPanel); - - if(topID >= 0) - { - removeComponent(topID); - refreshComponents(); - } - } - - return super.onMouseClick(mx, my, click); + } + + private final GuiTransform refBounds = new GuiTransform(); + + // I don't think I need to theme these. Not hard to change later if necessary + private final BoxLine boxLine = new BoxLine(); + private final IGuiColor parCol = new GuiColorStatic(0xFFFF0000); + private final IGuiColor ancCol = new GuiColorStatic(0xFFFFFF00); + private final IGuiColor boundsCol = new GuiColorStatic(0xFF0000FF); + + private void drawTransformBounds(@Nonnull IGuiRect rect, boolean showNumbers) { + if (rect.getParent() != null) { boxLine.drawLine(rect.getParent(), rect.getParent(), 2, parCol, 1F); } + boxLine.drawLine(rect, rect, 2, boundsCol, 1F); + + if (rect.getParent() == null) { return; } + + int midX = rect.getX() + rect.getWidth() / 2; + int midY = rect.getY() + rect.getHeight() / 2; + + int x1 = rect.getParent().getX(); + int x2 = rect.getX(); + int x3 = x2 + rect.getWidth(); + int x4 = rect.getParent().getX() + rect.getParent().getWidth(); + int ax1 = x1; + int ax2 = x4; + + int y1 = rect.getParent().getY(); + int y2 = rect.getY(); + int y3 = y2 + rect.getHeight(); + int y4 = rect.getParent().getY() + rect.getParent().getHeight(); + int ay1 = y1; + int ay2 = y4; + + if (rect instanceof GuiTransform) { + GuiTransform trans = (GuiTransform) rect; + ax1 = x1 + MathHelper.floor(trans.getParent().getWidth() * trans.getAnchor().x); + ax2 = x1 + MathHelper.floor(trans.getParent().getWidth() * trans.getAnchor().z); + + ay1 = y1 + MathHelper.floor(trans.getParent().getHeight() * trans.getAnchor().y); + ay2 = y1 + MathHelper.floor(trans.getParent().getHeight() * trans.getAnchor().w); + + // X axis line + drawSimpleLine(x1, midY, ax1, midY, 2, ancCol); + drawSimpleLine(ax2, midY, x4, midY, 2, ancCol); + + // X axis cross bar + drawSimpleLine(ax1, midY - 8, ax1, midY + 8, 2, ancCol); + drawSimpleLine(ax2, midY - 8, ax2, midY + 8, 2, ancCol); + + // Y axis line + drawSimpleLine(midX, y1, midX, ay1, 2, ancCol); + drawSimpleLine(midX, ay2, midX, y4, 2, ancCol); + + // Y axis cross bar + drawSimpleLine(midX - 8, ay1, midX + 8, ay1, 2, ancCol); + drawSimpleLine(midX - 8, ay2, midX + 8, ay2, 2, ancCol); } - - @Override - public boolean onKeyTyped(char c, int keycode) + + drawSimpleLine(ax1, midY, x2, midY, 2, parCol); + drawSimpleLine(x3, midY, ax2, midY, 2, parCol); + + drawSimpleLine(midX, ay1, midX, y2, 2, parCol); + drawSimpleLine(midX, y3, midX, ay2, 2, parCol); + } + + private void drawSimpleLine(int x1, int y1, int x2, int y2, int width, IGuiColor color) { + GlStateManager.pushMatrix(); + + GlStateManager.disableTexture2D(); + color.applyGlColor(); + GL11.glLineWidth(width); + + GL11.glBegin(GL11.GL_LINES); + GL11.glVertex2f(x1, y1); + GL11.glVertex2f(x2, y2); + GL11.glEnd(); + + GL11.glLineWidth(1F); + GlStateManager.enableTexture2D(); + GlStateManager.color(1F, 1F, 1F, 1F); + + GlStateManager.popMatrix(); + } + + @Override + public boolean onMouseClick(int mx, int my, int click) { + if (toolMode == 0 || !cvPreview.getTransform().contains(mx, my)) { return super.onMouseClick(mx, my, click); } + + if (toolMode == 1) { + if (click == 0) { + IGuiPanel topPanel = + getPanelUnderMouse(mx, my, 0); // Has a bit of give in it so tiny panels can still be grabbed + selectedID = PANEL_DB.getID(topPanel); + if (selectedID >= 0) { selPn = topPanel; } + } else if (click == 1) { + selPn = null; + selectedID = -1; + } + } else if (toolMode == 2 && click == 0 && paletteSel != null) // Create { - return super.onKeyTyped(c, keycode); - } - - private void refreshComponents() + IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); + if (topPanel == null) { topPanel = cvPreview; } + + GuiTransform drawBounds; + + int edge = getNearbyEdges(topPanel.getTransform(), mx, my, 16, true); + + if (edge > 0) { + drawBounds = PRE_TF_EDGE.get(edge); + drawBounds.setParent(topPanel.getTransform()); + } else { + int segment = getSegmentSlice(topPanel.getTransform(), mx, my); + drawBounds = PRE_TF_SEG[segment]; + drawBounds.setParent(topPanel.getTransform()); + } + + drawBounds = drawBounds.copy(); + if (topPanel == cvPreview) { + drawBounds.getPadding().setPadding(0, 0, 0, 0); + } else { + drawBounds.getPadding().setPadding(8, 8, 8, 8); + } + + ComponentPanel com = new ComponentPanel(drawBounds); + COM_DB.add(COM_DB.nextID(), com); + + com.panelType = paletteSel.toString(); + //com.setPanelData(ComponentRegistry.INSTANCE.getTemplateNbt(paletteSel)); + + int id = PANEL_DB.getID(topPanel); + selectedID = id; // Quick select this new panel + com.cvParentID = id; + + refreshComponents(); + + selPn = PANEL_DB.getValue(id); + } else if (toolMode == 3 && !cvPreview.getChildren().isEmpty()) // Resize { - PANEL_DB.reset(); - cvPreview.resetCanvas(); - - // Instantiate all the panels first - COM_DB.getEntries().forEach((entry) -> { - IGuiPanel pan = entry.getValue().build(); - if(pan != null) PANEL_DB.add(entry.getID(), pan); // Should never be null but for my sanity... - }); - - // Rebuild from back to front (this is a part is bit annoying) we can also do the transform parenting here too - Queue parentQueue = new ArrayDeque<>(); - parentQueue.add(-1); - while(!parentQueue.isEmpty()) - { - int pID = parentQueue.poll(); - IGuiPanel pPan = PANEL_DB.getValue(pID); - if(pPan == null) pPan = cvPreview; - - if(pPan instanceof IGuiCanvas) // Skip if we can't parent it - { - IGuiCanvas pCan = ((IGuiCanvas)pPan); - getCanvasChildren(pID).forEach((entry) -> { - pCan.addPanel(PANEL_DB.getValue(entry.getID())); - parentQueue.add(entry.getID()); // Queue these up for the next layer pass - }); - } - - // Transform parenting (must occur after canvas parenting) - ComponentPanel com = COM_DB.getValue(pID); - IGuiPanel tPan = com == null ? null : PANEL_DB.getValue(com.tfParentID); - if(tPan != null) pPan.getTransform().setParent(tPan.getTransform()); - } - - if(selectedID >= 0) - { - selPn = PANEL_DB.getValue(selectedID); - if(selPn == null) selectedID = -1; + if (click == 0 && selPn == null) { + IGuiPanel topPanel = + getPanelUnderMouse(mx, my, 0); // Has a bit of give in it so tiny panels can still be grabbed + selectedID = PANEL_DB.getID(topPanel); + if (selectedID >= 0) { selPn = topPanel; } + } else if (click == 0) { + int edgePad = getNearbyEdges(selPn.getTransform(), mx, my, 4, true); + int edgePar = 0; + + if (edgePad <= 0 && selPn.getTransform() instanceof GuiTransform) { + // We want a version of the transform without the padding but still keeping anchor offsets (because that's what we're grabbing + GuiTransform temp = + new GuiTransform(((GuiTransform) selPn.getTransform()).getAnchor(), new GuiPadding(0, 0, 0, 0), 0); + temp.setParent(selPn.getTransform().getParent()); + edgePar = selPn.getTransform().getParent() == null ? 0 : getNearbyEdges(temp, mx, my, 4, false); } - } - - private void removeComponent(int comID) - { - Queue parentQueue = new ArrayDeque<>(); - parentQueue.add(comID); - - while(!parentQueue.isEmpty()) - { - int pID = parentQueue.poll(); - - getCanvasChildren(pID).forEach((entry) -> parentQueue.add(entry.getID())); - getTransformChildren(pID).forEach((entry) -> entry.getValue().tfParentID = -1); - - COM_DB.removeID(pID); - PANEL_DB.removeID(pID); + + if (edgePad > 0) { + dragID = selectedID; + dragType = edgePad; + } else if (edgePar > 0) { + dragID = selectedID; + dragType = edgePar | 16; // Offset indicates anchor adjustments } - } - - @Nonnull - private List> getCanvasChildren(int panelID) + } else if (click == 1) { + selPn = null; + selectedID = -1; + } + } else if (toolMode == 5 && cvPreview.getTransform().contains(mx, my)) // Delete { - List> list = new ArrayList<>(); - - COM_DB.getEntries().forEach((entry) -> { - if(entry.getValue().cvParentID == panelID) list.add(entry); - }); - - return list; + IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); + int topID = topPanel == null ? -1 : PANEL_DB.getID(topPanel); + + if (topID >= 0) { + removeComponent(topID); + refreshComponents(); + } } - - @Nonnull - private List> getTransformChildren(int panelID) - { - List> list = new ArrayList<>(); - - COM_DB.getEntries().forEach((entry) -> { - if(entry.getValue().tfParentID == panelID) list.add(entry); + + return super.onMouseClick(mx, my, click); + } + + @Override + public boolean onKeyTyped(char c, int keycode) { + return super.onKeyTyped(c, keycode); + } + + private void refreshComponents() { + PANEL_DB.reset(); + cvPreview.resetCanvas(); + + // Instantiate all the panels first + COM_DB.getEntries().forEach((entry) -> { + IGuiPanel pan = entry.getValue().build(); + if (pan != null) { + PANEL_DB.add(entry.getID(), pan); // Should never be null but for my sanity... + } + }); + + // Rebuild from back to front (this is a part is bit annoying) we can also do the transform parenting here too + Queue parentQueue = new ArrayDeque<>(); + parentQueue.add(-1); + while (!parentQueue.isEmpty()) { + int pID = parentQueue.poll(); + IGuiPanel pPan = PANEL_DB.getValue(pID); + if (pPan == null) { pPan = cvPreview; } + + if (pPan instanceof IGuiCanvas) // Skip if we can't parent it + { + IGuiCanvas pCan = ((IGuiCanvas) pPan); + getCanvasChildren(pID).forEach((entry) -> { + pCan.addPanel(PANEL_DB.getValue(entry.getID())); + parentQueue.add(entry.getID()); // Queue these up for the next layer pass }); - - return list; + } + + // Transform parenting (must occur after canvas parenting) + ComponentPanel com = COM_DB.getValue(pID); + IGuiPanel tPan = com == null ? null : PANEL_DB.getValue(com.tfParentID); + if (tPan != null) { pPan.getTransform().setParent(tPan.getTransform()); } } - - private IGuiPanel getPanelUnderMouse(int mx, int my, int range) - { - ListIterator iter = cvPreview.getChildren().listIterator(cvPreview.getChildren().size()); - IGuiPanel topPanel = null; - - while(iter.hasPrevious()) - { - IGuiPanel pan = iter.previous(); - if(containsRanged(pan.getTransform(), mx, my, range)) // Note: We don't care if this is clickable or not. We just care about the bounds - { - topPanel = pan; - if(pan instanceof IGuiCanvas) // Check if there are any children here that we need - { - iter = ((IGuiCanvas)pan).getChildren().listIterator(((IGuiCanvas)pan).getChildren().size()); - continue; - } - break; - } - } - - return topPanel; + + if (selectedID >= 0) { + selPn = PANEL_DB.getValue(selectedID); + if (selPn == null) { selectedID = -1; } } - - private void openTrayNBT(NBTTagCompound tag) - { - cvPropTray.setEnabled(true); - cvPropTray.resetCanvas(); - - btnTrayToggle.setIcon(PresetIcon.ICON_DOWN.getTexture()); - - // TODO: This panel doesn't work on its own - PanelScrollingNBT cvNbt = new PanelScrollingNBT(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 8, 0), 0), tag, 1, 2, 3, 4); - cvPropTray.addPanel(cvNbt); - - PanelVScrollBar scPropTray = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 0, 0, 0), 0)); - cvNbt.setScrollDriverY(scPropTray); - cvPropTray.addPanel(scPropTray); + } + + private void removeComponent(int comID) { + Queue parentQueue = new ArrayDeque<>(); + parentQueue.add(comID); + + while (!parentQueue.isEmpty()) { + int pID = parentQueue.poll(); + + getCanvasChildren(pID).forEach((entry) -> parentQueue.add(entry.getID())); + getTransformChildren(pID).forEach((entry) -> entry.getValue().tfParentID = -1); + + COM_DB.removeID(pID); + PANEL_DB.removeID(pID); } - - private void openTrayPalette() - { - cvPropTray.setEnabled(true); - cvPropTray.resetCanvas(); - - btnTrayToggle.setIcon(PresetIcon.ICON_DOWN.getTexture()); - - CanvasScrolling cvScroll = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 8, 0), 0)); - cvPropTray.addPanel(cvScroll); - - PanelVScrollBar scPropTray = new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 0, 0, 0), 0)); - cvScroll.setScrollDriverY(scPropTray); - cvPropTray.addPanel(scPropTray); - - final int cvWidth = cvScroll.getTransform().getWidth(); - List resList = ComponentRegistry.INSTANCE.getRegisteredIDs(); - for(int i = 0; i < resList.size(); i++) + } + + @Nonnull + private List> getCanvasChildren(int panelID) { + List> list = new ArrayList<>(); + + COM_DB.getEntries().forEach((entry) -> { + if (entry.getValue().cvParentID == panelID) { list.add(entry); } + }); + + return list; + } + + @Nonnull + private List> getTransformChildren(int panelID) { + List> list = new ArrayList<>(); + + COM_DB.getEntries().forEach((entry) -> { + if (entry.getValue().tfParentID == panelID) { list.add(entry); } + }); + + return list; + } + + private IGuiPanel getPanelUnderMouse(int mx, int my, int range) { + ListIterator iter = cvPreview.getChildren().listIterator(cvPreview.getChildren().size()); + IGuiPanel topPanel = null; + + while (iter.hasPrevious()) { + IGuiPanel pan = iter.previous(); + if (containsRanged(pan.getTransform(), mx, my, + range)) // Note: We don't care if this is clickable or not. We just care about the bounds + { + topPanel = pan; + if (pan instanceof IGuiCanvas) // Check if there are any children here that we need { - ResourceLocation res = resList.get(i); - PanelButtonStorage btnID = new PanelButtonStorage<>(new GuiRectangle(0, i * 16, cvWidth, 16, 0), -1, res.toString(), res); - btnID.setCallback((id) -> paletteSel = id); - cvScroll.addPanel(btnID); + iter = ((IGuiCanvas) pan).getChildren().listIterator(((IGuiCanvas) pan).getChildren().size()); + continue; } + break; + } } - - private void closeTray() - { - cvPropTray.resetCanvas(); - cvPropTray.setEnabled(false); - - btnTrayToggle.setIcon(PresetIcon.ICON_UP.getTexture()); - } - - private int getNearbyEdges(IGuiRect rect, int mx, int my, int range, boolean bounded) - { - int value = 0; - - boolean boundX = mx >= rect.getX() && mx < rect.getX() + rect.getWidth(); - boolean boundY = my >= rect.getY() && my < rect.getY() + rect.getHeight(); - - // Bottom - Top (bits 1 & 2) - if(Math.abs(my - (rect.getY() + rect.getHeight())) <= range && (!bounded || boundX)) - { - value |= 2; - } else if(Math.abs(my - rect.getY()) <= range && mx >= rect.getX() && (!bounded || boundX)) - { - value |= 1; - } - - // Right - Left (bits 4 & 8) - if(Math.abs(mx - (rect.getX() + rect.getWidth())) <= range && (!bounded || boundY)) - { - value |= 8; - } else if(Math.abs(mx - rect.getX()) <= range && my >= rect.getY() && (!bounded || boundY)) - { - value |= 4; - } - - return value; + + return topPanel; + } + + private void openTrayNBT(NBTTagCompound tag) { + cvPropTray.setEnabled(true); + cvPropTray.resetCanvas(); + + btnTrayToggle.setIcon(PresetIcon.ICON_DOWN.getTexture()); + + // TODO: This panel doesn't work on its own + PanelScrollingNBT cvNbt = + new PanelScrollingNBT(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 8, 0), 0), tag, 1, 2, 3, 4); + cvPropTray.addPanel(cvNbt); + + PanelVScrollBar scPropTray = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 0, 0, 0), 0)); + cvNbt.setScrollDriverY(scPropTray); + cvPropTray.addPanel(scPropTray); + } + + private void openTrayPalette() { + cvPropTray.setEnabled(true); + cvPropTray.resetCanvas(); + + btnTrayToggle.setIcon(PresetIcon.ICON_DOWN.getTexture()); + + CanvasScrolling cvScroll = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 8, 0), 0)); + cvPropTray.addPanel(cvScroll); + + PanelVScrollBar scPropTray = + new PanelVScrollBar(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-8, 0, 0, 0), 0)); + cvScroll.setScrollDriverY(scPropTray); + cvPropTray.addPanel(scPropTray); + + final int cvWidth = cvScroll.getTransform().getWidth(); + List resList = ComponentRegistry.INSTANCE.getRegisteredIDs(); + for (int i = 0; i < resList.size(); i++) { + ResourceLocation res = resList.get(i); + PanelButtonStorage btnID = + new PanelButtonStorage<>(new GuiRectangle(0, i * 16, cvWidth, 16, 0), -1, res.toString(), res); + btnID.setCallback((id) -> paletteSel = id); + cvScroll.addPanel(btnID); } - - private int getSegmentSlice(IGuiRect rect, int mx, int my) - { - if(!rect.contains(mx, my)) return -1; - - int dx = mx - rect.getX(); - int dy = my - rect.getY(); - - int segX = dx / (rect.getWidth() / 3); - int segY = dy / (rect.getHeight() / 3); - - return segY * 3 + segX; + } + + private void closeTray() { + cvPropTray.resetCanvas(); + cvPropTray.setEnabled(false); + + btnTrayToggle.setIcon(PresetIcon.ICON_UP.getTexture()); + } + + private int getNearbyEdges(IGuiRect rect, int mx, int my, int range, boolean bounded) { + int value = 0; + + boolean boundX = mx >= rect.getX() && mx < rect.getX() + rect.getWidth(); + boolean boundY = my >= rect.getY() && my < rect.getY() + rect.getHeight(); + + // Bottom - Top (bits 1 & 2) + if (Math.abs(my - (rect.getY() + rect.getHeight())) <= range && (!bounded || boundX)) { + value |= 2; + } else if (Math.abs(my - rect.getY()) <= range && mx >= rect.getX() && (!bounded || boundX)) { + value |= 1; } - - // Similar to the one built into IGuiRect but with an aditional range added on - private boolean containsRanged(IGuiRect rect, int x3, int y3, int range) - { - int x1 = rect.getX(); - int y1 = rect.getY(); - int w = rect.getWidth(); - int h = rect.getHeight(); - int x2 = x1 + w; - int y2 = y1 + h; - return x3 >= x1 - range && x3 < x2 + range && y3 >= y1 - range && y3 < y2 + range; - } - - private static final GuiTransform[] PRE_TF_SEG = new GuiTransform[]{ - new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), - new GuiTransform(new Vector4f(0F, 0F, 1F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), - new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), - - new GuiTransform(new Vector4f(0F, 0F, 0.5F, 1F), new GuiPadding(0, 0, 0, 0), 0), - new GuiTransform(new Vector4f(0F, 0F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), - new GuiTransform(new Vector4f(0.5F, 0F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), - - new GuiTransform(new Vector4f(0F, 0.5F, 0.5F, 1F), new GuiPadding(0, 0, 0, 0), 0), - new GuiTransform(new Vector4f(0F, 0.5F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), - new GuiTransform(new Vector4f(0.5F, 0.5F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0) - }; - - private static final Map PRE_TF_EDGE; - - static - { - HashMap tmp = new HashMap<>(); - - // Edge Bit Map = R L B T - - //Corners - tmp.put(0b0101, new GuiTransform(GuiAlign.TOP_LEFT, new GuiPadding(-4, -4, -4, -4), 0)); - tmp.put(0b1001, new GuiTransform(GuiAlign.TOP_RIGHT, new GuiPadding(-4, -4, -4, -4), 0)); - tmp.put(0b1010, new GuiTransform(GuiAlign.BOTTOM_RIGHT, new GuiPadding(-4, -4, -4, -4), 0)); - tmp.put(0b0110, new GuiTransform(GuiAlign.BOTTOM_LEFT, new GuiPadding(-4, -4, -4, -4), 0)); - - //Edges - tmp.put(0b0001, new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); - tmp.put(0b1000, new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); - tmp.put(0b0010, new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); - tmp.put(0b0100, new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); - - PRE_TF_EDGE = Collections.unmodifiableMap(tmp); + + // Right - Left (bits 4 & 8) + if (Math.abs(mx - (rect.getX() + rect.getWidth())) <= range && (!bounded || boundY)) { + value |= 8; + } else if (Math.abs(mx - rect.getX()) <= range && my >= rect.getY() && (!bounded || boundY)) { + value |= 4; } + + return value; + } + + private int getSegmentSlice(IGuiRect rect, int mx, int my) { + if (!rect.contains(mx, my)) { return -1; } + + int dx = mx - rect.getX(); + int dy = my - rect.getY(); + + int segX = dx / (rect.getWidth() / 3); + int segY = dy / (rect.getHeight() / 3); + + return segY * 3 + segX; + } + + // Similar to the one built into IGuiRect but with an aditional range added on + private boolean containsRanged(IGuiRect rect, int x3, int y3, int range) { + int x1 = rect.getX(); + int y1 = rect.getY(); + int w = rect.getWidth(); + int h = rect.getHeight(); + int x2 = x1 + w; + int y2 = y1 + h; + return x3 >= x1 - range && x3 < x2 + range && y3 >= y1 - range && y3 < y2 + range; + } + + private static final GuiTransform[] PRE_TF_SEG = new GuiTransform[] { + new GuiTransform(new Vector4f(0F, 0F, 0.5F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), + new GuiTransform(new Vector4f(0F, 0F, 1F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), + new GuiTransform(new Vector4f(0.5F, 0F, 1F, 0.5F), new GuiPadding(0, 0, 0, 0), 0), + + new GuiTransform(new Vector4f(0F, 0F, 0.5F, 1F), new GuiPadding(0, 0, 0, 0), 0), + new GuiTransform(new Vector4f(0F, 0F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), + new GuiTransform(new Vector4f(0.5F, 0F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), + + new GuiTransform(new Vector4f(0F, 0.5F, 0.5F, 1F), new GuiPadding(0, 0, 0, 0), 0), + new GuiTransform(new Vector4f(0F, 0.5F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0), + new GuiTransform(new Vector4f(0.5F, 0.5F, 1F, 1F), new GuiPadding(0, 0, 0, 0), 0) + }; + + private static final Map PRE_TF_EDGE; + + static { + HashMap tmp = new HashMap<>(); + + // Edge Bit Map = R L B T + + //Corners + tmp.put(0b0101, new GuiTransform(GuiAlign.TOP_LEFT, new GuiPadding(-4, -4, -4, -4), 0)); + tmp.put(0b1001, new GuiTransform(GuiAlign.TOP_RIGHT, new GuiPadding(-4, -4, -4, -4), 0)); + tmp.put(0b1010, new GuiTransform(GuiAlign.BOTTOM_RIGHT, new GuiPadding(-4, -4, -4, -4), 0)); + tmp.put(0b0110, new GuiTransform(GuiAlign.BOTTOM_LEFT, new GuiPadding(-4, -4, -4, -4), 0)); + + //Edges + tmp.put(0b0001, new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); + tmp.put(0b1000, new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); + tmp.put(0b0010, new GuiTransform(GuiAlign.BOTTOM_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); + tmp.put(0b0100, new GuiTransform(GuiAlign.LEFT_EDGE, new GuiPadding(-4, -4, -4, -4), 0)); + + PRE_TF_EDGE = Collections.unmodifiableMap(tmp); + } } diff --git a/src/main/java/betterquesting/commands/BQ_CommandAdmin.java b/src/main/java/betterquesting/commands/BQ_CommandAdmin.java index 5433d0477..870b6ab0a 100644 --- a/src/main/java/betterquesting/commands/BQ_CommandAdmin.java +++ b/src/main/java/betterquesting/commands/BQ_CommandAdmin.java @@ -13,158 +13,137 @@ import net.minecraftforge.server.permission.DefaultPermissionLevel; import net.minecraftforge.server.permission.PermissionAPI; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; -public class BQ_CommandAdmin extends CommandBase -{ - private final List coms = new ArrayList<>(); - - public BQ_CommandAdmin() - { - PermissionAPI.registerNode("betterquesting.command.admin", DefaultPermissionLevel.OP, "admin commmand permission"); - - coms.add(new QuestCommandEdit()); - coms.add(new QuestCommandHardcore()); - coms.add(new QuestCommandReset()); - coms.add(new QuestCommandComplete()); - coms.add(new QuestCommandDelete()); - coms.add(new QuestCommandDefaults()); - coms.add(new QuestCommandLives()); - coms.add(new QuestCommandPurge()); - } - - @Override - public String getName() - { - return "bq_admin"; - } - - @Override - public boolean checkPermission(MinecraftServer server, ICommandSender sender) - { - return !(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer)sender, "betterquesting.command.admin"); - } - - @Override - public String getUsage(ICommandSender sender) - { - StringBuilder txt = new StringBuilder(); - - for(int i = 0; i < coms.size(); i++) - { - QuestCommandBase c = coms.get(i); - txt.append("/bq_admin ").append(c.getCommand()); - - if(c.getUsageSuffix().length() > 0) - { - txt.append(" ").append(c.getUsageSuffix()); - } - - if(i < coms.size() -1) - { - txt.append(", "); - } - } - - return txt.toString(); - } - - /** - * Adds the strings available in this command to the given list of tab completion options. - */ - @Override - public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] strings, BlockPos pos) - { - if(strings.length == 1) - { - List base = new ArrayList<>(); - for(QuestCommandBase c : coms) - { - if(!(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) - { - base.add(c.getCommand()); - } - } - return getListOfStringsMatchingLastWord(strings, base.toArray(new String[0])); - } else if(strings.length > 1) - { - for(QuestCommandBase c : coms) - { - if(c.getCommand().equalsIgnoreCase(strings[0])) - { - if(!(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) - { - return c.autoComplete(server, sender, strings); - } - } - } - } - - return Collections.emptyList(); +public class BQ_CommandAdmin extends CommandBase { + private final List coms = new ArrayList<>(); + + public BQ_CommandAdmin() { + PermissionAPI.registerNode("betterquesting.command.admin", DefaultPermissionLevel.OP, "admin commmand permission"); + + coms.add(new QuestCommandEdit()); + coms.add(new QuestCommandHardcore()); + coms.add(new QuestCommandReset()); + coms.add(new QuestCommandComplete()); + coms.add(new QuestCommandDelete()); + coms.add(new QuestCommandDefaults()); + coms.add(new QuestCommandLives()); + coms.add(new QuestCommandPurge()); + } + + @Nonnull + @Override + public String getName() { + return "bq_admin"; + } + + @Override + public boolean checkPermission(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender) { + return !(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, "betterquesting.command.admin"); + } + + @Nonnull + @Override + public String getUsage(@Nonnull ICommandSender sender) { + StringBuilder txt = new StringBuilder(); + + for (int i = 0; i < coms.size(); i++) { + QuestCommandBase c = coms.get(i); + txt.append("/bq_admin ").append(c.getCommand()); + + if (!c.getUsageSuffix().isEmpty()) { + txt.append(" ").append(c.getUsageSuffix()); + } + + if (i < coms.size() - 1) { + txt.append(", "); + } + } + + return txt.toString(); + } + + /** + * Adds the strings available in this command to the given list of tab completion options. + */ + @Nonnull + @Override + public List getTabCompletions(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] strings, BlockPos pos) { + if (strings.length == 1) { + List base = new ArrayList<>(); + for (QuestCommandBase c : coms) { + if (!(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) { + base.add(c.getCommand()); + } + } + return getListOfStringsMatchingLastWord(strings, base.toArray(new String[0])); + } else if (strings.length > 1) { + for (QuestCommandBase c : coms) { + if (c.getCommand().equalsIgnoreCase(strings[0])) { + if (!(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) { + return c.autoComplete(server, sender, strings); + } + } + } + } + + return Collections.emptyList(); + } + + @Override + public int getRequiredPermissionLevel() { + return 2; + } + + @Override + public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] args) throws CommandException { + if (args.length < 1) { + throw new WrongUsageException(this.getUsage(sender)); } - - @Override - public int getRequiredPermissionLevel() - { - return 2; + + for (QuestCommandBase c : coms) { + if (c.getCommand().equalsIgnoreCase(args[0])) { + if (!(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) { + if (c.validArgs(args)) { + c.runCommand(server, this, sender, args); + return; + } else { + throw c.getException(this); + } + } else { + TextComponentTranslation cc = new TextComponentTranslation("commands.generic.permission"); + cc.getStyle().setColor(TextFormatting.RED); + sender.sendMessage(cc); + return; + } + } } - @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException - { - if(args.length < 1) - { - throw new WrongUsageException(this.getUsage(sender)); - } - - for(QuestCommandBase c : coms) - { - if(c.getCommand().equalsIgnoreCase(args[0])) - { - if(!(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) - { - if(c.validArgs(args)) - { - c.runCommand(server, this, sender, args); - return; - } else - { - throw c.getException(this); - } - } else - { - TextComponentTranslation cc = new TextComponentTranslation("commands.generic.permission"); - cc.getStyle().setColor(TextFormatting.RED); - sender.sendMessage(cc); - return; - } - } - } - - throw new WrongUsageException(this.getUsage(sender)); - } - - /** - * Return whether the specified command parameter index is a username parameter. - */ - @Override - public boolean isUsernameIndex(String[] args, int index) - { - if(args.length < 1) - { - return false; - } - - for(QuestCommandBase c : coms) - { - if(c.getCommand().equalsIgnoreCase(args[0])) - { - return c.isArgUsername(args, index); - } - } - - return false; + throw new WrongUsageException(this.getUsage(sender)); + } + + /** + * Return whether the specified command parameter index is a username parameter. + */ + @Override + public boolean isUsernameIndex(String[] args, int index) { + if (args.length < 1) { + return false; } + + for (QuestCommandBase c : coms) { + if (c.getCommand().equalsIgnoreCase(args[0])) { + return c.isArgUsername(args, index); + } + } + + return false; + } } diff --git a/src/main/java/betterquesting/commands/BQ_CommandDebug.java b/src/main/java/betterquesting/commands/BQ_CommandDebug.java index 2dcdc4ff7..91c749a50 100644 --- a/src/main/java/betterquesting/commands/BQ_CommandDebug.java +++ b/src/main/java/betterquesting/commands/BQ_CommandDebug.java @@ -6,53 +6,49 @@ import betterquesting.client.themes.ThemeRegistry; import com.google.gson.JsonObject; import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Tuple; +import javax.annotation.Nonnull; import java.io.File; import java.util.HashSet; import java.util.Set; -public class BQ_CommandDebug extends CommandBase -{ - @Override - public String getName() - { - return "bq_debug"; - } - - @Override - public String getUsage(ICommandSender sender) - { - return "TO BE USED IN DEV ONLY"; - } - - @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException - { - final String dir = "D:/Jon Stuff/Github/Repositories/BetterQuesting - 1.12/jars/test_dlc_theme"; - - JsonObject manifest = new JsonObject(); - manifest.addProperty("format", 0); - manifest.addProperty("themeID", "dlc_theme:test"); - manifest.addProperty("themeName", "DLC TEST"); - - JsonObject jsonTheme = JsonHelper.ReadFromFile(new File(dir, "bq_themes.json")); - Set> textures = new HashSet<>(); - textures.add(new Tuple<>(new ResourceLocation("dlc_theme:textures/gui/new_gui.png"),new File(dir, "new_gui.png"))); - SupporterAPI.buildCompressedFile(new File(dir, "theme.thm"), manifest, jsonTheme, textures, null, null, -1); - - ResourceTheme r = SupporterAPI.readCompressedFile(new File(dir, "theme.thm")); - if(r != null) - { - ThemeRegistry.INSTANCE.registerTheme(r); - System.out.println("SUCCESS"); - } else - { - System.out.println("FAILED"); - } +public class BQ_CommandDebug extends CommandBase { + @Override + @Nonnull + public String getName() { + return "bq_debug"; + } + + @Override + @Nonnull + public String getUsage(@Nonnull ICommandSender sender) { + return "TO BE USED IN DEV ONLY"; + } + + @Override + public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, @Nonnull String[] args) { + final String dir = "D:/Jon Stuff/Github/Repositories/BetterQuesting - 1.12/jars/test_dlc_theme"; + + JsonObject manifest = new JsonObject(); + manifest.addProperty("format", 0); + manifest.addProperty("themeID", "dlc_theme:test"); + manifest.addProperty("themeName", "DLC TEST"); + + JsonObject jsonTheme = JsonHelper.ReadFromFile(new File(dir, "bq_themes.json")); + Set> textures = new HashSet<>(); + textures.add(new Tuple<>(new ResourceLocation("dlc_theme:textures/gui/new_gui.png"), new File(dir, "new_gui.png"))); + SupporterAPI.buildCompressedFile(new File(dir, "theme.thm"), manifest, jsonTheme, textures, null, null, -1); + + ResourceTheme r = SupporterAPI.readCompressedFile(new File(dir, "theme.thm")); + if (r != null) { + ThemeRegistry.INSTANCE.registerTheme(r); + System.out.println("SUCCESS"); + } else { + System.out.println("FAILED"); } + } } diff --git a/src/main/java/betterquesting/commands/BQ_CommandUser.java b/src/main/java/betterquesting/commands/BQ_CommandUser.java index f90ebd0a6..ad7d0365d 100644 --- a/src/main/java/betterquesting/commands/BQ_CommandUser.java +++ b/src/main/java/betterquesting/commands/BQ_CommandUser.java @@ -15,153 +15,132 @@ import net.minecraftforge.server.permission.DefaultPermissionLevel; import net.minecraftforge.server.permission.PermissionAPI; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; -public class BQ_CommandUser extends CommandBase -{ - private final List coms = new ArrayList<>(); - - public BQ_CommandUser() - { - PermissionAPI.registerNode("betterquesting.command.user", DefaultPermissionLevel.ALL, "user commmand permission"); - - coms.add(new QuestCommandHelp()); - coms.add(new QuestCommandRefresh()); - coms.add(new QuestCommandSPHardcore()); - } - - @Override - public String getName() - { - return "bq_user"; - } - - @Override - public int getRequiredPermissionLevel() - { - return 0; - } - - @Override - public boolean checkPermission(MinecraftServer server, ICommandSender sender) - { - return !(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer)sender, "betterquesting.command.user"); - } - - @Override - public String getUsage(ICommandSender sender) - { - StringBuilder txt = new StringBuilder(); - - for(int i = 0; i < coms.size(); i++) - { - QuestCommandBase c = coms.get(i); - txt.append("/bq_user ").append(c.getCommand()); - - if(c.getUsageSuffix().length() > 0) - { - txt.append(" ").append(c.getUsageSuffix()); - } - - if(i < coms.size() -1) - { - txt.append(", "); - } - } - - return txt.toString(); - } - - /** - * Adds the strings available in this command to the given list of tab completion options. - */ - @Override - public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] strings, BlockPos pos) - { - if(strings.length == 1) - { - List base = new ArrayList<>(); - for(QuestCommandBase c : coms) - { - if(!(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) - { - base.add(c.getCommand()); - } - } - return getListOfStringsMatchingLastWord(strings, base.toArray(new String[0])); - } else if(strings.length > 1) - { - for(QuestCommandBase c : coms) - { - if(c.getCommand().equalsIgnoreCase(strings[0])) - { - if(!(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) - { - return c.autoComplete(server, sender, strings); - } - } - } - } - - return Collections.emptyList(); +public class BQ_CommandUser extends CommandBase { + private final List coms = new ArrayList<>(); + + public BQ_CommandUser() { + PermissionAPI.registerNode("betterquesting.command.user", DefaultPermissionLevel.ALL, "user commmand permission"); + + coms.add(new QuestCommandHelp()); + coms.add(new QuestCommandRefresh()); + coms.add(new QuestCommandSPHardcore()); + } + + @Nonnull + @Override + public String getName() { + return "bq_user"; + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public boolean checkPermission(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender) { + return !(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, "betterquesting.command.user"); + } + + @Nonnull + @Override + public String getUsage(@Nonnull ICommandSender sender) { + StringBuilder txt = new StringBuilder(); + + for (int i = 0; i < coms.size(); i++) { + QuestCommandBase c = coms.get(i); + txt.append("/bq_user ").append(c.getCommand()); + + if (!c.getUsageSuffix().isEmpty()) { + txt.append(" ").append(c.getUsageSuffix()); + } + + if (i < coms.size() - 1) { + txt.append(", "); + } + } + + return txt.toString(); + } + + /** + * Adds the strings available in this command to the given list of tab completion options. + */ + @Nonnull + @Override + public List getTabCompletions(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] strings, BlockPos pos) { + if (strings.length == 1) { + List base = new ArrayList<>(); + for (QuestCommandBase c : coms) { + if (!(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) { + base.add(c.getCommand()); + } + } + return getListOfStringsMatchingLastWord(strings, base.toArray(new String[0])); + } else if (strings.length > 1) { + for (QuestCommandBase c : coms) { + if (c.getCommand().equalsIgnoreCase(strings[0])) { + if (!(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) { + return c.autoComplete(server, sender, strings); + } + } + } + } + + return Collections.emptyList(); + } + + @Override + public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] args) throws CommandException { + if (args.length < 1) { + throw new WrongUsageException(this.getUsage(sender)); } - - @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException - { - if(args.length < 1) - { - throw new WrongUsageException(this.getUsage(sender)); - } - - for(QuestCommandBase c : coms) - { - if(c.getCommand().equalsIgnoreCase(args[0])) - { - if(!(sender instanceof EntityPlayer) || PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) - { - if(c.validArgs(args)) - { - c.runCommand(server, this, sender, args); - return; - } else - { - throw c.getException(this); - } - } else - { - TextComponentTranslation cc = new TextComponentTranslation("commands.generic.permission"); - cc.getStyle().setColor(TextFormatting.RED); - sender.sendMessage(cc); - return; - } - } - } - - throw new WrongUsageException(this.getUsage(sender)); - } - - /** - * Return whether the specified command parameter index is a username parameter. - */ - @Override - public boolean isUsernameIndex(String[] args, int index) - { - if(args.length < 1) - { - return false; - } - - for(QuestCommandBase c : coms) - { - if(c.getCommand().equalsIgnoreCase(args[0])) - { - return c.isArgUsername(args, index); - } - } - - return false; + + for (QuestCommandBase c : coms) { + if (c.getCommand().equalsIgnoreCase(args[0])) { + if (!(sender instanceof EntityPlayer) || + PermissionAPI.hasPermission((EntityPlayer) sender, c.getPermissionNode())) { + if (c.validArgs(args)) { + c.runCommand(server, this, sender, args); + return; + } else { + throw c.getException(this); + } + } else { + TextComponentTranslation cc = new TextComponentTranslation("commands.generic.permission"); + cc.getStyle().setColor(TextFormatting.RED); + sender.sendMessage(cc); + return; + } + } } + + throw new WrongUsageException(this.getUsage(sender)); + } + + /** + * Return whether the specified command parameter index is a username parameter. + */ + @Override + public boolean isUsernameIndex(String[] args, int index) { + if (args.length < 1) { + return false; + } + + for (QuestCommandBase c : coms) { + if (c.getCommand().equalsIgnoreCase(args[0])) { + return c.isArgUsername(args, index); + } + } + + return false; + } } diff --git a/src/main/java/betterquesting/commands/QuestCommandBase.java b/src/main/java/betterquesting/commands/QuestCommandBase.java index 522ca43c5..fb4098e9c 100644 --- a/src/main/java/betterquesting/commands/QuestCommandBase.java +++ b/src/main/java/betterquesting/commands/QuestCommandBase.java @@ -15,97 +15,82 @@ import java.util.List; import java.util.UUID; -public abstract class QuestCommandBase -{ - public abstract String getCommand(); - - public String getUsageSuffix() - { - return ""; - } - - public QuestCommandBase() - { - this.registerPermission(); - } - - public abstract String getPermissionNode(); - - public abstract DefaultPermissionLevel getPermissionLevel(); - - public abstract String getPermissionDescription(); - - private void registerPermission() - { - PermissionAPI.registerNode(this.getPermissionNode(), this.getPermissionLevel(), this.getPermissionDescription()); - } - - /** - * Are the passed arguments valid?
- * NOTE: Argument 1 is always the returned value of getCommand() - */ - public boolean validArgs(String[] args) - { - return args.length == 1; - } - - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - return Collections.emptyList(); - } - - public abstract void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException; - - public final WrongUsageException getException(CommandBase command) - { - String message = command.getName() + " " + getCommand(); - - if(getUsageSuffix().length() > 0) - { - message += " " + getUsageSuffix(); - } - - return new WrongUsageException(message); - } - - /** - * Attempts to find the players ID from the given name or convert it to a UUID if valid - */ - public UUID findPlayerID(MinecraftServer server, ICommandSender sender, String name) - { - UUID playerID; - - EntityPlayerMP player = null; - - try - { - player = CommandBase.getEntity(server, sender, name, EntityPlayerMP.class); - } catch(Exception ignored){} - - if(player == null) - { - if(name.startsWith("@")) - { - return null; - } - - try - { - playerID = UUID.fromString(name); - } catch(Exception e) - { - playerID = NameCache.INSTANCE.getUUID(name); - } - } else - { - playerID = QuestingAPI.getQuestingUUID(player); - } - - return playerID; - } - - public boolean isArgUsername(String[] args, int index) - { - return false; - } +public abstract class QuestCommandBase { + public abstract String getCommand(); + + public String getUsageSuffix() { + return ""; + } + + public QuestCommandBase() { + this.registerPermission(); + } + + public abstract String getPermissionNode(); + + public abstract DefaultPermissionLevel getPermissionLevel(); + + public abstract String getPermissionDescription(); + + private void registerPermission() { + PermissionAPI.registerNode(this.getPermissionNode(), this.getPermissionLevel(), this.getPermissionDescription()); + } + + /** + * Are the passed arguments valid?
+ * NOTE: Argument 1 is always the returned value of getCommand() + */ + public boolean validArgs(String[] args) { + return args.length == 1; + } + + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + return Collections.emptyList(); + } + + public abstract void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException; + + public final WrongUsageException getException(CommandBase command) { + String message = command.getName() + " " + getCommand(); + + if (!getUsageSuffix().isEmpty()) { + message += " " + getUsageSuffix(); + } + + return new WrongUsageException(message); + } + + /** + * Attempts to find the players ID from the given name or convert it to a UUID if valid + */ + public UUID findPlayerID(MinecraftServer server, ICommandSender sender, String name) { + UUID playerID; + + EntityPlayerMP player = null; + + try { + player = CommandBase.getEntity(server, sender, name, EntityPlayerMP.class); + } catch (Exception ignored) { } + + if (player == null) { + if (name.startsWith("@")) { + return null; + } + + try { + playerID = UUID.fromString(name); + } catch (Exception e) { + playerID = NameCache.INSTANCE.getUUID(name); + } + } else { + playerID = QuestingAPI.getQuestingUUID(player); + } + + return playerID; + } + + public boolean isArgUsername(String[] args, int index) { + return false; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java b/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java index 650ca699a..fa2204d05 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java @@ -19,95 +19,82 @@ import java.util.List; import java.util.UUID; -public class QuestCommandComplete extends QuestCommandBase -{ - @Override - public String getUsageSuffix() - { - return " [username|uuid]"; - } - - @Override - public boolean validArgs(String[] args) - { - return args.length == 2 || args.length == 3; - } - - @Override - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - if(args.length == 2) - { - List list = new ArrayList<>(); - for(DBEntry i : QuestDatabase.INSTANCE.getEntries()) - { - list.add("" + i.getID()); - } - return list; - } else if(args.length == 3) - { - return CommandBase.getListOfStringsMatchingLastWord(args, NameCache.INSTANCE.getAllNames()); - } - - return Collections.emptyList(); - } - - @Override - public String getCommand() - { - return "complete"; - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - UUID uuid; - - if(args.length >= 3) - { - uuid = this.findPlayerID(server, sender, args[2]); - - if(uuid == null) - { - throw this.getException(command); - } - } else - { - uuid = this.findPlayerID(server, sender, sender.getName()); - } - - if(uuid == null) return; - - String pName = NameCache.INSTANCE.getName(uuid); - - int id = Integer.parseInt(args[1].trim()); - IQuest quest = QuestDatabase.INSTANCE.getValue(id); - if(quest == null) throw getException(command); - NetQuestEdit.setQuestStates(new int[]{id}, true, uuid); - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.complete", new TextComponentTranslation(quest.getProperty(NativeProps.NAME)), pName)); - } - - @Override - public boolean isArgUsername(String[] args, int index) - { - return index == 2; - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.complete"; - } - - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } - - @Override - public String getPermissionDescription() - { - return "Permission to force completes a quest for the given user"; - } +public class QuestCommandComplete extends QuestCommandBase { + @Override + public String getUsageSuffix() { + return " [username|uuid]"; + } + + @Override + public boolean validArgs(String[] args) { + return args.length == 2 || args.length == 3; + } + + @Override + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + if (args.length == 2) { + List list = new ArrayList<>(); + for (DBEntry i : QuestDatabase.INSTANCE.getEntries()) { + list.add("" + i.getID()); + } + return list; + } else if (args.length == 3) { + return CommandBase.getListOfStringsMatchingLastWord(args, NameCache.INSTANCE.getAllNames()); + } + + return Collections.emptyList(); + } + + @Override + public String getCommand() { + return "complete"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException { + UUID uuid; + + if (args.length >= 3) { + uuid = this.findPlayerID(server, sender, args[2]); + + if (uuid == null) { + throw this.getException(command); + } + } else { + uuid = this.findPlayerID(server, sender, sender.getName()); + } + + if (uuid == null) { return; } + + String pName = NameCache.INSTANCE.getName(uuid); + + int id = Integer.parseInt(args[1].trim()); + IQuest quest = QuestDatabase.INSTANCE.getValue(id); + if (quest == null) { throw getException(command); } + NetQuestEdit.setQuestStates(new int[] { id }, true, uuid); + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.complete", + new TextComponentTranslation(quest.getProperty(NativeProps.NAME)), + pName)); + } + + @Override + public boolean isArgUsername(String[] args, int index) { + return index == 2; + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.complete"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } + + @Override + public String getPermissionDescription() { + return "Permission to force completes a quest for the given user"; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandDefaults.java b/src/main/java/betterquesting/commands/admin/QuestCommandDefaults.java index 9986e524d..3ce4fd11b 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandDefaults.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandDefaults.java @@ -29,153 +29,127 @@ import java.util.Collections; import java.util.List; -public class QuestCommandDefaults extends QuestCommandBase -{ - @Override - public String getUsageSuffix() - { - return "[save|load|set] [file_name]"; - } - - @Override - public boolean validArgs(String[] args) - { - return args.length == 2 || args.length == 3; - } - - @Override - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - if(args.length == 2) - { - return CommandBase.getListOfStringsMatchingLastWord(args, "save", "load", "set"); - } else if(args.length == 3) - { - return Collections.singletonList("DefaultQuests"); - } - - return Collections.emptyList(); - } - - @Override - public String getCommand() - { - return "default"; - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - File qFile; - - if(args.length == 3 && !args[2].equalsIgnoreCase("DefaultQuests")) - { - qFile = new File(BQ_Settings.defaultDir, "saved_quests/" + args[2] + ".json"); - } else - { - qFile = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); - } - - if(args[1].equalsIgnoreCase("save")) - { - NBTTagCompound base = new NBTTagCompound(); - base.setTag("questSettings", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); - base.setTag("questDatabase", QuestDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); - base.setTag("questLines", QuestLineDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); - base.setString("format", BetterQuesting.FORMAT); - JsonHelper.WriteToFile(qFile, NBTConverter.NBTtoJSON_Compound(base, new JsonObject(), true)); - - if(args.length == 3 && !args[2].equalsIgnoreCase("DefaultQuests")) - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.save2", args[2] + ".json")); - } else - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.save")); - } - } else if(args[1].equalsIgnoreCase("load")) - { - if(qFile.exists()) - { - boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); - boolean hardMode = QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); - - NBTTagList jsonP = QuestDatabase.INSTANCE.writeProgressToNBT(new NBTTagList(), null); - - JsonObject j1 = JsonHelper.ReadFromFile(qFile); - NBTTagCompound nbt1 = NBTConverter.JSONtoNBT_Object(j1, new NBTTagCompound(), true); - - ILegacyLoader loader = LegacyLoaderRegistry.getLoader(nbt1.hasKey("format", 8) ? nbt1.getString("format") : "0.0.0"); - - if(loader == null) - { - QuestSettings.INSTANCE.readFromNBT(nbt1.getCompoundTag("questSettings")); - QuestDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questDatabase", 10), false); - QuestLineDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questLines", 10), false); - } else - { - loader.readFromJson(j1); - } - - QuestDatabase.INSTANCE.readProgressFromNBT(jsonP, false); - - QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, editMode); - QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, hardMode); - - if(args.length == 3 && !args[2].equalsIgnoreCase("DefaultQuests")) - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.load2", args[2] + ".json")); - } else - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.load")); - } - - NetSettingSync.sendSync(null); - NetQuestSync.quickSync(-1, true, true); - NetChapterSync.sendSync(null, null); - SaveLoadHandler.INSTANCE.markDirty(); - } else - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.none")); - } - } else if(args[1].equalsIgnoreCase("set") && args.length == 3) - { - if(qFile.exists() && !args[2].equalsIgnoreCase("DefaultQuests")) - { - File defFile = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); - - if(defFile.exists()) - { - defFile.delete(); - } - - JsonHelper.CopyPaste(qFile, defFile); - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.set", args[2])); - } else - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.none")); - } - } else - { - throw getException(command); - } - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.default"; - } - - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } - - @Override - public String getPermissionDescription() - { - return "Permission to saves/loads the current quest database to/from the global default directory"; - } +public class QuestCommandDefaults extends QuestCommandBase { + @Override + public String getUsageSuffix() { + return "[save|load|set] [file_name]"; + } + + @Override + public boolean validArgs(String[] args) { + return args.length == 2 || args.length == 3; + } + + @Override + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + if (args.length == 2) { + return CommandBase.getListOfStringsMatchingLastWord(args, "save", "load", "set"); + } else if (args.length == 3) { + return Collections.singletonList("DefaultQuests"); + } + + return Collections.emptyList(); + } + + @Override + public String getCommand() { + return "default"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException { + File qFile; + + if (args.length == 3 && !args[2].equalsIgnoreCase("DefaultQuests")) { + qFile = new File(BQ_Settings.defaultDir, "saved_quests/" + args[2] + ".json"); + } else { + qFile = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); + } + + if (args[1].equalsIgnoreCase("save")) { + NBTTagCompound base = new NBTTagCompound(); + base.setTag("questSettings", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); + base.setTag("questDatabase", QuestDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); + base.setTag("questLines", QuestLineDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); + base.setString("format", BetterQuesting.FORMAT); + JsonHelper.WriteToFile(qFile, NBTConverter.NBTtoJSON_Compound(base, new JsonObject(), true)); + + if (args.length == 3 && !args[2].equalsIgnoreCase("DefaultQuests")) { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.save2", args[2] + ".json")); + } else { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.save")); + } + } else if (args[1].equalsIgnoreCase("load")) { + if (qFile.exists()) { + boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); + boolean hardMode = QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); + + NBTTagList jsonP = QuestDatabase.INSTANCE.writeProgressToNBT(new NBTTagList(), null); + + JsonObject j1 = JsonHelper.ReadFromFile(qFile); + NBTTagCompound nbt1 = NBTConverter.JSONtoNBT_Object(j1, new NBTTagCompound(), true); + + ILegacyLoader loader = + LegacyLoaderRegistry.getLoader(nbt1.hasKey("format", 8) ? nbt1.getString("format") : "0.0.0"); + + if (loader == null) { + QuestSettings.INSTANCE.readFromNBT(nbt1.getCompoundTag("questSettings")); + QuestDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questDatabase", 10), false); + QuestLineDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questLines", 10), false); + } else { + loader.readFromJson(j1); + } + + QuestDatabase.INSTANCE.readProgressFromNBT(jsonP, false); + + QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, editMode); + QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, hardMode); + + if (args.length == 3 && !args[2].equalsIgnoreCase("DefaultQuests")) { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.load2", args[2] + ".json")); + } else { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.load")); + } + + NetSettingSync.sendSync(null); + NetQuestSync.quickSync(-1, true, true); + NetChapterSync.sendSync(null, null); + SaveLoadHandler.INSTANCE.markDirty(); + } else { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.none")); + } + } else if (args[1].equalsIgnoreCase("set") && args.length == 3) { + if (qFile.exists() && !args[2].equalsIgnoreCase("DefaultQuests")) { + File defFile = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); + + if (defFile.exists()) { + defFile.delete(); + } + + JsonHelper.CopyPaste(qFile, defFile); + + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.set", args[2])); + } else { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.default.none")); + } + } else { + throw getException(command); + } + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.default"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } + + @Override + public String getPermissionDescription() { + return "Permission to saves/loads the current quest database to/from the global default directory"; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandDelete.java b/src/main/java/betterquesting/commands/admin/QuestCommandDelete.java index bfa5993da..77c0563e3 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandDelete.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandDelete.java @@ -21,87 +21,75 @@ import java.util.Collections; import java.util.List; -public class QuestCommandDelete extends QuestCommandBase -{ - @Override - public String getUsageSuffix() - { - return "[all|]"; - } - - @Override - public boolean validArgs(String[] args) - { - return args.length == 2; - } - - @Override - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - if(args.length == 2) - { - List list = new ArrayList<>(); - list.add("all"); - - for(DBEntry i : QuestDatabase.INSTANCE.getEntries()) - { - list.add("" + i.getID()); - } - return list; - } - - return Collections.emptyList(); - } - - @Override - public String getCommand() - { - return "delete"; - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - if(args[1].equalsIgnoreCase("all")) - { - QuestDatabase.INSTANCE.reset(); - QuestLineDatabase.INSTANCE.reset(); - NetQuestSync.sendSync(null, null, true, true); - NetChapterSync.sendSync(null, null); - SaveLoadHandler.INSTANCE.markDirty(); - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.delete.all")); - } else - { - try - { - int id = Integer.parseInt(args[1].trim()); - IQuest quest = QuestDatabase.INSTANCE.getValue(id); - NetQuestEdit.deleteQuests(new int[]{id}); - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.delete.single", new TextComponentTranslation(quest.getProperty(NativeProps.NAME)))); - } catch(Exception e) - { - throw getException(command); - } - } - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.delete"; - } +public class QuestCommandDelete extends QuestCommandBase { + @Override + public String getUsageSuffix() { + return "[all|]"; + } - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } + @Override + public boolean validArgs(String[] args) { + return args.length == 2; + } - @Override - public String getPermissionDescription() - { - return "Permission to delete given quest(s) and progression data however it does not delete new world defaults"; - } + @Override + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + if (args.length == 2) { + List list = new ArrayList<>(); + list.add("all"); + + for (DBEntry i : QuestDatabase.INSTANCE.getEntries()) { + list.add("" + i.getID()); + } + return list; + } + + return Collections.emptyList(); + } + + @Override + public String getCommand() { + return "delete"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException { + if (args[1].equalsIgnoreCase("all")) { + QuestDatabase.INSTANCE.reset(); + QuestLineDatabase.INSTANCE.reset(); + NetQuestSync.sendSync(null, null, true, true); + NetChapterSync.sendSync(null, null); + SaveLoadHandler.INSTANCE.markDirty(); + + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.delete.all")); + } else { + try { + int id = Integer.parseInt(args[1].trim()); + IQuest quest = QuestDatabase.INSTANCE.getValue(id); + NetQuestEdit.deleteQuests(new int[] { id }); + + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.delete.single", + new TextComponentTranslation( + quest.getProperty(NativeProps.NAME)))); + } catch (Exception e) { + throw getException(command); + } + } + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.delete"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } + + @Override + public String getPermissionDescription() { + return "Permission to delete given quest(s) and progression data however it does not delete new world defaults"; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java b/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java index a79e069c5..b7fdb35b1 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java @@ -15,80 +15,68 @@ import java.util.Collections; import java.util.List; -public class QuestCommandEdit extends QuestCommandBase -{ - @Override - public String getCommand() - { - return "edit"; - } - - @Override - public String getUsageSuffix() - { - return "[true|false]"; - } - - @Override - public boolean validArgs(String[] args) - { - return args.length == 1 || args.length == 2; - } - - @Override - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - return args.length == 2 ? CommandBase.getListOfStringsMatchingLastWord(args, "true","false") : Collections.emptyList(); - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - boolean flag = !QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); - - if(args.length == 2) - { - try - { - if(args[1].equalsIgnoreCase("on")) - { - flag = true; - } else if(args[1].equalsIgnoreCase("off")) - { - flag = false; - } else - { - flag = Boolean.parseBoolean(args[1]); - } - } catch(Exception e) - { - throw this.getException(command); - } - } - - QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, flag); - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.edit", new TextComponentTranslation(QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)? "options.on" : "options.off"))); - - SaveLoadHandler.INSTANCE.markDirty(); - NetSettingSync.sendSync(null); - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.edit"; - } +public class QuestCommandEdit extends QuestCommandBase { + @Override + public String getCommand() { + return "edit"; + } - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } + @Override + public String getUsageSuffix() { + return "[true|false]"; + } - @Override - public String getPermissionDescription() - { - return "Permission to activate quest editing mode on and off"; - } + @Override + public boolean validArgs(String[] args) { + return args.length == 1 || args.length == 2; + } + + @Override + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + return args.length == 2 ? CommandBase.getListOfStringsMatchingLastWord(args, "true", "false") + : Collections.emptyList(); + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException { + boolean flag = !QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); + + if (args.length == 2) { + try { + if (args[1].equalsIgnoreCase("on")) { + flag = true; + } else if (args[1].equalsIgnoreCase("off")) { + flag = false; + } else { + flag = Boolean.parseBoolean(args[1]); + } + } catch (Exception e) { + throw this.getException(command); + } + } + + QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, flag); + + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.edit", new TextComponentTranslation( + QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE) ? "options.on" : "options.off"))); + + SaveLoadHandler.INSTANCE.markDirty(); + NetSettingSync.sendSync(null); + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.edit"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } + + @Override + public String getPermissionDescription() { + return "Permission to activate quest editing mode on and off"; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java b/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java index 45a54e937..76e77a85c 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java @@ -15,79 +15,67 @@ import java.util.Collections; import java.util.List; -public class QuestCommandHardcore extends QuestCommandBase -{ - @Override - public String getCommand() - { - return "hardcore"; - } - - @Override - public String getUsageSuffix() - { - return "[true|false]"; - } - - @Override - public boolean validArgs(String[] args) - { - return args.length == 1 || args.length == 2; - } - - @Override - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - return args.length == 2 ? CommandBase.getListOfStringsMatchingLastWord(args, "true","false") : Collections.emptyList(); - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - boolean flag = !QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); - - if(args.length == 2) - { - try - { - if(args[1].equalsIgnoreCase("on")) - { - flag = true; - } else if(args[1].equalsIgnoreCase("off")) - { - flag = false; - } else - { - flag = Boolean.parseBoolean(args[1]); - } - } catch(Exception e) - { - throw this.getException(command); - } - } - - QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, flag); - SaveLoadHandler.INSTANCE.markDirty(); - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.hardcore", new TextComponentTranslation(QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE)? "options.on" : "options.off"))); - NetSettingSync.sendSync(null); - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.hardcore"; - } +public class QuestCommandHardcore extends QuestCommandBase { + @Override + public String getCommand() { + return "hardcore"; + } - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } + @Override + public String getUsageSuffix() { + return "[true|false]"; + } - @Override - public String getPermissionDescription() - { - return "Permission to activate or not the use of hardcore lives"; - } + @Override + public boolean validArgs(String[] args) { + return args.length == 1 || args.length == 2; + } + + @Override + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + return args.length == 2 ? CommandBase.getListOfStringsMatchingLastWord(args, "true", "false") + : Collections.emptyList(); + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException { + boolean flag = !QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE); + + if (args.length == 2) { + try { + if (args[1].equalsIgnoreCase("on")) { + flag = true; + } else if (args[1].equalsIgnoreCase("off")) { + flag = false; + } else { + flag = Boolean.parseBoolean(args[1]); + } + } catch (Exception e) { + throw this.getException(command); + } + } + + QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, flag); + SaveLoadHandler.INSTANCE.markDirty(); + + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.hardcore", new TextComponentTranslation( + QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE) ? "options.on" : "options.off"))); + NetSettingSync.sendSync(null); + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.hardcore"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } + + @Override + public String getPermissionDescription() { + return "Permission to activate or not the use of hardcore lives"; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandLives.java b/src/main/java/betterquesting/commands/admin/QuestCommandLives.java index 0587089c6..ba5b62e83 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandLives.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandLives.java @@ -19,163 +19,135 @@ import java.util.List; import java.util.UUID; -public class QuestCommandLives extends QuestCommandBase -{ - @Override - public String getCommand() - { - return "lives"; - } - - @Override - public String getUsageSuffix() - { - return "[add|set|max|default] [username|uuid]"; - } - - @Override - public boolean validArgs(String[] args) - { - return args.length == 4 || args.length == 3; - } - - @Override - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - if(args.length == 4 && (args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("set"))) - { - return CommandBase.getListOfStringsMatchingLastWord(args, NameCache.INSTANCE.getAllNames()); - } else if(args.length == 2) - { - return CommandBase.getListOfStringsMatchingLastWord(args, "add", "set", "max", "default"); - } - - return Collections.emptyList(); - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - String action = args[1]; - int value; - UUID playerID = null; - - try - { - value = Integer.parseInt(args[2]); - } catch(Exception e) - { - throw getException(command); - } - - if(args.length >= 4) - { - playerID = this.findPlayerID(server, sender, args[3]); - - if(playerID == null) - { - throw getException(command); - } - } - - String pName = playerID == null? "NULL" : NameCache.INSTANCE.getName(playerID); - - if(action.equalsIgnoreCase("set")) - { - value = Math.max(1, value); - - if(playerID != null) - { - LifeDatabase.INSTANCE.setLives(playerID, value); - EntityPlayerMP target = server.getPlayerList().getPlayerByUUID(playerID); - //noinspection ConstantConditions - if(target != null) NetLifeSync.sendSync(new EntityPlayerMP[]{target}, new UUID[]{playerID}); - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.set_player", pName, value)); - } else - { - for(EntityPlayerMP p : server.getPlayerList().getPlayers()) // TODO: Make this work for offline players - { - UUID uuid = QuestingAPI.getQuestingUUID(p); - LifeDatabase.INSTANCE.setLives(uuid, value); - NetLifeSync.sendSync(new EntityPlayerMP[]{p}, new UUID[]{uuid}); - } - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.set_all", value)); - } - } else if(action.equalsIgnoreCase("add")) - { - if(playerID != null) - { - int lives = LifeDatabase.INSTANCE.getLives(playerID) + value; - LifeDatabase.INSTANCE.setLives(playerID, lives); - EntityPlayerMP target = server.getPlayerList().getPlayerByUUID(playerID); - //noinspection ConstantConditions - if(target != null) NetLifeSync.sendSync(new EntityPlayerMP[]{target}, new UUID[]{playerID}); - - if(value >= 0) - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.add_player", value, pName, lives)); - } else - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.remove_player", Math.abs(value), pName, lives)); - } - } else - { - for(EntityPlayerMP p : server.getPlayerList().getPlayers()) - { - UUID uuid = QuestingAPI.getQuestingUUID(p); - int lives = LifeDatabase.INSTANCE.getLives(uuid); - LifeDatabase.INSTANCE.setLives(uuid, lives + value); - NetLifeSync.sendSync(new EntityPlayerMP[]{p}, new UUID[]{uuid}); - } - - if(value >= 0) - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.add_all", value)); - } else - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.remove_all", Math.abs(value))); - } - } - } else if(action.equalsIgnoreCase("max")) - { - value = Math.max(1, value); - QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_MAX, value); - // TODO: Sync this for display purposes client side - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.max", value)); - } else if(action.equalsIgnoreCase("default")) - { - value = Math.max(1, value); - QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_DEF, value); - // TODO: Sync this for display purposes client side - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.default" + value)); - } else - { - throw getException(command); - } - } - - @Override - public boolean isArgUsername(String[] args, int index) - { - return index == 3; - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.lives"; - } - - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } - - @Override - public String getPermissionDescription() - { - return "Permission to set lives to the given user"; - } +public class QuestCommandLives extends QuestCommandBase { + @Override + public String getCommand() { + return "lives"; + } + + @Override + public String getUsageSuffix() { + return "[add|set|max|default] [username|uuid]"; + } + + @Override + public boolean validArgs(String[] args) { + return args.length == 4 || args.length == 3; + } + + @Override + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + if (args.length == 4 && (args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("set"))) { + return CommandBase.getListOfStringsMatchingLastWord(args, NameCache.INSTANCE.getAllNames()); + } else if (args.length == 2) { + return CommandBase.getListOfStringsMatchingLastWord(args, "add", "set", "max", "default"); + } + + return Collections.emptyList(); + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException { + String action = args[1]; + int value; + UUID playerID = null; + + try { + value = Integer.parseInt(args[2]); + } catch (Exception e) { + throw getException(command); + } + + if (args.length >= 4) { + playerID = this.findPlayerID(server, sender, args[3]); + + if (playerID == null) { + throw getException(command); + } + } + + String pName = playerID == null ? "NULL" : NameCache.INSTANCE.getName(playerID); + + if (action.equalsIgnoreCase("set")) { + value = Math.max(1, value); + + if (playerID != null) { + LifeDatabase.INSTANCE.setLives(playerID, value); + EntityPlayerMP target = server.getPlayerList().getPlayerByUUID(playerID); + //noinspection ConstantConditions + if (target != null) { NetLifeSync.sendSync(new EntityPlayerMP[] { target }, new UUID[] { playerID }); } + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.set_player", pName, value)); + } else { + for (EntityPlayerMP p : server.getPlayerList().getPlayers()) // TODO: Make this work for offline players + { + UUID uuid = QuestingAPI.getQuestingUUID(p); + LifeDatabase.INSTANCE.setLives(uuid, value); + NetLifeSync.sendSync(new EntityPlayerMP[] { p }, new UUID[] { uuid }); + } + + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.set_all", value)); + } + } else if (action.equalsIgnoreCase("add")) { + if (playerID != null) { + int lives = LifeDatabase.INSTANCE.getLives(playerID) + value; + LifeDatabase.INSTANCE.setLives(playerID, lives); + EntityPlayerMP target = server.getPlayerList().getPlayerByUUID(playerID); + //noinspection ConstantConditions + if (target != null) { NetLifeSync.sendSync(new EntityPlayerMP[] { target }, new UUID[] { playerID }); } + + if (value >= 0) { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.add_player", value, pName, lives)); + } else { + sender.sendMessage( + new TextComponentTranslation("betterquesting.cmd.lives.remove_player", Math.abs(value), pName, lives)); + } + } else { + for (EntityPlayerMP p : server.getPlayerList().getPlayers()) { + UUID uuid = QuestingAPI.getQuestingUUID(p); + int lives = LifeDatabase.INSTANCE.getLives(uuid); + LifeDatabase.INSTANCE.setLives(uuid, lives + value); + NetLifeSync.sendSync(new EntityPlayerMP[] { p }, new UUID[] { uuid }); + } + + if (value >= 0) { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.add_all", value)); + } else { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.remove_all", Math.abs(value))); + } + } + } else if (action.equalsIgnoreCase("max")) { + value = Math.max(1, value); + QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_MAX, value); + // TODO: Sync this for display purposes client side + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.max", value)); + } else if (action.equalsIgnoreCase("default")) { + value = Math.max(1, value); + QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_DEF, value); + // TODO: Sync this for display purposes client side + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.default" + value)); + } else { + throw getException(command); + } + } + + @Override + public boolean isArgUsername(String[] args, int index) { + return index == 3; + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.lives"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } + + @Override + public String getPermissionDescription() { + return "Permission to set lives to the given user"; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java b/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java index 7d71e9493..1db4eaba6 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java @@ -19,60 +19,51 @@ import java.util.List; import java.util.TreeSet; -public class QuestCommandPurge extends QuestCommandBase -{ - @Override - public String getCommand() - { - return "purge_hidden_quests"; +public class QuestCommandPurge extends QuestCommandBase { + @Override + public String getCommand() { + return "purge_hidden_quests"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) { + TreeSet knownKeys = new TreeSet<>(); + + for (DBEntry entry : QuestLineDatabase.INSTANCE.getEntries()) { + for (DBEntry qle : entry.getValue().getEntries()) { + knownKeys.add(qle.getID()); + } } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) - { - TreeSet knownKeys = new TreeSet<>(); - - for(DBEntry entry : QuestLineDatabase.INSTANCE.getEntries()) - { - for(DBEntry qle : entry.getValue().getEntries()) - { - knownKeys.add(qle.getID()); - } - } - - Iterator keyIterator = knownKeys.iterator(); - List removeQueue = new ArrayList<>(); - int n = -1; - - for(DBEntry entry : QuestDatabase.INSTANCE.getEntries()) - { - while(n < entry.getID() && keyIterator.hasNext()) n = keyIterator.next(); - if(n != entry.getID()) removeQueue.add(entry.getID()); - } - - int removed = removeQueue.size(); - int[] bulkIDs = new int[removeQueue.size()]; - for(n = 0; n < bulkIDs.length; n++) bulkIDs[n] = removeQueue.get(n); - NetQuestEdit.deleteQuests(bulkIDs); - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.purge_hidden", removed)); + + Iterator keyIterator = knownKeys.iterator(); + List removeQueue = new ArrayList<>(); + int n = -1; + + for (DBEntry entry : QuestDatabase.INSTANCE.getEntries()) { + while (n < entry.getID() && keyIterator.hasNext()) { n = keyIterator.next(); } + if (n != entry.getID()) { removeQueue.add(entry.getID()); } } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.purge"; - } - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } + int removed = removeQueue.size(); + int[] bulkIDs = new int[removeQueue.size()]; + for (n = 0; n < bulkIDs.length; n++) { bulkIDs[n] = removeQueue.get(n); } + NetQuestEdit.deleteQuests(bulkIDs); + + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.purge_hidden", removed)); + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.purge"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } - @Override - public String getPermissionDescription() - { - return "Permission to purge all hidden quests and progression data however it does not delete any in new world defaults"; - } + @Override + public String getPermissionDescription() { + return "Permission to purge all hidden quests and progression data however it does not delete any in new world defaults"; + } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandReset.java b/src/main/java/betterquesting/commands/admin/QuestCommandReset.java index 271c1b2cd..1480bef38 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandReset.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandReset.java @@ -20,138 +20,113 @@ import java.util.List; import java.util.UUID; -public class QuestCommandReset extends QuestCommandBase -{ - @Override - public String getUsageSuffix() - { - return "[all|] [username|uuid]"; - } - - @Override - public boolean validArgs(String[] args) - { - return args.length == 2 || args.length == 3; - } - - @Override - public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) - { - if(args.length == 2) - { - List list = new ArrayList<>(); - list.add("all"); - - for(DBEntry i : QuestDatabase.INSTANCE.getEntries()) - { - list.add("" + i.getID()); - } - - return list; - } else if(args.length == 3) - { - return CommandBase.getListOfStringsMatchingLastWord(args, NameCache.INSTANCE.getAllNames()); - } - - return Collections.emptyList(); - } - - @Override - public String getCommand() - { - return "reset"; - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - String action = args[1]; - - UUID uuid = null; - - if(args.length == 3) - { - uuid = this.findPlayerID(server, sender, args[2]); - - if(uuid == null) - { - throw this.getException(command); - } - } - - String pName = uuid == null? "NULL" : NameCache.INSTANCE.getName(uuid); - EntityPlayerMP player = uuid == null ? null : server.getPlayerList().getPlayerByUUID(uuid); - - if(action.equalsIgnoreCase("all")) - { - for(DBEntry entry : QuestDatabase.INSTANCE.getEntries()) - { - if(uuid != null) - { - entry.getValue().resetUser(uuid, true); // Clear progress and state - } else - { - entry.getValue().resetUser(null, true); - } - } - - if(uuid != null) - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.player_all", pName)); - if(player != null) NetQuestSync.sendSync(player, null, false, true); - } else - { - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.all_all")); - NetQuestSync.quickSync(-1, false, true); - } - - } else - { - try - { - int id = Integer.parseInt(action.trim()); - IQuest quest = QuestDatabase.INSTANCE.getValue(id); - - if(uuid != null) - { - quest.resetUser(uuid, true); // Clear progress and state - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.player_single", new TextComponentTranslation(quest.getProperty(NativeProps.NAME)), pName)); - if(player != null) NetQuestSync.sendSync(player, new int[]{id}, false, true); - } else - { - quest.resetUser(null, true); - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.all_single", new TextComponentTranslation(quest.getProperty(NativeProps.NAME)))); - NetQuestSync.quickSync(id, false, true); - } - } catch(Exception e) - { - throw getException(command); - } - } - } - - @Override - public boolean isArgUsername(String[] args, int index) - { - return index == 2; - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.admin.reset"; - } - - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.OP; - } - - @Override - public String getPermissionDescription() - { - return "Permission to erases quest completion data for the given user"; - } - +public class QuestCommandReset extends QuestCommandBase { + @Override + public String getUsageSuffix() { + return "[all|] [username|uuid]"; + } + + @Override + public boolean validArgs(String[] args) { + return args.length == 2 || args.length == 3; + } + + @Override + public List autoComplete(MinecraftServer server, ICommandSender sender, String[] args) { + if (args.length == 2) { + List list = new ArrayList<>(); + list.add("all"); + + for (DBEntry i : QuestDatabase.INSTANCE.getEntries()) { + list.add("" + i.getID()); + } + + return list; + } else if (args.length == 3) { + return CommandBase.getListOfStringsMatchingLastWord(args, NameCache.INSTANCE.getAllNames()); + } + + return Collections.emptyList(); + } + + @Override + public String getCommand() { + return "reset"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) + throws CommandException { + String action = args[1]; + + UUID uuid = null; + + if (args.length == 3) { + uuid = this.findPlayerID(server, sender, args[2]); + + if (uuid == null) { + throw this.getException(command); + } + } + + String pName = uuid == null ? "NULL" : NameCache.INSTANCE.getName(uuid); + EntityPlayerMP player = uuid == null ? null : server.getPlayerList().getPlayerByUUID(uuid); + + if (action.equalsIgnoreCase("all")) { + for (DBEntry entry : QuestDatabase.INSTANCE.getEntries()) { + entry.getValue().resetUser(uuid, true); // Clear progress and state + } + + if (uuid != null) { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.player_all", pName)); + NetQuestSync.sendSync(player, null, false, true); + } else { + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.all_all")); + NetQuestSync.quickSync(-1, false, true); + } + + } else { + try { + int id = Integer.parseInt(action.trim()); + IQuest quest = QuestDatabase.INSTANCE.getValue(id); + + if (uuid != null) { + quest.resetUser(uuid, true); // Clear progress and state + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.player_single", + new TextComponentTranslation( + quest.getProperty(NativeProps.NAME)), pName)); + NetQuestSync.sendSync(player, new int[] { id }, false, true); + } else { + quest.resetUser(null, true); + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.reset.all_single", + new TextComponentTranslation( + quest.getProperty(NativeProps.NAME)))); + NetQuestSync.quickSync(id, false, true); + } + } catch (Exception e) { + throw getException(command); + } + } + } + + @Override + public boolean isArgUsername(String[] args, int index) { + return index == 2; + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.admin.reset"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.OP; + } + + @Override + public String getPermissionDescription() { + return "Permission to erases quest completion data for the given user"; + } + } diff --git a/src/main/java/betterquesting/commands/user/QuestCommandHelp.java b/src/main/java/betterquesting/commands/user/QuestCommandHelp.java index 67597090b..23a7c5c16 100644 --- a/src/main/java/betterquesting/commands/user/QuestCommandHelp.java +++ b/src/main/java/betterquesting/commands/user/QuestCommandHelp.java @@ -1,52 +1,43 @@ package betterquesting.commands.user; +import betterquesting.commands.QuestCommandBase; +import betterquesting.core.BetterQuesting; import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraftforge.server.permission.DefaultPermissionLevel; -import betterquesting.commands.QuestCommandBase; -import betterquesting.core.BetterQuesting; -public class QuestCommandHelp extends QuestCommandBase -{ - @Override - public String getCommand() - { - return "help"; - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - if(sender instanceof EntityPlayer) - { - EntityPlayer player = (EntityPlayer)sender; - if(!player.inventory.addItemStackToInventory(new ItemStack(BetterQuesting.guideBook))) - { - player.dropItem(new ItemStack(BetterQuesting.guideBook), true, false); - } - } - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.user.help"; - } +public class QuestCommandHelp extends QuestCommandBase { + @Override + public String getCommand() { + return "help"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) { + if (sender instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) sender; + if (!player.inventory.addItemStackToInventory(new ItemStack(BetterQuesting.guideBook))) { + player.dropItem(new ItemStack(BetterQuesting.guideBook), true, false); + } + } + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.user.help"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.ALL; + } - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.ALL; - } + @Override + public String getPermissionDescription() { + return "Permission to execute command which gives the player a copy of the in game starter guide."; + } - @Override - public String getPermissionDescription() - { - return "Permission to execute command which gives the player a copy of the in game starter guide."; - } - } diff --git a/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java b/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java index da1428db1..d7a3bf846 100644 --- a/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java +++ b/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java @@ -15,48 +15,40 @@ import net.minecraft.util.text.TextComponentTranslation; import net.minecraftforge.server.permission.DefaultPermissionLevel; -public class QuestCommandRefresh extends QuestCommandBase -{ - @Override - public String getCommand() - { - return "refresh"; - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) - { - if(!(sender instanceof EntityPlayerMP)) return; - EntityPlayerMP player = (EntityPlayerMP)sender; - - if(server.isDedicatedServer() || !server.getServerOwner().equals(player.getGameProfile().getName())) - { - NetBulkSync.sendReset(player, true, true); - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.refresh")); - } else - { - boolean nameChanged = NameCache.INSTANCE.updateName(player); - DBEntry party = PartyManager.INSTANCE.getParty(QuestingAPI.getQuestingUUID(player)); - if(nameChanged && party != null) NetNameSync.quickSync(null, party.getID()); - } - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.user.refresh"; - } - - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.ALL; - } - - @Override - public String getPermissionDescription() - { - return "Permission to manually resync the local questing database with the server in case of potential desync issues"; - } - +public class QuestCommandRefresh extends QuestCommandBase { + @Override + public String getCommand() { + return "refresh"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) { + if (!(sender instanceof EntityPlayerMP)) { return; } + EntityPlayerMP player = (EntityPlayerMP) sender; + + if (server.isDedicatedServer() || !server.getServerOwner().equals(player.getGameProfile().getName())) { + NetBulkSync.sendReset(player, true, true); + sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.refresh")); + } else { + boolean nameChanged = NameCache.INSTANCE.updateName(player); + DBEntry party = PartyManager.INSTANCE.getParty(QuestingAPI.getQuestingUUID(player)); + if (nameChanged && party != null) { NetNameSync.quickSync(null, party.getID()); } + } + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.user.refresh"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.ALL; + } + + @Override + public String getPermissionDescription() { + return "Permission to manually resync the local questing database with the server in case of potential desync issues"; + } + } diff --git a/src/main/java/betterquesting/commands/user/QuestCommandSPHardcore.java b/src/main/java/betterquesting/commands/user/QuestCommandSPHardcore.java index 2c76118d7..110faf9cf 100644 --- a/src/main/java/betterquesting/commands/user/QuestCommandSPHardcore.java +++ b/src/main/java/betterquesting/commands/user/QuestCommandSPHardcore.java @@ -6,54 +6,47 @@ import betterquesting.network.handlers.NetSettingSync; import betterquesting.storage.QuestSettings; import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.server.permission.DefaultPermissionLevel; -public class QuestCommandSPHardcore extends QuestCommandBase -{ - @Override - public String getCommand() - { - return "hardcore"; - } - - @Override - public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) throws CommandException - { - if(!server.isSinglePlayer() || !server.getServerOwner().equalsIgnoreCase(sender.getName())) - { - TextComponentTranslation cc = new TextComponentTranslation("commands.generic.permission"); - cc.getStyle().setColor(TextFormatting.RED); - sender.sendMessage(cc); - return; - } - - QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, true); - SaveLoadHandler.INSTANCE.markDirty(); - - sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.hardcore", new TextComponentTranslation("options.on"))); - NetSettingSync.sendSync(null); - } - - @Override - public String getPermissionNode() - { - return "betterquesting.command.user.hardcores"; - } - - @Override - public DefaultPermissionLevel getPermissionLevel() - { - return DefaultPermissionLevel.ALL; - } - - @Override - public String getPermissionDescription() - { - return "Permission to manually resyncs the local questing database with the server in case of potential desync issues"; - } +public class QuestCommandSPHardcore extends QuestCommandBase { + @Override + public String getCommand() { + return "hardcore"; + } + + @Override + public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) { + if (!server.isSinglePlayer() || !server.getServerOwner().equalsIgnoreCase(sender.getName())) { + TextComponentTranslation cc = new TextComponentTranslation("commands.generic.permission"); + cc.getStyle().setColor(TextFormatting.RED); + sender.sendMessage(cc); + return; + } + + QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, true); + SaveLoadHandler.INSTANCE.markDirty(); + + sender.sendMessage( + new TextComponentTranslation("betterquesting.cmd.hardcore", new TextComponentTranslation("options.on"))); + NetSettingSync.sendSync(null); + } + + @Override + public String getPermissionNode() { + return "betterquesting.command.user.hardcores"; + } + + @Override + public DefaultPermissionLevel getPermissionLevel() { + return DefaultPermissionLevel.ALL; + } + + @Override + public String getPermissionDescription() { + return "Permission to manually resyncs the local questing database with the server in case of potential desync issues"; + } } diff --git a/src/main/java/betterquesting/core/BetterQuesting.java b/src/main/java/betterquesting/core/BetterQuesting.java index f2a470948..b4a5924f8 100644 --- a/src/main/java/betterquesting/core/BetterQuesting.java +++ b/src/main/java/betterquesting/core/BetterQuesting.java @@ -14,7 +14,7 @@ import betterquesting.handlers.SaveLoadHandler; import betterquesting.items.ItemExtraLife; import betterquesting.items.ItemGuideBook; -import betterquesting.network.PacketQuesting; +import betterquesting.network.BetterQuestingPacketHandler; import betterquesting.network.PacketTypeRegistry; import net.minecraft.block.Block; import net.minecraft.command.ICommandManager; @@ -35,87 +35,85 @@ import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.fml.relauncher.Side; import org.apache.logging.log4j.Logger; -@Mod(modid = BetterQuesting.MODID, version = BetterQuesting.VERSION, name = BetterQuesting.NAME, guiFactory = "betterquesting.handlers.ConfigGuiFactory") -public class BetterQuesting -{ - public static final String VERSION = "@VERSION@"; - public static final String MODID = "betterquesting"; - public static final String NAME = "BetterQuesting"; - public static final String FORMAT = "2.0.0"; - - // TODO: Possibly make use of this in future - private static final String MCL_API = "Yo1nkbXn7uVptLoL3GpkAaT7HsU8QFGJ"; - - @Instance(MODID) - public static BetterQuesting instance; - - @SidedProxy(clientSide = "betterquesting.core.proxies.ClientProxy", serverSide = "betterquesting.core.proxies.CommonProxy") - public static CommonProxy proxy; - public SimpleNetworkWrapper network; - public static Logger logger; - - public static CreativeTabs tabQuesting = new CreativeTabQuesting(); - - public static Item extraLife = new ItemExtraLife(); - public static Item guideBook = new ItemGuideBook(); - - public static Block submitStation = new BlockSubmitStation(); - - @EventHandler - public void preInit(FMLPreInitializationEvent event) - { - logger = event.getModLog(); - network = NetworkRegistry.INSTANCE.newSimpleChannel("BQ_NET_CHAN"); - - ConfigHandler.config = new Configuration(event.getSuggestedConfigurationFile(), true); - ConfigHandler.initConfigs(); - - proxy.registerHandlers(); - - PacketTypeRegistry.INSTANCE.init(); - - network.registerMessage(PacketQuesting.HandleClient.class, PacketQuesting.class, 0, Side.CLIENT); - network.registerMessage(PacketQuesting.HandleServer.class, PacketQuesting.class, 0, Side.SERVER); - - CapabilityProviderQuestCache.register(); - } - - @EventHandler - public void init(FMLInitializationEvent event) - { - FluidRegistry.registerFluid(FluidPlaceholder.fluidPlaceholder); - - GameRegistry.registerTileEntity(TileSubmitStation.class, new ResourceLocation(MODID + ":submit_station")); - - EntityRegistry.registerModEntity(new ResourceLocation(MODID + ":placeholder"), EntityPlaceholder.class, "placeholder", 0, this, 16, 1, false); - } - - @EventHandler - public void postInit(FMLPostInitializationEvent event) - { +@Mod( + modid = BetterQuesting.MODID, + version = BetterQuesting.VERSION, + name = BetterQuesting.NAME, + guiFactory = "betterquesting.handlers.ConfigGuiFactory" +) +public class BetterQuesting { + public static final String VERSION = "@VERSION@"; + public static final String MODID = "betterquesting"; + public static final String NAME = "BetterQuesting"; + public static final String FORMAT = "2.0.0"; + + // TODO: Possibly make use of this in future + private static final String MCL_API = "Yo1nkbXn7uVptLoL3GpkAaT7HsU8QFGJ"; + + @Instance(MODID) + public static BetterQuesting instance; + + @SidedProxy(clientSide = "betterquesting.core.proxies.ClientProxy", + serverSide = "betterquesting.core.proxies.CommonProxy") + public static CommonProxy proxy; + public SimpleNetworkWrapper network; + public static Logger logger; + + public static final CreativeTabs tabQuesting = new CreativeTabQuesting(); + + public static final Item extraLife = new ItemExtraLife(); + public static final Item guideBook = new ItemGuideBook(); + + public static final Block submitStation = new BlockSubmitStation(); + + @EventHandler + public void preInit(FMLPreInitializationEvent event) { + logger = event.getModLog(); + network = NetworkRegistry.INSTANCE.newSimpleChannel("BQ_NET_CHAN"); + + ConfigHandler.config = new Configuration(event.getSuggestedConfigurationFile(), true); + ConfigHandler.initConfigs(); + + proxy.registerHandlers(); + + PacketTypeRegistry.INSTANCE.init(); + + BetterQuestingPacketHandler.init(); + network = BetterQuestingPacketHandler.INSTANCE; + + CapabilityProviderQuestCache.register(); + } + + @EventHandler + public void init(FMLInitializationEvent event) { + FluidRegistry.registerFluid(FluidPlaceholder.fluidPlaceholder); + + GameRegistry.registerTileEntity(TileSubmitStation.class, new ResourceLocation(MODID + ":submit_station")); + + EntityRegistry.registerModEntity(new ResourceLocation(MODID + ":placeholder"), EntityPlaceholder.class, + "placeholder", 0, this, 16, 1, false); + } + + @EventHandler + public void serverStart(FMLServerStartingEvent event) { + MinecraftServer server = event.getServer(); + ICommandManager command = server.getCommandManager(); + ServerCommandManager manager = (ServerCommandManager) command; + + manager.registerCommand(new BQ_CommandAdmin()); + manager.registerCommand(new BQ_CommandUser()); + + if ((Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) { + manager.registerCommand(new BQ_CommandDebug()); } - - @EventHandler - public void serverStart(FMLServerStartingEvent event) - { - MinecraftServer server = event.getServer(); - ICommandManager command = server.getCommandManager(); - ServerCommandManager manager = (ServerCommandManager) command; - - manager.registerCommand(new BQ_CommandAdmin()); - manager.registerCommand(new BQ_CommandUser()); - - if((Boolean)Launch.blackboard.get("fml.deobfuscatedEnvironment")) manager.registerCommand(new BQ_CommandDebug()); - - SaveLoadHandler.INSTANCE.loadDatabases(server); - } - - @EventHandler - public void serverStop(FMLServerStoppedEvent event) - { - SaveLoadHandler.INSTANCE.unloadDatabases(); - } + + SaveLoadHandler.INSTANCE.loadDatabases(server); + } + + @EventHandler + public void serverStop(FMLServerStoppedEvent event) { + SaveLoadHandler.INSTANCE.unloadDatabases(); + } } diff --git a/src/main/java/betterquesting/core/ExpansionLoader.java b/src/main/java/betterquesting/core/ExpansionLoader.java index 33f069bf5..ad95e4b85 100644 --- a/src/main/java/betterquesting/core/ExpansionLoader.java +++ b/src/main/java/betterquesting/core/ExpansionLoader.java @@ -19,35 +19,32 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -public class ExpansionLoader -{ - public static final ExpansionLoader INSTANCE = new ExpansionLoader(); - - public void initCommonAPIs() - { - QuestingAPI.registerAPI(ApiReference.QUEST_DB, QuestDatabase.INSTANCE); - QuestingAPI.registerAPI(ApiReference.LINE_DB, QuestLineDatabase.INSTANCE); - QuestingAPI.registerAPI(ApiReference.PARTY_DB, PartyManager.INSTANCE); - QuestingAPI.registerAPI(ApiReference.LIFE_DB, LifeDatabase.INSTANCE); - - QuestingAPI.registerAPI(ApiReference.TASK_REG, TaskRegistry.INSTANCE); - QuestingAPI.registerAPI(ApiReference.REWARD_REG, RewardRegistry.INSTANCE); - - QuestingAPI.registerAPI(ApiReference.PACKET_SENDER, PacketSender.INSTANCE); - QuestingAPI.registerAPI(ApiReference.PACKET_REG, PacketTypeRegistry.INSTANCE); - - QuestingAPI.registerAPI(ApiReference.SETTINGS, QuestSettings.INSTANCE); - QuestingAPI.registerAPI(ApiReference.NAME_CACHE, NameCache.INSTANCE); - - QuestingAPI.registerAPI(ApiReference.CREATIVE_TAB, BetterQuesting.tabQuesting); - } - - @SideOnly(Side.CLIENT) - public void initClientAPIs() - { - QuestingAPI.registerAPI(ApiReference.THEME_REG, ThemeRegistry.INSTANCE); - QuestingAPI.registerAPI(ApiReference.RESOURCE_REG, ResourceRegistry.INSTANCE); - QuestingAPI.registerAPI(ApiReference.TOOL_REG, ToolboxRegistry.INSTANCE); - QuestingAPI.registerAPI(ApiReference.IMPORT_REG, ImporterRegistry.INSTANCE); - } +public class ExpansionLoader { + public static final ExpansionLoader INSTANCE = new ExpansionLoader(); + + public void initCommonAPIs() { + QuestingAPI.registerAPI(ApiReference.QUEST_DB, QuestDatabase.INSTANCE); + QuestingAPI.registerAPI(ApiReference.LINE_DB, QuestLineDatabase.INSTANCE); + QuestingAPI.registerAPI(ApiReference.PARTY_DB, PartyManager.INSTANCE); + QuestingAPI.registerAPI(ApiReference.LIFE_DB, LifeDatabase.INSTANCE); + + QuestingAPI.registerAPI(ApiReference.TASK_REG, TaskRegistry.INSTANCE); + QuestingAPI.registerAPI(ApiReference.REWARD_REG, RewardRegistry.INSTANCE); + + QuestingAPI.registerAPI(ApiReference.PACKET_SENDER, PacketSender.INSTANCE); + QuestingAPI.registerAPI(ApiReference.PACKET_REG, PacketTypeRegistry.INSTANCE); + + QuestingAPI.registerAPI(ApiReference.SETTINGS, QuestSettings.INSTANCE); + QuestingAPI.registerAPI(ApiReference.NAME_CACHE, NameCache.INSTANCE); + + QuestingAPI.registerAPI(ApiReference.CREATIVE_TAB, BetterQuesting.tabQuesting); + } + + @SideOnly(Side.CLIENT) + public void initClientAPIs() { + QuestingAPI.registerAPI(ApiReference.THEME_REG, ThemeRegistry.INSTANCE); + QuestingAPI.registerAPI(ApiReference.RESOURCE_REG, ResourceRegistry.INSTANCE); + QuestingAPI.registerAPI(ApiReference.TOOL_REG, ToolboxRegistry.INSTANCE); + QuestingAPI.registerAPI(ApiReference.IMPORT_REG, ImporterRegistry.INSTANCE); + } } diff --git a/src/main/java/betterquesting/core/RegEventHandler.java b/src/main/java/betterquesting/core/RegEventHandler.java index 5ce274e6e..0f2d120a5 100644 --- a/src/main/java/betterquesting/core/RegEventHandler.java +++ b/src/main/java/betterquesting/core/RegEventHandler.java @@ -21,88 +21,87 @@ import java.util.List; @Mod.EventBusSubscriber -public class RegEventHandler -{ - public static final List ALL_ITEMS = new ArrayList<>(); - public static final List ALL_BLOCKS = new ArrayList<>(); - public static final List ALL_RECIPES = new ArrayList<>(); - - private static boolean setupRecipes = false; - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public static void registerModelEvent(ModelRegistryEvent event) - { - BetterQuesting.proxy.registerRenderers(); - } - - @SubscribeEvent - public static void registerBlockEvent(RegistryEvent.Register event) - { - event.getRegistry().registerAll(ALL_BLOCKS.toArray(new Block[0])); - } - - @SubscribeEvent - public static void registerItemEvent(RegistryEvent.Register event) - { - event.getRegistry().registerAll(ALL_ITEMS.toArray(new Item[0])); - } - - @SubscribeEvent - public static void registerRecipeEvent(RegistryEvent.Register event) - { - if(!setupRecipes) - { - initRecipes(); - } - - IRecipe[] tmp = ALL_RECIPES.toArray(new IRecipe[0]); - event.getRegistry().registerAll(tmp); - } - - public static void registerBlock(Block b, String name) - { - ResourceLocation res = new ResourceLocation(BetterQuesting.MODID + ":" + name); - ALL_BLOCKS.add(b.setRegistryName(res)); - ALL_ITEMS.add(new ItemBlock(b).setRegistryName(res)); - } - - public static void registerItem(Item i, String name) - { - ResourceLocation res = new ResourceLocation(BetterQuesting.MODID + ":" + name); - ALL_ITEMS.add(i.setRegistryName(res)); - } - - public static void addShapelessRecipe(String name, String group, ItemStack stack, Object... ing) - { - ResourceLocation rName = new ResourceLocation(BetterQuesting.MODID, name); - ResourceLocation rGroup = new ResourceLocation(BetterQuesting.MODID, group); - - ALL_RECIPES.add(new ShapelessOreRecipe(rGroup, stack, ing).setRegistryName(rName)); - } - - public static void initRecipes() - { - addShapelessRecipe("submit_station", "questing", new ItemStack(BetterQuesting.submitStation), new ItemStack(Items.BOOK), new ItemStack(Blocks.GLASS), new ItemStack(Blocks.CHEST)); - - addShapelessRecipe("life_full_0", "questing", new ItemStack(BetterQuesting.extraLife, 1, 0), new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2)); - addShapelessRecipe("life_full_1", "questing", new ItemStack(BetterQuesting.extraLife, 1, 0), new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 1)); - addShapelessRecipe("life_full_2", "questing", new ItemStack(BetterQuesting.extraLife, 1, 0), new ItemStack(BetterQuesting.extraLife, 1, 1), new ItemStack(BetterQuesting.extraLife, 1, 1)); - - addShapelessRecipe("life_half_0", "questing", new ItemStack(BetterQuesting.extraLife, 2, 1), new ItemStack(BetterQuesting.extraLife, 1, 0)); - addShapelessRecipe("life_half_1", "questing", new ItemStack(BetterQuesting.extraLife, 1, 1), new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2)); - - addShapelessRecipe("life_quarter_0", "questing", new ItemStack(BetterQuesting.extraLife, 2, 2), new ItemStack(BetterQuesting.extraLife, 1, 1)); - - setupRecipes = true; +public class RegEventHandler { + public static final List ALL_ITEMS = new ArrayList<>(); + public static final List ALL_BLOCKS = new ArrayList<>(); + public static final List ALL_RECIPES = new ArrayList<>(); + + private static boolean setupRecipes = false; + + @SubscribeEvent + @SideOnly(Side.CLIENT) + public static void registerModelEvent(ModelRegistryEvent event) { + BetterQuesting.proxy.registerRenderers(); + } + + @SubscribeEvent + public static void registerBlockEvent(RegistryEvent.Register event) { + event.getRegistry().registerAll(ALL_BLOCKS.toArray(new Block[0])); + } + + @SubscribeEvent + public static void registerItemEvent(RegistryEvent.Register event) { + event.getRegistry().registerAll(ALL_ITEMS.toArray(new Item[0])); + } + + @SubscribeEvent + public static void registerRecipeEvent(RegistryEvent.Register event) { + if (!setupRecipes) { + initRecipes(); } - - // SETUP ALL THE THINGS - static { - registerItem(ItemPlaceholder.placeholder, "placeholder"); - registerItem(BetterQuesting.extraLife, "extra_life"); - registerItem(BetterQuesting.guideBook, "guide_book"); - - registerBlock(BetterQuesting.submitStation, "submit_station"); - } + + IRecipe[] tmp = ALL_RECIPES.toArray(new IRecipe[0]); + event.getRegistry().registerAll(tmp); + } + + public static void registerBlock(Block b, String name) { + ResourceLocation res = new ResourceLocation(BetterQuesting.MODID + ":" + name); + ALL_BLOCKS.add(b.setRegistryName(res)); + ALL_ITEMS.add(new ItemBlock(b).setRegistryName(res)); + } + + public static void registerItem(Item i, String name) { + ResourceLocation res = new ResourceLocation(BetterQuesting.MODID + ":" + name); + ALL_ITEMS.add(i.setRegistryName(res)); + } + + public static void addShapelessRecipe(String name, String group, ItemStack stack, Object... ing) { + ResourceLocation rName = new ResourceLocation(BetterQuesting.MODID, name); + ResourceLocation rGroup = new ResourceLocation(BetterQuesting.MODID, group); + + ALL_RECIPES.add(new ShapelessOreRecipe(rGroup, stack, ing).setRegistryName(rName)); + } + + public static void initRecipes() { + addShapelessRecipe("submit_station", "questing", new ItemStack(BetterQuesting.submitStation), + new ItemStack(Items.BOOK), new ItemStack(Blocks.GLASS), new ItemStack(Blocks.CHEST)); + + addShapelessRecipe("life_full_0", "questing", new ItemStack(BetterQuesting.extraLife, 1, 0), + new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2), + new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2)); + addShapelessRecipe("life_full_1", "questing", new ItemStack(BetterQuesting.extraLife, 1, 0), + new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2), + new ItemStack(BetterQuesting.extraLife, 1, 1)); + addShapelessRecipe("life_full_2", "questing", new ItemStack(BetterQuesting.extraLife, 1, 0), + new ItemStack(BetterQuesting.extraLife, 1, 1), new ItemStack(BetterQuesting.extraLife, 1, 1)); + + addShapelessRecipe("life_half_0", "questing", new ItemStack(BetterQuesting.extraLife, 2, 1), + new ItemStack(BetterQuesting.extraLife, 1, 0)); + addShapelessRecipe("life_half_1", "questing", new ItemStack(BetterQuesting.extraLife, 1, 1), + new ItemStack(BetterQuesting.extraLife, 1, 2), new ItemStack(BetterQuesting.extraLife, 1, 2)); + + addShapelessRecipe("life_quarter_0", "questing", new ItemStack(BetterQuesting.extraLife, 2, 2), + new ItemStack(BetterQuesting.extraLife, 1, 1)); + + setupRecipes = true; + } + + // SETUP ALL THE THINGS + static { + registerItem(ItemPlaceholder.placeholder, "placeholder"); + registerItem(BetterQuesting.extraLife, "extra_life"); + registerItem(BetterQuesting.guideBook, "guide_book"); + + registerBlock(BetterQuesting.submitStation, "submit_station"); + } } diff --git a/src/main/java/betterquesting/core/proxies/ClientProxy.java b/src/main/java/betterquesting/core/proxies/ClientProxy.java index 495f7d717..b00290b62 100644 --- a/src/main/java/betterquesting/core/proxies/ClientProxy.java +++ b/src/main/java/betterquesting/core/proxies/ClientProxy.java @@ -29,106 +29,97 @@ import java.util.ArrayList; -public class ClientProxy extends CommonProxy -{ - @Override - public boolean isClient() - { - return true; - } - - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public void registerHandlers() - { - super.registerHandlers(); - - if(!Minecraft.getMinecraft().getFramebuffer().isStencilEnabled()) - { - if(!Minecraft.getMinecraft().getFramebuffer().enableStencil()) - { - BetterQuesting.logger.error("[!] FAILED TO ENABLE STENCIL BUFFER. GUIS WILL BREAK! [!]"); - } - } - - MinecraftForge.EVENT_BUS.register(PEventBroadcaster.INSTANCE); - - ExpansionLoader.INSTANCE.initClientAPIs(); - - MinecraftForge.EVENT_BUS.register(new QuestNotification()); - BQ_Keybindings.RegisterKeys(); - - try - { - //String tmp = "defaultResourcePacks"; - ArrayList list = ObfuscationReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "field_110449_ao", "defaultResourcePacks"); - QuestResourcesFolder qRes1 = new QuestResourcesFolder(); - QuestResourcesFile qRes2 = new QuestResourcesFile(); - list.add(qRes1); - list.add(qRes2); - ((SimpleReloadableResourceManager)Minecraft.getMinecraft().getResourceManager()).reloadResourcePack(qRes1); // Make sure the pack(s) are visible to everything - ((SimpleReloadableResourceManager)Minecraft.getMinecraft().getResourceManager()).reloadResourcePack(qRes2); // Make sure the pack(s) are visible to everything - } catch(Exception e) - { - BetterQuesting.logger.error("Unable to install questing resource loaders", e); - } - - RenderingRegistry.registerEntityRenderingHandler(EntityPlaceholder.class, new PlaceholderRenderFactory()); - - ToolboxRegistry.INSTANCE.registerToolTab(new ResourceLocation(BetterQuesting.MODID, "main"), ToolboxTabMain.INSTANCE); - } - - @Override - public void registerRenderers() - { - super.registerRenderers(); - - registerBlockModel(BetterQuesting.submitStation); - registerItemModel(ItemPlaceholder.placeholder); - registerItemModel(BetterQuesting.extraLife, 0, BetterQuesting.MODID + ":heart_full"); - registerItemModel(BetterQuesting.extraLife, 1, BetterQuesting.MODID + ":heart_half"); - registerItemModel(BetterQuesting.extraLife, 2, BetterQuesting.MODID + ":heart_quarter"); - registerItemModel(BetterQuesting.guideBook); - - ThemeRegistry.INSTANCE.loadResourceThemes(); - } - - @SideOnly(Side.CLIENT) - public static void registerBlockModel(Block block) - { - registerBlockModel(block, 0, block.getRegistryName().toString()); - } - - @SideOnly(Side.CLIENT) - public static void registerBlockModel(Block block, int meta, String name) - { - Item item = Item.getItemFromBlock(block); - ModelResourceLocation model = new ModelResourceLocation(name, "inventory"); - - if(!name.equals(item.getRegistryName().toString())) - { - ModelBakery.registerItemVariants(item, model); - } - - ModelLoader.setCustomModelResourceLocation(item, meta, model); - } - - @SideOnly(Side.CLIENT) - public static void registerItemModel(Item item) - { - registerItemModel(item, 0, item.getRegistryName().toString()); - } - - @SideOnly(Side.CLIENT) - public static void registerItemModel(Item item, int meta, String name) - { - ModelResourceLocation model = new ModelResourceLocation(name, "inventory"); - - if(!name.equals(item.getRegistryName().toString())) - { - ModelBakery.registerItemVariants(item, model); - } - - ModelLoader.setCustomModelResourceLocation(item, meta, model); - } +public class ClientProxy extends CommonProxy { + @Override + public boolean isClient() { + return true; + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void registerHandlers() { + super.registerHandlers(); + + if (!Minecraft.getMinecraft().getFramebuffer().isStencilEnabled()) { + if (!Minecraft.getMinecraft().getFramebuffer().enableStencil()) { + BetterQuesting.logger.error("[!] FAILED TO ENABLE STENCIL BUFFER. GUIS WILL BREAK! [!]"); + } + } + + MinecraftForge.EVENT_BUS.register(PEventBroadcaster.INSTANCE); + + ExpansionLoader.INSTANCE.initClientAPIs(); + + MinecraftForge.EVENT_BUS.register(new QuestNotification()); + BQ_Keybindings.RegisterKeys(); + + try { + //String tmp = "defaultResourcePacks"; + ArrayList list = + ObfuscationReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "field_110449_ao", + "defaultResourcePacks"); + QuestResourcesFolder qRes1 = new QuestResourcesFolder(); + QuestResourcesFile qRes2 = new QuestResourcesFile(); + list.add(qRes1); + list.add(qRes2); + ((SimpleReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).reloadResourcePack( + qRes1); // Make sure the pack(s) are visible to everything + ((SimpleReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).reloadResourcePack( + qRes2); // Make sure the pack(s) are visible to everything + } catch (Exception e) { + BetterQuesting.logger.error("Unable to install questing resource loaders", e); + } + + RenderingRegistry.registerEntityRenderingHandler(EntityPlaceholder.class, new PlaceholderRenderFactory()); + + ToolboxRegistry.INSTANCE.registerToolTab(new ResourceLocation(BetterQuesting.MODID, "main"), + ToolboxTabMain.INSTANCE); + } + + @Override + public void registerRenderers() { + super.registerRenderers(); + + registerBlockModel(BetterQuesting.submitStation); + registerItemModel(ItemPlaceholder.placeholder); + registerItemModel(BetterQuesting.extraLife, 0, BetterQuesting.MODID + ":heart_full"); + registerItemModel(BetterQuesting.extraLife, 1, BetterQuesting.MODID + ":heart_half"); + registerItemModel(BetterQuesting.extraLife, 2, BetterQuesting.MODID + ":heart_quarter"); + registerItemModel(BetterQuesting.guideBook); + + ThemeRegistry.INSTANCE.loadResourceThemes(); + } + + @SideOnly(Side.CLIENT) + public static void registerBlockModel(Block block) { + registerBlockModel(block, 0, block.getRegistryName().toString()); + } + + @SideOnly(Side.CLIENT) + public static void registerBlockModel(Block block, int meta, String name) { + Item item = Item.getItemFromBlock(block); + ModelResourceLocation model = new ModelResourceLocation(name, "inventory"); + + if (!name.equals(item.getRegistryName().toString())) { + ModelBakery.registerItemVariants(item, model); + } + + ModelLoader.setCustomModelResourceLocation(item, meta, model); + } + + @SideOnly(Side.CLIENT) + public static void registerItemModel(Item item) { + registerItemModel(item, 0, item.getRegistryName().toString()); + } + + @SideOnly(Side.CLIENT) + public static void registerItemModel(Item item, int meta, String name) { + ModelResourceLocation model = new ModelResourceLocation(name, "inventory"); + + if (!name.equals(item.getRegistryName().toString())) { + ModelBakery.registerItemVariants(item, model); + } + + ModelLoader.setCustomModelResourceLocation(item, meta, model); + } } diff --git a/src/main/java/betterquesting/core/proxies/CommonProxy.java b/src/main/java/betterquesting/core/proxies/CommonProxy.java index abe2978f0..9382729b7 100644 --- a/src/main/java/betterquesting/core/proxies/CommonProxy.java +++ b/src/main/java/betterquesting/core/proxies/CommonProxy.java @@ -7,25 +7,21 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkRegistry; -public class CommonProxy -{ - public boolean isClient() - { - return false; - } - - public void registerHandlers() - { - ExpansionLoader.INSTANCE.initCommonAPIs(); - - //EventHandler handler = new EventHandler(); - MinecraftForge.EVENT_BUS.register(EventHandler.INSTANCE); - MinecraftForge.TERRAIN_GEN_BUS.register(EventHandler.INSTANCE); - - NetworkRegistry.INSTANCE.registerGuiHandler(BetterQuesting.instance, new GuiHandler()); - } - - public void registerRenderers() - { - } +public class CommonProxy { + public boolean isClient() { + return false; + } + + public void registerHandlers() { + ExpansionLoader.INSTANCE.initCommonAPIs(); + + //EventHandler handler = new EventHandler(); + MinecraftForge.EVENT_BUS.register(EventHandler.INSTANCE); + MinecraftForge.TERRAIN_GEN_BUS.register(EventHandler.INSTANCE); + + NetworkRegistry.INSTANCE.registerGuiHandler(BetterQuesting.instance, new GuiHandler()); + } + + public void registerRenderers() { + } } diff --git a/src/main/java/betterquesting/handlers/ConfigGuiFactory.java b/src/main/java/betterquesting/handlers/ConfigGuiFactory.java index 7cfe6bbf0..838c9d407 100644 --- a/src/main/java/betterquesting/handlers/ConfigGuiFactory.java +++ b/src/main/java/betterquesting/handlers/ConfigGuiFactory.java @@ -1,33 +1,28 @@ package betterquesting.handlers; -import java.util.Set; +import betterquesting.client.gui.GuiBQConfig; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.client.IModGuiFactory; -import betterquesting.client.gui.GuiBQConfig; -public class ConfigGuiFactory implements IModGuiFactory -{ - @Override - public void initialize(Minecraft minecraftInstance) - { - } +import java.util.Set; + +public class ConfigGuiFactory implements IModGuiFactory { + @Override + public void initialize(Minecraft minecraftInstance) { } - @Override - public Set runtimeGuiCategories() - { - return null; - } + @Override + public Set runtimeGuiCategories() { + return null; + } - @Override - public boolean hasConfigGui() - { - return true; - } + @Override + public boolean hasConfigGui() { + return true; + } - @Override - public GuiScreen createConfigGui(GuiScreen parentScreen) - { - return new GuiBQConfig(parentScreen); - } + @Override + public GuiScreen createConfigGui(GuiScreen parentScreen) { + return new GuiBQConfig(parentScreen); + } } diff --git a/src/main/java/betterquesting/handlers/ConfigHandler.java b/src/main/java/betterquesting/handlers/ConfigHandler.java index 9e51e8e8a..24dcdd254 100644 --- a/src/main/java/betterquesting/handlers/ConfigHandler.java +++ b/src/main/java/betterquesting/handlers/ConfigHandler.java @@ -5,26 +5,28 @@ import net.minecraftforge.common.config.Configuration; import org.apache.logging.log4j.Level; -public class ConfigHandler -{ - public static Configuration config; - - public static void initConfigs() - { - if(config == null) - { - BetterQuesting.logger.log(Level.ERROR, "Config attempted to be loaded before it was initialised!"); - return; - } - - config.load(); - - BQ_Settings.questNotices = config.getBoolean("Quest Notices", Configuration.CATEGORY_GENERAL, true, "Enabled the popup notices when quests are completed or updated"); - BQ_Settings.curTheme = config.getString("Theme", Configuration.CATEGORY_GENERAL, "betterquesting:light", "The current questing theme"); - BQ_Settings.useBookmark = config.getBoolean("Use Quest Bookmark", Configuration.CATEGORY_GENERAL, true, "Jumps the user to the last opened quest"); - BQ_Settings.guiWidth = config.getInt("Max GUI Width", Configuration.CATEGORY_GENERAL, -1, -1, Integer.MAX_VALUE, "Clamps the max UI width (-1 to disable)"); - BQ_Settings.guiHeight = config.getInt("Max GUI Height", Configuration.CATEGORY_GENERAL, -1, -1, Integer.MAX_VALUE, "Clamps the max UI height (-1 to disable)"); - - config.save(); - } +public class ConfigHandler { + public static Configuration config; + + public static void initConfigs() { + if (config == null) { + BetterQuesting.logger.log(Level.ERROR, "Config attempted to be loaded before it was initialised!"); + return; + } + + config.load(); + + BQ_Settings.questNotices = config.getBoolean("Quest Notices", Configuration.CATEGORY_GENERAL, true, + "Enabled the popup notices when quests are completed or updated"); + BQ_Settings.curTheme = + config.getString("Theme", Configuration.CATEGORY_GENERAL, "betterquesting:light", "The current questing theme"); + BQ_Settings.useBookmark = config.getBoolean("Use Quest Bookmark", Configuration.CATEGORY_GENERAL, true, + "Jumps the user to the last opened quest"); + BQ_Settings.guiWidth = config.getInt("Max GUI Width", Configuration.CATEGORY_GENERAL, -1, -1, Integer.MAX_VALUE, + "Clamps the max UI width (-1 to disable)"); + BQ_Settings.guiHeight = config.getInt("Max GUI Height", Configuration.CATEGORY_GENERAL, -1, -1, Integer.MAX_VALUE, + "Clamps the max UI height (-1 to disable)"); + + config.save(); + } } diff --git a/src/main/java/betterquesting/handlers/EventHandler.java b/src/main/java/betterquesting/handlers/EventHandler.java index 68c70dbe7..353bfdcf2 100644 --- a/src/main/java/betterquesting/handlers/EventHandler.java +++ b/src/main/java/betterquesting/handlers/EventHandler.java @@ -67,327 +67,301 @@ /** * Event handling for standard quests and core BetterQuesting functionality */ -public class EventHandler -{ - public static final EventHandler INSTANCE = new EventHandler(); - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void onKey(InputEvent.KeyInputEvent event) - { - Minecraft mc = Minecraft.getMinecraft(); - - if(mc.currentScreen == null && BQ_Keybindings.openQuests.isPressed()) - { - if(mc.player.isSneaking() && mc.player.getName().equalsIgnoreCase("Funwayguy")) - { - mc.displayGuiScreen(new GuiScreenTest(mc.currentScreen)); - } else - { - if(BQ_Settings.useBookmark && GuiHome.bookmark != null) - { - mc.displayGuiScreen(GuiHome.bookmark); - } else - { - mc.displayGuiScreen(ThemeRegistry.INSTANCE.getGui(PresetGUIs.HOME, GArgsNone.NONE)); - } - } - } - } - - @SubscribeEvent - public void onCapabilityPlayer(AttachCapabilitiesEvent event) - { - if(!(event.getObject() instanceof EntityPlayer)) return; - event.addCapability(CapabilityProviderQuestCache.LOC_QUEST_CACHE, new CapabilityProviderQuestCache()); +public class EventHandler { + public static final EventHandler INSTANCE = new EventHandler(); + + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void onKey(InputEvent.KeyInputEvent event) { + Minecraft mc = Minecraft.getMinecraft(); + + if (mc.currentScreen == null && BQ_Keybindings.openQuests.isPressed()) { + if (mc.player.isSneaking() && mc.player.getName().equalsIgnoreCase("Funwayguy")) { + mc.displayGuiScreen(new GuiScreenTest(mc.currentScreen)); + } else { + if (BQ_Settings.useBookmark && GuiHome.bookmark != null) { + mc.displayGuiScreen(GuiHome.bookmark); + } else { + mc.displayGuiScreen(ThemeRegistry.INSTANCE.getGui(PresetGUIs.HOME, GArgsNone.NONE)); + } + } } - - @SubscribeEvent - public void onPlayerClone(Clone event) - { - betterquesting.api2.cache.QuestCache oCache = event.getOriginal().getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - betterquesting.api2.cache.QuestCache nCache = event.getEntityPlayer().getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - - if(oCache != null && nCache != null) nCache.deserializeNBT(oCache.serializeNBT()); + } + + @SubscribeEvent + public void onCapabilityPlayer(AttachCapabilitiesEvent event) { + if (!(event.getObject() instanceof EntityPlayer)) { return; } + event.addCapability(CapabilityProviderQuestCache.LOC_QUEST_CACHE, new CapabilityProviderQuestCache()); + } + + @SubscribeEvent + public void onPlayerClone(Clone event) { + betterquesting.api2.cache.QuestCache oCache = + event.getOriginal().getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + betterquesting.api2.cache.QuestCache nCache = + event.getEntityPlayer().getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + + if (oCache != null && nCache != null) { nCache.deserializeNBT(oCache.serializeNBT()); } + } + + @SubscribeEvent + public void onLivingUpdate(LivingUpdateEvent event) { + if (event.getEntityLiving().world.isRemote) { return; } + if (!(event.getEntityLiving() instanceof EntityPlayerMP)) { return; } + if (event.getEntityLiving().ticksExisted % 20 != 0) { + return; // Only triggers once per second } - - @SubscribeEvent - public void onLivingUpdate(LivingUpdateEvent event) - { - if(event.getEntityLiving().world.isRemote) return; - if(!(event.getEntityLiving() instanceof EntityPlayerMP)) return; - if(event.getEntityLiving().ticksExisted%20 != 0) return; // Only triggers once per second - - EntityPlayerMP player = (EntityPlayerMP)event.getEntityLiving(); - betterquesting.api2.cache.QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); - - if(qc == null) return; - - List> activeQuests = QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests()); - List> pendingAutoClaims = QuestDatabase.INSTANCE.bulkLookup(qc.getPendingAutoClaims()); - QResetTime[] pendingResets = qc.getScheduledResets(); - - UUID uuid = QuestingAPI.getQuestingUUID(player); - boolean refreshCache = false; - - if(!editMode && player.ticksExisted%60 == 0) // Passive quest state check every 3 seconds - { - List com = new ArrayList<>(); - - for(DBEntry quest : activeQuests) - { - if(!quest.getValue().isUnlocked(uuid)) continue; // Although it IS active, it cannot be completed yet - - if(quest.getValue().canSubmit(player)) quest.getValue().update(player); - - if(quest.getValue().isComplete(uuid) && !quest.getValue().canSubmit(player)) - { - refreshCache = true; - qc.markQuestDirty(quest.getID()); - - com.add(quest.getID()); - if(!quest.getValue().getProperty(NativeProps.SILENT)) postPresetNotice(quest.getValue(), player, 2); - } - } - - MinecraftForge.EVENT_BUS.post(new QuestEvent(Type.COMPLETED, uuid, com)); - } - - if(!editMode && player.getServer() != null) // Repeatable quest resets - { - List res = new ArrayList<>(); - long totalTime = System.currentTimeMillis(); - - for(QResetTime rTime : pendingResets) - { - IQuest entry = QuestDatabase.INSTANCE.getValue(rTime.questID); - - if(totalTime >= rTime.time && !entry.canSubmit(player)) // REEEEEEEEEset - { - if(entry.getProperty(NativeProps.GLOBAL)) - { - entry.resetUser(null, false); - } else - { - entry.resetUser(uuid, false); - } - - refreshCache = true; - qc.markQuestDirty(rTime.questID); - res.add(rTime.questID); - if(!entry.getProperty(NativeProps.SILENT)) postPresetNotice(entry, player, 1); - } else break; // Entries are sorted by time so we fail fast and skip checking the others - } - - MinecraftForge.EVENT_BUS.post(new QuestEvent(Type.RESET, uuid, res)); + + EntityPlayerMP player = (EntityPlayerMP) event.getEntityLiving(); + betterquesting.api2.cache.QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); + + if (qc == null) { return; } + + List> activeQuests = QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests()); + List> pendingAutoClaims = QuestDatabase.INSTANCE.bulkLookup(qc.getPendingAutoClaims()); + QResetTime[] pendingResets = qc.getScheduledResets(); + + UUID uuid = QuestingAPI.getQuestingUUID(player); + boolean refreshCache = false; + + if (!editMode && player.ticksExisted % 60 == 0) // Passive quest state check every 3 seconds + { + List com = new ArrayList<>(); + + for (DBEntry quest : activeQuests) { + if (!quest.getValue().isUnlocked(uuid)) { + continue; // Although it IS active, it cannot be completed yet } - - if(!editMode) - { - for(DBEntry entry : pendingAutoClaims) // Auto claims - { - if(entry.getValue().canClaim(player)) - { - entry.getValue().claimReward(player); - refreshCache = true; - qc.markQuestDirty(entry.getID()); - // Not going to notify of auto-claims anymore. Kinda pointless if they're already being pinged for completion - } - } + + if (quest.getValue().canSubmit(player)) { quest.getValue().update(player); } + + if (quest.getValue().isComplete(uuid) && !quest.getValue().canSubmit(player)) { + refreshCache = true; + qc.markQuestDirty(quest.getID()); + + com.add(quest.getID()); + if (!quest.getValue().getProperty(NativeProps.SILENT)) { postPresetNotice(quest.getValue(), player, 2); } } - - if(refreshCache || player.ticksExisted % 200 == 0) // Refresh the cache if something changed or every 10 seconds + } + + MinecraftForge.EVENT_BUS.post(new QuestEvent(Type.COMPLETED, uuid, com)); + } + + if (!editMode && player.getServer() != null) // Repeatable quest resets + { + List res = new ArrayList<>(); + long totalTime = System.currentTimeMillis(); + + for (QResetTime rTime : pendingResets) { + IQuest entry = QuestDatabase.INSTANCE.getValue(rTime.questID); + + if (totalTime >= rTime.time && !entry.canSubmit(player)) // REEEEEEEEEset { - qc.updateCache(player); + if (entry.getProperty(NativeProps.GLOBAL)) { + entry.resetUser(null, false); + } else { + entry.resetUser(uuid, false); + } + + refreshCache = true; + qc.markQuestDirty(rTime.questID); + res.add(rTime.questID); + if (!entry.getProperty(NativeProps.SILENT)) { postPresetNotice(entry, player, 1); } + } else { + break; // Entries are sorted by time so we fail fast and skip checking the others } - - if(qc.getDirtyQuests().length > 0) NetQuestSync.sendSync(player, qc.getDirtyQuests(), false, true); - qc.cleanAllQuests(); - } - - // TODO: Create a new message inbox system for these things. On screen popups aren't ideal in combat - private static void postPresetNotice(IQuest quest, EntityPlayer player, int preset) - { - if(!(player instanceof EntityPlayerMP)) return; - ItemStack icon = quest.getProperty(NativeProps.ICON).getBaseStack(); - String mainText = ""; - String subText = quest.getProperty(NativeProps.NAME); - String sound = ""; - - switch(preset) - { - case 0: - { - mainText = "betterquesting.notice.unlock"; - sound = quest.getProperty(NativeProps.SOUND_UNLOCK); - break; - } - case 1: - { - mainText = "betterquesting.notice.update"; - sound = quest.getProperty(NativeProps.SOUND_UPDATE); - break; - } - case 2: - { - mainText = "betterquesting.notice.complete"; - sound = quest.getProperty(NativeProps.SOUND_COMPLETE); - break; - } - } - - NetNotices.sendNotice(quest.getProperty(NativeProps.GLOBAL) ? null : new EntityPlayerMP[]{(EntityPlayerMP)player}, icon, mainText, subText, sound); - } - - @SubscribeEvent - public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) - { - if(event.getModID().equals(BetterQuesting.MODID)) - { - ConfigHandler.config.save(); - ConfigHandler.initConfigs(); - } - } - - @SubscribeEvent - public void onWorldSave(WorldEvent.Save event) - { - if(!event.getWorld().isRemote && BQ_Settings.curWorldDir != null && event.getWorld().provider.getDimension() == 0) - { - SaveLoadHandler.INSTANCE.saveDatabases(); - } - } - - @SubscribeEvent - public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) - { - if(event.player.world.isRemote || event.player.getServer() == null || !(event.player instanceof EntityPlayerMP)) return; - - EntityPlayerMP mpPlayer = (EntityPlayerMP)event.player; - - if(BetterQuesting.proxy.isClient() && !mpPlayer.getServer().isDedicatedServer() && event.player.getServer().getServerOwner().equals(mpPlayer.getGameProfile().getName())) - { - NameCache.INSTANCE.updateName(mpPlayer); - return; + } + + MinecraftForge.EVENT_BUS.post(new QuestEvent(Type.RESET, uuid, res)); + } + + if (!editMode) { + for (DBEntry entry : pendingAutoClaims) // Auto claims + { + if (entry.getValue().canClaim(player)) { + entry.getValue().claimReward(player); + refreshCache = true; + qc.markQuestDirty(entry.getID()); + // Not going to notify of auto-claims anymore. Kinda pointless if they're already being pinged for completion } - - NetBulkSync.sendReset(mpPlayer, true, true); - } - - @SubscribeEvent - public void onPlayerRespawn(PlayerRespawnEvent event) - { - if(QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE) && event.player instanceof EntityPlayerMP && !((EntityPlayerMP)event.player).queuedEndExit) - { - EntityPlayerMP mpPlayer = (EntityPlayerMP)event.player; - - int lives = LifeDatabase.INSTANCE.getLives(QuestingAPI.getQuestingUUID(mpPlayer)); - - if(lives <= 0) - { - MinecraftServer server = mpPlayer.getServer(); - if(server == null) return; - - mpPlayer.setGameType(GameType.SPECTATOR); - if(!server.isDedicatedServer()) mpPlayer.getServerWorld().getGameRules().setOrCreateGameRule("spectatorsGenerateChunks", "false"); - } else - { - if(lives == 1) - { - mpPlayer.sendStatusMessage(new TextComponentString("This is your last life!"), true); - } else - { - mpPlayer.sendStatusMessage(new TextComponentString(lives + " lives remaining!"), true); - } - } - } - } - - @SubscribeEvent - public void onLivingDeath(LivingDeathEvent event) - { - if(event.getEntityLiving().world.isRemote || !QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE)) - { - return; - } - - if(event.getEntityLiving() instanceof EntityPlayer) - { - UUID uuid = QuestingAPI.getQuestingUUID(((EntityPlayer)event.getEntityLiving())); - - int lives = LifeDatabase.INSTANCE.getLives(uuid); - LifeDatabase.INSTANCE.setLives(uuid, lives - 1); - } - } - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void onTextureStitch(TextureStitchEvent.Pre event) - { - if(event.getMap() == Minecraft.getMinecraft().getTextureMapBlocks()) - { - event.getMap().registerSprite(FluidPlaceholder.fluidPlaceholder.getStill()); - } - } - - @SubscribeEvent - @SideOnly(Side.CLIENT) - public void onDataUpdated(DatabaseEvent.Update event) - { - // TODO: Change this to a proper panel event. Also explain WHAT updated - final GuiScreen screen = Minecraft.getMinecraft().currentScreen; - if(screen instanceof INeedsRefresh) Minecraft.getMinecraft().addScheduledTask(((INeedsRefresh)screen)::refreshGui); - } - - @SubscribeEvent - public void onCommand(CommandEvent event) - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - - if(server != null && (event.getCommand().getName().equalsIgnoreCase("op") || event.getCommand().getName().equalsIgnoreCase("deop"))) - { - EntityPlayerMP playerMP = server.getPlayerList().getPlayerByUsername(event.getParameters()[0]); - if(playerMP != null) opQueue.add(playerMP); // Has to be delayed until after the event when the command has executed - } - } - - private final ArrayDeque opQueue = new ArrayDeque<>(); - private boolean openToLAN = false; - - @SubscribeEvent - public void onServerTick(ServerTickEvent event) + } + } + + if (refreshCache || player.ticksExisted % 200 == 0) // Refresh the cache if something changed or every 10 seconds { - if(event.phase != Phase.END) return; - - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - - if(!server.isDedicatedServer()) - { - boolean tmp = openToLAN; - openToLAN = server instanceof IntegratedServer && ((IntegratedServer)server).getPublic(); - if(openToLAN && !tmp) opQueue.addAll(server.getPlayerList().getPlayers()); - } else if(!openToLAN) - { - openToLAN = true; + qc.updateCache(player); + } + + if (qc.getDirtyQuests().length > 0) { NetQuestSync.sendSync(player, qc.getDirtyQuests(), false, true); } + qc.cleanAllQuests(); + } + + // TODO: Create a new message inbox system for these things. On screen popups aren't ideal in combat + private static void postPresetNotice(IQuest quest, EntityPlayer player, int preset) { + if (!(player instanceof EntityPlayerMP)) { return; } + ItemStack icon = quest.getProperty(NativeProps.ICON).getBaseStack(); + String mainText = ""; + String subText = quest.getProperty(NativeProps.NAME); + String sound = ""; + + switch (preset) { + case 0: { + mainText = "betterquesting.notice.unlock"; + sound = quest.getProperty(NativeProps.SOUND_UNLOCK); + break; + } + case 1: { + mainText = "betterquesting.notice.update"; + sound = quest.getProperty(NativeProps.SOUND_UPDATE); + break; + } + case 2: { + mainText = "betterquesting.notice.complete"; + sound = quest.getProperty(NativeProps.SOUND_COMPLETE); + break; + } + } + + NetNotices.sendNotice( + quest.getProperty(NativeProps.GLOBAL) ? null : new EntityPlayerMP[] { (EntityPlayerMP) player }, icon, mainText, + subText, sound); + } + + @SubscribeEvent + public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { + if (event.getModID().equals(BetterQuesting.MODID)) { + ConfigHandler.config.save(); + ConfigHandler.initConfigs(); + } + } + + @SubscribeEvent + public void onWorldSave(WorldEvent.Save event) { + if (!event.getWorld().isRemote && BQ_Settings.curWorldDir != null && + event.getWorld().provider.getDimension() == 0) { + SaveLoadHandler.INSTANCE.saveDatabases(); + } + } + + @SubscribeEvent + public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) { + if (event.player.world.isRemote || event.player.getServer() == null || !(event.player instanceof EntityPlayerMP)) { + return; + } + + EntityPlayerMP mpPlayer = (EntityPlayerMP) event.player; + + if (BetterQuesting.proxy.isClient() && !mpPlayer.getServer().isDedicatedServer() && + event.player.getServer().getServerOwner().equals(mpPlayer.getGameProfile().getName())) { + NameCache.INSTANCE.updateName(mpPlayer); + return; + } + + NetBulkSync.sendReset(mpPlayer, true, true); + } + + @SubscribeEvent + public void onPlayerRespawn(PlayerRespawnEvent event) { + if (QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE) && event.player instanceof EntityPlayerMP && + !((EntityPlayerMP) event.player).queuedEndExit) { + EntityPlayerMP mpPlayer = (EntityPlayerMP) event.player; + + int lives = LifeDatabase.INSTANCE.getLives(QuestingAPI.getQuestingUUID(mpPlayer)); + + if (lives <= 0) { + MinecraftServer server = mpPlayer.getServer(); + if (server == null) { return; } + + mpPlayer.setGameType(GameType.SPECTATOR); + if (!server.isDedicatedServer()) { + mpPlayer.getServerWorld().getGameRules().setOrCreateGameRule("spectatorsGenerateChunks", "false"); } - - while(!opQueue.isEmpty()) - { - EntityPlayerMP playerMP = opQueue.poll(); - if(playerMP != null && NameCache.INSTANCE.updateName(playerMP)) - { - DBEntry party = PartyManager.INSTANCE.getParty(QuestingAPI.getQuestingUUID(playerMP)); - if(party != null) - { - NetNameSync.quickSync(null, party.getID()); - } else - { - NetNameSync.sendNames(new EntityPlayerMP[]{playerMP}, new UUID[]{QuestingAPI.getQuestingUUID(playerMP)}, null); - } - } + } else { + if (lives == 1) { + mpPlayer.sendStatusMessage(new TextComponentString("This is your last life!"), true); + } else { + mpPlayer.sendStatusMessage(new TextComponentString(lives + " lives remaining!"), true); + } + } + } + } + + @SubscribeEvent + public void onLivingDeath(LivingDeathEvent event) { + if (event.getEntityLiving().world.isRemote || !QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE)) { + return; + } + + if (event.getEntityLiving() instanceof EntityPlayer) { + UUID uuid = QuestingAPI.getQuestingUUID(((EntityPlayer) event.getEntityLiving())); + + int lives = LifeDatabase.INSTANCE.getLives(uuid); + LifeDatabase.INSTANCE.setLives(uuid, lives - 1); + } + } + + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void onTextureStitch(TextureStitchEvent.Pre event) { + if (event.getMap() == Minecraft.getMinecraft().getTextureMapBlocks()) { + event.getMap().registerSprite(FluidPlaceholder.fluidPlaceholder.getStill()); + } + } + + @SubscribeEvent + @SideOnly(Side.CLIENT) + public void onDataUpdated(DatabaseEvent.Update event) { + // TODO: Change this to a proper panel event. Also explain WHAT updated + final GuiScreen screen = Minecraft.getMinecraft().currentScreen; + if (screen instanceof INeedsRefresh) { + Minecraft.getMinecraft().addScheduledTask(((INeedsRefresh) screen)::refreshGui); + } + } + + @SubscribeEvent + public void onCommand(CommandEvent event) { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + + if (server != null && (event.getCommand().getName().equalsIgnoreCase("op") || + event.getCommand().getName().equalsIgnoreCase("deop"))) { + EntityPlayerMP playerMP = server.getPlayerList().getPlayerByUsername(event.getParameters()[0]); + if (playerMP != null) { + opQueue.add(playerMP); // Has to be delayed until after the event when the command has executed + } + } + } + + private final ArrayDeque opQueue = new ArrayDeque<>(); + private boolean openToLAN = false; + + @SubscribeEvent + public void onServerTick(ServerTickEvent event) { + if (event.phase != Phase.END) { return; } + + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + + if (!server.isDedicatedServer()) { + boolean tmp = openToLAN; + openToLAN = server instanceof IntegratedServer && ((IntegratedServer) server).getPublic(); + if (openToLAN && !tmp) { opQueue.addAll(server.getPlayerList().getPlayers()); } + } else if (!openToLAN) { + openToLAN = true; + } + + while (!opQueue.isEmpty()) { + EntityPlayerMP playerMP = opQueue.poll(); + if (playerMP != null && NameCache.INSTANCE.updateName(playerMP)) { + DBEntry party = PartyManager.INSTANCE.getParty(QuestingAPI.getQuestingUUID(playerMP)); + if (party != null) { + NetNameSync.quickSync(null, party.getID()); + } else { + NetNameSync.sendNames(new EntityPlayerMP[] { playerMP }, new UUID[] { QuestingAPI.getQuestingUUID(playerMP) }, + null); } - - if(server.getTickCounter() % 60 == 0) PartyInvitations.INSTANCE.cleanExpired(); + } } + + if (server.getTickCounter() % 60 == 0) { PartyInvitations.INSTANCE.cleanExpired(); } + } } diff --git a/src/main/java/betterquesting/handlers/GuiHandler.java b/src/main/java/betterquesting/handlers/GuiHandler.java index 858f543d3..8f62e73d9 100644 --- a/src/main/java/betterquesting/handlers/GuiHandler.java +++ b/src/main/java/betterquesting/handlers/GuiHandler.java @@ -1,8 +1,8 @@ package betterquesting.handlers; import betterquesting.blocks.TileSubmitStation; -import betterquesting.client.gui2.inventory.ContainerSubmitStation; import betterquesting.client.gui2.GuiQuestHelp; +import betterquesting.client.gui2.inventory.ContainerSubmitStation; import betterquesting.client.gui2.inventory.GuiSubmitStation; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; @@ -10,35 +10,29 @@ import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; -public class GuiHandler implements IGuiHandler -{ - @Override - public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) - { - TileEntity tile = world.getTileEntity(new BlockPos(x, y, z)); - - if(ID == 0 && tile instanceof TileSubmitStation) - { - return new ContainerSubmitStation(player.inventory, (TileSubmitStation)tile); - } - - return null; - } - - @Override - public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) - { - TileEntity tile = world.getTileEntity(new BlockPos(x, y, z)); - - if(ID == 0 && tile instanceof TileSubmitStation) - { - return new GuiSubmitStation(null, player.inventory, (TileSubmitStation)tile); - } else if(ID == 1) - { - return new GuiQuestHelp(null); - } - - return null; - } - +public class GuiHandler implements IGuiHandler { + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity tile = world.getTileEntity(new BlockPos(x, y, z)); + + if (ID == 0 && tile instanceof TileSubmitStation) { + return new ContainerSubmitStation(player.inventory, (TileSubmitStation) tile); + } + + return null; + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity tile = world.getTileEntity(new BlockPos(x, y, z)); + + if (ID == 0 && tile instanceof TileSubmitStation) { + return new GuiSubmitStation(null, player.inventory, (TileSubmitStation) tile); + } else if (ID == 1) { + return new GuiQuestHelp(null); + } + + return null; + } + } diff --git a/src/main/java/betterquesting/handlers/SaveLoadHandler.java b/src/main/java/betterquesting/handlers/SaveLoadHandler.java index 4326a80fc..656cacb53 100644 --- a/src/main/java/betterquesting/handlers/SaveLoadHandler.java +++ b/src/main/java/betterquesting/handlers/SaveLoadHandler.java @@ -28,261 +28,258 @@ import java.io.File; -public class SaveLoadHandler -{ - public static SaveLoadHandler INSTANCE = new SaveLoadHandler(); - - private boolean hasUpdate = false; - private boolean isDirty = false; - - public boolean hasUpdate() - { - return this.hasUpdate; - } - - public void resetUpdate() - { - this.hasUpdate = false; - } - - public void markDirty() - { - this.isDirty = true; +public class SaveLoadHandler { + public static final SaveLoadHandler INSTANCE = new SaveLoadHandler(); + + private boolean hasUpdate = false; + private boolean isDirty = false; + + public boolean hasUpdate() { + return this.hasUpdate; + } + + public void resetUpdate() { + this.hasUpdate = false; + } + + public void markDirty() { + this.isDirty = true; + } + + public void loadDatabases(MinecraftServer server) { + QuestSettings.INSTANCE.reset(); + QuestDatabase.INSTANCE.reset(); + QuestLineDatabase.INSTANCE.reset(); + LifeDatabase.INSTANCE.reset(); + NameCache.INSTANCE.reset(); + + hasUpdate = false; + + if (BetterQuesting.proxy.isClient()) { + GuiHome.bookmark = null; + QuestNotification.resetNotices(); } - - public void loadDatabases(MinecraftServer server) - { - QuestSettings.INSTANCE.reset(); - QuestDatabase.INSTANCE.reset(); - QuestLineDatabase.INSTANCE.reset(); - LifeDatabase.INSTANCE.reset(); - NameCache.INSTANCE.reset(); - - hasUpdate = false; - - if(BetterQuesting.proxy.isClient()) - { - GuiHome.bookmark = null; - QuestNotification.resetNotices(); - } - - File rootDir; - - if(BetterQuesting.proxy.isClient()) - { - BQ_Settings.curWorldDir = server.getFile("saves/" + server.getFolderName() + "/betterquesting"); - rootDir = server.getFile("saves/" + server.getFolderName()); - } else - { - BQ_Settings.curWorldDir = server.getFile(server.getFolderName() + "/betterquesting"); - rootDir = server.getFile(server.getFolderName()); - } - - File fileDatabase = new File(BQ_Settings.curWorldDir, "QuestDatabase.json"); - File fileProgress = new File(BQ_Settings.curWorldDir, "QuestProgress.json"); - File fileParties = new File(BQ_Settings.curWorldDir, "QuestingParties.json"); - File fileLives = new File(BQ_Settings.curWorldDir, "LifeDatabase.json"); - File fileNames = new File(BQ_Settings.curWorldDir, "NameCache.json"); - - // MOVE BQ1 LEGACY FILES - - if(new File(rootDir, "QuestDatabase.json").exists() && !fileDatabase.exists()) - { - File legFileDat = new File(rootDir, "QuestDatabase.json"); - File legFilePro = new File(rootDir, "QuestProgress.json"); - File legFilePar = new File(rootDir, "QuestingParties.json"); - File legFileLiv = new File(rootDir, "LifeDatabase.json"); - File legFileNam = new File(rootDir, "NameCache.json"); - - JsonHelper.CopyPaste(legFileDat, fileDatabase); - JsonHelper.CopyPaste(legFilePro, fileProgress); - JsonHelper.CopyPaste(legFilePar, fileParties); - JsonHelper.CopyPaste(legFileLiv, fileLives); - JsonHelper.CopyPaste(legFileNam, fileNames); - - legFileDat.delete(); - legFilePro.delete(); - legFilePar.delete(); - legFileLiv.delete(); - legFileNam.delete(); - } - - // === CONFIG === - - boolean useDef = !fileDatabase.exists(); - int packVer = 0; - String packName = ""; - - if(useDef) // LOAD DEFAULTS - { - fileDatabase = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); - isDirty = true; - } else - { - JsonObject defTmp = JsonHelper.ReadFromFile(new File(BQ_Settings.defaultDir, "DefaultQuests.json")); - QuestSettings tmpSettings = new QuestSettings(); - tmpSettings.readFromNBT(NBTConverter.JSONtoNBT_Object(defTmp, new NBTTagCompound(), true).getCompoundTag("questSettings")); - packVer = tmpSettings.getProperty(NativeProps.PACK_VER); - packName = tmpSettings.getProperty(NativeProps.PACK_NAME); - } - - JsonObject j1 = JsonHelper.ReadFromFile(fileDatabase); - - NBTTagCompound nbt1 = NBTConverter.JSONtoNBT_Object(j1, new NBTTagCompound(), true); - - String fVer = nbt1.hasKey("format", 8) ? nbt1.getString("format") : "0.0.0"; - String bVer = nbt1.getString("build"); - String cVer = Loader.instance().getIndexedModList().get(BetterQuesting.MODID).getVersion(); - - if(!cVer.equalsIgnoreCase(bVer) && !useDef) // RUN BACKUPS - { - String fsVer = JsonHelper.makeFileNameSafe(bVer); - - if(fsVer.length() <= 0) fsVer = "pre-251"; - - BetterQuesting.logger.warn("BetterQuesting has been updated to from \"" + fsVer + "\" to \"" + cVer + "\"! Creating back ups..."); - - JsonHelper.CopyPaste(fileDatabase, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, "QuestDatabase_backup_" + fsVer + ".json")); - JsonHelper.CopyPaste(fileProgress, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, "QuestProgress_backup_" + fsVer + ".json")); - JsonHelper.CopyPaste(fileParties, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, "QuestingParties_backup_" + fsVer + ".json")); - JsonHelper.CopyPaste(fileNames, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, "NameCache_backup_" + fsVer + ".json")); - JsonHelper.CopyPaste(fileLives, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, "LifeDatabase_backup_" + fsVer + ".json")); - } - - ILegacyLoader loader = LegacyLoaderRegistry.getLoader(fVer); - - if(loader == null) - { - QuestSettings.INSTANCE.readFromNBT(nbt1.getCompoundTag("questSettings")); - QuestDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questDatabase", 10), false); - QuestLineDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questLines", 10), false); - } else - { - loader.readFromJson(j1); - } - - if(useDef) QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, false); // Force edit off - hasUpdate = packName.equals(QuestSettings.INSTANCE.getProperty(NativeProps.PACK_NAME)) && packVer > QuestSettings.INSTANCE.getProperty(NativeProps.PACK_VER); - - // === PROGRESS === - - JsonObject j2 = JsonHelper.ReadFromFile(fileProgress); - - if(loader == null) - { - NBTTagCompound nbt2 = NBTConverter.JSONtoNBT_Object(j2, new NBTTagCompound(), true); - QuestDatabase.INSTANCE.readProgressFromNBT(nbt2.getTagList("questProgress", 10), false); - } else - { - loader.readProgressFromJson(j2); - } - - // === PARTIES === - - JsonObject j3 = JsonHelper.ReadFromFile(fileParties); - - NBTTagCompound nbt3 = NBTConverter.JSONtoNBT_Object(j3, new NBTTagCompound(), true); - PartyManager.INSTANCE.readFromNBT(nbt3.getTagList("parties", 10), false); - - // === NAMES === - - JsonObject j4 = JsonHelper.ReadFromFile(fileNames); - - NBTTagCompound nbt4 = NBTConverter.JSONtoNBT_Object(j4, new NBTTagCompound(), true); - NameCache.INSTANCE.readFromNBT(nbt4.getTagList("nameCache", 10), false); - - // === LIVES === - - JsonObject j5 = JsonHelper.ReadFromFile(fileLives); - - NBTTagCompound nbt5 = NBTConverter.JSONtoNBT_Object(j5, new NBTTagCompound(), true); - LifeDatabase.INSTANCE.readFromNBT(nbt5.getCompoundTag("lifeDatabase"), false); - - BetterQuesting.logger.info("Loaded " + QuestDatabase.INSTANCE.size() + " quests"); - BetterQuesting.logger.info("Loaded " + QuestLineDatabase.INSTANCE.size() + " quest lines"); - BetterQuesting.logger.info("Loaded " + PartyManager.INSTANCE.size() + " parties"); - BetterQuesting.logger.info("Loaded " + NameCache.INSTANCE.size() + " names"); - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Load(DBType.ALL)); + + File rootDir; + + if (BetterQuesting.proxy.isClient()) { + BQ_Settings.curWorldDir = server.getFile("saves/" + server.getFolderName() + "/betterquesting"); + rootDir = server.getFile("saves/" + server.getFolderName()); + } else { + BQ_Settings.curWorldDir = server.getFile(server.getFolderName() + "/betterquesting"); + rootDir = server.getFile(server.getFolderName()); } - - public void saveDatabases() + + File fileDatabase = new File(BQ_Settings.curWorldDir, "QuestDatabase.json"); + File fileProgress = new File(BQ_Settings.curWorldDir, "QuestProgress.json"); + File fileParties = new File(BQ_Settings.curWorldDir, "QuestingParties.json"); + File fileLives = new File(BQ_Settings.curWorldDir, "LifeDatabase.json"); + File fileNames = new File(BQ_Settings.curWorldDir, "NameCache.json"); + + // MOVE BQ1 LEGACY FILES + + if (new File(rootDir, "QuestDatabase.json").exists() && !fileDatabase.exists()) { + File legFileDat = new File(rootDir, "QuestDatabase.json"); + File legFilePro = new File(rootDir, "QuestProgress.json"); + File legFilePar = new File(rootDir, "QuestingParties.json"); + File legFileLiv = new File(rootDir, "LifeDatabase.json"); + File legFileNam = new File(rootDir, "NameCache.json"); + + JsonHelper.CopyPaste(legFileDat, fileDatabase); + JsonHelper.CopyPaste(legFilePro, fileProgress); + JsonHelper.CopyPaste(legFilePar, fileParties); + JsonHelper.CopyPaste(legFileLiv, fileLives); + JsonHelper.CopyPaste(legFileNam, fileNames); + + legFileDat.delete(); + legFilePro.delete(); + legFilePar.delete(); + legFileLiv.delete(); + legFileNam.delete(); + } + + // === CONFIG === + + boolean useDef = !fileDatabase.exists(); + int packVer = 0; + String packName = ""; + + if (useDef) // LOAD DEFAULTS { - // === CONFIG === - - if(isDirty || QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) - { - NBTTagCompound jsonCon = new NBTTagCompound(); - - jsonCon.setTag("questSettings", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); - jsonCon.setTag("questDatabase", QuestDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); - jsonCon.setTag("questLines", QuestLineDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); - - jsonCon.setString("format", BetterQuesting.FORMAT); - jsonCon.setString("build", Loader.instance().getIndexedModList().get(BetterQuesting.MODID).getVersion()); - - JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "QuestDatabase.json"), NBTConverter.NBTtoJSON_Compound(jsonCon, new JsonObject(), true)); - } - - // === PROGRESS === - - NBTTagCompound jsonProg = new NBTTagCompound(); - - jsonProg.setTag("questProgress", QuestDatabase.INSTANCE.writeProgressToNBT(new NBTTagList(), null)); - - JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "QuestProgress.json"), NBTConverter.NBTtoJSON_Compound(jsonProg, new JsonObject(), true)); - - // === PARTIES === - - NBTTagCompound jsonP = new NBTTagCompound(); - - jsonP.setTag("parties", PartyManager.INSTANCE.writeToNBT(new NBTTagList(), null)); - - JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "QuestingParties.json"), NBTConverter.NBTtoJSON_Compound(jsonP, new JsonObject(), true)); - - // === NAMES === - - NBTTagCompound jsonN = new NBTTagCompound(); - - jsonN.setTag("nameCache", NameCache.INSTANCE.writeToNBT(new NBTTagList(), null)); - - JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "NameCache.json"), NBTConverter.NBTtoJSON_Compound(jsonN, new JsonObject(), true)); - - // === LIVES === - - NBTTagCompound jsonL = new NBTTagCompound(); - - jsonL.setTag("lifeDatabase", LifeDatabase.INSTANCE.writeToNBT(new NBTTagCompound(), null)); - - JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "LifeDatabase.json"), NBTConverter.NBTtoJSON_Compound(jsonL, new JsonObject(), true)); - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Save(DBType.ALL)); - - isDirty = false; + fileDatabase = new File(BQ_Settings.defaultDir, "DefaultQuests.json"); + isDirty = true; + } else { + JsonObject defTmp = JsonHelper.ReadFromFile(new File(BQ_Settings.defaultDir, "DefaultQuests.json")); + QuestSettings tmpSettings = new QuestSettings(); + tmpSettings.readFromNBT( + NBTConverter.JSONtoNBT_Object(defTmp, new NBTTagCompound(), true).getCompoundTag("questSettings")); + packVer = tmpSettings.getProperty(NativeProps.PACK_VER); + packName = tmpSettings.getProperty(NativeProps.PACK_NAME); } - - public void unloadDatabases() + + JsonObject j1 = JsonHelper.ReadFromFile(fileDatabase); + + NBTTagCompound nbt1 = NBTConverter.JSONtoNBT_Object(j1, new NBTTagCompound(), true); + + String fVer = nbt1.hasKey("format", 8) ? nbt1.getString("format") : "0.0.0"; + String bVer = nbt1.getString("build"); + String cVer = Loader.instance().getIndexedModList().get(BetterQuesting.MODID).getVersion(); + + if (!cVer.equalsIgnoreCase(bVer) && !useDef) // RUN BACKUPS { - BQThreadedIO.INSTANCE.enqueue(() -> { - BQ_Settings.curWorldDir = null; - hasUpdate = false; - isDirty = false; - - QuestSettings.INSTANCE.reset(); - QuestDatabase.INSTANCE.reset(); - QuestLineDatabase.INSTANCE.reset(); - LifeDatabase.INSTANCE.reset(); - NameCache.INSTANCE.reset(); - PartyInvitations.INSTANCE.reset(); - PartyManager.INSTANCE.reset(); - - if(BetterQuesting.proxy.isClient()) - { - GuiHome.bookmark = null; - QuestNotification.resetNotices(); - } - - // TODO: Fire an event to that expansions can use to reset their own databases if necessary - }); + String fsVer = JsonHelper.makeFileNameSafe(bVer); + + if (fsVer.isEmpty()) { fsVer = "pre-251"; } + + BetterQuesting.logger.warn( + "BetterQuesting has been updated to from \"" + fsVer + "\" to \"" + cVer + "\"! Creating back ups..."); + + JsonHelper.CopyPaste(fileDatabase, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, + "QuestDatabase_backup_" + fsVer + ".json")); + JsonHelper.CopyPaste(fileProgress, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, + "QuestProgress_backup_" + fsVer + ".json")); + JsonHelper.CopyPaste(fileParties, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, + "QuestingParties_backup_" + fsVer + ".json")); + JsonHelper.CopyPaste(fileNames, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, + "NameCache_backup_" + fsVer + ".json")); + JsonHelper.CopyPaste(fileLives, new File(BQ_Settings.curWorldDir + "/backup/" + fsVer, + "LifeDatabase_backup_" + fsVer + ".json")); } + + ILegacyLoader loader = LegacyLoaderRegistry.getLoader(fVer); + + if (loader == null) { + QuestSettings.INSTANCE.readFromNBT(nbt1.getCompoundTag("questSettings")); + QuestDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questDatabase", 10), false); + QuestLineDatabase.INSTANCE.readFromNBT(nbt1.getTagList("questLines", 10), false); + } else { + loader.readFromJson(j1); + } + + if (useDef) { + QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, false); // Force edit off + } + hasUpdate = packName.equals(QuestSettings.INSTANCE.getProperty(NativeProps.PACK_NAME)) && + packVer > QuestSettings.INSTANCE.getProperty(NativeProps.PACK_VER); + + // === PROGRESS === + + JsonObject j2 = JsonHelper.ReadFromFile(fileProgress); + + if (loader == null) { + NBTTagCompound nbt2 = NBTConverter.JSONtoNBT_Object(j2, new NBTTagCompound(), true); + QuestDatabase.INSTANCE.readProgressFromNBT(nbt2.getTagList("questProgress", 10), false); + } else { + loader.readProgressFromJson(j2); + } + + // === PARTIES === + + JsonObject j3 = JsonHelper.ReadFromFile(fileParties); + + NBTTagCompound nbt3 = NBTConverter.JSONtoNBT_Object(j3, new NBTTagCompound(), true); + PartyManager.INSTANCE.readFromNBT(nbt3.getTagList("parties", 10), false); + + // === NAMES === + + JsonObject j4 = JsonHelper.ReadFromFile(fileNames); + + NBTTagCompound nbt4 = NBTConverter.JSONtoNBT_Object(j4, new NBTTagCompound(), true); + NameCache.INSTANCE.readFromNBT(nbt4.getTagList("nameCache", 10), false); + + // === LIVES === + + JsonObject j5 = JsonHelper.ReadFromFile(fileLives); + + NBTTagCompound nbt5 = NBTConverter.JSONtoNBT_Object(j5, new NBTTagCompound(), true); + LifeDatabase.INSTANCE.readFromNBT(nbt5.getCompoundTag("lifeDatabase"), false); + + BetterQuesting.logger.info("Loaded " + QuestDatabase.INSTANCE.size() + " quests"); + BetterQuesting.logger.info("Loaded " + QuestLineDatabase.INSTANCE.size() + " quest lines"); + BetterQuesting.logger.info("Loaded " + PartyManager.INSTANCE.size() + " parties"); + BetterQuesting.logger.info("Loaded " + NameCache.INSTANCE.size() + " names"); + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Load(DBType.ALL)); + } + + public void saveDatabases() { + // === CONFIG === + + if (isDirty || QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) { + NBTTagCompound jsonCon = new NBTTagCompound(); + + jsonCon.setTag("questSettings", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); + jsonCon.setTag("questDatabase", QuestDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); + jsonCon.setTag("questLines", QuestLineDatabase.INSTANCE.writeToNBT(new NBTTagList(), null)); + + jsonCon.setString("format", BetterQuesting.FORMAT); + jsonCon.setString("build", Loader.instance().getIndexedModList().get(BetterQuesting.MODID).getVersion()); + + JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "QuestDatabase.json"), + NBTConverter.NBTtoJSON_Compound(jsonCon, new JsonObject(), true)); + } + + // === PROGRESS === + + NBTTagCompound jsonProg = new NBTTagCompound(); + + jsonProg.setTag("questProgress", QuestDatabase.INSTANCE.writeProgressToNBT(new NBTTagList(), null)); + + JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "QuestProgress.json"), + NBTConverter.NBTtoJSON_Compound(jsonProg, new JsonObject(), true)); + + // === PARTIES === + + NBTTagCompound jsonP = new NBTTagCompound(); + + jsonP.setTag("parties", PartyManager.INSTANCE.writeToNBT(new NBTTagList(), null)); + + JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "QuestingParties.json"), + NBTConverter.NBTtoJSON_Compound(jsonP, new JsonObject(), true)); + + // === NAMES === + + NBTTagCompound jsonN = new NBTTagCompound(); + + jsonN.setTag("nameCache", NameCache.INSTANCE.writeToNBT(new NBTTagList(), null)); + + JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "NameCache.json"), + NBTConverter.NBTtoJSON_Compound(jsonN, new JsonObject(), true)); + + // === LIVES === + + NBTTagCompound jsonL = new NBTTagCompound(); + + jsonL.setTag("lifeDatabase", LifeDatabase.INSTANCE.writeToNBT(new NBTTagCompound(), null)); + + JsonHelper.WriteToFile(new File(BQ_Settings.curWorldDir, "LifeDatabase.json"), + NBTConverter.NBTtoJSON_Compound(jsonL, new JsonObject(), true)); + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Save(DBType.ALL)); + + isDirty = false; + } + + public void unloadDatabases() { + BQThreadedIO.INSTANCE.enqueue(() -> { + BQ_Settings.curWorldDir = null; + hasUpdate = false; + isDirty = false; + + QuestSettings.INSTANCE.reset(); + QuestDatabase.INSTANCE.reset(); + QuestLineDatabase.INSTANCE.reset(); + LifeDatabase.INSTANCE.reset(); + NameCache.INSTANCE.reset(); + PartyInvitations.INSTANCE.reset(); + PartyManager.INSTANCE.reset(); + + if (BetterQuesting.proxy.isClient()) { + GuiHome.bookmark = null; + QuestNotification.resetNotices(); + } + + // TODO: Fire an event to that expansions can use to reset their own databases if necessary + }); + } } diff --git a/src/main/java/betterquesting/items/ItemExtraLife.java b/src/main/java/betterquesting/items/ItemExtraLife.java index 61cc07174..929ef6f1d 100644 --- a/src/main/java/betterquesting/items/ItemExtraLife.java +++ b/src/main/java/betterquesting/items/ItemExtraLife.java @@ -21,101 +21,89 @@ import javax.annotation.Nonnull; import java.util.UUID; -public class ItemExtraLife extends Item -{ - public ItemExtraLife() - { - this.setTranslationKey("betterquesting.extra_life"); - this.setCreativeTab(BetterQuesting.tabQuesting); - this.setHasSubtypes(true); - } +public class ItemExtraLife extends Item { + public ItemExtraLife() { + this.setTranslationKey("betterquesting.extra_life"); + this.setCreativeTab(BetterQuesting.tabQuesting); + this.setHasSubtypes(true); + } - /** - * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer - */ - @Nonnull - @Override - public ActionResult onItemRightClick(World world, EntityPlayer player, @Nonnull EnumHand hand) - { - ItemStack stack = player.getHeldItem(hand); - - if(stack.getItemDamage() != 0 || hand != EnumHand.MAIN_HAND) - { - return new ActionResult<>(EnumActionResult.PASS, stack); - } else if(QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE)) - { - if(!player.capabilities.isCreativeMode) - { - stack.grow(-1); - } - - UUID uuid = QuestingAPI.getQuestingUUID(player); - int lives = LifeDatabase.INSTANCE.getLives(uuid); - - if(lives >= QuestSettings.INSTANCE.getProperty(NativeProps.LIVES_MAX)) - { - if(!world.isRemote) - { - player.sendStatusMessage(new TextComponentString(TextFormatting.RED.toString()).appendSibling(new TextComponentTranslation("betterquesting.gui.full_lives")), true); - } - - return new ActionResult<>(EnumActionResult.PASS, stack); - } + /** + * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer + */ + @Nonnull + @Override + public ActionResult onItemRightClick(@Nonnull World world, EntityPlayer player, @Nonnull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); - player.world.playSound(null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_LEVELUP, SoundCategory.PLAYERS, 1F, 1F); - - if(!world.isRemote) - { - LifeDatabase.INSTANCE.setLives(uuid, lives + 1); - - player.sendStatusMessage(new TextComponentTranslation("betterquesting.gui.remaining_lives", TextFormatting.YELLOW.toString() + (lives + 1)), true); - } - } else if(!world.isRemote) - { - player.sendStatusMessage(new TextComponentTranslation("betterquesting.msg.heart_disabled"), true); - } - - return new ActionResult<>(EnumActionResult.PASS, stack); - } + if (stack.getItemDamage() != 0 || hand != EnumHand.MAIN_HAND) { + return new ActionResult<>(EnumActionResult.PASS, stack); + } else if (QuestSettings.INSTANCE.getProperty(NativeProps.HARDCORE)) { + if (!player.capabilities.isCreativeMode) { + stack.grow(-1); + } + + UUID uuid = QuestingAPI.getQuestingUUID(player); + int lives = LifeDatabase.INSTANCE.getLives(uuid); - /** - * Returns the unlocalized name of this item. This version accepts an ItemStack so different stacks can have - * different names based on their damage or NBT. - */ - @Override - @Nonnull - public String getTranslationKey(ItemStack stack) - { - switch(stack.getItemDamage()%3) - { - case 2: - return this.getTranslationKey() + ".quarter"; - case 1: - return this.getTranslationKey() + ".half"; - default: - return this.getTranslationKey() + ".full"; + if (lives >= QuestSettings.INSTANCE.getProperty(NativeProps.LIVES_MAX)) { + if (!world.isRemote) { + player.sendStatusMessage(new TextComponentString(TextFormatting.RED.toString()).appendSibling( + new TextComponentTranslation("betterquesting.gui.full_lives")), true); } + + return new ActionResult<>(EnumActionResult.PASS, stack); + } + + player.world.playSound(null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_PLAYER_LEVELUP, + SoundCategory.PLAYERS, 1F, 1F); + + if (!world.isRemote) { + LifeDatabase.INSTANCE.setLives(uuid, lives + 1); + + player.sendStatusMessage(new TextComponentTranslation("betterquesting.gui.remaining_lives", + TextFormatting.YELLOW.toString() + (lives + 1)), true); + } + } else if (!world.isRemote) { + player.sendStatusMessage(new TextComponentTranslation("betterquesting.msg.heart_disabled"), true); } - - @Override - @SideOnly(Side.CLIENT) - public boolean hasEffect(ItemStack stack) - { - return stack.getItemDamage() == 0; + + return new ActionResult<>(EnumActionResult.PASS, stack); + } + + /** + * Returns the unlocalized name of this item. This version accepts an ItemStack so different stacks can have + * different names based on their damage or NBT. + */ + @Override + @Nonnull + public String getTranslationKey(ItemStack stack) { + switch (stack.getItemDamage() % 3) { + case 2: + return this.getTranslationKey() + ".quarter"; + case 1: + return this.getTranslationKey() + ".half"; + default: + return this.getTranslationKey() + ".full"; } + } + + @Override + @SideOnly(Side.CLIENT) + public boolean hasEffect(ItemStack stack) { + return stack.getItemDamage() == 0; + } - /** - * returns a list of items with the same ID, but different meta (eg: dye returns 16 items) - */ - @Override - @SideOnly(Side.CLIENT) - public void getSubItems(@Nonnull CreativeTabs tab, @Nonnull NonNullList list) - { - if(this.isInCreativeTab(tab)) - { - list.add(new ItemStack(this, 1, 0)); - list.add(new ItemStack(this, 1, 1)); - list.add(new ItemStack(this, 1, 2)); - } + /** + * returns a list of items with the same ID, but different meta (eg: dye returns 16 items) + */ + @Override + @SideOnly(Side.CLIENT) + public void getSubItems(@Nonnull CreativeTabs tab, @Nonnull NonNullList list) { + if (this.isInCreativeTab(tab)) { + list.add(new ItemStack(this, 1, 0)); + list.add(new ItemStack(this, 1, 1)); + list.add(new ItemStack(this, 1, 2)); } + } } diff --git a/src/main/java/betterquesting/items/ItemGuideBook.java b/src/main/java/betterquesting/items/ItemGuideBook.java index a6405e094..57991c6ca 100644 --- a/src/main/java/betterquesting/items/ItemGuideBook.java +++ b/src/main/java/betterquesting/items/ItemGuideBook.java @@ -1,5 +1,6 @@ package betterquesting.items; +import betterquesting.core.BetterQuesting; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -9,36 +10,33 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import betterquesting.core.BetterQuesting; -public class ItemGuideBook extends Item -{ - public ItemGuideBook() - { - this.setTranslationKey("betterquesting.guide"); - this.setCreativeTab(BetterQuesting.tabQuesting); - } +import javax.annotation.Nonnull; - /** - * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer - */ - @Override - public ActionResult onItemRightClick(World world, EntityPlayer player, EnumHand hand) - { - ItemStack stack = player.getHeldItem(hand); - - if(world.isRemote && hand == EnumHand.MAIN_HAND) - { - player.openGui(BetterQuesting.instance, 1, world, 0, 0, 0); - } - - return new ActionResult<>(EnumActionResult.PASS, stack); - } - - @Override - @SideOnly(Side.CLIENT) - public boolean hasEffect(ItemStack stack) - { - return true; +public class ItemGuideBook extends Item { + public ItemGuideBook() { + this.setTranslationKey("betterquesting.guide"); + this.setCreativeTab(BetterQuesting.tabQuesting); + } + + /** + * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer + */ + @Nonnull + @Override + public ActionResult onItemRightClick(World world, EntityPlayer player, @Nonnull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + + if (world.isRemote && hand == EnumHand.MAIN_HAND) { + player.openGui(BetterQuesting.instance, 1, world, 0, 0, 0); } + + return new ActionResult<>(EnumActionResult.PASS, stack); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean hasEffect(@Nonnull ItemStack stack) { + return true; + } } diff --git a/src/main/java/betterquesting/legacy/ILegacyLoader.java b/src/main/java/betterquesting/legacy/ILegacyLoader.java index 06cfe44c8..66152359f 100644 --- a/src/main/java/betterquesting/legacy/ILegacyLoader.java +++ b/src/main/java/betterquesting/legacy/ILegacyLoader.java @@ -2,8 +2,8 @@ import com.google.gson.JsonElement; -public interface ILegacyLoader -{ - void readFromJson(JsonElement json); - void readProgressFromJson(JsonElement json); +public interface ILegacyLoader { + void readFromJson(JsonElement json); + + void readProgressFromJson(JsonElement json); } diff --git a/src/main/java/betterquesting/legacy/LegacyLoaderRegistry.java b/src/main/java/betterquesting/legacy/LegacyLoaderRegistry.java index f3cf4a616..b2a1534ca 100644 --- a/src/main/java/betterquesting/legacy/LegacyLoaderRegistry.java +++ b/src/main/java/betterquesting/legacy/LegacyLoaderRegistry.java @@ -1,19 +1,17 @@ package betterquesting.legacy; -import java.util.HashMap; import betterquesting.legacy.v0.LegacyLoader_v0; -public class LegacyLoaderRegistry -{ - private static HashMap legReg = new HashMap(); - - public static ILegacyLoader getLoader(String version) - { - return legReg.get(version); - } - - static - { - legReg.put("0.0.0", LegacyLoader_v0.INSTANCE); - } +import java.util.HashMap; + +public class LegacyLoaderRegistry { + private static final HashMap legReg = new HashMap<>(); + + public static ILegacyLoader getLoader(String version) { + return legReg.get(version); + } + + static { + legReg.put("0.0.0", LegacyLoader_v0.INSTANCE); + } } diff --git a/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java b/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java index d35efcff3..39c699a4f 100644 --- a/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java +++ b/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java @@ -27,263 +27,226 @@ import java.util.ArrayList; import java.util.List; -public final class LegacyLoader_v0 implements ILegacyLoader -{ - public static final LegacyLoader_v0 INSTANCE = new LegacyLoader_v0(); - - private LegacyLoader_v0() - { - } - - @Override - public void readFromJson(JsonElement rawJson) - { - if(rawJson == null || !rawJson.isJsonObject()) - { - // Not going to bother with converting progression - return; - } - - JsonObject json = rawJson.getAsJsonObject(); - - if(json.has("editMode")) // This IS the file you are looking for - { - QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, JsonHelper.GetBoolean(json, "editMode", true)); - QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, JsonHelper.GetBoolean(json, "hardcore", false)); - - QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_DEF, JsonHelper.GetNumber(json, "defLives", 3).intValue()); - QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_MAX, JsonHelper.GetNumber(json, "maxLives", 10).intValue()); - - readQuestDatabase(JsonHelper.GetArray(json, "questDatabase")); - readLineDatabase(JsonHelper.GetArray(json, "questLines")); - } - } - - public void readQuestDatabase(JsonArray jAry) - { - QuestDatabase.INSTANCE.reset(); - - for(JsonElement je : jAry) - { - if(je == null || !je.isJsonObject()) - { - continue; - } - - JsonObject json = je.getAsJsonObject(); - int qID = JsonHelper.GetNumber(json, "questID", -1).intValue(); - IQuest quest = QuestDatabase.INSTANCE.getValue(qID); - boolean flag = quest == null; - quest = quest != null? quest : new QuestInstance(); - readQuest(quest, json); - - if(flag) - { - QuestDatabase.INSTANCE.add(qID, quest); - } - } - } - - @Override - public void readProgressFromJson(JsonElement json) +public final class LegacyLoader_v0 implements ILegacyLoader { + public static final LegacyLoader_v0 INSTANCE = new LegacyLoader_v0(); + + private LegacyLoader_v0() { + } + + @Override + public void readFromJson(JsonElement rawJson) { + if (rawJson == null || !rawJson.isJsonObject()) { + // Not going to bother with converting progression + return; + } + + JsonObject json = rawJson.getAsJsonObject(); + + if (json.has("editMode")) // This IS the file you are looking for { - if(!json.isJsonObject()) return; - QuestDatabase.INSTANCE.readProgressFromNBT(NBTConverter.JSONtoNBT_Object(json.getAsJsonObject(), new NBTTagCompound(), true).getTagList("questProgress", 10), false); + QuestSettings.INSTANCE.setProperty(NativeProps.EDIT_MODE, JsonHelper.GetBoolean(json, "editMode", true)); + QuestSettings.INSTANCE.setProperty(NativeProps.HARDCORE, JsonHelper.GetBoolean(json, "hardcore", false)); + + QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_DEF, JsonHelper.GetNumber(json, "defLives", 3).intValue()); + QuestSettings.INSTANCE.setProperty(NativeProps.LIVES_MAX, JsonHelper.GetNumber(json, "maxLives", 10).intValue()); + + readQuestDatabase(JsonHelper.GetArray(json, "questDatabase")); + readLineDatabase(JsonHelper.GetArray(json, "questLines")); + } + } + + public void readQuestDatabase(JsonArray jAry) { + QuestDatabase.INSTANCE.reset(); + + for (JsonElement je : jAry) { + if (je == null || !je.isJsonObject()) { + continue; + } + + JsonObject json = je.getAsJsonObject(); + int qID = JsonHelper.GetNumber(json, "questID", -1).intValue(); + IQuest quest = QuestDatabase.INSTANCE.getValue(qID); + boolean flag = quest == null; + quest = quest != null ? quest : new QuestInstance(); + readQuest(quest, json); + + if (flag) { + QuestDatabase.INSTANCE.add(qID, quest); + } + } + } + + @Override + public void readProgressFromJson(JsonElement json) { + if (!json.isJsonObject()) { return; } + QuestDatabase.INSTANCE.readProgressFromNBT( + NBTConverter.JSONtoNBT_Object(json.getAsJsonObject(), new NBTTagCompound(), true) + .getTagList("questProgress", 10), false); + } + + public void readLineDatabase(JsonArray jAry) { + QuestLineDatabase.INSTANCE.reset(); + + for (JsonElement je : jAry) { + if (je == null || !je.isJsonObject()) { + continue; + } + + IQuestLine qLine = new QuestLine(); + readLine(qLine, je.getAsJsonObject()); + + QuestLineDatabase.INSTANCE.add(QuestLineDatabase.INSTANCE.nextID(), qLine); + } + } + + public void readQuest(IQuest quest, JsonObject json) { + quest.setProperty(NativeProps.NAME, JsonHelper.GetString(json, "name", "New Quest")); + quest.setProperty(NativeProps.DESC, JsonHelper.GetString(json, "description", "No Description")); + quest.setProperty(NativeProps.MAIN, JsonHelper.GetBoolean(json, "isMain", false)); + quest.setProperty(NativeProps.SILENT, JsonHelper.GetBoolean(json, "isSilent", false)); + quest.setProperty(NativeProps.LOCKED_PROGRESS, JsonHelper.GetBoolean(json, "lockedProgress", false)); + quest.setProperty(NativeProps.SIMULTANEOUS, JsonHelper.GetBoolean(json, "simultaneous", false)); + quest.setProperty(NativeProps.GLOBAL, JsonHelper.GetBoolean(json, "globalQuest", false)); + quest.setProperty(NativeProps.GLOBAL_SHARE, JsonHelper.GetBoolean(json, "globalShare", false)); + quest.setProperty(NativeProps.AUTO_CLAIM, JsonHelper.GetBoolean(json, "autoClaim", false)); + quest.setProperty(NativeProps.REPEAT_TIME, JsonHelper.GetNumber(json, "repeatTime", 2000).intValue()); + quest.setProperty(NativeProps.LOGIC_QUEST, EnumLogic.valueOf(JsonHelper.GetString(json, "logic", "AND"))); + quest.setProperty(NativeProps.LOGIC_TASK, EnumLogic.valueOf(JsonHelper.GetString(json, "taskLogic", "AND"))); + quest.setProperty(NativeProps.ICON, JsonHelper.JsonToItemStack( + NBTConverter.JSONtoNBT_Object(JsonHelper.GetObject(json, "icon"), new NBTTagCompound(), true))); + + JsonArray reqAry = JsonHelper.GetArray(json, "preRequisites"); + int[] req = new int[reqAry.size()]; + for (int i = 0; i < req.length; i++) { + JsonElement je = reqAry.get(i); + if (je == null || !je.isJsonPrimitive() || !je.getAsJsonPrimitive().isNumber()) { + req[i] = -1; + } else { + req[i] = je.getAsInt(); + } + } + quest.setRequirements(req); + + IDatabaseNBT taskDB = quest.getTasks(); + List uaTasks = new ArrayList<>(); + + for (JsonElement entry : JsonHelper.GetArray(json, "tasks")) { + if (entry == null || !entry.isJsonObject()) { + continue; + } + + JsonObject jsonTask = entry.getAsJsonObject(); + ResourceLocation loc = new ResourceLocation(JsonHelper.GetString(jsonTask, "taskID", "")); + int index = JsonHelper.GetNumber(jsonTask, "index", -1).intValue(); + ITask task = TaskRegistry.INSTANCE.createNew(loc); + + if (task instanceof TaskPlaceholder) { + JsonObject jt2 = JsonHelper.GetObject(jsonTask, "orig_data"); + ResourceLocation loc2 = new ResourceLocation(JsonHelper.GetString(jt2, "taskID", "")); + ITask t2 = TaskRegistry.INSTANCE.createNew(loc2); + + if (t2 != null) // Restored original task + { + jsonTask = jt2; + task = t2; + } + } + + NBTTagCompound nbtTask = NBTConverter.JSONtoNBT_Object(jsonTask, new NBTTagCompound(), true); + + if (task != null) { + task.readFromNBT(nbtTask); + + if (index >= 0) { + taskDB.add(index, task); + } else { + uaTasks.add(task); + } + } else { + TaskPlaceholder tph = new TaskPlaceholder(); + tph.setTaskConfigData(nbtTask); + + if (index >= 0) { + taskDB.add(index, tph); + } else { + uaTasks.add(tph); + } + } + } + + for (ITask t : uaTasks) { + taskDB.add(taskDB.nextID(), t); + } + + IDatabaseNBT rewardDB = quest.getRewards(); + List unassigned = new ArrayList<>(); + + for (JsonElement entry : JsonHelper.GetArray(json, "rewards")) { + if (entry == null || !entry.isJsonObject()) { + continue; + } + + JsonObject jsonReward = entry.getAsJsonObject(); + ResourceLocation loc = new ResourceLocation(JsonHelper.GetString(jsonReward, "rewardID", "")); + int index = JsonHelper.GetNumber(jsonReward, "index", -1).intValue(); + IReward reward = RewardRegistry.INSTANCE.createNew(loc); + + if (reward instanceof RewardPlaceholder) { + JsonObject jr2 = JsonHelper.GetObject(jsonReward, "orig_data"); + ResourceLocation loc2 = new ResourceLocation(JsonHelper.GetString(jr2, "rewardID", "")); + IReward r2 = RewardRegistry.INSTANCE.createNew(loc2); + + if (r2 != null) { + jsonReward = jr2; + reward = r2; + } + } + + NBTTagCompound nbtReward = NBTConverter.JSONtoNBT_Object(jsonReward, new NBTTagCompound(), true); + + if (reward != null) { + reward.readFromNBT(nbtReward); + + if (index >= 0) { + rewardDB.add(index, reward); + } else { + unassigned.add(reward); + } + } else { + RewardPlaceholder rph = new RewardPlaceholder(); + rph.setRewardConfigData(nbtReward); + + if (index >= 0) { + rewardDB.add(index, rph); + } else { + unassigned.add(rph); + } + } + } + + for (IReward r : unassigned) { + rewardDB.add(rewardDB.nextID(), r); + } + } + + public void readLine(IQuestLine qLine, JsonObject json) { + qLine.setProperty(NativeProps.NAME, JsonHelper.GetString(json, "name", "New Quest Line")); + qLine.setProperty(NativeProps.DESC, JsonHelper.GetString(json, "description", "No Description")); + + for (JsonElement je : JsonHelper.GetArray(json, "quests")) { + if (je == null || !je.isJsonObject()) { + continue; + } + + JsonObject json2 = je.getAsJsonObject(); + + IQuestLineEntry entry = new QuestLineEntry(JsonHelper.GetNumber(json2, "x", 0).intValue(), + JsonHelper.GetNumber(json2, "y", 0).intValue(), 24, 24); + int qID = JsonHelper.GetNumber(json2, "id", -1).intValue(); + + if (qID >= 0) { + qLine.add(qID, entry); + } } - - public void readLineDatabase(JsonArray jAry) - { - QuestLineDatabase.INSTANCE.reset(); - - for(JsonElement je : jAry) - { - if(je == null || !je.isJsonObject()) - { - continue; - } - - IQuestLine qLine = new QuestLine(); - readLine(qLine, je.getAsJsonObject()); - - QuestLineDatabase.INSTANCE.add(QuestLineDatabase.INSTANCE.nextID(), qLine); - } - } - - public void readQuest(IQuest quest, JsonObject json) - { - quest.setProperty(NativeProps.NAME, JsonHelper.GetString(json, "name", "New Quest")); - quest.setProperty(NativeProps.DESC, JsonHelper.GetString(json, "description", "No Description")); - quest.setProperty(NativeProps.MAIN, JsonHelper.GetBoolean(json, "isMain", false)); - quest.setProperty(NativeProps.SILENT, JsonHelper.GetBoolean(json, "isSilent", false)); - quest.setProperty(NativeProps.LOCKED_PROGRESS, JsonHelper.GetBoolean(json, "lockedProgress", false)); - quest.setProperty(NativeProps.SIMULTANEOUS, JsonHelper.GetBoolean(json, "simultaneous", false)); - quest.setProperty(NativeProps.GLOBAL, JsonHelper.GetBoolean(json, "globalQuest", false)); - quest.setProperty(NativeProps.GLOBAL_SHARE, JsonHelper.GetBoolean(json, "globalShare", false)); - quest.setProperty(NativeProps.AUTO_CLAIM, JsonHelper.GetBoolean(json, "autoClaim", false)); - quest.setProperty(NativeProps.REPEAT_TIME, JsonHelper.GetNumber(json, "repeatTime", 2000).intValue()); - quest.setProperty(NativeProps.LOGIC_QUEST, EnumLogic.valueOf(JsonHelper.GetString(json, "logic", "AND"))); - quest.setProperty(NativeProps.LOGIC_TASK, EnumLogic.valueOf(JsonHelper.GetString(json, "taskLogic", "AND"))); - quest.setProperty(NativeProps.ICON, JsonHelper.JsonToItemStack(NBTConverter.JSONtoNBT_Object(JsonHelper.GetObject(json, "icon"), new NBTTagCompound(), true))); - - JsonArray reqAry = JsonHelper.GetArray(json, "preRequisites"); - int[] req = new int[reqAry.size()]; - for(int i = 0; i < req.length; i++) - { - JsonElement je = reqAry.get(i); - if(je == null || !je.isJsonPrimitive() || !je.getAsJsonPrimitive().isNumber()) - { - req[i] = -1; - } else - { - req[i] = je.getAsInt(); - } - } - quest.setRequirements(req); - - IDatabaseNBT taskDB = quest.getTasks(); - List uaTasks = new ArrayList<>(); - - for(JsonElement entry : JsonHelper.GetArray(json, "tasks")) - { - if(entry == null || !entry.isJsonObject()) - { - continue; - } - - JsonObject jsonTask = entry.getAsJsonObject(); - ResourceLocation loc = new ResourceLocation(JsonHelper.GetString(jsonTask, "taskID", "")); - int index = JsonHelper.GetNumber(jsonTask, "index", -1).intValue(); - ITask task = TaskRegistry.INSTANCE.createNew(loc); - - if(task instanceof TaskPlaceholder) - { - JsonObject jt2 = JsonHelper.GetObject(jsonTask, "orig_data"); - ResourceLocation loc2 = new ResourceLocation(JsonHelper.GetString(jt2, "taskID", "")); - ITask t2 = TaskRegistry.INSTANCE.createNew(loc2); - - if(t2 != null) // Restored original task - { - jsonTask = jt2; - task = t2; - } - } - - NBTTagCompound nbtTask = NBTConverter.JSONtoNBT_Object(jsonTask, new NBTTagCompound(), true); - - if(task != null) - { - task.readFromNBT(nbtTask); - - if(index >= 0) - { - taskDB.add(index, task); - } else - { - uaTasks.add(task); - } - } else - { - TaskPlaceholder tph = new TaskPlaceholder(); - tph.setTaskConfigData(nbtTask); - - if(index >= 0) - { - taskDB.add(index, tph); - } else - { - uaTasks.add(tph); - } - } - } - - for(ITask t : uaTasks) - { - taskDB.add(taskDB.nextID(), t); - } - - IDatabaseNBT rewardDB = quest.getRewards(); - List unassigned = new ArrayList<>(); - - for(JsonElement entry : JsonHelper.GetArray(json, "rewards")) - { - if(entry == null || !entry.isJsonObject()) - { - continue; - } - - JsonObject jsonReward = entry.getAsJsonObject(); - ResourceLocation loc = new ResourceLocation(JsonHelper.GetString(jsonReward, "rewardID", "")); - int index = JsonHelper.GetNumber(jsonReward, "index", -1).intValue(); - IReward reward = RewardRegistry.INSTANCE.createNew(loc); - - if(reward instanceof RewardPlaceholder) - { - JsonObject jr2 = JsonHelper.GetObject(jsonReward, "orig_data"); - ResourceLocation loc2 = new ResourceLocation(JsonHelper.GetString(jr2, "rewardID", "")); - IReward r2 = RewardRegistry.INSTANCE.createNew(loc2); - - if(r2 != null) - { - jsonReward = jr2; - reward = r2; - } - } - - NBTTagCompound nbtReward = NBTConverter.JSONtoNBT_Object(jsonReward, new NBTTagCompound(), true); - - if(reward != null) - { - reward.readFromNBT(nbtReward); - - if(index >= 0) - { - rewardDB.add(index, reward); - } else - { - unassigned.add(reward); - } - } else - { - RewardPlaceholder rph = new RewardPlaceholder(); - rph.setRewardConfigData(nbtReward); - - if(index >= 0) - { - rewardDB.add(index, rph); - } else - { - unassigned.add(rph); - } - } - } - - for(IReward r : unassigned) - { - rewardDB.add(rewardDB.nextID(), r); - } - } - - public void readLine(IQuestLine qLine, JsonObject json) - { - qLine.setProperty(NativeProps.NAME, JsonHelper.GetString(json, "name", "New Quest Line")); - qLine.setProperty(NativeProps.DESC, JsonHelper.GetString(json, "description", "No Description")); - - for(JsonElement je : JsonHelper.GetArray(json, "quests")) - { - if(je == null || !je.isJsonObject()) - { - continue; - } - - JsonObject json2 = je.getAsJsonObject(); - - IQuestLineEntry entry = new QuestLineEntry(JsonHelper.GetNumber(json2, "x", 0).intValue(), JsonHelper.GetNumber(json2, "y", 0).intValue(), 24, 24); - int qID = JsonHelper.GetNumber(json2, "id", -1).intValue(); - - if(qID >= 0) - { - qLine.add(qID, entry); - } - } - } + } } diff --git a/src/main/java/betterquesting/misc/QuestResourcesFile.java b/src/main/java/betterquesting/misc/QuestResourcesFile.java index c5c1141c7..d7a1b60fe 100644 --- a/src/main/java/betterquesting/misc/QuestResourcesFile.java +++ b/src/main/java/betterquesting/misc/QuestResourcesFile.java @@ -23,196 +23,162 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -public class QuestResourcesFile implements IResourcePack, Closeable -{ - - private static final ResourceLocation UNKNOWN_PACK_TEXTURE = new ResourceLocation("textures/misc/unknown_pack.png"); - - private static final File rootFolder = new File("config/betterquesting/resources/"); - private static final Splitter entryNameSplitter = Splitter.on('/').omitEmptyStrings().limit(3); - private List zipList = null; - private BufferedImage bufferedImage = null; - - @Nonnull - @Override - public InputStream getInputStream(@Nonnull ResourceLocation loc) throws IOException - { - String locName = locationToName(loc); - - for(ZipFile zipfile : getZipFiles()) - { - ZipEntry zipentry = zipfile.getEntry(locName); - - if (zipentry != null) - { - return zipfile.getInputStream(zipentry); - } - } - - throw new ResourcePackFileNotFoundException(rootFolder, locName); - } - - @Override - public boolean resourceExists(@Nonnull ResourceLocation loc) - { - String locName = locationToName(loc); - - try - { - for(ZipFile zipfile : getZipFiles()) - { - ZipEntry zipentry = zipfile.getEntry(locName); - - if (zipentry != null) - { - return true; - } - } - } catch(Exception ignored){} - - return false; - } - - @Override - @Nonnull - public Set getResourceDomains() - { - HashSet hashset = Sets.newHashSet(); - - try - { - for(ZipFile f : getZipFiles()) - { - hashset.addAll(GetZipDomains(f)); - } - } catch(Exception ignored){} - - return hashset; - } - - private Set GetZipDomains(ZipFile zipfile) - { - Enumeration enumeration = zipfile.entries(); - HashSet hashset = Sets.newHashSet(); - - while (enumeration.hasMoreElements()) - { - ZipEntry zipentry = enumeration.nextElement(); - String s = zipentry.getName(); - - if (s.startsWith("assets/")) - { - ArrayList arraylist = Lists.newArrayList(entryNameSplitter.split(s)); - - if (arraylist.size() > 1) - { - String s1 = arraylist.get(1); - - if (!s1.equals(s1.toLowerCase())) - { - this.logNameNotLowercase(s1, zipfile.getName()); - } - else - { - hashset.add(s1); - } - } - } - } +public class QuestResourcesFile implements IResourcePack, Closeable { + + private static final ResourceLocation UNKNOWN_PACK_TEXTURE = new ResourceLocation("textures/misc/unknown_pack.png"); + + private static final File rootFolder = new File("config/betterquesting/resources/"); + private static final Splitter entryNameSplitter = Splitter.on('/').omitEmptyStrings().limit(3); + private List zipList = null; + private BufferedImage bufferedImage = null; + + @Nonnull + @Override + public InputStream getInputStream(@Nonnull ResourceLocation loc) throws IOException { + String locName = locationToName(loc); + + for (ZipFile zipfile : getZipFiles()) { + ZipEntry zipentry = zipfile.getEntry(locName); + + if (zipentry != null) { + return zipfile.getInputStream(zipentry); + } + } + + throw new ResourcePackFileNotFoundException(rootFolder, locName); + } + + @Override + public boolean resourceExists(@Nonnull ResourceLocation loc) { + String locName = locationToName(loc); - return hashset; - } - - @Override - public T getPackMetadata(@Nonnull MetadataSerializer meta, @Nonnull String s) - { - return null; - } - - @Nonnull - @Override - public BufferedImage getPackImage() - { - if(bufferedImage != null) return bufferedImage; - - try - { - bufferedImage = TextureUtil.readBufferedImage(Minecraft.getMinecraft().getResourceManager().getResource(UNKNOWN_PACK_TEXTURE).getInputStream()); + try { + for (ZipFile zipfile : getZipFiles()) { + ZipEntry zipentry = zipfile.getEntry(locName); + + if (zipentry != null) { + return true; } - catch (IOException ioexception) - { - throw new Error("Couldn't bind resource pack icon", ioexception); + } + } catch (Exception ignored) { } + + return false; + } + + @Override + @Nonnull + public Set getResourceDomains() { + HashSet hashset = Sets.newHashSet(); + + try { + for (ZipFile f : getZipFiles()) { + hashset.addAll(GetZipDomains(f)); + } + } catch (Exception ignored) { } + + return hashset; + } + + private Set GetZipDomains(ZipFile zipfile) { + Enumeration enumeration = zipfile.entries(); + HashSet hashset = Sets.newHashSet(); + + while (enumeration.hasMoreElements()) { + ZipEntry zipentry = enumeration.nextElement(); + String s = zipentry.getName(); + + if (s.startsWith("assets/")) { + ArrayList arraylist = Lists.newArrayList(entryNameSplitter.split(s)); + + if (arraylist.size() > 1) { + String s1 = arraylist.get(1); + + if (!s1.equals(s1.toLowerCase())) { + this.logNameNotLowercase(s1, zipfile.getName()); + } else { + hashset.add(s1); + } } - - return bufferedImage; - } - - @Nonnull - @Override - public String getPackName() - { - return BetterQuesting.NAME + "_files"; - } - - private List getZipFiles() - { - if(zipList != null) return zipList; - - if(!rootFolder.exists() && !rootFolder.mkdirs()) - { - return Collections.emptyList(); - } - - File[] files = rootFolder.listFiles(); - if(files == null || files.length <= 0) return Collections.emptyList(); - - zipList = new ArrayList<>(); - - for(File f : files) - { - if (f.exists() && f.isFile()) - { - try - { - zipList.add(new ZipFile(f)); - } catch(Exception ignored){} - } - } - - return zipList; + } } - private static String locationToName(ResourceLocation loc) - { - return String.format("%s/%s/%s", "assets", loc.getNamespace(), loc.getPath()); + return hashset; + } + + @Override + public T getPackMetadata(@Nonnull MetadataSerializer meta, @Nonnull String s) { + return null; + } + + @Nonnull + @Override + public BufferedImage getPackImage() { + if (bufferedImage != null) { return bufferedImage; } + + try { + bufferedImage = TextureUtil.readBufferedImage( + Minecraft.getMinecraft().getResourceManager().getResource(UNKNOWN_PACK_TEXTURE).getInputStream()); + } catch (IOException ioexception) { + throw new Error("Couldn't bind resource pack icon", ioexception); + } + + return bufferedImage; + } + + @Nonnull + @Override + public String getPackName() { + return BetterQuesting.NAME + "_files"; + } + + private List getZipFiles() { + if (zipList != null) { return zipList; } + + if (!rootFolder.exists() && !rootFolder.mkdirs()) { + return Collections.emptyList(); } - private void logNameNotLowercase(String name, String file) - { - BetterQuesting.logger.log(Level.WARN, "ResourcePack: ignored non-lowercase namespace: {} in {}", new Object[] {name, file}); + File[] files = rootFolder.listFiles(); + if (files == null || files.length == 0) { return Collections.emptyList(); } + + zipList = new ArrayList<>(); + + for (File f : files) { + if (f.exists() && f.isFile()) { + try { + zipList.add(new ZipFile(f)); + } catch (Exception ignored) { } + } } - - @Override - public void finalize() throws Throwable - { - this.close(); - super.finalize(); + + return zipList; + } + + private static String locationToName(ResourceLocation loc) { + return String.format("%s/%s/%s", "assets", loc.getNamespace(), loc.getPath()); + } + + private void logNameNotLowercase(String name, String file) { + BetterQuesting.logger.log(Level.WARN, "ResourcePack: ignored non-lowercase namespace: {} in {}", + new Object[] { name, file }); + } + + @Override + protected void finalize() throws Throwable { + this.close(); + super.finalize(); + } + + @Override + public void close() throws IOException { + if (zipList != null) { + for (ZipFile zip : zipList) { + if (zip != null) { + zip.close(); + } + } + + zipList = null; } - - @Override - public void close() throws IOException - { - if(zipList != null) - { - for(ZipFile zip : zipList) - { - if(zip != null) - { - zip.close(); - } - } - - zipList = null; - } - } + } } diff --git a/src/main/java/betterquesting/misc/QuestResourcesFolder.java b/src/main/java/betterquesting/misc/QuestResourcesFolder.java index e9d41fe7d..5aa46c8f7 100644 --- a/src/main/java/betterquesting/misc/QuestResourcesFolder.java +++ b/src/main/java/betterquesting/misc/QuestResourcesFolder.java @@ -13,105 +13,90 @@ import javax.annotation.Nonnull; import java.awt.image.BufferedImage; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; import java.util.Collections; import java.util.HashSet; import java.util.Set; -public class QuestResourcesFolder implements IResourcePack -{ - private static final ResourceLocation UNKNOWN_PACK_TEXTURE = new ResourceLocation("textures/misc/unknown_pack.png"); - - private static final File rootFolder = new File("config/betterquesting/resources/"); - private BufferedImage bufferedImage = null; - - @Nonnull - @Override - public InputStream getInputStream(@Nonnull ResourceLocation location) throws IOException - { - if(!resourceExists(location)) - { - throw new ResourcePackFileNotFoundException(rootFolder, location.toString()); - } - - // TODO: Figure out if we can fix UTF8 encoding from here - return new FileInputStream(new File(rootFolder.getPath() + "/" + location.getNamespace(), location.getPath())); - } - - @Override - public boolean resourceExists(@Nonnull ResourceLocation location) - { - File res = new File(rootFolder.getPath() + "/" + location.getNamespace(), location.getPath()); - return res.exists(); - } - - @Nonnull - @Override - public Set getResourceDomains() - { - if(!rootFolder.exists() && !rootFolder.mkdirs()) - { - return Collections.emptySet(); - } - - String[] content = rootFolder.list(); - if(content == null || content.length <= 0) return Collections.emptySet(); - - HashSet folders = new HashSet<>(); - for(String s : content) - { - File f = new File(rootFolder, s); - - if(f.exists() && f.isDirectory()) - { - if(!f.getName().equals(f.getName().toLowerCase())) - { - logNameNotLowercase(f.getName(), f.toString()); - } else - { - folders.add(f.getName()); - } - } - } - - return folders; - } - - @Override - public T getPackMetadata(@Nonnull MetadataSerializer meta, @Nonnull String s) - { - return null; - } - - @Nonnull - @Override - public BufferedImage getPackImage() - { - if(bufferedImage != null) return bufferedImage; - - try - { - bufferedImage = TextureUtil.readBufferedImage(Minecraft.getMinecraft().getResourceManager().getResource(UNKNOWN_PACK_TEXTURE).getInputStream()); - } - catch (IOException ioexception) - { - throw new Error("Couldn't bind resource pack icon", ioexception); +public class QuestResourcesFolder implements IResourcePack { + private static final ResourceLocation UNKNOWN_PACK_TEXTURE = new ResourceLocation("textures/misc/unknown_pack.png"); + + private static final File rootFolder = new File("config/betterquesting/resources/"); + private BufferedImage bufferedImage = null; + + @Nonnull + @Override + public InputStream getInputStream(@Nonnull ResourceLocation location) throws IOException { + if (!resourceExists(location)) { + throw new ResourcePackFileNotFoundException(rootFolder, location.toString()); + } + + // TODO: Figure out if we can fix UTF8 encoding from here + return Files.newInputStream(new File(rootFolder.getPath() + "/" + location.getNamespace(), location.getPath()).toPath()); + } + + @Override + public boolean resourceExists(@Nonnull ResourceLocation location) { + File res = new File(rootFolder.getPath() + "/" + location.getNamespace(), location.getPath()); + return res.exists(); + } + + @Nonnull + @Override + public Set getResourceDomains() { + if (!rootFolder.exists() && !rootFolder.mkdirs()) { + return Collections.emptySet(); + } + + String[] content = rootFolder.list(); + if (content == null || content.length == 0) { return Collections.emptySet(); } + + HashSet folders = new HashSet<>(); + for (String s : content) { + File f = new File(rootFolder, s); + + if (f.exists() && f.isDirectory()) { + if (!f.getName().equals(f.getName().toLowerCase())) { + logNameNotLowercase(f.getName(), f.toString()); + } else { + folders.add(f.getName()); } - - return bufferedImage; - } - - @Nonnull - @Override - public String getPackName() - { - return BetterQuesting.NAME + "_folders"; - } - - private void logNameNotLowercase(String name, String file) - { - BetterQuesting.logger.log(Level.WARN, "ResourcePack: ignored non-lowercase namespace: {} in {}", new Object[] {name, file}); + } } + + return folders; + } + + @Override + public T getPackMetadata(@Nonnull MetadataSerializer meta, @Nonnull String s) { + return null; + } + + @Nonnull + @Override + public BufferedImage getPackImage() { + if (bufferedImage != null) { return bufferedImage; } + + try { + bufferedImage = TextureUtil.readBufferedImage( + Minecraft.getMinecraft().getResourceManager().getResource(UNKNOWN_PACK_TEXTURE).getInputStream()); + } catch (IOException ioexception) { + throw new Error("Couldn't bind resource pack icon", ioexception); + } + + return bufferedImage; + } + + @Nonnull + @Override + public String getPackName() { + return BetterQuesting.NAME + "_folders"; + } + + private void logNameNotLowercase(String name, String file) { + BetterQuesting.logger.log(Level.WARN, "ResourcePack: ignored non-lowercase namespace: {} in {}", + new Object[] { name, file }); + } } diff --git a/src/main/java/betterquesting/misc/Util.java b/src/main/java/betterquesting/misc/Util.java new file mode 100644 index 000000000..a8f1886fc --- /dev/null +++ b/src/main/java/betterquesting/misc/Util.java @@ -0,0 +1,40 @@ +package betterquesting.misc; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +public class Util { + public static Iterable closedOpenRange(int from, int to, boolean reverse) { + return reverse ? () -> new Iterator() { + int curr = to - 1; + + @Override + public boolean hasNext() { + return curr >= from; + } + + @Override + public Integer next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return curr--; + } + } : () -> new Iterator() { + int curr = from; + + @Override + public boolean hasNext() { + return curr < to; + } + + @Override + public Integer next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return curr++; + } + }; + } +} diff --git a/src/main/java/betterquesting/network/BetterQuestingPacketHandler.java b/src/main/java/betterquesting/network/BetterQuestingPacketHandler.java new file mode 100644 index 000000000..1164909f3 --- /dev/null +++ b/src/main/java/betterquesting/network/BetterQuestingPacketHandler.java @@ -0,0 +1,16 @@ +package betterquesting.network; + +import betterquesting.core.BetterQuesting; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; +import net.minecraftforge.fml.relauncher.Side; + +public class BetterQuestingPacketHandler { + public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(BetterQuesting.MODID); + + public static void init() { + INSTANCE.registerMessage(PacketQuesting.HandleClient.class, PacketQuesting.class, 0, Side.CLIENT); + INSTANCE.registerMessage(PacketQuesting.HandleServer.class, PacketQuesting.class, 0, Side.SERVER); + INSTANCE.registerMessage(new PacketSetupStation.Handler(), PacketSetupStation.class, 1, Side.SERVER); + } +} diff --git a/src/main/java/betterquesting/network/PacketAssembly.java b/src/main/java/betterquesting/network/PacketAssembly.java index c2999dc3f..73073580f 100644 --- a/src/main/java/betterquesting/network/PacketAssembly.java +++ b/src/main/java/betterquesting/network/PacketAssembly.java @@ -14,151 +14,129 @@ import java.util.*; import java.util.zip.GZIPInputStream; -public final class PacketAssembly -{ - public static final PacketAssembly INSTANCE = new PacketAssembly(); - - // TODO: Allow for simultaneous packet assembly (may not be necessary) - // TODO: Implement PROPER thread safety that doesn't cause dirty read/writes - // TODO: Add a scheduler to bulk up multiple data packets to send on the next tick (also may be unnecessary) - // Player assigned packet buffers - private final HashMap buffer = new HashMap<>(); - - // Internal server packet buffer (server to server or client side) - private byte[] serverBuf = null; - //private int id = 0; - - private static final int bufSize = 20480; // 20KB - - public List splitPacket(NBTTagCompound tags) - { - try - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - CompressedStreamTools.writeCompressed(tags, baos); - baos.flush(); - byte[] data = baos.toByteArray(); - baos.close(); - int req = MathHelper.ceil(data.length/(float)bufSize); - List pkts = new ArrayList<>(req); - - for(int p = 0; p < req; p++) - { - int idx = p*bufSize; - int s = Math.min(data.length - idx, bufSize); - NBTTagCompound container = new NBTTagCompound(); - byte[] part = new byte[s]; - - System.arraycopy(data, idx, part, 0, s); - - container.setInteger("size", data.length); // If the buffer isn't yet created, how big is it - container.setInteger("index", idx); // Where should this piece start writing too - container.setBoolean("end", p == req - 1); - container.setTag("data", new NBTTagByteArray(part)); // The raw byte data to write - - pkts.add(container); - } - - return pkts; - } catch(Exception e) - { - BetterQuesting.logger.error("Unable to split build packet!", e); - return Collections.emptyList(); - } - } - - /** - * Appends a packet onto the buffer and returns an assembled NBTTagCompound when complete - */ - public NBTTagCompound assemblePacket(UUID owner, NBTTagCompound tags) - { - int size = tags.getInteger("size"); - int index = tags.getInteger("index"); - boolean end = tags.getBoolean("end"); - byte[] data = tags.getByteArray("data"); - - byte[] tmp = getBuffer(owner); - - if(tmp == null) - { - tmp = new byte[size]; - setBuffer(owner, tmp); - } else if(tmp.length != size) - { - BetterQuesting.logger.error("Unexpected change in BQ packet byte length: " + size + " > " + tmp.length); - clearBuffer(owner); - return null; - } - - System.arraycopy(data, 0, tmp, index, data.length); +public final class PacketAssembly { + public static final PacketAssembly INSTANCE = new PacketAssembly(); + + // TODO: Allow for simultaneous packet assembly (may not be necessary) + // TODO: Implement PROPER thread safety that doesn't cause dirty read/writes + // TODO: Add a scheduler to bulk up multiple data packets to send on the next tick (also may be unnecessary) + // Player assigned packet buffers + private final HashMap buffer = new HashMap<>(); + + // Internal server packet buffer (server to server or client side) + private byte[] serverBuf = null; + //private int id = 0; + + private static final int bufSize = 20480; // 20KB + + public List splitPacket(NBTTagCompound tags) { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + CompressedStreamTools.writeCompressed(tags, baos); + baos.flush(); + byte[] data = baos.toByteArray(); + baos.close(); + int req = MathHelper.ceil(data.length / (float) bufSize); + List pkts = new ArrayList<>(req); + + for (int p = 0; p < req; p++) { + int idx = p * bufSize; + int s = Math.min(data.length - idx, bufSize); + NBTTagCompound container = new NBTTagCompound(); + byte[] part = new byte[s]; + + System.arraycopy(data, idx, part, 0, s); + + container.setInteger("size", data.length); // If the buffer isn't yet created, how big is it + container.setInteger("index", idx); // Where should this piece start writing too + container.setBoolean("end", p == req - 1); + container.setTag("data", new NBTTagByteArray(part)); // The raw byte data to write + + pkts.add(container); + } + + return pkts; + } catch (Exception e) { + BetterQuesting.logger.error("Unable to split build packet!", e); + return Collections.emptyList(); + } + } + + /** + * Appends a packet onto the buffer and returns an assembled NBTTagCompound when complete + */ + public NBTTagCompound assemblePacket(UUID owner, NBTTagCompound tags) { + int size = tags.getInteger("size"); + int index = tags.getInteger("index"); + boolean end = tags.getBoolean("end"); + byte[] data = tags.getByteArray("data"); + + byte[] tmp = getBuffer(owner); + + if (tmp == null) { + tmp = new byte[size]; + setBuffer(owner, tmp); + } else if (tmp.length != size) { + BetterQuesting.logger.error("Unexpected change in BQ packet byte length: " + size + " > " + tmp.length); + clearBuffer(owner); + return null; + } + + System.arraycopy(data, 0, tmp, index, data.length); /*for(int i = 0; i < data.length && index + i < size; i++) { tmp[index + i] = data[i]; }*/ - - if(end) - { - clearBuffer(owner); - - try - { - DataInputStream dis = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(tmp)))); - NBTTagCompound tag = CompressedStreamTools.read(dis , NBTSizeTracker.INFINITE); - dis.close(); - return tag; - } catch(Exception e) - { - throw new RuntimeException("Unable to assemble BQ packet", e); - } - } - - return null; - } - - public byte[] getBuffer(UUID owner) - { - if(owner == null) - { - return serverBuf; - } else - { - synchronized(buffer) - { - return buffer.get(owner); - } - } - } - - public void setBuffer(UUID owner, byte[] value) - { - if(owner == null) - { - serverBuf = value; - } else - { - synchronized(buffer) - { - if(buffer.containsKey(owner)) - { - throw new IllegalStateException("Attepted to start more than one BQ packet assembly for UUID " + owner.toString()); - } - - buffer.put(owner, value); - } - } - } - - public void clearBuffer(UUID owner) - { - if(owner == null) - { - serverBuf = null; - } else - { - synchronized(buffer) - { - buffer.remove(owner); - } - } - } + + if (end) { + clearBuffer(owner); + + try { + DataInputStream dis = + new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(tmp)))); + NBTTagCompound tag = CompressedStreamTools.read(dis, NBTSizeTracker.INFINITE); + dis.close(); + return tag; + } catch (Exception e) { + throw new RuntimeException("Unable to assemble BQ packet", e); + } + } + + return null; + } + + public byte[] getBuffer(UUID owner) { + if (owner == null) { + return serverBuf; + } else { + synchronized (buffer) { + return buffer.get(owner); + } + } + } + + public void setBuffer(UUID owner, byte[] value) { + if (owner == null) { + serverBuf = value; + } else { + synchronized (buffer) { + if (buffer.containsKey(owner)) { + throw new IllegalStateException( + "Attepted to start more than one BQ packet assembly for UUID " + owner); + } + + buffer.put(owner, value); + } + } + } + + public void clearBuffer(UUID owner) { + if (owner == null) { + serverBuf = null; + } else { + synchronized (buffer) { + buffer.remove(owner); + } + } + } } diff --git a/src/main/java/betterquesting/network/PacketQuesting.java b/src/main/java/betterquesting/network/PacketQuesting.java index ead327a8b..cbf7e0404 100644 --- a/src/main/java/betterquesting/network/PacketQuesting.java +++ b/src/main/java/betterquesting/network/PacketQuesting.java @@ -16,104 +16,97 @@ import java.util.function.Consumer; -public class PacketQuesting implements IMessage -{ - protected NBTTagCompound tags = new NBTTagCompound(); - - @SuppressWarnings("unused") - public PacketQuesting() // For use only by forge - { - } - - public PacketQuesting(NBTTagCompound tags) // Use PacketDataTypes to instantiate new packets - { - this.tags = tags; - } - - @Override - public void fromBytes(ByteBuf buf) - { - tags = ByteBufUtils.readTag(buf); - } - - @Override - public void toBytes(ByteBuf buf) - { - ByteBufUtils.writeTag(buf, tags); - } - - public static class HandleServer implements IMessageHandler - { - @Override - public IMessage onMessage(PacketQuesting packet, MessageContext ctx) - { - if(packet == null || packet.tags == null || ctx.getServerHandler().player.getServer() == null) - { - BetterQuesting.logger.log(Level.ERROR, "A critical NPE error occured during while handling a BetterQuesting packet server side", new NullPointerException()); - return null; - } - - final EntityPlayerMP sender = ctx.getServerHandler().player; - final NBTTagCompound message = PacketAssembly.INSTANCE.assemblePacket(sender == null? null : QuestingAPI.getQuestingUUID(sender),packet.tags); - - if(message == null) - { - return null; - } else if(!message.hasKey("ID")) - { - BetterQuesting.logger.log(Level.WARN, "Recieved a packet server side without an ID"); - return null; - } - - final Consumer> method = PacketTypeRegistry.INSTANCE.getServerHandler(new ResourceLocation(message.getString("ID"))); - - if(method == null) - { - BetterQuesting.logger.log(Level.WARN, "Recieved a packet server side with an invalid ID: " + message.getString("ID")); - return null; - } else if(sender != null) - { - sender.getServer().addScheduledTask(() -> method.accept(new Tuple<>(message, sender))); - } - - return null; - } - } - - public static class HandleClient implements IMessageHandler - { - @Override - public IMessage onMessage(PacketQuesting packet, MessageContext ctx) - { - if(packet == null || packet.tags == null) - { - BetterQuesting.logger.log(Level.ERROR, "A critical NPE error occured during while handling a BetterQuesting packet client side", new NullPointerException()); - return null; - } - - final NBTTagCompound message = PacketAssembly.INSTANCE.assemblePacket(null, packet.tags); - - if(message == null) - { - return null; - } else if(!message.hasKey("ID")) - { - BetterQuesting.logger.log(Level.WARN, "Recieved a packet server side without an ID"); - return null; - } - - final Consumer method = PacketTypeRegistry.INSTANCE.getClientHandler(new ResourceLocation(message.getString("ID"))); - - if(method == null) - { - BetterQuesting.logger.log(Level.WARN, "Recieved a packet server side with an invalid ID: " + message.getString("ID")); - return null; - } else - { - Minecraft.getMinecraft().addScheduledTask(() -> method.accept(message)); - } - - return null; - } - } +public class PacketQuesting implements IMessage { + protected NBTTagCompound tags = new NBTTagCompound(); + + @SuppressWarnings("unused") + public PacketQuesting() // For use only by forge + { + } + + public PacketQuesting(NBTTagCompound tags) // Use PacketDataTypes to instantiate new packets + { + this.tags = tags; + } + + @Override + public void fromBytes(ByteBuf buf) { + tags = ByteBufUtils.readTag(buf); + } + + @Override + public void toBytes(ByteBuf buf) { + ByteBufUtils.writeTag(buf, tags); + } + + public static class HandleServer implements IMessageHandler { + @Override + public IMessage onMessage(PacketQuesting packet, MessageContext ctx) { + if (packet == null || packet.tags == null || ctx.getServerHandler().player.getServer() == null) { + BetterQuesting.logger.log(Level.ERROR, + "A critical NPE error occured during while handling a BetterQuesting packet server side", + new NullPointerException()); + return null; + } + + final EntityPlayerMP sender = ctx.getServerHandler().player; + final NBTTagCompound message = + PacketAssembly.INSTANCE.assemblePacket(sender == null ? null : QuestingAPI.getQuestingUUID(sender), + packet.tags); + + if (message == null) { + return null; + } else if (!message.hasKey("ID")) { + BetterQuesting.logger.log(Level.WARN, "Recieved a packet server side without an ID"); + return null; + } + + final Consumer> method = + PacketTypeRegistry.INSTANCE.getServerHandler(new ResourceLocation(message.getString("ID"))); + + if (method == null) { + BetterQuesting.logger.log(Level.WARN, + "Recieved a packet server side with an invalid ID: " + message.getString("ID")); + return null; + } else if (sender != null) { + sender.getServer().addScheduledTask(() -> method.accept(new Tuple<>(message, sender))); + } + + return null; + } + } + + public static class HandleClient implements IMessageHandler { + @Override + public IMessage onMessage(PacketQuesting packet, MessageContext ctx) { + if (packet == null || packet.tags == null) { + BetterQuesting.logger.log(Level.ERROR, + "A critical NPE error occured during while handling a BetterQuesting packet client side", + new NullPointerException()); + return null; + } + + final NBTTagCompound message = PacketAssembly.INSTANCE.assemblePacket(null, packet.tags); + + if (message == null) { + return null; + } else if (!message.hasKey("ID")) { + BetterQuesting.logger.log(Level.WARN, "Recieved a packet server side without an ID"); + return null; + } + + final Consumer method = + PacketTypeRegistry.INSTANCE.getClientHandler(new ResourceLocation(message.getString("ID"))); + + if (method == null) { + BetterQuesting.logger.log(Level.WARN, + "Recieved a packet server side with an invalid ID: " + message.getString("ID")); + return null; + } else { + Minecraft.getMinecraft().addScheduledTask(() -> method.accept(message)); + } + + return null; + } + } } diff --git a/src/main/java/betterquesting/network/PacketSender.java b/src/main/java/betterquesting/network/PacketSender.java index b9e4f54a0..33deb4aee 100644 --- a/src/main/java/betterquesting/network/PacketSender.java +++ b/src/main/java/betterquesting/network/PacketSender.java @@ -10,76 +10,64 @@ import java.util.List; -public class PacketSender implements IPacketSender -{ - public static final PacketSender INSTANCE = new PacketSender(); - - @Override - public void sendToPlayers(QuestingPacket payload, EntityPlayerMP... players) - { - payload.getPayload().setString("ID", payload.getHandler().toString()); - - BQThreadedIO.INSTANCE.enqueue(() -> { - List fragments = PacketAssembly.INSTANCE.splitPacket(payload.getPayload()); - for(EntityPlayerMP p : players) - { - for(NBTTagCompound tag : fragments) - { - BetterQuesting.instance.network.sendTo(new PacketQuesting(tag), p); - } - } - }); - } - - @Override - public void sendToAll(QuestingPacket payload) - { - payload.getPayload().setString("ID", payload.getHandler().toString()); - - BQThreadedIO.INSTANCE.enqueue(() -> { - for(NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) - { - BetterQuesting.instance.network.sendToAll(new PacketQuesting(p)); - } - }); - } - - @Override - public void sendToServer(QuestingPacket payload) - { - payload.getPayload().setString("ID", payload.getHandler().toString()); - - BQThreadedIO.INSTANCE.enqueue(() -> { - for(NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) - { - BetterQuesting.instance.network.sendToServer(new PacketQuesting(p)); - } - }); - } - - @Override - public void sendToAround(QuestingPacket payload, TargetPoint point) - { - payload.getPayload().setString("ID", payload.getHandler().toString()); - - BQThreadedIO.INSTANCE.enqueue(() -> { - for(NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) - { - BetterQuesting.instance.network.sendToAllAround(new PacketQuesting(p), point); - } - }); - } - - @Override - public void sendToDimension(QuestingPacket payload, int dimension) - { - payload.getPayload().setString("ID", payload.getHandler().toString()); - - BQThreadedIO.INSTANCE.enqueue(() -> { - for(NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) - { - BetterQuesting.instance.network.sendToDimension(new PacketQuesting(p), dimension); - } - }); - } +public class PacketSender implements IPacketSender { + public static final PacketSender INSTANCE = new PacketSender(); + + @Override + public void sendToPlayers(QuestingPacket payload, EntityPlayerMP... players) { + payload.getPayload().setString("ID", payload.getHandler().toString()); + + BQThreadedIO.INSTANCE.enqueue(() -> { + List fragments = PacketAssembly.INSTANCE.splitPacket(payload.getPayload()); + for (EntityPlayerMP p : players) { + for (NBTTagCompound tag : fragments) { + BetterQuesting.instance.network.sendTo(new PacketQuesting(tag), p); + } + } + }); + } + + @Override + public void sendToAll(QuestingPacket payload) { + payload.getPayload().setString("ID", payload.getHandler().toString()); + + BQThreadedIO.INSTANCE.enqueue(() -> { + for (NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) { + BetterQuesting.instance.network.sendToAll(new PacketQuesting(p)); + } + }); + } + + @Override + public void sendToServer(QuestingPacket payload) { + payload.getPayload().setString("ID", payload.getHandler().toString()); + + BQThreadedIO.INSTANCE.enqueue(() -> { + for (NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) { + BetterQuesting.instance.network.sendToServer(new PacketQuesting(p)); + } + }); + } + + @Override + public void sendToAround(QuestingPacket payload, TargetPoint point) { + payload.getPayload().setString("ID", payload.getHandler().toString()); + + BQThreadedIO.INSTANCE.enqueue(() -> { + for (NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) { + BetterQuesting.instance.network.sendToAllAround(new PacketQuesting(p), point); + } + }); + } + + @Override + public void sendToDimension(QuestingPacket payload, int dimension) { + payload.getPayload().setString("ID", payload.getHandler().toString()); + + BQThreadedIO.INSTANCE.enqueue(() -> { + for (NBTTagCompound p : PacketAssembly.INSTANCE.splitPacket(payload.getPayload())) { + BetterQuesting.instance.network.sendToDimension(new PacketQuesting(p), dimension); + } + }); + } } diff --git a/src/main/java/betterquesting/network/PacketSetupStation.java b/src/main/java/betterquesting/network/PacketSetupStation.java new file mode 100644 index 000000000..ae8924b0b --- /dev/null +++ b/src/main/java/betterquesting/network/PacketSetupStation.java @@ -0,0 +1,77 @@ +package betterquesting.network; + +import betterquesting.blocks.TileSubmitStation; +import betterquesting.client.gui2.inventory.ContainerSubmitStation; +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.WorldServer; +import net.minecraftforge.fml.common.network.simpleimpl.IMessage; +import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; +import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; + +public class PacketSetupStation implements IMessage { + private BlockPos stationPos; + private int questId; + private int taskId; + private byte sync; + + public PacketSetupStation() { } + + public PacketSetupStation(BlockPos stationPos, int questId, int taskId, byte sync) { + this.stationPos = stationPos; + this.questId = questId; + this.taskId = taskId; + this.sync = sync; + } + + @Override + public void fromBytes(ByteBuf buf) { + stationPos = BlockPos.fromLong(buf.readLong()); + questId = buf.readInt(); + taskId = buf.readInt(); + sync = buf.readByte(); + } + + @Override + public void toBytes(ByteBuf buf) { + buf.writeLong(stationPos.toLong()); + buf.writeInt(questId); + buf.writeInt(taskId); + buf.writeByte(sync); + } + + static class Handler implements IMessageHandler { + @Override + public IMessage onMessage(PacketSetupStation message, MessageContext ctx) { + EntityPlayerMP player = ctx.getServerHandler().player; + WorldServer world = player.getServerWorld(); + BlockPos stationPos = message.stationPos; + int questId = message.questId; + int taskId = message.taskId; + byte sync = message.sync; + world.addScheduledTask(() -> { + TileEntity tile = world.getTileEntity(stationPos); + if (!(tile instanceof TileSubmitStation)) { + return; + } + TileSubmitStation oss = (TileSubmitStation) tile; + if (!oss.isUsableByPlayer(player)) { + return; + } + Container container = player.openContainer; + if (!(container instanceof ContainerSubmitStation)) { + return; + } + ContainerSubmitStation containerSS = (ContainerSubmitStation) container; + if (containerSS.tile != oss || containerSS.windowId != sync) { //If Vanilla checks windowId then there is some point in it, right? + return; + } + oss.setupTask(player.getUniqueID(), questId, taskId); + }); + return null; + } + } +} diff --git a/src/main/java/betterquesting/network/PacketTypeRegistry.java b/src/main/java/betterquesting/network/PacketTypeRegistry.java index b3dcdfaff..49895ab3a 100644 --- a/src/main/java/betterquesting/network/PacketTypeRegistry.java +++ b/src/main/java/betterquesting/network/PacketTypeRegistry.java @@ -14,70 +14,64 @@ import java.util.HashMap; import java.util.function.Consumer; -public class PacketTypeRegistry implements IPacketRegistry -{ - public static final PacketTypeRegistry INSTANCE = new PacketTypeRegistry(); - - private final HashMap>> serverHandlers = new HashMap<>(); - private final HashMap> clientHandlers = new HashMap<>(); - - public void init() - { - NetQuestSync.registerHandler(); - NetQuestEdit.registerHandler(); - NetQuestAction.registerHandler(); - - NetChapterSync.registerHandler(); - NetChapterEdit.registerHandler(); - - NetPartySync.registerHandler(); - NetPartyAction.registerHandler(); - NetInviteSync.registerHandler(); - - NetLifeSync.registerHandler(); - NetNameSync.registerHandler(); - NetNotices.registerHandler(); - NetStationEdit.registerHandler(); - NetImport.registerHandler(); - NetSettingSync.registerHandler(); - - NetCacheSync.registerHandler(); - NetBulkSync.registerHandler(); - } - - @Override - public void registerServerHandler(@Nonnull ResourceLocation idName, @Nonnull Consumer> method) - { - if(serverHandlers.containsKey(idName)) - { - throw new IllegalArgumentException("Cannot register dupliate packet handler: " + idName); - } - - serverHandlers.put(idName, method); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerClientHandler(@Nonnull ResourceLocation idName, @Nonnull Consumer method) - { - if(clientHandlers.containsKey(idName)) - { - throw new IllegalArgumentException("Cannot register dupliate packet handler: " + idName); - } - - clientHandlers.put(idName, method); - } - - @Nullable - public Consumer> getServerHandler(@Nonnull ResourceLocation idName) - { - return serverHandlers.get(idName); +//TODO Clean up this trainwreck +public class PacketTypeRegistry implements IPacketRegistry { + public static final PacketTypeRegistry INSTANCE = new PacketTypeRegistry(); + + private final HashMap>> serverHandlers = + new HashMap<>(); + private final HashMap> clientHandlers = new HashMap<>(); + + public void init() { + NetQuestSync.registerHandler(); + NetQuestEdit.registerHandler(); + NetQuestAction.registerHandler(); + + NetChapterSync.registerHandler(); + NetChapterEdit.registerHandler(); + + NetPartySync.registerHandler(); + NetPartyAction.registerHandler(); + NetInviteSync.registerHandler(); + + NetLifeSync.registerHandler(); + NetNameSync.registerHandler(); + NetNotices.registerHandler(); + NetImport.registerHandler(); + NetSettingSync.registerHandler(); + + NetCacheSync.registerHandler(); + NetBulkSync.registerHandler(); + } + + @Override + public void registerServerHandler(@Nonnull ResourceLocation idName, + @Nonnull Consumer> method) { + if (serverHandlers.containsKey(idName)) { + throw new IllegalArgumentException("Cannot register dupliate packet handler: " + idName); } - - @Nullable - @SideOnly(Side.CLIENT) - public Consumer getClientHandler(@Nonnull ResourceLocation idName) - { - return clientHandlers.get(idName); + + serverHandlers.put(idName, method); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerClientHandler(@Nonnull ResourceLocation idName, @Nonnull Consumer method) { + if (clientHandlers.containsKey(idName)) { + throw new IllegalArgumentException("Cannot register dupliate packet handler: " + idName); } + + clientHandlers.put(idName, method); + } + + @Nullable + public Consumer> getServerHandler(@Nonnull ResourceLocation idName) { + return serverHandlers.get(idName); + } + + @Nullable + @SideOnly(Side.CLIENT) + public Consumer getClientHandler(@Nonnull ResourceLocation idName) { + return clientHandlers.get(idName); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetBulkSync.java b/src/main/java/betterquesting/network/handlers/NetBulkSync.java index 7220fa766..2aa3a673e 100644 --- a/src/main/java/betterquesting/network/handlers/NetBulkSync.java +++ b/src/main/java/betterquesting/network/handlers/NetBulkSync.java @@ -27,82 +27,73 @@ public class NetBulkSync // Clears local data and negotiates a full resync with the server { - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:main_sync"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetBulkSync::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetBulkSync::onClient); - } + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:main_sync"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetBulkSync::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetBulkSync::onClient); } - - public static void sendReset(@Nullable EntityPlayerMP player, boolean reset, boolean respond) + } + + public static void sendReset(@Nullable EntityPlayerMP player, boolean reset, boolean respond) { + NBTTagCompound payload = new NBTTagCompound(); + payload.setBoolean("reset", reset); + payload.setBoolean("respond", respond); + + if (player == null) // Don't use this on a large server unless absolutely necessary! { - NBTTagCompound payload = new NBTTagCompound(); - payload.setBoolean("reset", reset); - payload.setBoolean("respond", respond); - - if(player == null) // Don't use this on a large server unless absolutely necessary! - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } else - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } else { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); } - - public static void sendSync(@Nonnull EntityPlayerMP player) - { - boolean nameChanged = NameCache.INSTANCE.updateName(player); - UUID playerID = QuestingAPI.getQuestingUUID(player); - - NetSettingSync.sendSync(player); - NetQuestSync.sendSync(player, null, true, true); - NetChapterSync.sendSync(player, null); - NetLifeSync.sendSync(new EntityPlayerMP[]{player}, new UUID[]{playerID}); - DBEntry party = PartyManager.INSTANCE.getParty(playerID); - List> invites = PartyInvitations.INSTANCE.getPartyInvites(playerID); - int partyCount = invites.size() + (party == null ? 0 : 1); - if(partyCount > 0) - { - int[] pids = new int[partyCount]; - for(int i = 0; i < invites.size(); i++) - { - pids[i] = invites.get(i).getKey(); - } - if(party != null) pids[partyCount - 1] = party.getID(); - NetPartySync.sendSync(new EntityPlayerMP[]{player}, pids); - } - if(party != null) - { - NetNameSync.quickSync(nameChanged ? null : player, party.getID()); - } else - { - NetNameSync.sendNames(new EntityPlayerMP[]{player}, new UUID[]{playerID}, null); - } - NetInviteSync.sendSync(player); - NetCacheSync.sendSync(player); + } + + public static void sendSync(@Nonnull EntityPlayerMP player) { + boolean nameChanged = NameCache.INSTANCE.updateName(player); + UUID playerID = QuestingAPI.getQuestingUUID(player); + + NetSettingSync.sendSync(player); + NetQuestSync.sendSync(player, null, true, true); + NetChapterSync.sendSync(player, null); + NetLifeSync.sendSync(new EntityPlayerMP[] { player }, new UUID[] { playerID }); + DBEntry party = PartyManager.INSTANCE.getParty(playerID); + List> invites = PartyInvitations.INSTANCE.getPartyInvites(playerID); + int partyCount = invites.size() + (party == null ? 0 : 1); + if (partyCount > 0) { + int[] pids = new int[partyCount]; + for (int i = 0; i < invites.size(); i++) { + pids[i] = invites.get(i).getKey(); + } + if (party != null) { pids[partyCount - 1] = party.getID(); } + NetPartySync.sendSync(new EntityPlayerMP[] { player }, pids); + } + if (party != null) { + NetNameSync.quickSync(nameChanged ? null : player, party.getID()); + } else { + NetNameSync.sendNames(new EntityPlayerMP[] { player }, new UUID[] { playerID }, null); } - - private static void onServer(Tuple message) + NetInviteSync.sendSync(player); + NetCacheSync.sendSync(player); + } + + private static void onServer(Tuple message) { + sendSync(message.getSecond()); // Can include more sync options at a later date + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + if (message.getBoolean("reset") && + !Minecraft.getMinecraft().isIntegratedServerRunning()) // DON'T do this on LAN hosts { - sendSync(message.getSecond()); // Can include more sync options at a later date + SaveLoadHandler.INSTANCE.unloadDatabases(); } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) + + if (message.getBoolean( + "respond")) // Client doesn't really have to honour this but it would mess with things otherwise { - if(message.getBoolean("reset") && !Minecraft.getMinecraft().isIntegratedServerRunning()) // DON'T do this on LAN hosts - { - SaveLoadHandler.INSTANCE.unloadDatabases(); - } - - if(message.getBoolean("respond")) // Client doesn't really have to honour this but it would mess with things otherwise - { - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, new NBTTagCompound())); - } + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, new NBTTagCompound())); } + } } diff --git a/src/main/java/betterquesting/network/handlers/NetCacheSync.java b/src/main/java/betterquesting/network/handlers/NetCacheSync.java index b1f8c4474..6a8797057 100644 --- a/src/main/java/betterquesting/network/handlers/NetCacheSync.java +++ b/src/main/java/betterquesting/network/handlers/NetCacheSync.java @@ -16,32 +16,27 @@ import javax.annotation.Nonnull; -public class NetCacheSync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:cache_sync"); - - public static void registerHandler() - { - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetCacheSync::onClient); - } - } - - public static void sendSync(@Nonnull EntityPlayerMP player) - { - QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if(qc == null) return; - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", qc.serializeNBT()); - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - EntityPlayer player = Minecraft.getMinecraft().player; - QuestCache qc = player != null ? player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null) : null; - if(qc != null) qc.deserializeNBT(message.getCompoundTag("data")); +public class NetCacheSync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:cache_sync"); + + public static void registerHandler() { + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetCacheSync::onClient); } + } + + public static void sendSync(@Nonnull EntityPlayerMP player) { + QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc == null) { return; } + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", qc.serializeNBT()); + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + EntityPlayer player = Minecraft.getMinecraft().player; + QuestCache qc = player != null ? player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null) : null; + if (qc != null) { qc.deserializeNBT(message.getCompoundTag("data")); } + } } diff --git a/src/main/java/betterquesting/network/handlers/NetChapterEdit.java b/src/main/java/betterquesting/network/handlers/NetChapterEdit.java index 62242188c..61b6ba473 100644 --- a/src/main/java/betterquesting/network/handlers/NetChapterEdit.java +++ b/src/main/java/betterquesting/network/handlers/NetChapterEdit.java @@ -23,167 +23,153 @@ import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.logging.log4j.Level; -public class NetChapterEdit -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:chapter_edit"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetChapterEdit::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetChapterEdit::onClient); - } +public class NetChapterEdit { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:chapter_edit"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetChapterEdit::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetChapterEdit::onClient); } - - @SideOnly(Side.CLIENT) - public static void sendEdit(NBTTagCompound payload) // TODO: Make these use proper methods for each action rather than directly assembling the payload - { - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + @SideOnly(Side.CLIENT) + public static void sendEdit( + NBTTagCompound payload) // TODO: Make these use proper methods for each action rather than directly assembling the payload + { + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + EntityPlayerMP sender = message.getSecond(); + MinecraftServer server = sender.getServer(); + if (server == null) { + return; // Here mostly just to keep intellisense happy } - - private static void onServer(Tuple message) + + boolean isOP = server.getPlayerList().canSendCommands(sender.getGameProfile()); + + if (!isOP) // OP pre-check { - EntityPlayerMP sender = message.getSecond(); - MinecraftServer server = sender.getServer(); - if(server == null) return; // Here mostly just to keep intellisense happy - - boolean isOP = server.getPlayerList().canSendCommands(sender.getGameProfile()); - - if(!isOP) // OP pre-check - { - BetterQuesting.logger.log(Level.WARN, "Player " + sender.getName() + " (UUID:" + QuestingAPI.getQuestingUUID(sender) + ") tried to edit chapters without OP permissions!"); - sender.sendStatusMessage(new TextComponentString(TextFormatting.RED + "You need to be OP to edit quests!"), true); - return; // Player is not operator. Do nothing - } - - NBTTagCompound tag = message.getFirst(); - int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); - - switch(action) - { - case 0: - { - editChapters(tag.getTagList("data", 10)); - break; - } - case 1: - { - deleteChapters(tag.getIntArray("chapterIDs")); - break; - } - case 2: - { - reorderChapters(tag.getIntArray("chapterIDs")); - break; - } - case 3: - { - createChapters(tag.getTagList("data", 10)); - break; - } - default: - { - BetterQuesting.logger.log(Level.ERROR, "Invalid chapter edit action '" + action + "'. Full payload:\n" + message.getFirst().toString()); - } - } + BetterQuesting.logger.log(Level.WARN, + "Player " + sender.getName() + " (UUID:" + QuestingAPI.getQuestingUUID(sender) + + ") tried to edit chapters without OP permissions!"); + sender.sendStatusMessage(new TextComponentString(TextFormatting.RED + "You need to be OP to edit quests!"), true); + return; // Player is not operator. Do nothing } - - private static void editChapters(NBTTagList data) - { - int[] ids = new int[data.tagCount()]; - for(int i = 0; i < data.tagCount(); i++) - { - NBTTagCompound entry = data.getCompoundTagAt(i); - int chapterID = entry.getInteger("chapterID"); - ids[i] = chapterID; - - IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); - if(chapter != null) chapter.readFromNBT(entry.getCompoundTag("config"), false); - } - - SaveLoadHandler.INSTANCE.markDirty(); - NetChapterSync.sendSync(null, ids); + + NBTTagCompound tag = message.getFirst(); + int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); + + switch (action) { + case 0: { + editChapters(tag.getTagList("data", 10)); + break; + } + case 1: { + deleteChapters(tag.getIntArray("chapterIDs")); + break; + } + case 2: { + reorderChapters(tag.getIntArray("chapterIDs")); + break; + } + case 3: { + createChapters(tag.getTagList("data", 10)); + break; + } + default: { + BetterQuesting.logger.log(Level.ERROR, "Invalid chapter edit action '" + action + "'. Full payload:\n" + + message.getFirst()); + } } - - private static void deleteChapters(int[] chapterIDs) - { - for(int id : chapterIDs) - { - QuestLineDatabase.INSTANCE.removeID(id); - } - - SaveLoadHandler.INSTANCE.markDirty(); - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("chapterIDs", chapterIDs); - payload.setInteger("action", 1); - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } + + private static void editChapters(NBTTagList data) { + int[] ids = new int[data.tagCount()]; + for (int i = 0; i < data.tagCount(); i++) { + NBTTagCompound entry = data.getCompoundTagAt(i); + int chapterID = entry.getInteger("chapterID"); + ids[i] = chapterID; + + IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); + if (chapter != null) { chapter.readFromNBT(entry.getCompoundTag("config"), false); } } - - private static void reorderChapters(int[] chapterIDs) - { - for(int n = 0; n < chapterIDs.length; n++) - { - QuestLineDatabase.INSTANCE.setOrderIndex(chapterIDs[n], n); - } - - SaveLoadHandler.INSTANCE.markDirty(); - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("chapterIDs", chapterIDs); - payload.setInteger("action", 2); - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + + SaveLoadHandler.INSTANCE.markDirty(); + NetChapterSync.sendSync(null, ids); + } + + private static void deleteChapters(int[] chapterIDs) { + for (int id : chapterIDs) { + QuestLineDatabase.INSTANCE.removeID(id); } - - private static void createChapters(NBTTagList data) // Includes future copy potential - { - int[] ids = new int[data.tagCount()]; - for(int i = 0; i < data.tagCount(); i++) - { - NBTTagCompound entry = data.getCompoundTagAt(i); - int chapterID = entry.hasKey("chapterID", 99) ? entry.getInteger("chapterID") : -1; - if(chapterID < 0) chapterID = QuestLineDatabase.INSTANCE.nextID(); - ids[i] = chapterID; - - IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); - if(chapter == null) chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); - if(entry.hasKey("config", 10)) chapter.readFromNBT(entry.getCompoundTag("config"), false); - } - - SaveLoadHandler.INSTANCE.markDirty(); - NetChapterSync.sendSync(null, ids); + + SaveLoadHandler.INSTANCE.markDirty(); + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("chapterIDs", chapterIDs); + payload.setInteger("action", 1); + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } + + private static void reorderChapters(int[] chapterIDs) { + for (int n = 0; n < chapterIDs.length; n++) { + QuestLineDatabase.INSTANCE.setOrderIndex(chapterIDs[n], n); } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) + + SaveLoadHandler.INSTANCE.markDirty(); + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("chapterIDs", chapterIDs); + payload.setInteger("action", 2); + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } + + private static void createChapters(NBTTagList data) // Includes future copy potential + { + int[] ids = new int[data.tagCount()]; + for (int i = 0; i < data.tagCount(); i++) { + NBTTagCompound entry = data.getCompoundTagAt(i); + int chapterID = entry.hasKey("chapterID", 99) ? entry.getInteger("chapterID") : -1; + if (chapterID < 0) { chapterID = QuestLineDatabase.INSTANCE.nextID(); } + ids[i] = chapterID; + + IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); + if (chapter == null) { chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); } + if (entry.hasKey("config", 10)) { chapter.readFromNBT(entry.getCompoundTag("config"), false); } + } + + SaveLoadHandler.INSTANCE.markDirty(); + NetChapterSync.sendSync(null, ids); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + int action = !message.hasKey("action", 99) ? -1 : message.getInteger("action"); + + switch (action) // Change to a switch statement when more actions are required { - int action = !message.hasKey("action", 99) ? -1 : message.getInteger("action"); - - switch(action) // Change to a switch statement when more actions are required - { - case 1: // Delete - { - for(int id : message.getIntArray("chapterIDs")) - { - QuestLineDatabase.INSTANCE.removeID(id); - } - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); - break; - } - case 2: // Reorder - { - int[] chapterIDs = message.getIntArray("chapterIDs"); - for(int n = 0; n < chapterIDs.length; n++) - { - QuestLineDatabase.INSTANCE.setOrderIndex(chapterIDs[n], n); - } - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); - break; - } + case 1: // Delete + { + for (int id : message.getIntArray("chapterIDs")) { + QuestLineDatabase.INSTANCE.removeID(id); + } + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); + break; + } + case 2: // Reorder + { + int[] chapterIDs = message.getIntArray("chapterIDs"); + for (int n = 0; n < chapterIDs.length; n++) { + QuestLineDatabase.INSTANCE.setOrderIndex(chapterIDs[n], n); } + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); + break; + } } + } } diff --git a/src/main/java/betterquesting/network/handlers/NetChapterSync.java b/src/main/java/betterquesting/network/handlers/NetChapterSync.java index f91f2a462..a2b26658d 100644 --- a/src/main/java/betterquesting/network/handlers/NetChapterSync.java +++ b/src/main/java/betterquesting/network/handlers/NetChapterSync.java @@ -22,100 +22,90 @@ import javax.annotation.Nullable; import java.util.List; -public class NetChapterSync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:chapter_sync"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetChapterSync::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetChapterSync::onClient); - } - } - - public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] chapterIDs) - { - if(chapterIDs != null && chapterIDs.length <= 0) return; - - BQThreadedIO.INSTANCE.enqueue(() -> { - NBTTagList data = new NBTTagList(); - final List> chapterSubset = chapterIDs == null ? QuestLineDatabase.INSTANCE.getEntries() : QuestLineDatabase.INSTANCE.bulkLookup(chapterIDs); - - for(DBEntry chapter : chapterSubset) - { - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("chapterID", chapter.getID()); - //entry.setInteger("order", QuestLineDatabase.INSTANCE.getOrderIndex(chapter.getID())); - entry.setTag("config", chapter.getValue().writeToNBT(new NBTTagCompound(), null)); - data.appendTag(entry); - } - - List> allSort = QuestLineDatabase.INSTANCE.getSortedEntries(); - int[] aryOrder = new int[allSort.size()]; - for(int i = 0; i < aryOrder.length; i++) - { - aryOrder[i] = allSort.get(i).getID(); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setBoolean("merge", chapterIDs != null); - payload.setTag("data", data); - payload.setIntArray("order", aryOrder); - - if(player == null) - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } else - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } - }); - } - - @SideOnly(Side.CLIENT) - public static void requestSync(@Nullable int[] chapterIDs) - { - NBTTagCompound payload = new NBTTagCompound(); - if(chapterIDs != null) payload.setIntArray("requestIDs", chapterIDs); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); +public class NetChapterSync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:chapter_sync"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetChapterSync::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetChapterSync::onClient); } - - private static void onServer(Tuple message) - { - NBTTagCompound payload = message.getFirst(); - int[] reqIDs = !payload.hasKey("requestIDs") ? null : payload.getIntArray("requestIDs"); - sendSync(message.getSecond(), reqIDs); + } + + public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] chapterIDs) { + if (chapterIDs != null && chapterIDs.length == 0) { return; } + + BQThreadedIO.INSTANCE.enqueue(() -> { + NBTTagList data = new NBTTagList(); + final List> chapterSubset = chapterIDs == null ? QuestLineDatabase.INSTANCE.getEntries() + : QuestLineDatabase.INSTANCE.bulkLookup( + chapterIDs); + + for (DBEntry chapter : chapterSubset) { + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("chapterID", chapter.getID()); + //entry.setInteger("order", QuestLineDatabase.INSTANCE.getOrderIndex(chapter.getID())); + entry.setTag("config", chapter.getValue().writeToNBT(new NBTTagCompound(), null)); + data.appendTag(entry); + } + + List> allSort = QuestLineDatabase.INSTANCE.getSortedEntries(); + int[] aryOrder = new int[allSort.size()]; + for (int i = 0; i < aryOrder.length; i++) { + aryOrder[i] = allSort.get(i).getID(); + } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setBoolean("merge", chapterIDs != null); + payload.setTag("data", data); + payload.setIntArray("order", aryOrder); + + if (player == null) { + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } else { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } + }); + } + + @SideOnly(Side.CLIENT) + public static void requestSync(@Nullable int[] chapterIDs) { + NBTTagCompound payload = new NBTTagCompound(); + if (chapterIDs != null) { payload.setIntArray("requestIDs", chapterIDs); } + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + NBTTagCompound payload = message.getFirst(); + int[] reqIDs = !payload.hasKey("requestIDs") ? null : payload.getIntArray("requestIDs"); + sendSync(message.getSecond(), reqIDs); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + NBTTagList data = message.getTagList("data", 10); + if (!message.getBoolean("merge")) { QuestLineDatabase.INSTANCE.reset(); } + + for (int i = 0; i < data.tagCount(); i++) { + NBTTagCompound tag = data.getCompoundTagAt(i); + if (!tag.hasKey("chapterID", 99)) { continue; } + int chapterID = tag.getInteger("chapterID"); + //int order = tag.getInteger("order"); + + IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); // TODO: Send to client side database + if (chapter == null) { chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); } + + //QuestLineDatabase.INSTANCE.setOrderIndex(chapterID, order); + chapter.readFromNBT(tag.getCompoundTag("config"), + false); // Merging isn't really a problem unless a chapter is excessively sized. Can be improved later if necessary } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - NBTTagList data = message.getTagList("data", 10); - if(!message.getBoolean("merge")) QuestLineDatabase.INSTANCE.reset(); - - for(int i = 0; i < data.tagCount(); i++) - { - NBTTagCompound tag = data.getCompoundTagAt(i); - if(!tag.hasKey("chapterID", 99)) continue; - int chapterID = tag.getInteger("chapterID"); - //int order = tag.getInteger("order"); - - IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); // TODO: Send to client side database - if(chapter == null) chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); - - //QuestLineDatabase.INSTANCE.setOrderIndex(chapterID, order); - chapter.readFromNBT(tag.getCompoundTag("config"), false); // Merging isn't really a problem unless a chapter is excessively sized. Can be improved later if necessary - } - - int[] aryOrder = message.getIntArray("order"); - for(int i = 0; i < aryOrder.length; i++) - { - QuestLineDatabase.INSTANCE.setOrderIndex(aryOrder[i], i); - } - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); + + int[] aryOrder = message.getIntArray("order"); + for (int i = 0; i < aryOrder.length; i++) { + QuestLineDatabase.INSTANCE.setOrderIndex(aryOrder[i], i); } + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetImport.java b/src/main/java/betterquesting/network/handlers/NetImport.java index 29aff879f..cc42aa2a0 100644 --- a/src/main/java/betterquesting/network/handlers/NetImport.java +++ b/src/main/java/betterquesting/network/handlers/NetImport.java @@ -27,133 +27,119 @@ import java.util.HashMap; import java.util.List; -public class NetImport -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:import"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetImport::onServer); - } - - public static void sendImport(@Nonnull IQuestDatabase questDB, @Nonnull IQuestLineDatabase chapterDB) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("quests", questDB.writeToNBT(new NBTTagList(), null)); - payload.setTag("chapters", chapterDB.writeToNBT(new NBTTagList(), null)); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); +public class NetImport { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:import"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetImport::onServer); + } + + public static void sendImport(@Nonnull IQuestDatabase questDB, @Nonnull IQuestLineDatabase chapterDB) { + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("quests", questDB.writeToNBT(new NBTTagList(), null)); + payload.setTag("chapters", chapterDB.writeToNBT(new NBTTagList(), null)); + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + EntityPlayerMP sender = message.getSecond(); + if (sender.getServer() == null) { return; } + + boolean isOP = sender.getServer().getPlayerList().canSendCommands(sender.getGameProfile()); + + if (!isOP) { + BetterQuesting.logger.log(Level.WARN, + "Player " + sender.getName() + " (UUID:" + QuestingAPI.getQuestingUUID(sender) + + ") tried to import quests without OP permissions!"); + sender.sendStatusMessage(new TextComponentString(TextFormatting.RED + "You need to be OP to edit quests!"), + false); + return; // Player is not operator. Do nothing } - - private static void onServer(Tuple message) - { - EntityPlayerMP sender = message.getSecond(); - if(sender.getServer() == null) return; - - boolean isOP = sender.getServer().getPlayerList().canSendCommands(sender.getGameProfile()); - - if(!isOP) - { - BetterQuesting.logger.log(Level.WARN, "Player " + sender.getName() + " (UUID:" + QuestingAPI.getQuestingUUID(sender) + ") tried to import quests without OP permissions!"); - sender.sendStatusMessage(new TextComponentString(TextFormatting.RED + "You need to be OP to edit quests!"), false); - return; // Player is not operator. Do nothing - } - - ImportedQuests impQuestDB = new ImportedQuests(); - IQuestLineDatabase impQuestLineDB = new ImportedQuestLines(); - - impQuestDB.readFromNBT(message.getFirst().getTagList("quests", 10), false); - impQuestLineDB.readFromNBT(message.getFirst().getTagList("chapters", 10), false); - - BetterQuesting.logger.log(Level.INFO, "Importing " + impQuestDB.size() + " quest(s) and " + impQuestLineDB.size() + " quest line(s) from " + sender.getGameProfile().getName()); - - HashMap remapped = getRemappedIDs(impQuestDB.getEntries()); - - for(DBEntry entry : impQuestDB.getEntries()) - { - int[] oldIDs = Arrays.copyOf(entry.getValue().getRequirements(), entry.getValue().getRequirements().length); - - for(int n = 0; n < oldIDs.length; n++) - { - if(remapped.containsKey(oldIDs[n])) - { - oldIDs[n] = remapped.get(oldIDs[n]); - } - } - - entry.getValue().setRequirements(oldIDs); - - QuestDatabase.INSTANCE.add(remapped.get(entry.getID()), entry.getValue()); - } - - for(DBEntry questLine : impQuestLineDB.getEntries()) - { - List> pendingQLE = new ArrayList<>(); - - for(DBEntry qle : questLine.getValue().getEntries()) - { - pendingQLE.add(qle); - questLine.getValue().removeID(qle.getID()); - } - - for(DBEntry qle : pendingQLE) - { - if(!remapped.containsKey(qle.getID())) - { - BetterQuesting.logger.error("Failed to import quest into quest line. Unable to remap ID " + qle.getID()); - continue; - } - - questLine.getValue().add(remapped.get(qle.getID()), qle.getValue()); - } - - QuestLineDatabase.INSTANCE.add(QuestLineDatabase.INSTANCE.nextID(), questLine.getValue()); - } - - SaveLoadHandler.INSTANCE.markDirty(); - NetQuestSync.quickSync(-1, true, true); - NetChapterSync.sendSync(null, null); - } - - /** - * Takes a list of imported IDs and returns a remapping to unused IDs - */ - private static HashMap getRemappedIDs(List> idList) - { - int[] nextIDs = getNextIDs(idList.size()); - HashMap remapped = new HashMap<>(); - - for(int i = 0; i < nextIDs.length; i++) - { - remapped.put(idList.get(i).getID(), nextIDs[i]); - } - - return remapped; - } - - private static int[] getNextIDs(int num) - { - List> listDB = QuestDatabase.INSTANCE.getEntries(); - int[] nxtIDs = new int[num]; - - if(listDB.size() <= 0 || listDB.get(listDB.size() - 1).getID() == listDB.size() - 1) - { - for(int i = 0; i < num; i++) nxtIDs[i] = listDB.size() + i; - return nxtIDs; + + ImportedQuests impQuestDB = new ImportedQuests(); + IQuestLineDatabase impQuestLineDB = new ImportedQuestLines(); + + impQuestDB.readFromNBT(message.getFirst().getTagList("quests", 10), false); + impQuestLineDB.readFromNBT(message.getFirst().getTagList("chapters", 10), false); + + BetterQuesting.logger.log(Level.INFO, "Importing " + impQuestDB.size() + " quest(s) and " + impQuestLineDB.size() + + " quest line(s) from " + sender.getGameProfile().getName()); + + HashMap remapped = getRemappedIDs(impQuestDB.getEntries()); + + for (DBEntry entry : impQuestDB.getEntries()) { + int[] oldIDs = Arrays.copyOf(entry.getValue().getRequirements(), entry.getValue().getRequirements().length); + + for (int n = 0; n < oldIDs.length; n++) { + if (remapped.containsKey(oldIDs[n])) { + oldIDs[n] = remapped.get(oldIDs[n]); } - - int n1 = 0; - int n2 = 0; - for(int i = 0; i < num; i++) - { - while(n2 < listDB.size() && listDB.get(n2).getID() == n1) - { - n1++; - n2++; - } - - nxtIDs[i] = n1++; + } + + entry.getValue().setRequirements(oldIDs); + + QuestDatabase.INSTANCE.add(remapped.get(entry.getID()), entry.getValue()); + } + + for (DBEntry questLine : impQuestLineDB.getEntries()) { + List> pendingQLE = new ArrayList<>(); + + for (DBEntry qle : questLine.getValue().getEntries()) { + pendingQLE.add(qle); + questLine.getValue().removeID(qle.getID()); + } + + for (DBEntry qle : pendingQLE) { + if (!remapped.containsKey(qle.getID())) { + BetterQuesting.logger.error("Failed to import quest into quest line. Unable to remap ID " + qle.getID()); + continue; } - - return nxtIDs; + + questLine.getValue().add(remapped.get(qle.getID()), qle.getValue()); + } + + QuestLineDatabase.INSTANCE.add(QuestLineDatabase.INSTANCE.nextID(), questLine.getValue()); + } + + SaveLoadHandler.INSTANCE.markDirty(); + NetQuestSync.quickSync(-1, true, true); + NetChapterSync.sendSync(null, null); + } + + /** + * Takes a list of imported IDs and returns a remapping to unused IDs + */ + private static HashMap getRemappedIDs(List> idList) { + int[] nextIDs = getNextIDs(idList.size()); + HashMap remapped = new HashMap<>(); + + for (int i = 0; i < nextIDs.length; i++) { + remapped.put(idList.get(i).getID(), nextIDs[i]); } + + return remapped; + } + + private static int[] getNextIDs(int num) { + List> listDB = QuestDatabase.INSTANCE.getEntries(); + int[] nxtIDs = new int[num]; + + if (listDB.isEmpty() || listDB.get(listDB.size() - 1).getID() == listDB.size() - 1) { + for (int i = 0; i < num; i++) { nxtIDs[i] = listDB.size() + i; } + return nxtIDs; + } + + int n1 = 0; + int n2 = 0; + for (int i = 0; i < num; i++) { + while (n2 < listDB.size() && listDB.get(n2).getID() == n1) { + n1++; + n2++; + } + + nxtIDs[i] = n1++; + } + + return nxtIDs; + } } diff --git a/src/main/java/betterquesting/network/handlers/NetInviteSync.java b/src/main/java/betterquesting/network/handlers/NetInviteSync.java index 69d6e2e6d..9622c8645 100644 --- a/src/main/java/betterquesting/network/handlers/NetInviteSync.java +++ b/src/main/java/betterquesting/network/handlers/NetInviteSync.java @@ -21,49 +21,41 @@ import java.util.Collections; import java.util.UUID; -public class NetInviteSync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:invite_sync"); - - public static void registerHandler() - { - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetInviteSync::onClient); - } - } - - // If I need to send other people's invites to players then I'll deal with that another time - public static void sendSync(@Nonnull EntityPlayerMP player) - { - NBTTagCompound payload = new NBTTagCompound(); - UUID playerID = QuestingAPI.getQuestingUUID(player); - payload.setInteger("action", 0); - payload.setTag("data", PartyInvitations.INSTANCE.writeToNBT(new NBTTagList(), Collections.singletonList(playerID))); - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } - - public static void sendRevoked(@Nonnull EntityPlayerMP player, int... IDs) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 1); - payload.setIntArray("IDs", IDs); - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); +public class NetInviteSync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:invite_sync"); + + public static void registerHandler() { + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetInviteSync::onClient); } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - int action = message.getInteger("action"); - if(action == 0) - { - PartyInvitations.INSTANCE.readFromNBT(message.getTagList("data", 10), true); - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); - } else if(action == 1) - { - UUID playerID = QuestingAPI.getQuestingUUID(Minecraft.getMinecraft().player); - PartyInvitations.INSTANCE.revokeInvites(playerID, message.getIntArray("IDs")); - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); - } + } + + // If I need to send other people's invites to players then I'll deal with that another time + public static void sendSync(@Nonnull EntityPlayerMP player) { + NBTTagCompound payload = new NBTTagCompound(); + UUID playerID = QuestingAPI.getQuestingUUID(player); + payload.setInteger("action", 0); + payload.setTag("data", PartyInvitations.INSTANCE.writeToNBT(new NBTTagList(), Collections.singletonList(playerID))); + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } + + public static void sendRevoked(@Nonnull EntityPlayerMP player, int... IDs) { + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 1); + payload.setIntArray("IDs", IDs); + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + int action = message.getInteger("action"); + if (action == 0) { + PartyInvitations.INSTANCE.readFromNBT(message.getTagList("data", 10), true); + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); + } else if (action == 1) { + UUID playerID = QuestingAPI.getQuestingUUID(Minecraft.getMinecraft().player); + PartyInvitations.INSTANCE.revokeInvites(playerID, message.getIntArray("IDs")); + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); } + } } diff --git a/src/main/java/betterquesting/network/handlers/NetLifeSync.java b/src/main/java/betterquesting/network/handlers/NetLifeSync.java index bc1960c7f..9f7d0faa6 100644 --- a/src/main/java/betterquesting/network/handlers/NetLifeSync.java +++ b/src/main/java/betterquesting/network/handlers/NetLifeSync.java @@ -15,36 +15,30 @@ import java.util.Arrays; import java.util.UUID; -public class NetLifeSync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:life_sync"); - - public static void registerHandler() - { - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetLifeSync::onClient); - } - } - - public static void sendSync(@Nullable EntityPlayerMP[] players, @Nullable UUID[] playerIDs) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", LifeDatabase.INSTANCE.writeToNBT(new NBTTagCompound(), playerIDs == null ? null : Arrays.asList(playerIDs))); - payload.setBoolean("merge", playerIDs != null); - - if(players != null) - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); - } else - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } +public class NetLifeSync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:life_sync"); + + public static void registerHandler() { + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetLifeSync::onClient); } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - LifeDatabase.INSTANCE.readFromNBT(message.getCompoundTag("data"), message.getBoolean("merge")); + } + + public static void sendSync(@Nullable EntityPlayerMP[] players, @Nullable UUID[] playerIDs) { + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", LifeDatabase.INSTANCE.writeToNBT(new NBTTagCompound(), + playerIDs == null ? null : Arrays.asList(playerIDs))); + payload.setBoolean("merge", playerIDs != null); + + if (players != null) { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); + } else { + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); } + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + LifeDatabase.INSTANCE.readFromNBT(message.getCompoundTag("data"), message.getBoolean("merge")); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetNameSync.java b/src/main/java/betterquesting/network/handlers/NetNameSync.java index d5a4fd9f0..e2d17a578 100644 --- a/src/main/java/betterquesting/network/handlers/NetNameSync.java +++ b/src/main/java/betterquesting/network/handlers/NetNameSync.java @@ -28,133 +28,110 @@ import java.util.List; import java.util.UUID; -public class NetNameSync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:name_sync"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetNameSync::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetNameSync::onClient); - } +public class NetNameSync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:name_sync"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetNameSync::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetNameSync::onClient); + } + } + + @SideOnly(Side.CLIENT) + public static void sendRequest(@Nullable UUID[] uuids, @Nullable String[] names) { + // NOTE: You can make an empty request if you want EVERYTHING (but I would not recommend it on large servers) + NBTTagCompound payload = new NBTTagCompound(); + if (uuids != null) { + NBTTagList uList = new NBTTagList(); + for (UUID id : uuids) { + if (id == null) { continue; } + uList.appendTag(new NBTTagString(id.toString())); + } + payload.setTag("uuids", uList); } - - @SideOnly(Side.CLIENT) - public static void sendRequest(@Nullable UUID[] uuids, @Nullable String[] names) - { - // NOTE: You can make an empty request if you want EVERYTHING (but I would not recommend it on large servers) - NBTTagCompound payload = new NBTTagCompound(); - if(uuids != null) - { - NBTTagList uList = new NBTTagList(); - for(UUID id : uuids) - { - if(id == null) continue; - uList.appendTag(new NBTTagString(id.toString())); - } - payload.setTag("uuids", uList); - } - if(names != null) - { - NBTTagList nList = new NBTTagList(); - for(String s : names) - { - if(StringUtils.isNullOrEmpty(s)) continue; - nList.appendTag(new NBTTagString(s)); - } - payload.setTag("names", nList); - } - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + if (names != null) { + NBTTagList nList = new NBTTagList(); + for (String s : names) { + if (StringUtils.isNullOrEmpty(s)) { continue; } + nList.appendTag(new NBTTagString(s)); + } + payload.setTag("names", nList); + } + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + public static void quickSync(@Nullable EntityPlayerMP player, int partyID) { + IParty party = PartyManager.INSTANCE.getValue(partyID); + if (party == null) { return; } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", NameCache.INSTANCE.writeToNBT(new NBTTagList(), party.getMembers())); + payload.setBoolean("merge", true); + + if (player != null) { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } else { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + List playerList = new ArrayList<>(); + for (UUID playerID : party.getMembers()) { + EntityPlayerMP p = server.getPlayerList().getPlayerByUUID(playerID); + //noinspection ConstantConditions + if (p != null) { playerList.add(p); } + } + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), + playerList.toArray(new EntityPlayerMP[0])); } - - public static void quickSync(@Nullable EntityPlayerMP player, int partyID) - { - IParty party = PartyManager.INSTANCE.getValue(partyID); - if(party == null) return; - - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", NameCache.INSTANCE.writeToNBT(new NBTTagList(), party.getMembers())); - payload.setBoolean("merge", true); - - if(player != null) - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } else - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - List playerList = new ArrayList<>(); - for(UUID playerID : party.getMembers()) - { - EntityPlayerMP p = server.getPlayerList().getPlayerByUUID(playerID); - //noinspection ConstantConditions - if(p != null) playerList.add(p); - } - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), playerList.toArray(new EntityPlayerMP[0])); - } + } + + public static void sendNames(@Nullable EntityPlayerMP[] players, @Nullable UUID[] uuids, @Nullable String[] names) { + List idList = (uuids == null && names == null) ? null : new ArrayList<>(); + if (uuids != null) { idList.addAll(Arrays.asList(uuids)); } + if (names != null) { + for (String s : names) { + UUID id = NameCache.INSTANCE.getUUID(s); + if (id != null) { idList.add(id); } + } } - - public static void sendNames(@Nullable EntityPlayerMP[] players, @Nullable UUID[] uuids, @Nullable String[] names) - { - List idList = (uuids == null && names == null) ? null : new ArrayList<>(); - if(uuids != null) idList.addAll(Arrays.asList(uuids)); - if(names != null) - { - for(String s : names) - { - UUID id = NameCache.INSTANCE.getUUID(s); - if(id != null) idList.add(id); - } - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", NameCache.INSTANCE.writeToNBT(new NBTTagList(), idList)); - payload.setBoolean("merge", idList != null); - - if(players == null) - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } else - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); - } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", NameCache.INSTANCE.writeToNBT(new NBTTagList(), idList)); + payload.setBoolean("merge", idList != null); + + if (players == null) { + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } else { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); } - - private static void onServer(Tuple message) - { - UUID[] uuids = null; - String[] names = null; - - if(message.getFirst().hasKey("uuids", 9)) - { - NBTTagList uList = message.getFirst().getTagList("uuids", 8); - uuids = new UUID[uList.tagCount()]; - for(int i = 0; i < uuids.length; i++) - { - try - { - uuids[i] = UUID.fromString(uList.getStringTagAt(i)); - } catch(Exception ignored){} - } - } - if(message.getFirst().hasKey("names", 9)) - { - NBTTagList uList = message.getFirst().getTagList("names", 8); - names = new String[uList.tagCount()]; - for(int i = 0; i < names.length; i++) - { - names[i] =uList.getStringTagAt(i); - } - } - sendNames(new EntityPlayerMP[]{message.getSecond()}, uuids, names); + } + + private static void onServer(Tuple message) { + UUID[] uuids = null; + String[] names = null; + + if (message.getFirst().hasKey("uuids", 9)) { + NBTTagList uList = message.getFirst().getTagList("uuids", 8); + uuids = new UUID[uList.tagCount()]; + for (int i = 0; i < uuids.length; i++) { + try { + uuids[i] = UUID.fromString(uList.getStringTagAt(i)); + } catch (Exception ignored) { } + } } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - NameCache.INSTANCE.readFromNBT(message.getTagList("data", 10), message.getBoolean("merge")); - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.NAMES)); + if (message.getFirst().hasKey("names", 9)) { + NBTTagList uList = message.getFirst().getTagList("names", 8); + names = new String[uList.tagCount()]; + for (int i = 0; i < names.length; i++) { + names[i] = uList.getStringTagAt(i); + } } + sendNames(new EntityPlayerMP[] { message.getSecond() }, uuids, names); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + NameCache.INSTANCE.readFromNBT(message.getTagList("data", 10), message.getBoolean("merge")); + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.NAMES)); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetNotices.java b/src/main/java/betterquesting/network/handlers/NetNotices.java index 4e2cb560d..50976b0c4 100644 --- a/src/main/java/betterquesting/network/handlers/NetNotices.java +++ b/src/main/java/betterquesting/network/handlers/NetNotices.java @@ -14,43 +14,37 @@ import javax.annotation.Nullable; -public class NetNotices -{ - // TODO: Convert over to inbox system in future - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:notification"); - - public static void registerHandler() - { - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetNotices::onClient); - } - } - - public static void sendNotice(@Nullable EntityPlayerMP[] players, ItemStack icon, String mainText, String subText, String sound) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("icon", (icon != null ? icon : ItemStack.EMPTY).writeToNBT(new NBTTagCompound())); - if(mainText != null) payload.setString("mainText", mainText); - if(subText != null) payload.setString("subText", subText); - if(sound != null) payload.setString("sound", sound); - - if(players != null) - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); - } else - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } +public class NetNotices { + // TODO: Convert over to inbox system in future + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:notification"); + + public static void registerHandler() { + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetNotices::onClient); } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - ItemStack stack = new ItemStack(message.getCompoundTag("icon")); - String mainTxt = message.getString("mainText"); - String subTxt = message.getString("subText"); - String sound = message.getString("sound"); - QuestNotification.ScheduleNotice(mainTxt, subTxt, stack, sound); + } + + public static void sendNotice(@Nullable EntityPlayerMP[] players, ItemStack icon, String mainText, String subText, + String sound) { + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("icon", (icon != null ? icon : ItemStack.EMPTY).writeToNBT(new NBTTagCompound())); + if (mainText != null) { payload.setString("mainText", mainText); } + if (subText != null) { payload.setString("subText", subText); } + if (sound != null) { payload.setString("sound", sound); } + + if (players != null) { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); + } else { + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); } + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + ItemStack stack = new ItemStack(message.getCompoundTag("icon")); + String mainTxt = message.getString("mainText"); + String subTxt = message.getString("subText"); + String sound = message.getString("sound"); + QuestNotification.ScheduleNotice(mainTxt, subTxt, stack, sound); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetPartyAction.java b/src/main/java/betterquesting/network/handlers/NetPartyAction.java index 4a6b04d83..3ffbd49c2 100644 --- a/src/main/java/betterquesting/network/handlers/NetPartyAction.java +++ b/src/main/java/betterquesting/network/handlers/NetPartyAction.java @@ -28,238 +28,214 @@ import java.util.UUID; -public class NetPartyAction -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:party_action"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetPartyAction::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetPartyAction::onClient); - } +public class NetPartyAction { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:party_action"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetPartyAction::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetPartyAction::onClient); } - - @SideOnly(Side.CLIENT) - public static void sendAction(NBTTagCompound payload) - { - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + @SideOnly(Side.CLIENT) + public static void sendAction(NBTTagCompound payload) { + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + EntityPlayerMP sender = message.getSecond(); + + int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); + int partyID = !message.getFirst().hasKey("partyID", 99) ? -1 : message.getFirst().getInteger("partyID"); + IParty party = PartyManager.INSTANCE.getValue(partyID); + int permission = party == null ? 0 : checkPermission(QuestingAPI.getQuestingUUID(sender), party); + + switch (action) { + case 0: { + createParty(sender, message.getFirst().getString("name")); + break; + } + case 1: { + if (permission < 3) { break; } + deleteParty(partyID); + break; + } + case 2: { + if (permission < 2) { break; } + editParty(partyID, party, message.getFirst().getCompoundTag("data")); + break; + } + case 3: { + if (permission < 2) { break; } + inviteUser(partyID, message.getFirst().getString("username"), message.getFirst().getLong("expiry")); + break; + } + case 4: { + acceptInvite(partyID, sender); // Probably the only thing an OP can't force + break; + } + case 5: { + kickUser(partyID, sender, party, message.getFirst().getString("username"), permission); + break; + } + default: { + BetterQuesting.logger.log(Level.ERROR, "Invalid party action '" + action + "'. Full payload:\n" + + message.getFirst()); + } } - - private static void onServer(Tuple message) - { - EntityPlayerMP sender = message.getSecond(); - - int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); - int partyID = !message.getFirst().hasKey("partyID", 99) ? -1 : message.getFirst().getInteger("partyID"); - IParty party = PartyManager.INSTANCE.getValue(partyID); - int permission = party == null ? 0 : checkPermission(QuestingAPI.getQuestingUUID(sender), party); - - switch(action) - { - case 0: - { - createParty(sender, message.getFirst().getString("name")); - break; - } - case 1: - { - if(permission < 3) break; - deleteParty(partyID); - break; - } - case 2: - { - if(permission < 2) break; - editParty(partyID, party, message.getFirst().getCompoundTag("data")); - break; - } - case 3: - { - if(permission < 2) break; - inviteUser(partyID, message.getFirst().getString("username"), message.getFirst().getLong("expiry")); - break; - } - case 4: - { - acceptInvite(partyID, sender); // Probably the only thing an OP can't force - break; - } - case 5: - { - kickUser(partyID, sender, party, message.getFirst().getString("username"), permission); - break; - } - default: - { - BetterQuesting.logger.log(Level.ERROR, "Invalid party action '" + action + "'. Full payload:\n" + message.getFirst().toString()); - } - } + } + + private static void createParty(EntityPlayerMP sender, String name) { + UUID playerID = QuestingAPI.getQuestingUUID(sender); + if (PartyManager.INSTANCE.getParty(playerID) != null) { return; } + + int partyID = PartyManager.INSTANCE.nextID(); + IParty party = PartyManager.INSTANCE.createNew(partyID); + party.getProperties().setProperty(NativeProps.NAME, name); + party.setStatus(playerID, EnumPartyStatus.OWNER); + NetPartySync.sendSync(new EntityPlayerMP[] { sender }, new int[] { partyID }); + } + + private static void deleteParty(int partyID) { + PartyManager.INSTANCE.removeID(partyID); + PartyInvitations.INSTANCE.purgeInvites(partyID); + + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 1); + payload.setInteger("partyID", partyID); + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); // Invites need to be purged from everyone + } + + private static void editParty(int partyID, IParty party, NBTTagCompound settings) { + party.readProperties(settings); + NetPartySync.quickSync(partyID); + } + + private static void inviteUser(int partyID, String username, long expiry) { + UUID uuid = null; + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + EntityPlayerMP player = server.getPlayerList().getPlayerByUsername(username); + if (player != null) { uuid = QuestingAPI.getQuestingUUID(player); } + if (uuid == null) { uuid = NameCache.INSTANCE.getUUID(username); } + if (uuid != null) { + PartyInvitations.INSTANCE.postInvite(uuid, partyID, expiry); + if (player != null) { + NetPartySync.sendSync(new EntityPlayerMP[] { player }, new int[] { partyID }); + NetInviteSync.sendSync(player); + } + } else { + BetterQuesting.logger.error( + "Unable to identify " + username + " to invite to party " + partyID); // No idea who this is } - - private static void createParty(EntityPlayerMP sender, String name) - { - UUID playerID = QuestingAPI.getQuestingUUID(sender); - if(PartyManager.INSTANCE.getParty(playerID) != null) return; - - int partyID = PartyManager.INSTANCE.nextID(); - IParty party = PartyManager.INSTANCE.createNew(partyID); - party.getProperties().setProperty(NativeProps.NAME, name); - party.setStatus(playerID, EnumPartyStatus.OWNER); - NetPartySync.sendSync(new EntityPlayerMP[]{sender}, new int[]{partyID}); + } + + private static void acceptInvite(int partyID, EntityPlayerMP sender) { + UUID playerID = QuestingAPI.getQuestingUUID(sender); + DBEntry party = PartyManager.INSTANCE.getParty(playerID); + if (party != null) { return; } + if (PartyInvitations.INSTANCE.acceptInvite(playerID, partyID)) { + NetPartySync.quickSync(partyID); + NetNameSync.quickSync(sender, partyID); + } else { + BetterQuesting.logger.error("Invalid invite for " + sender.getName() + " to party " + partyID); } - - private static void deleteParty(int partyID) + NetInviteSync.sendSync(sender); + } + + private static void kickUser(int partyID, EntityPlayerMP sender, IParty party, String username, + int permission) // Is also the leave action (self kick if you will) + { + if (party == null) { + BetterQuesting.logger.error("Tried to kick a player from a non-existant party (" + partyID + ")"); + return; + } + + UUID uuid = null; + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + EntityPlayerMP player = server.getPlayerList().getPlayerByUsername(username); + if (player != null) { uuid = QuestingAPI.getQuestingUUID(player); } + if (uuid == null) { uuid = NameCache.INSTANCE.getUUID(username); } + if (uuid == null) { + BetterQuesting.logger.error("Unable to identify " + username + " to remove them from party " + partyID); + return; // No idea who this is + } + + if (uuid.equals(QuestingAPI.getQuestingUUID(sender)) || checkPermission(uuid, party) < + permission) // For future reference, this is checking the target has a permission lower than the sender { + // Even if the kick isn't confirmed we still need to tell the clients incase of desync + if (party.getStatus(uuid) != null) { party.kickUser(uuid); } + + if (!party.getMembers().isEmpty()) { + NetPartySync.quickSync(partyID); + if (player != null) { + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 5); + payload.setInteger("partyID", partyID); + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } + } else // No more members. Delete the party + { PartyManager.INSTANCE.removeID(partyID); PartyInvitations.INSTANCE.purgeInvites(partyID); - + NBTTagCompound payload = new NBTTagCompound(); payload.setInteger("action", 1); payload.setInteger("partyID", partyID); - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); // Invites need to be purged from everyone + PacketSender.INSTANCE.sendToAll( + new QuestingPacket(ID_NAME, payload)); // Invites need to be purged from everyone + } + } else { + BetterQuesting.logger.error("Insufficient permissions to kick " + username + " from party " + partyID); } - - private static void editParty(int partyID, IParty party, NBTTagCompound settings) - { - party.readProperties(settings); - NetPartySync.quickSync(partyID); - } - - private static void inviteUser(int partyID, String username, long expiry) - { - UUID uuid = null; - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - EntityPlayerMP player = server.getPlayerList().getPlayerByUsername(username); - if(player != null) uuid = QuestingAPI.getQuestingUUID(player); - if(uuid == null) uuid = NameCache.INSTANCE.getUUID(username); - if(uuid != null) - { - PartyInvitations.INSTANCE.postInvite(uuid, partyID, expiry); - if(player != null) - { - NetPartySync.sendSync(new EntityPlayerMP[]{player},new int[]{partyID}); - NetInviteSync.sendSync(player); - } - } else - { - BetterQuesting.logger.error("Unable to identify " + username + " to invite to party " + partyID); // No idea who this is - } + } + + private static int checkPermission(UUID playerID, IParty party) { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + EntityPlayerMP player = server == null ? null : server.getPlayerList().getPlayerByUUID(playerID); + if (player != null && server.getPlayerList().canSendCommands(player.getGameProfile())) { + return 4; // Can kick owners or force invites without needing to be a member of the party } - - private static void acceptInvite(int partyID, EntityPlayerMP sender) - { - UUID playerID = QuestingAPI.getQuestingUUID(sender); - DBEntry party = PartyManager.INSTANCE.getParty(playerID); - if(party != null) return; - if(PartyInvitations.INSTANCE.acceptInvite(playerID, partyID)) - { - NetPartySync.quickSync(partyID); - NetNameSync.quickSync(sender, partyID); - } else - { - BetterQuesting.logger.error("Invalid invite for " + sender.getName() + " to party " + partyID); - } - NetInviteSync.sendSync(sender); + EnumPartyStatus status = party.getStatus(playerID); + if (status == null) { + return 0; // Only OPs can edit parties they aren't a member of } - - private static void kickUser(int partyID, EntityPlayerMP sender, IParty party, String username, int permission) // Is also the leave action (self kick if you will) - { - if(party == null) - { - BetterQuesting.logger.error("Tried to kick a player from a non-existant party (" + partyID + ")"); - return; - } - - UUID uuid = null; - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - EntityPlayerMP player = server.getPlayerList().getPlayerByUsername(username); - if(player != null) uuid = QuestingAPI.getQuestingUUID(player); - if(uuid == null) uuid = NameCache.INSTANCE.getUUID(username); - if(uuid == null) - { - BetterQuesting.logger.error("Unable to identify " + username + " to remove them from party " + partyID); - return; // No idea who this is - } - - if(uuid.equals(QuestingAPI.getQuestingUUID(sender)) || checkPermission(uuid, party) < permission) // For future reference, this is checking the target has a permission lower than the sender - { - // Even if the kick isn't confirmed we still need to tell the clients incase of desync - if(party.getStatus(uuid) != null) party.kickUser(uuid); - - if(party.getMembers().size() > 0) - { - NetPartySync.quickSync(partyID); - if(player != null) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 5); - payload.setInteger("partyID", partyID); - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } - } else // No more members. Delete the party - { - PartyManager.INSTANCE.removeID(partyID); - PartyInvitations.INSTANCE.purgeInvites(partyID); - - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 1); - payload.setInteger("partyID", partyID); - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); // Invites need to be purged from everyone - } - } else - { - BetterQuesting.logger.error("Insufficient permissions to kick " + username + " from party " + partyID); - } - } - - private static int checkPermission(UUID playerID, IParty party) - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - EntityPlayerMP player = server == null ? null : server.getPlayerList().getPlayerByUUID(playerID); - if(player != null && server.getPlayerList().canSendCommands(player.getGameProfile())) return 4; // Can kick owners or force invites without needing to be a member of the party - EnumPartyStatus status = party.getStatus(playerID); - if(status == null) return 0; // Only OPs can edit parties they aren't a member of - - switch(status) - { - case MEMBER: - return 1; - case ADMIN: - return 2; - case OWNER: - return 3; - default: - return 0; - } + + switch (status) { + case MEMBER: + return 1; + case ADMIN: + return 2; + case OWNER: + return 3; + default: + return 0; } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - int action = !message.hasKey("action", 99) ? -1 : message.getInteger("action"); - int partyID = !message.hasKey("partyID", 99) ? -1 : message.getInteger("partyID"); - - switch(action) - { - case 1: // Delete - { - PartyManager.INSTANCE.removeID(partyID); - PartyInvitations.INSTANCE.purgeInvites(partyID); - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); - break; - } - case 5: // Kicked - { - IParty party = PartyManager.INSTANCE.getValue(partyID); - if(party != null) - { - party.kickUser(QuestingAPI.getQuestingUUID(Minecraft.getMinecraft().player)); - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); - } - } + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + int action = !message.hasKey("action", 99) ? -1 : message.getInteger("action"); + int partyID = !message.hasKey("partyID", 99) ? -1 : message.getInteger("partyID"); + + switch (action) { + case 1: // Delete + { + PartyManager.INSTANCE.removeID(partyID); + PartyInvitations.INSTANCE.purgeInvites(partyID); + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); + break; + } + case 5: // Kicked + { + IParty party = PartyManager.INSTANCE.getValue(partyID); + if (party != null) { + party.kickUser(QuestingAPI.getQuestingUUID(Minecraft.getMinecraft().player)); + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); } + } } + } } diff --git a/src/main/java/betterquesting/network/handlers/NetPartySync.java b/src/main/java/betterquesting/network/handlers/NetPartySync.java index b218d97de..951887c14 100644 --- a/src/main/java/betterquesting/network/handlers/NetPartySync.java +++ b/src/main/java/betterquesting/network/handlers/NetPartySync.java @@ -26,99 +26,87 @@ import java.util.UUID; // Ignore the invite system here. We'll deal wih that elsewhere -public class NetPartySync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:party_sync"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetPartySync::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetPartySync::onClient); - } - } - - public static void quickSync(int partyID) - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - IParty party = PartyManager.INSTANCE.getValue(partyID); - - if(server == null || party == null) return; - - List players = new ArrayList<>(); - for(UUID uuid : party.getMembers()) - { - EntityPlayerMP p = server.getPlayerList().getPlayerByUUID(uuid); - //noinspection ConstantConditions - if(p != null) players.add(p); - } - - sendSync(players.toArray(new EntityPlayerMP[0]), new int[]{partyID}); +public class NetPartySync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:party_sync"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetPartySync::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetPartySync::onClient); } - - public static void sendSync(@Nullable EntityPlayerMP[] players, @Nullable int[] partyIDs) - { - if(partyIDs != null && partyIDs.length <= 0) return; - if(players != null && players.length <= 0) return; - - NBTTagList dataList = new NBTTagList(); - final List> partySubset = partyIDs == null ? PartyManager.INSTANCE.getEntries() : PartyManager.INSTANCE.bulkLookup(partyIDs); - for(DBEntry party : partySubset) - { - NBTTagCompound entry = new NBTTagCompound(); - entry.setInteger("partyID", party.getID()); - entry.setTag("config", party.getValue().writeToNBT(new NBTTagCompound())); - dataList.appendTag(entry); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", dataList); - payload.setBoolean("merge", partyIDs != null); - - if(players == null) - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } else - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); - } + } + + public static void quickSync(int partyID) { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + IParty party = PartyManager.INSTANCE.getValue(partyID); + + if (server == null || party == null) { return; } + + List players = new ArrayList<>(); + for (UUID uuid : party.getMembers()) { + EntityPlayerMP p = server.getPlayerList().getPlayerByUUID(uuid); + //noinspection ConstantConditions + if (p != null) { players.add(p); } } - - @SideOnly(Side.CLIENT) - public static void requestSync(@Nullable int[] partyIDs) - { - NBTTagCompound payload = new NBTTagCompound(); - if(partyIDs != null) payload.setIntArray("partyIDs", partyIDs); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + + sendSync(players.toArray(new EntityPlayerMP[0]), new int[] { partyID }); + } + + public static void sendSync(@Nullable EntityPlayerMP[] players, @Nullable int[] partyIDs) { + if (partyIDs != null && partyIDs.length == 0) { return; } + if (players != null && players.length == 0) { return; } + + NBTTagList dataList = new NBTTagList(); + final List> partySubset = + partyIDs == null ? PartyManager.INSTANCE.getEntries() : PartyManager.INSTANCE.bulkLookup(partyIDs); + for (DBEntry party : partySubset) { + NBTTagCompound entry = new NBTTagCompound(); + entry.setInteger("partyID", party.getID()); + entry.setTag("config", party.getValue().writeToNBT(new NBTTagCompound())); + dataList.appendTag(entry); } - - private static void onServer(Tuple message) - { - NBTTagCompound payload = message.getFirst(); - int[] reqIDs = !payload.hasKey("partyIDs") ? null : payload.getIntArray("partyIDs"); - sendSync(new EntityPlayerMP[]{message.getSecond()}, reqIDs); + + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", dataList); + payload.setBoolean("merge", partyIDs != null); + + if (players == null) { + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } else { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - NBTTagList data = message.getTagList("data", 10); - if(!message.getBoolean("merge")) PartyManager.INSTANCE.reset(); - - for(int i = 0; i < data.tagCount(); i++) - { - NBTTagCompound tag = data.getCompoundTagAt(i); - if(!tag.hasKey("partyID", 99)) continue; - int partyID = tag.getInteger("partyID"); - - IParty party = PartyManager.INSTANCE.getValue(partyID); // TODO: Send to client side database - if(party == null) party = PartyManager.INSTANCE.createNew(partyID); - - party.readFromNBT(tag.getCompoundTag("config")); - } - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); + } + + @SideOnly(Side.CLIENT) + public static void requestSync(@Nullable int[] partyIDs) { + NBTTagCompound payload = new NBTTagCompound(); + if (partyIDs != null) { payload.setIntArray("partyIDs", partyIDs); } + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + NBTTagCompound payload = message.getFirst(); + int[] reqIDs = !payload.hasKey("partyIDs") ? null : payload.getIntArray("partyIDs"); + sendSync(new EntityPlayerMP[] { message.getSecond() }, reqIDs); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + NBTTagList data = message.getTagList("data", 10); + if (!message.getBoolean("merge")) { PartyManager.INSTANCE.reset(); } + + for (int i = 0; i < data.tagCount(); i++) { + NBTTagCompound tag = data.getCompoundTagAt(i); + if (!tag.hasKey("partyID", 99)) { continue; } + int partyID = tag.getInteger("partyID"); + + IParty party = PartyManager.INSTANCE.getValue(partyID); // TODO: Send to client side database + if (party == null) { party = PartyManager.INSTANCE.createNew(partyID); } + + party.readFromNBT(tag.getCompoundTag("config")); } + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.PARTY)); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetQuestAction.java b/src/main/java/betterquesting/network/handlers/NetQuestAction.java index 205555101..2dd720f1a 100644 --- a/src/main/java/betterquesting/network/handlers/NetQuestAction.java +++ b/src/main/java/betterquesting/network/handlers/NetQuestAction.java @@ -18,76 +18,64 @@ import javax.annotation.Nonnull; import java.util.List; -public class NetQuestAction -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:quest_action"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetQuestAction::onServer); - } - - @SideOnly(Side.CLIENT) - public static void requestClaim(@Nonnull int[] questIDs) - { - if(questIDs.length <= 0) return; - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 0); - payload.setIntArray("questIDs", questIDs); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); - } - - @SideOnly(Side.CLIENT) - public static void requestDetect(@Nonnull int[] questIDs) - { - if(questIDs.length <= 0) return; - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 1); - payload.setIntArray("questIDs", questIDs); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); - } - - private static void onServer(Tuple message) - { - int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); - - switch(action) - { - case 0: - { - claimQuest(message.getFirst().getIntArray("questIDs"), message.getSecond()); - break; - } - case 1: - { - detectQuest(message.getFirst().getIntArray("questIDs"), message.getSecond()); - break; - } - default: - { - BetterQuesting.logger.log(Level.ERROR, "Invalid quest user action '" + action + "'. Full payload:\n" + message.getFirst().toString()); - } - } +public class NetQuestAction { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:quest_action"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetQuestAction::onServer); + } + + @SideOnly(Side.CLIENT) + public static void requestClaim(@Nonnull int[] questIDs) { + if (questIDs.length == 0) { return; } + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 0); + payload.setIntArray("questIDs", questIDs); + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + @SideOnly(Side.CLIENT) + public static void requestDetect(@Nonnull int[] questIDs) { + if (questIDs.length == 0) { return; } + NBTTagCompound payload = new NBTTagCompound(); + payload.setInteger("action", 1); + payload.setIntArray("questIDs", questIDs); + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); + + switch (action) { + case 0: { + claimQuest(message.getFirst().getIntArray("questIDs"), message.getSecond()); + break; + } + case 1: { + detectQuest(message.getFirst().getIntArray("questIDs"), message.getSecond()); + break; + } + default: { + BetterQuesting.logger.log(Level.ERROR, "Invalid quest user action '" + action + "'. Full payload:\n" + + message.getFirst()); + } } - - public static void claimQuest(int[] questIDs, EntityPlayerMP player) - { - List> qLists = QuestDatabase.INSTANCE.bulkLookup(questIDs); - - for(DBEntry entry : qLists) - { - if(!entry.getValue().canClaim(player)) continue; - entry.getValue().claimReward(player); - } + } + + public static void claimQuest(int[] questIDs, EntityPlayerMP player) { + List> qLists = QuestDatabase.INSTANCE.bulkLookup(questIDs); + + for (DBEntry entry : qLists) { + if (!entry.getValue().canClaim(player)) { continue; } + entry.getValue().claimReward(player); } - - public static void detectQuest(int[] questIDs, EntityPlayerMP player) - { - List> qLists = QuestDatabase.INSTANCE.bulkLookup(questIDs); - - for(DBEntry entry : qLists) - { - entry.getValue().detect(player); - } + } + + public static void detectQuest(int[] questIDs, EntityPlayerMP player) { + List> qLists = QuestDatabase.INSTANCE.bulkLookup(questIDs); + + for (DBEntry entry : qLists) { + entry.getValue().detect(player); } + } } diff --git a/src/main/java/betterquesting/network/handlers/NetQuestEdit.java b/src/main/java/betterquesting/network/handlers/NetQuestEdit.java index c091e997d..fb9cbcfa8 100644 --- a/src/main/java/betterquesting/network/handlers/NetQuestEdit.java +++ b/src/main/java/betterquesting/network/handlers/NetQuestEdit.java @@ -31,192 +31,176 @@ import java.util.List; import java.util.UUID; -public class NetQuestEdit -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:quest_edit"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetQuestEdit::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetQuestEdit::onClient); - } +public class NetQuestEdit { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:quest_edit"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetQuestEdit::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetQuestEdit::onClient); } - - @SideOnly(Side.CLIENT) - public static void sendEdit(NBTTagCompound payload) // TODO: Make these use proper methods for each action rather than directly assembling the payload - { - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + @SideOnly(Side.CLIENT) + public static void sendEdit( + NBTTagCompound payload) // TODO: Make these use proper methods for each action rather than directly assembling the payload + { + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + EntityPlayerMP sender = message.getSecond(); + MinecraftServer server = sender.getServer(); + if (server == null) { + return; // Here mostly just to keep intellisense happy } - - private static void onServer(Tuple message) + + boolean isOP = server.getPlayerList().canSendCommands(sender.getGameProfile()); + + if (!isOP) // OP pre-check { - EntityPlayerMP sender = message.getSecond(); - MinecraftServer server = sender.getServer(); - if(server == null) return; // Here mostly just to keep intellisense happy - - boolean isOP = server.getPlayerList().canSendCommands(sender.getGameProfile()); - - if(!isOP) // OP pre-check - { - BetterQuesting.logger.log(Level.WARN, "Player " + sender.getName() + " (UUID:" + QuestingAPI.getQuestingUUID(sender) + ") tried to edit quests without OP permissions!"); - sender.sendStatusMessage(new TextComponentString(TextFormatting.RED + "You need to be OP to edit quests!"), true); - return; // Player is not operator. Do nothing - } - - NBTTagCompound tag = message.getFirst(); - UUID senderID = QuestingAPI.getQuestingUUID(sender); - int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); - - switch(action) - { - case 0: - { - editQuests(tag.getTagList("data", 10)); - break; - } - case 1: - { - deleteQuests(tag.getIntArray("questIDs")); - break; - } - case 2: - { - // TODO: Allow the editor to send a target player name/UUID - setQuestStates(tag.getIntArray("questIDs"), tag.getBoolean("state"), senderID); - break; - } - case 3: - { - createQuests(tag.getTagList("data", 10)); - break; - } - default: - { - BetterQuesting.logger.log(Level.ERROR, "Invalid quest edit action '" + action + "'. Full payload:\n" + message.getFirst().toString()); - } - } + BetterQuesting.logger.log(Level.WARN, + "Player " + sender.getName() + " (UUID:" + QuestingAPI.getQuestingUUID(sender) + + ") tried to edit quests without OP permissions!"); + sender.sendStatusMessage(new TextComponentString(TextFormatting.RED + "You need to be OP to edit quests!"), true); + return; // Player is not operator. Do nothing } - - // Serverside only - public static void editQuests(NBTTagList data) - { - int[] ids = new int[data.tagCount()]; - for(int i = 0; i < data.tagCount(); i++) - { - NBTTagCompound entry = data.getCompoundTagAt(i); - int questID = entry.getInteger("questID"); - ids[i] = questID; - - IQuest quest = QuestDatabase.INSTANCE.getValue(questID); - if(quest != null) quest.readFromNBT(entry.getCompoundTag("config")); - } - - SaveLoadHandler.INSTANCE.markDirty(); - NetQuestSync.sendSync(null, ids, true, false); + + NBTTagCompound tag = message.getFirst(); + UUID senderID = QuestingAPI.getQuestingUUID(sender); + int action = !message.getFirst().hasKey("action", 99) ? -1 : message.getFirst().getInteger("action"); + + switch (action) { + case 0: { + editQuests(tag.getTagList("data", 10)); + break; + } + case 1: { + deleteQuests(tag.getIntArray("questIDs")); + break; + } + case 2: { + // TODO: Allow the editor to send a target player name/UUID + setQuestStates(tag.getIntArray("questIDs"), tag.getBoolean("state"), senderID); + break; + } + case 3: { + createQuests(tag.getTagList("data", 10)); + break; + } + default: { + BetterQuesting.logger.log(Level.ERROR, "Invalid quest edit action '" + action + "'. Full payload:\n" + + message.getFirst()); + } } - - // Serverside only - public static void deleteQuests(int[] questIDs) - { - for(int id : questIDs) - { - QuestDatabase.INSTANCE.removeID(id); - QuestLineDatabase.INSTANCE.removeQuest(id); - } - - SaveLoadHandler.INSTANCE.markDirty(); - - NBTTagCompound payload = new NBTTagCompound(); - payload.setIntArray("questIDs", questIDs); - payload.setInteger("action", 1); - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } + + // Serverside only + public static void editQuests(NBTTagList data) { + int[] ids = new int[data.tagCount()]; + for (int i = 0; i < data.tagCount(); i++) { + NBTTagCompound entry = data.getCompoundTagAt(i); + int questID = entry.getInteger("questID"); + ids[i] = questID; + + IQuest quest = QuestDatabase.INSTANCE.getValue(questID); + if (quest != null) { quest.readFromNBT(entry.getCompoundTag("config")); } } - - // Serverside only - public static void setQuestStates(int[] questIDs, boolean state, UUID targetID) - { - List> questList = QuestDatabase.INSTANCE.bulkLookup(questIDs); - - for(DBEntry entry : questList) + + SaveLoadHandler.INSTANCE.markDirty(); + NetQuestSync.sendSync(null, ids, true, false); + } + + // Serverside only + public static void deleteQuests(int[] questIDs) { + for (int id : questIDs) { + QuestDatabase.INSTANCE.removeID(id); + QuestLineDatabase.INSTANCE.removeQuest(id); + } + + SaveLoadHandler.INSTANCE.markDirty(); + + NBTTagCompound payload = new NBTTagCompound(); + payload.setIntArray("questIDs", questIDs); + payload.setInteger("action", 1); + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } + + // Serverside only + public static void setQuestStates(int[] questIDs, boolean state, UUID targetID) { + List> questList = QuestDatabase.INSTANCE.bulkLookup(questIDs); + + for (DBEntry entry : questList) { + if (!state) { + entry.getValue().resetUser(targetID, true); + continue; + } + + if (entry.getValue().isComplete(targetID)) { + entry.getValue().setClaimed(targetID, 0); + } else { + entry.getValue().setComplete(targetID, 0); + + int done = 0; + + if (!entry.getValue().getProperty(NativeProps.LOGIC_TASK) + .getResult(done, entry.getValue().getTasks().size())) // Preliminary check { - if(!state) - { - entry.getValue().resetUser(targetID, true); - continue; - } - - if(entry.getValue().isComplete(targetID)) - { - entry.getValue().setClaimed(targetID, 0); - } else - { - entry.getValue().setComplete(targetID, 0); - - int done = 0; - - if(!entry.getValue().getProperty(NativeProps.LOGIC_TASK).getResult(done, entry.getValue().getTasks().size())) // Preliminary check - { - for(DBEntry task : entry.getValue().getTasks().getEntries()) - { - task.getValue().setComplete(targetID); - done++; - - if(entry.getValue().getProperty(NativeProps.LOGIC_TASK).getResult(done, entry.getValue().getTasks().size())) - { - break; // Only complete enough quests to claim the reward - } - } - } + for (DBEntry task : entry.getValue().getTasks().getEntries()) { + task.getValue().setComplete(targetID); + done++; + + if (entry.getValue().getProperty(NativeProps.LOGIC_TASK) + .getResult(done, entry.getValue().getTasks().size())) { + break; // Only complete enough quests to claim the reward } + } } - - SaveLoadHandler.INSTANCE.markDirty(); - - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if(server == null) return; - EntityPlayerMP player = server.getPlayerList().getPlayerByUUID(targetID); - //noinspection ConstantConditions - if(player == null) return; - NetQuestSync.sendSync(player, questIDs, false, true); + } } - - // Serverside only - public static void createQuests(NBTTagList data) - { - int[] ids = new int[data.tagCount()]; - for(int i = 0; i < data.tagCount(); i++) - { - NBTTagCompound entry = data.getCompoundTagAt(i); - int questID = entry.hasKey("questID", 99) ? entry.getInteger("questID") : -1; - if(questID < 0) questID = QuestDatabase.INSTANCE.nextID(); - ids[i] = questID; - - IQuest quest = QuestDatabase.INSTANCE.getValue(questID); - if(quest == null) quest = QuestDatabase.INSTANCE.createNew(questID); - if(entry.hasKey("config", 10)) quest.readFromNBT(entry.getCompoundTag("config")); - } - - SaveLoadHandler.INSTANCE.markDirty(); - NetQuestSync.sendSync(null, ids, true, false); + + SaveLoadHandler.INSTANCE.markDirty(); + + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + if (server == null) { return; } + EntityPlayerMP player = server.getPlayerList().getPlayerByUUID(targetID); + //noinspection ConstantConditions + if (player == null) { return; } + NetQuestSync.sendSync(player, questIDs, false, true); + } + + // Serverside only + public static void createQuests(NBTTagList data) { + int[] ids = new int[data.tagCount()]; + for (int i = 0; i < data.tagCount(); i++) { + NBTTagCompound entry = data.getCompoundTagAt(i); + int questID = entry.hasKey("questID", 99) ? entry.getInteger("questID") : -1; + if (questID < 0) { questID = QuestDatabase.INSTANCE.nextID(); } + ids[i] = questID; + + IQuest quest = QuestDatabase.INSTANCE.getValue(questID); + if (quest == null) { quest = QuestDatabase.INSTANCE.createNew(questID); } + if (entry.hasKey("config", 10)) { quest.readFromNBT(entry.getCompoundTag("config")); } } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) // Imparts edit specific changes + + SaveLoadHandler.INSTANCE.markDirty(); + NetQuestSync.sendSync(null, ids, true, false); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) // Imparts edit specific changes + { + int action = !message.hasKey("action", 99) ? -1 : message.getInteger("action"); + + if (action == 1) // Change to a switch statement when more actions are required { - int action = !message.hasKey("action", 99) ? -1 : message.getInteger("action"); - - if(action == 1) // Change to a switch statement when more actions are required - { - for(int id : message.getIntArray("questIDs")) - { - QuestDatabase.INSTANCE.removeID(id); - QuestLineDatabase.INSTANCE.removeQuest(id); - } - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); - } + for (int id : message.getIntArray("questIDs")) { + QuestDatabase.INSTANCE.removeID(id); + QuestLineDatabase.INSTANCE.removeQuest(id); + } + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.CHAPTER)); } + } } diff --git a/src/main/java/betterquesting/network/handlers/NetQuestSync.java b/src/main/java/betterquesting/network/handlers/NetQuestSync.java index df3d948a0..4c6285c67 100644 --- a/src/main/java/betterquesting/network/handlers/NetQuestSync.java +++ b/src/main/java/betterquesting/network/handlers/NetQuestSync.java @@ -28,128 +28,118 @@ import java.util.List; import java.util.UUID; -public class NetQuestSync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:quest_sync"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetQuestSync::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetQuestSync::onClient); - } - } - - public static void quickSync(int questID, boolean config, boolean progress) - { - if(!config && !progress) return; - - int[] IDs = questID < 0 ? null : new int[]{questID}; - - if(config) sendSync(null, IDs, true, false); // We're not sending progress in this pass. - - if(progress) // Send everyone's individual progression - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if(server == null) return; - - for(EntityPlayerMP player : server.getPlayerList().getPlayers()) - { - sendSync(player, IDs, false, true); // Progression only this pass - } - } - } - - @Deprecated - public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] questIDs, boolean config, boolean progress) - { - sendSync(player, questIDs, null, config, progress); - } - - public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] questIDs, @Nullable int[] resetIDs, boolean config, boolean progress) - { - if((!config && !progress) || (questIDs != null && questIDs.length <= 0)) return; - - // Offload this to another thread as it could take a while to build - BQThreadedIO.INSTANCE.enqueue(() -> { - NBTTagList dataList = new NBTTagList(); - final List> questSubset = questIDs == null ? QuestDatabase.INSTANCE.getEntries() : QuestDatabase.INSTANCE.bulkLookup(questIDs); - final List pidList = player == null ? null : Collections.singletonList(QuestingAPI.getQuestingUUID(player)); - - for(DBEntry entry : questSubset) - { - NBTTagCompound tag = new NBTTagCompound(); - - if(config) tag.setTag("config", entry.getValue().writeToNBT(new NBTTagCompound())); - if(progress) tag.setTag("progress", entry.getValue().writeProgressToNBT(new NBTTagCompound(), pidList)); - if(resetIDs != null) tag.setIntArray("resets", resetIDs); - tag.setInteger("questID", entry.getID()); - dataList.appendTag(tag); - } - - NBTTagCompound payload = new NBTTagCompound(); - payload.setBoolean("merge", !config || questIDs != null); - payload.setTag("data", dataList); - - if(player == null) - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } else - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } - }); +public class NetQuestSync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:quest_sync"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetQuestSync::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetQuestSync::onClient); } - - // Asks the server to send specific quest data over - @SideOnly(Side.CLIENT) - public static void requestSync(@Nullable int[] questIDs, boolean configs, boolean progress) - { - NBTTagCompound payload = new NBTTagCompound(); - if(questIDs != null) payload.setIntArray("requestIDs", questIDs); - payload.setBoolean("getConfig", configs); - payload.setBoolean("getProgress", progress); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + public static void quickSync(int questID, boolean config, boolean progress) { + if (!config && !progress) { return; } + + int[] IDs = questID < 0 ? null : new int[] { questID }; + + if (config) { + sendSync(null, IDs, true, false); // We're not sending progress in this pass. } - - private static void onServer(Tuple message) + + if (progress) // Send everyone's individual progression { - NBTTagCompound payload = message.getFirst(); - int[] reqIDs = !payload.hasKey("requestIDs", 11) ? null : payload.getIntArray("requestIDs"); - sendSync(message.getSecond(), reqIDs, payload.getBoolean("getConfig"), payload.getBoolean("getProgress")); + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + if (server == null) { return; } + + for (EntityPlayerMP player : server.getPlayerList().getPlayers()) { + sendSync(player, IDs, false, true); // Progression only this pass + } } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - NBTTagList data = message.getTagList("data", 10); - boolean merge = message.getBoolean("merge"); - if(!merge) QuestDatabase.INSTANCE.reset(); - - for(int i = 0; i < data.tagCount(); i++) - { - NBTTagCompound tag = data.getCompoundTagAt(i); - if(!tag.hasKey("questID", 99)) continue; - int questID = tag.getInteger("questID"); - - IQuest quest = QuestDatabase.INSTANCE.getValue(questID); - - if(tag.hasKey("config", 10)) - { - if(quest == null) quest = QuestDatabase.INSTANCE.createNew(questID); - quest.readFromNBT(tag.getCompoundTag("config")); - } - - if(tag.hasKey("progress", 10) && quest != null) - { - // TODO: Fix this properly - // If there we're not running the LAN server off this client then we overwrite always - quest.readProgressFromNBT(tag.getCompoundTag("progress"), merge || Minecraft.getMinecraft().isIntegratedServerRunning()); - } - } - - MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.QUEST)); + } + + @Deprecated + public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] questIDs, boolean config, + boolean progress) { + sendSync(player, questIDs, null, config, progress); + } + + public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] questIDs, @Nullable int[] resetIDs, + boolean config, boolean progress) { + if ((!config && !progress) || (questIDs != null && questIDs.length == 0)) { return; } + + // Offload this to another thread as it could take a while to build + BQThreadedIO.INSTANCE.enqueue(() -> { + NBTTagList dataList = new NBTTagList(); + final List> questSubset = + questIDs == null ? QuestDatabase.INSTANCE.getEntries() : QuestDatabase.INSTANCE.bulkLookup(questIDs); + final List pidList = player == null ? null : Collections.singletonList(QuestingAPI.getQuestingUUID(player)); + + for (DBEntry entry : questSubset) { + NBTTagCompound tag = new NBTTagCompound(); + + if (config) { tag.setTag("config", entry.getValue().writeToNBT(new NBTTagCompound())); } + if (progress) { tag.setTag("progress", entry.getValue().writeProgressToNBT(new NBTTagCompound(), pidList)); } + if (resetIDs != null) { tag.setIntArray("resets", resetIDs); } + tag.setInteger("questID", entry.getID()); + dataList.appendTag(tag); + } + + NBTTagCompound payload = new NBTTagCompound(); + payload.setBoolean("merge", !config || questIDs != null); + payload.setTag("data", dataList); + + if (player == null) { + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); + } else { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } + }); + } + + // Asks the server to send specific quest data over + @SideOnly(Side.CLIENT) + public static void requestSync(@Nullable int[] questIDs, boolean configs, boolean progress) { + NBTTagCompound payload = new NBTTagCompound(); + if (questIDs != null) { payload.setIntArray("requestIDs", questIDs); } + payload.setBoolean("getConfig", configs); + payload.setBoolean("getProgress", progress); + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + private static void onServer(Tuple message) { + NBTTagCompound payload = message.getFirst(); + int[] reqIDs = !payload.hasKey("requestIDs", 11) ? null : payload.getIntArray("requestIDs"); + sendSync(message.getSecond(), reqIDs, payload.getBoolean("getConfig"), payload.getBoolean("getProgress")); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + NBTTagList data = message.getTagList("data", 10); + boolean merge = message.getBoolean("merge"); + if (!merge) { QuestDatabase.INSTANCE.reset(); } + + for (int i = 0; i < data.tagCount(); i++) { + NBTTagCompound tag = data.getCompoundTagAt(i); + if (!tag.hasKey("questID", 99)) { continue; } + int questID = tag.getInteger("questID"); + + IQuest quest = QuestDatabase.INSTANCE.getValue(questID); + + if (tag.hasKey("config", 10)) { + if (quest == null) { quest = QuestDatabase.INSTANCE.createNew(questID); } + quest.readFromNBT(tag.getCompoundTag("config")); + } + + if (tag.hasKey("progress", 10) && quest != null) { + // TODO: Fix this properly + // If there we're not running the LAN server off this client then we overwrite always + quest.readProgressFromNBT(tag.getCompoundTag("progress"), + merge || Minecraft.getMinecraft().isIntegratedServerRunning()); + } } + + MinecraftForge.EVENT_BUS.post(new DatabaseEvent.Update(DBType.QUEST)); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetSettingSync.java b/src/main/java/betterquesting/network/handlers/NetSettingSync.java index b2e4c30bb..a996ea46d 100644 --- a/src/main/java/betterquesting/network/handlers/NetSettingSync.java +++ b/src/main/java/betterquesting/network/handlers/NetSettingSync.java @@ -19,59 +19,51 @@ import javax.annotation.Nullable; -public class NetSettingSync -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:setting_sync"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetSettingSync::onServer); - - if(BetterQuesting.proxy.isClient()) - { - PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetSettingSync::onClient); - } - } - - @SideOnly(Side.CLIENT) - public static void requestEdit() - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); - } - - public static void sendSync(@Nullable EntityPlayerMP player) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setTag("data", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); - if(player != null) - { - PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); - } else - { - PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); - } +public class NetSettingSync { + private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:setting_sync"); + + public static void registerHandler() { + PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetSettingSync::onServer); + + if (BetterQuesting.proxy.isClient()) { + PacketTypeRegistry.INSTANCE.registerClientHandler(ID_NAME, NetSettingSync::onClient); } - - @SideOnly(Side.CLIENT) - private static void onClient(NBTTagCompound message) - { - QuestSettings.INSTANCE.readFromNBT(message.getCompoundTag("data")); + } + + @SideOnly(Side.CLIENT) + public static void requestEdit() { + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); + PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); + } + + public static void sendSync(@Nullable EntityPlayerMP player) { + NBTTagCompound payload = new NBTTagCompound(); + payload.setTag("data", QuestSettings.INSTANCE.writeToNBT(new NBTTagCompound())); + if (player != null) { + PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); + } else { + PacketSender.INSTANCE.sendToAll(new QuestingPacket(ID_NAME, payload)); } - - private static void onServer(Tuple message) - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if(!server.getPlayerList().canSendCommands(message.getSecond().getGameProfile())) - { - BetterQuesting.logger.log(Level.WARN, "Player " + message.getSecond().getName() + " (UUID:" + QuestingAPI.getQuestingUUID(message.getSecond()) + ") tried to edit settings without OP permissions!"); - sendSync(message.getSecond()); - return; - } - - QuestSettings.INSTANCE.readFromNBT(message.getFirst().getCompoundTag("data")); - SaveLoadHandler.INSTANCE.markDirty(); - sendSync(null); + } + + @SideOnly(Side.CLIENT) + private static void onClient(NBTTagCompound message) { + QuestSettings.INSTANCE.readFromNBT(message.getCompoundTag("data")); + } + + private static void onServer(Tuple message) { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + if (!server.getPlayerList().canSendCommands(message.getSecond().getGameProfile())) { + BetterQuesting.logger.log(Level.WARN, "Player " + message.getSecond().getName() + " (UUID:" + + QuestingAPI.getQuestingUUID(message.getSecond()) + + ") tried to edit settings without OP permissions!"); + sendSync(message.getSecond()); + return; } + + QuestSettings.INSTANCE.readFromNBT(message.getFirst().getCompoundTag("data")); + SaveLoadHandler.INSTANCE.markDirty(); + sendSync(null); + } } diff --git a/src/main/java/betterquesting/network/handlers/NetStationEdit.java b/src/main/java/betterquesting/network/handlers/NetStationEdit.java index 9cc760de0..4ef14fb0c 100644 --- a/src/main/java/betterquesting/network/handlers/NetStationEdit.java +++ b/src/main/java/betterquesting/network/handlers/NetStationEdit.java @@ -1,76 +1,19 @@ package betterquesting.network.handlers; -import betterquesting.api.api.QuestingAPI; -import betterquesting.api.network.QuestingPacket; -import betterquesting.api.questing.IQuest; -import betterquesting.api.questing.tasks.ITask; -import betterquesting.blocks.TileSubmitStation; -import betterquesting.network.PacketSender; -import betterquesting.network.PacketTypeRegistry; -import betterquesting.questing.QuestDatabase; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.Tuple; +import betterquesting.core.BetterQuesting; +import betterquesting.network.PacketSetupStation; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import java.util.UUID; +public class NetStationEdit { + @SideOnly(Side.CLIENT) + public static void setupStation(BlockPos pos, int questID, int taskID, byte windowsID) { + BetterQuesting.instance.network.sendToServer(new PacketSetupStation(pos, questID, taskID, windowsID)); + } -public class NetStationEdit -{ - private static final ResourceLocation ID_NAME = new ResourceLocation("betterquesting:station_edit"); - - public static void registerHandler() - { - PacketTypeRegistry.INSTANCE.registerServerHandler(ID_NAME, NetStationEdit::onServer); - } - - @SideOnly(Side.CLIENT) - public static void setupStation(BlockPos pos, int questID, int taskID) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 1); - payload.setInteger("questID", questID); - payload.setInteger("task", taskID); - payload.setLong("tilePos", pos.toLong()); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); - } - - @SideOnly(Side.CLIENT) - public static void resetStation(BlockPos pos) - { - NBTTagCompound payload = new NBTTagCompound(); - payload.setInteger("action", 0); - payload.setLong("tilePos", pos.toLong()); - PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); - } - - private static void onServer(Tuple message) - { - NBTTagCompound data = message.getFirst(); - BlockPos pos = BlockPos.fromLong(data.getLong("tilePos")); - TileEntity tile = message.getSecond().world.getTileEntity(pos); - - if(tile instanceof TileSubmitStation) - { - TileSubmitStation oss = (TileSubmitStation)tile; - if(oss.isUsableByPlayer(message.getSecond())) - { - int action = data.getInteger("action"); - if(action == 0) - { - oss.reset(); - } else if(action == 1) - { - UUID QID = QuestingAPI.getQuestingUUID(message.getSecond()); - IQuest quest = QuestDatabase.INSTANCE.getValue(data.getInteger("questID")); - ITask task = quest == null ? null : quest.getTasks().getValue(data.getInteger("taskID")); - if(quest != null && task != null) oss.setupTask(QID, quest, task); - } - } - } - } + @SideOnly(Side.CLIENT) + public static void resetStation(BlockPos pos, byte windowID) { + BetterQuesting.instance.network.sendToServer(new PacketSetupStation(pos, -1, -1, windowID)); + } } diff --git a/src/main/java/betterquesting/questing/QuestDatabase.java b/src/main/java/betterquesting/questing/QuestDatabase.java index 0e753b899..f194acddb 100644 --- a/src/main/java/betterquesting/questing/QuestDatabase.java +++ b/src/main/java/betterquesting/questing/QuestDatabase.java @@ -11,114 +11,99 @@ import java.util.List; import java.util.UUID; -public final class QuestDatabase extends SimpleDatabase implements IQuestDatabase -{ - public static final QuestDatabase INSTANCE = new QuestDatabase(); - - @Override - public synchronized IQuest createNew(int id) - { - IQuest quest = new QuestInstance(); - if(id >= 0) this.add(id, quest); - return quest; - } - - @Override - public synchronized boolean removeID(int id) - { - boolean success = super.removeID(id); - if(success) for(DBEntry entry : getEntries()) removeReq(entry.getValue(), id); - return success; +public final class QuestDatabase extends SimpleDatabase implements IQuestDatabase { + public static final QuestDatabase INSTANCE = new QuestDatabase(); + + @Override + public synchronized IQuest createNew(int id) { + IQuest quest = new QuestInstance(); + if (id >= 0) { this.add(id, quest); } + return quest; + } + + @Override + public synchronized boolean removeID(int id) { + boolean success = super.removeID(id); + if (success) { for (DBEntry entry : getEntries()) { removeReq(entry.getValue(), id); } } + return success; + } + + @Override + public synchronized boolean removeValue(IQuest value) { + int id = this.getID(value); + if (id < 0) { return false; } + boolean success = this.removeValue(value); + if (success) { for (DBEntry entry : getEntries()) { removeReq(entry.getValue(), id); } } + return success; + } + + private void removeReq(IQuest quest, int id) { + int[] orig = quest.getRequirements(); + if (orig.length == 0) { return; } + boolean hasRemoved = false; + int[] rem = new int[orig.length - 1]; + for (int i = 0; i < orig.length; i++) { + if (!hasRemoved && orig[i] == id) { + hasRemoved = true; + continue; + } else if (!hasRemoved && i >= rem.length) { break; } + + rem[!hasRemoved ? i : (i - 1)] = orig[i]; } - - @Override - public synchronized boolean removeValue(IQuest value) - { - int id = this.getID(value); - if(id < 0) return false; - boolean success = this.removeValue(value); - if(success) for(DBEntry entry : getEntries()) removeReq(entry.getValue(), id); - return success; + + if (hasRemoved) { quest.setRequirements(rem); } + } + + @Override + public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { + for (DBEntry entry : this.getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { continue; } + NBTTagCompound jq = entry.getValue().writeToNBT(new NBTTagCompound()); + if (subset != null && jq.isEmpty()) { continue; } + jq.setInteger("questID", entry.getID()); + json.appendTag(jq); } - - private void removeReq(IQuest quest, int id) - { - int[] orig = quest.getRequirements(); - if(orig.length <= 0) return; - boolean hasRemoved = false; - int[] rem = new int[orig.length - 1]; - for(int i = 0; i < orig.length; i++) - { - if(!hasRemoved && orig[i] == id) - { - hasRemoved = true; - continue; - } else if(!hasRemoved && i >= rem.length) break; - - rem[!hasRemoved ? i : (i - 1)] = orig[i]; - } - - if(hasRemoved) quest.setRequirements(rem); + + return json; + } + + @Override + public synchronized void readFromNBT(NBTTagList nbt, boolean merge) { + if (!merge) { this.reset(); } + + for (int i = 0; i < nbt.tagCount(); i++) { + NBTTagCompound qTag = nbt.getCompoundTagAt(i); + + int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; + if (qID < 0) { continue; } + + IQuest quest = getValue(qID); + if (quest == null) { quest = this.createNew(qID); } + quest.readFromNBT(qTag); + } + } + + @Override + public synchronized NBTTagList writeProgressToNBT(NBTTagList json, @Nullable List users) { + for (DBEntry entry : this.getEntries()) { + NBTTagCompound jq = entry.getValue().writeProgressToNBT(new NBTTagCompound(), users); + jq.setInteger("questID", entry.getID()); + json.appendTag(jq); + } + + return json; + } + + @Override + public synchronized void readProgressFromNBT(NBTTagList json, boolean merge) { + for (int i = 0; i < json.tagCount(); i++) { + NBTTagCompound qTag = json.getCompoundTagAt(i); + + int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; + if (qID < 0) { continue; } + + IQuest quest = getValue(qID); + if (quest != null) { quest.readProgressFromNBT(qTag, merge); } } - - @Override - public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) - { - for(DBEntry entry : this.getEntries()) - { - if(subset != null && !subset.contains(entry.getID())) continue; - NBTTagCompound jq = entry.getValue().writeToNBT(new NBTTagCompound()); - if(subset != null && jq.isEmpty()) continue; - jq.setInteger("questID", entry.getID()); - json.appendTag(jq); - } - - return json; - } - - @Override - public synchronized void readFromNBT(NBTTagList nbt, boolean merge) - { - if(!merge) this.reset(); - - for(int i = 0; i < nbt.tagCount(); i++) - { - NBTTagCompound qTag = nbt.getCompoundTagAt(i); - - int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; - if(qID < 0) continue; - - IQuest quest = getValue(qID); - if(quest == null) quest = this.createNew(qID); - quest.readFromNBT(qTag); - } - } - - @Override - public synchronized NBTTagList writeProgressToNBT(NBTTagList json, @Nullable List users) - { - for(DBEntry entry : this.getEntries()) - { - NBTTagCompound jq = entry.getValue().writeProgressToNBT(new NBTTagCompound(), users); - jq.setInteger("questID", entry.getID()); - json.appendTag(jq); - } - - return json; - } - - @Override - public synchronized void readProgressFromNBT(NBTTagList json, boolean merge) - { - for(int i = 0; i < json.tagCount(); i++) - { - NBTTagCompound qTag = json.getCompoundTagAt(i); - - int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; - if(qID < 0) continue; - - IQuest quest = getValue(qID); - if(quest != null) quest.readProgressFromNBT(qTag, merge); - } - } + } } diff --git a/src/main/java/betterquesting/questing/QuestInstance.java b/src/main/java/betterquesting/questing/QuestInstance.java index 7178a2733..3947b694c 100644 --- a/src/main/java/betterquesting/questing/QuestInstance.java +++ b/src/main/java/betterquesting/questing/QuestInstance.java @@ -32,550 +32,461 @@ import java.util.Map.Entry; import java.util.UUID; -public class QuestInstance implements IQuest -{ - private final TaskStorage tasks = new TaskStorage(); - private final RewardStorage rewards = new RewardStorage(); - - private final HashMap completeUsers = new HashMap<>(); - private int[] preRequisites = new int[0]; - - private final PropertyContainer qInfo = new PropertyContainer(); - - public QuestInstance() - { - this.setupProps(); - } - - private void setupProps() - { - setupValue(NativeProps.NAME, "New Quest"); - setupValue(NativeProps.DESC, "No Description"); - - setupValue(NativeProps.ICON, new BigItemStack(Items.NETHER_STAR)); - - setupValue(NativeProps.SOUND_COMPLETE); - setupValue(NativeProps.SOUND_UPDATE); - //setupValue(NativeProps.SOUND_UNLOCK); - - setupValue(NativeProps.LOGIC_QUEST, EnumLogic.AND); - setupValue(NativeProps.LOGIC_TASK, EnumLogic.AND); - - setupValue(NativeProps.REPEAT_TIME, -1); - setupValue(NativeProps.REPEAT_REL, true); - setupValue(NativeProps.LOCKED_PROGRESS, false); - setupValue(NativeProps.AUTO_CLAIM, false); - setupValue(NativeProps.SILENT, false); - setupValue(NativeProps.MAIN, false); - setupValue(NativeProps.GLOBAL_SHARE, false); - setupValue(NativeProps.SIMULTANEOUS, false); - setupValue(NativeProps.VISIBILITY, EnumQuestVisibility.NORMAL); - } - - private void setupValue(IPropertyType prop) - { - this.setupValue(prop, prop.getDefault()); - } - - private void setupValue(IPropertyType prop, T def) - { - qInfo.setProperty(prop, qInfo.getProperty(prop, def)); - } - - @Override - public void update(EntityPlayer player) - { - UUID playerID = QuestingAPI.getQuestingUUID(player); - - int done = 0; - - for(DBEntry entry : tasks.getEntries()) - { - if(entry.getValue().isComplete(playerID)) - { - done++; - } - } - - if(tasks.size() <= 0 || qInfo.getProperty(NativeProps.LOGIC_TASK).getResult(done, tasks.size())) - { - setComplete(playerID, System.currentTimeMillis()); - } else if(done > 0 && qInfo.getProperty(NativeProps.SIMULTANEOUS)) // TODO: There is actually an exploit here to do with locked progression bypassing simultaneous reset conditions. Fix? - { - resetUser(playerID, false); - } - } - - /** - * Fired when someone clicks the detect button for this quest - */ - @Override - public void detect(EntityPlayer player) - { - UUID playerID = QuestingAPI.getQuestingUUID(player); - QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if(qc == null) return; - int questID = QuestDatabase.INSTANCE.getID(this); - - if(isComplete(playerID) && (qInfo.getProperty(NativeProps.REPEAT_TIME) < 0 || rewards.size() <= 0)) - { - return; - } else if(!canSubmit(player)) - { - return; - } - - if(isUnlocked(playerID) || QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) - { - int done = 0; - boolean update = false; - - ParticipantInfo partInfo = new ParticipantInfo(player); - DBEntry dbe = new DBEntry<>(questID, this); - - for(DBEntry entry : tasks.getEntries()) - { - if(!entry.getValue().isComplete(playerID)) - { - entry.getValue().detect(partInfo, dbe); - - if(entry.getValue().isComplete(playerID)) - { - done++; - update = true; - } - } else - { - done++; - } - } - // Note: Tasks can mark the quest dirty themselves if progress changed but hasn't fully completed. - if(tasks.size() <= 0 || qInfo.getProperty(NativeProps.LOGIC_TASK).getResult(done, tasks.size())) - { - // State won't be auto updated in edit mode so we force change it here and mark it for re-sync - if(QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) setComplete(playerID, System.currentTimeMillis()); - qc.markQuestDirty(questID); - } else if(update && qInfo.getProperty(NativeProps.SIMULTANEOUS)) - { - resetUser(playerID, false); - qc.markQuestDirty(questID); - } else if(update) - { - qc.markQuestDirty(questID); - } - } - } - - @Override - public boolean hasClaimed(UUID uuid) - { - if(rewards.size() <= 0) return true; - - synchronized(completeUsers) - { - if(qInfo.getProperty(NativeProps.GLOBAL) && !qInfo.getProperty(NativeProps.GLOBAL_SHARE)) - { - // TODO: Figure out some replacement to track participation - for(NBTTagCompound entry : completeUsers.values()) - { - if(entry.getBoolean("claimed")) return true; - } - - return false; - } - - NBTTagCompound entry = getCompletionInfo(uuid); - return entry != null && entry.getBoolean("claimed"); - } - } - - @Override - public boolean canClaim(EntityPlayer player) - { - UUID pID = QuestingAPI.getQuestingUUID(player); - NBTTagCompound entry = getCompletionInfo(pID); - - if(entry == null || hasClaimed(pID) || canSubmit(player)) - { - return false; - } else - { - DBEntry dbe = new DBEntry<>(QuestDatabase.INSTANCE.getID(this), this); - for(DBEntry rew : rewards.getEntries()) - { - if(!rew.getValue().canClaim(player, dbe)) - { - return false; - } - } - } - - return true; - } - - @Override - public void claimReward(EntityPlayer player) - { - int questID = QuestDatabase.INSTANCE.getID(this); - DBEntry dbe = new DBEntry<>(questID, this); - for(DBEntry rew : rewards.getEntries()) - { - rew.getValue().claimReward(player, dbe); - } - - UUID pID = QuestingAPI.getQuestingUUID(player); - QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - - synchronized(completeUsers) - { - NBTTagCompound entry = getCompletionInfo(pID); - - if(entry == null) - { - entry = new NBTTagCompound(); - this.completeUsers.put(pID, entry); - } - - entry.setBoolean("claimed", true); - entry.setLong("timestamp", System.currentTimeMillis()); - } - - if(qc != null) qc.markQuestDirty(questID); - } - - @Override - public boolean canSubmit(@Nonnull EntityPlayer player) - { - UUID playerID = QuestingAPI.getQuestingUUID(player); - - synchronized(completeUsers) - { - NBTTagCompound entry = this.getCompletionInfo(playerID); - if(entry == null) return true; - - if(!entry.getBoolean("claimed") && getProperty(NativeProps.REPEAT_TIME) >= 0) // Complete but repeatable - { - if(tasks.size() <= 0) return true; - - int done = 0; - - for(DBEntry tsk : tasks.getEntries()) - { - if(tsk.getValue().isComplete(playerID)) - { - done += 1; - } - } - - return !qInfo.getProperty(NativeProps.LOGIC_TASK).getResult(done, tasks.size()); - } else - { - return false; - } - } - } - - @Override - public boolean isUnlocked(UUID uuid) - { - if(preRequisites.length <= 0) return true; - - int A = 0; - int B = preRequisites.length; - - for(DBEntry quest : QuestDatabase.INSTANCE.bulkLookup(getRequirements())) - { - if(quest.getValue().isComplete(uuid)) - { - A++; - } - } - - return qInfo.getProperty(NativeProps.LOGIC_QUEST).getResult(A, B); - } - - @Override - public void setComplete(UUID uuid, long timestamp) +public class QuestInstance implements IQuest { + private final TaskStorage tasks = new TaskStorage(); + private final RewardStorage rewards = new RewardStorage(); + + private final HashMap completeUsers = new HashMap<>(); + private int[] preRequisites = new int[0]; + + private final PropertyContainer qInfo = new PropertyContainer(); + + public QuestInstance() { + this.setupProps(); + } + + private void setupProps() { + setupValue(NativeProps.NAME, "New Quest"); + setupValue(NativeProps.DESC, "No Description"); + + setupValue(NativeProps.ICON, new BigItemStack(Items.NETHER_STAR)); + + setupValue(NativeProps.SOUND_COMPLETE); + setupValue(NativeProps.SOUND_UPDATE); + //setupValue(NativeProps.SOUND_UNLOCK); + + setupValue(NativeProps.LOGIC_QUEST, EnumLogic.AND); + setupValue(NativeProps.LOGIC_TASK, EnumLogic.AND); + + setupValue(NativeProps.REPEAT_TIME, -1); + setupValue(NativeProps.REPEAT_REL, true); + setupValue(NativeProps.LOCKED_PROGRESS, false); + setupValue(NativeProps.AUTO_CLAIM, false); + setupValue(NativeProps.SILENT, false); + setupValue(NativeProps.MAIN, false); + setupValue(NativeProps.GLOBAL_SHARE, false); + setupValue(NativeProps.SIMULTANEOUS, false); + setupValue(NativeProps.VISIBILITY, EnumQuestVisibility.NORMAL); + } + + private void setupValue(IPropertyType prop) { + this.setupValue(prop, prop.getDefault()); + } + + private void setupValue(IPropertyType prop, T def) { + qInfo.setProperty(prop, qInfo.getProperty(prop, def)); + } + + @Override + public void update(EntityPlayer player) { + UUID playerID = QuestingAPI.getQuestingUUID(player); + + int done = 0; + + for (DBEntry entry : tasks.getEntries()) { + if (entry.getValue().isComplete(playerID)) { + done++; + } + } + + if (tasks.size() <= 0 || qInfo.getProperty(NativeProps.LOGIC_TASK).getResult(done, tasks.size())) { + setComplete(playerID, System.currentTimeMillis()); + } else if (done > 0 && qInfo.getProperty( + NativeProps.SIMULTANEOUS)) // TODO: There is actually an exploit here to do with locked progression bypassing simultaneous reset conditions. Fix? { - if(uuid == null) return; - - synchronized(completeUsers) - { - NBTTagCompound entry = this.getCompletionInfo(uuid); - - if(entry == null) - { - entry = new NBTTagCompound(); - completeUsers.put(uuid, entry); - } - - entry.setBoolean("claimed", false); - entry.setLong("timestamp", timestamp); - } + resetUser(playerID, false); } - - /** - * Returns true if the quest has been completed at least once - */ - @Override - public boolean isComplete(UUID uuid) - { - if(qInfo.getProperty(NativeProps.GLOBAL)) - { - return completeUsers.size() > 0; - } else - { - return getCompletionInfo(uuid) != null; - } - } - - @Override - public EnumQuestState getState(UUID uuid) - { - if(this.isComplete(uuid)) - { - if(this.hasClaimed(uuid)) - { - return EnumQuestState.COMPLETED; - } else - { - return EnumQuestState.UNCLAIMED; - } - } else if(this.isUnlocked(uuid)) - { - return EnumQuestState.UNLOCKED; - } - - return EnumQuestState.LOCKED; - } - - @Override - public NBTTagCompound getCompletionInfo(UUID uuid) - { - synchronized(completeUsers) - { - return completeUsers.get(uuid); + } + + /** + * Fired when someone clicks the detect button for this quest + */ + @Override + public void detect(EntityPlayer player) { + UUID playerID = QuestingAPI.getQuestingUUID(player); + QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc == null) { return; } + int questID = QuestDatabase.INSTANCE.getID(this); + + if (isComplete(playerID) && (qInfo.getProperty(NativeProps.REPEAT_TIME) < 0 || rewards.size() <= 0)) { + return; + } else if (!canSubmit(player)) { + return; + } + + if (isUnlocked(playerID) || QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) { + int done = 0; + boolean update = false; + + ParticipantInfo partInfo = new ParticipantInfo(player); + DBEntry dbe = new DBEntry<>(questID, this); + + for (DBEntry entry : tasks.getEntries()) { + if (!entry.getValue().isComplete(playerID)) { + entry.getValue().detect(partInfo, dbe); + + if (entry.getValue().isComplete(playerID)) { + done++; + update = true; + } + } else { + done++; } - } - - @Override - public void setCompletionInfo(UUID uuid, NBTTagCompound nbt) - { - if(uuid == null) return; - - synchronized(completeUsers) - { - if(nbt == null) - { - completeUsers.remove(uuid); - } else - { - completeUsers.put(uuid, nbt); - } + } + // Note: Tasks can mark the quest dirty themselves if progress changed but hasn't fully completed. + if (tasks.size() <= 0 || qInfo.getProperty(NativeProps.LOGIC_TASK).getResult(done, tasks.size())) { + // State won't be auto updated in edit mode so we force change it here and mark it for re-sync + if (QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) { + setComplete(playerID, System.currentTimeMillis()); } + qc.markQuestDirty(questID); + } else if (update && qInfo.getProperty(NativeProps.SIMULTANEOUS)) { + resetUser(playerID, false); + qc.markQuestDirty(questID); + } else if (update) { + qc.markQuestDirty(questID); + } } - - /** - * Resets task progress and claim status. If performing a full reset, completion status will also be erased - */ - @Override - public void resetUser(@Nullable UUID uuid, boolean fullReset) - { - synchronized(completeUsers) - { - if(fullReset) - { - if(uuid == null) - { - completeUsers.clear(); - } else - { - completeUsers.remove(uuid); - } - } else - { - if(uuid == null) - { - completeUsers.forEach((key, value) -> { - value.setBoolean("claimed", false); - value.setLong("timestamp", 0); - }); - } else - { - NBTTagCompound entry = getCompletionInfo(uuid); - if(entry != null) - { - entry.setBoolean("claimed", false); - entry.setLong("timestamp", 0); - } - } - } - - tasks.getEntries().forEach((value) -> value.getValue().resetUser(uuid)); + } + + @Override + public boolean hasClaimed(UUID uuid) { + if (rewards.size() <= 0) { return true; } + + synchronized (completeUsers) { + if (qInfo.getProperty(NativeProps.GLOBAL) && !qInfo.getProperty(NativeProps.GLOBAL_SHARE)) { + // TODO: Figure out some replacement to track participation + for (NBTTagCompound entry : completeUsers.values()) { + if (entry.getBoolean("claimed")) { return true; } } - } - - @Override - public IDatabaseNBT getTasks() - { - return tasks; - } - - @Override - public IDatabaseNBT getRewards() - { - return rewards; - } - - @Nonnull - @Override - public int[] getRequirements() - { - return this.preRequisites; + + return false; + } + + NBTTagCompound entry = getCompletionInfo(uuid); + return entry != null && entry.getBoolean("claimed"); } - - public void setRequirements(@Nonnull int[] req) - { - this.preRequisites = req; + } + + @Override + public boolean canClaim(EntityPlayer player) { + UUID pID = QuestingAPI.getQuestingUUID(player); + NBTTagCompound entry = getCompletionInfo(pID); + + if (entry == null || hasClaimed(pID) || canSubmit(player)) { + return false; + } else { + DBEntry dbe = new DBEntry<>(QuestDatabase.INSTANCE.getID(this), this); + for (DBEntry rew : rewards.getEntries()) { + if (!rew.getValue().canClaim(player, dbe)) { + return false; + } + } } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound jObj) - { - jObj.setTag("properties", qInfo.writeToNBT(new NBTTagCompound())); - jObj.setTag("tasks", tasks.writeToNBT(new NBTTagList(), null)); - jObj.setTag("rewards", rewards.writeToNBT(new NBTTagList(), null)); - jObj.setTag("preRequisites", new NBTTagIntArray(getRequirements())); - - return jObj; - } - - @Override - public void readFromNBT(NBTTagCompound jObj) - { - this.qInfo.readFromNBT(jObj.getCompoundTag("properties")); - this.tasks.readFromNBT(jObj.getTagList("tasks", 10), false); - this.rewards.readFromNBT(jObj.getTagList("rewards", 10), false); - - if(jObj.getTagId("preRequisites") == 11) // Native NBT - { - setRequirements(jObj.getIntArray("preRequisites")); - } else // Probably an NBTTagList - { - NBTTagList rList = jObj.getTagList("preRequisites", 4); - int[] req = new int[rList.tagCount()]; - for(int i = 0; i < rList.tagCount(); i++) - { - NBTBase pTag = rList.get(i); - req[i] = pTag instanceof NBTPrimitive ? ((NBTPrimitive)pTag).getInt() : -1; - } - setRequirements(req); - } - - this.setupProps(); - } - - @Override - public NBTTagCompound writeProgressToNBT(NBTTagCompound json, @Nullable List users) - { - synchronized(completeUsers) - { - NBTTagList comJson = new NBTTagList(); - for(Entry entry : completeUsers.entrySet()) - { - if(users != null && !users.contains(entry.getKey())) continue; - NBTTagCompound tags = entry.getValue().copy(); - tags.setString("uuid", entry.getKey().toString()); - comJson.appendTag(tags); - } - json.setTag("completed", comJson); - - NBTTagList tskJson = tasks.writeProgressToNBT(new NBTTagList(), users); - json.setTag("tasks", tskJson); - - return json; + + return true; + } + + @Override + public void claimReward(EntityPlayer player) { + int questID = QuestDatabase.INSTANCE.getID(this); + DBEntry dbe = new DBEntry<>(questID, this); + for (DBEntry rew : rewards.getEntries()) { + rew.getValue().claimReward(player, dbe); + } + + UUID pID = QuestingAPI.getQuestingUUID(player); + QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + + synchronized (completeUsers) { + NBTTagCompound entry = getCompletionInfo(pID); + + if (entry == null) { + entry = new NBTTagCompound(); + this.completeUsers.put(pID, entry); + } + + entry.setBoolean("claimed", true); + entry.setLong("timestamp", System.currentTimeMillis()); + } + + if (qc != null) { qc.markQuestDirty(questID); } + } + + @Override + public boolean canSubmit(@Nonnull EntityPlayer player) { + UUID playerID = QuestingAPI.getQuestingUUID(player); + + synchronized (completeUsers) { + NBTTagCompound entry = this.getCompletionInfo(playerID); + if (entry == null) { return true; } + + if (!entry.getBoolean("claimed") && getProperty(NativeProps.REPEAT_TIME) >= 0) // Complete but repeatable + { + if (tasks.size() <= 0) { return true; } + + int done = 0; + + for (DBEntry tsk : tasks.getEntries()) { + if (tsk.getValue().isComplete(playerID)) { + done += 1; + } } - } - - @Override - public void readProgressFromNBT(NBTTagCompound json, boolean merge) - { - synchronized(completeUsers) - { - if(!merge) completeUsers.clear(); - NBTTagList comList = json.getTagList("completed", 10); - for(int i = 0; i < comList.tagCount(); i++) - { - NBTTagCompound entry = comList.getCompoundTagAt(i).copy(); - - try - { - UUID uuid = UUID.fromString(entry.getString("uuid")); - completeUsers.put(uuid, entry); - } catch(Exception e) - { - BetterQuesting.logger.log(Level.ERROR, "Unable to load UUID for quest", e); - } - } - - tasks.readProgressFromNBT(json.getTagList("tasks", 10), merge); + + return !qInfo.getProperty(NativeProps.LOGIC_TASK).getResult(done, tasks.size()); + } else { + return false; + } + } + } + + @Override + public boolean isUnlocked(UUID uuid) { + if (preRequisites.length == 0) { return true; } + + int A = 0; + int B = preRequisites.length; + + for (DBEntry quest : QuestDatabase.INSTANCE.bulkLookup(getRequirements())) { + if (quest.getValue().isComplete(uuid)) { + A++; + } + } + + return qInfo.getProperty(NativeProps.LOGIC_QUEST).getResult(A, B); + } + + @Override + public void setComplete(UUID uuid, long timestamp) { + if (uuid == null) { return; } + + synchronized (completeUsers) { + NBTTagCompound entry = this.getCompletionInfo(uuid); + + if (entry == null) { + entry = new NBTTagCompound(); + completeUsers.put(uuid, entry); + } + + entry.setBoolean("claimed", false); + entry.setLong("timestamp", timestamp); + } + } + + /** + * Returns true if the quest has been completed at least once + */ + @Override + public boolean isComplete(UUID uuid) { + if (qInfo.getProperty(NativeProps.GLOBAL)) { + return !completeUsers.isEmpty(); + } else { + return getCompletionInfo(uuid) != null; + } + } + + @Override + public EnumQuestState getState(UUID uuid) { + if (this.isComplete(uuid)) { + if (this.hasClaimed(uuid)) { + return EnumQuestState.COMPLETED; + } else { + return EnumQuestState.UNCLAIMED; + } + } else if (this.isUnlocked(uuid)) { + return EnumQuestState.UNLOCKED; + } + + return EnumQuestState.LOCKED; + } + + @Override + public NBTTagCompound getCompletionInfo(UUID uuid) { + synchronized (completeUsers) { + return completeUsers.get(uuid); + } + } + + @Override + public void setCompletionInfo(UUID uuid, NBTTagCompound nbt) { + if (uuid == null) { return; } + + synchronized (completeUsers) { + if (nbt == null) { + completeUsers.remove(uuid); + } else { + completeUsers.put(uuid, nbt); + } + } + } + + /** + * Resets task progress and claim status. If performing a full reset, completion status will also be erased + */ + @Override + public void resetUser(@Nullable UUID uuid, boolean fullReset) { + synchronized (completeUsers) { + if (fullReset) { + if (uuid == null) { + completeUsers.clear(); + } else { + completeUsers.remove(uuid); } - } - - @Override - public void setClaimed(UUID uuid, long timestamp) - { - synchronized(completeUsers) - { - NBTTagCompound entry = this.getCompletionInfo(uuid); - - if(entry != null) - { - entry.setBoolean("claimed", true); - entry.setLong("timestamp", timestamp); - } else - { - entry = new NBTTagCompound(); - entry.setBoolean("claimed", true); - entry.setLong("timestamp", timestamp); - completeUsers.put(uuid, entry); - } + } else { + if (uuid == null) { + completeUsers.forEach((key, value) -> { + value.setBoolean("claimed", false); + value.setLong("timestamp", 0); + }); + } else { + NBTTagCompound entry = getCompletionInfo(uuid); + if (entry != null) { + entry.setBoolean("claimed", false); + entry.setLong("timestamp", 0); + } } - } - - @Override - public T getProperty(IPropertyType prop) - { - return qInfo.getProperty(prop); + } + + tasks.getEntries().forEach((value) -> value.getValue().resetUser(uuid)); } - - @Override - public T getProperty(IPropertyType prop, T def) + } + + @Override + public IDatabaseNBT getTasks() { + return tasks; + } + + @Override + public IDatabaseNBT getRewards() { + return rewards; + } + + @Nonnull + @Override + public int[] getRequirements() { + return this.preRequisites; + } + + public void setRequirements(@Nonnull int[] req) { + this.preRequisites = req; + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound jObj) { + jObj.setTag("properties", qInfo.writeToNBT(new NBTTagCompound())); + jObj.setTag("tasks", tasks.writeToNBT(new NBTTagList(), null)); + jObj.setTag("rewards", rewards.writeToNBT(new NBTTagList(), null)); + jObj.setTag("preRequisites", new NBTTagIntArray(getRequirements())); + + return jObj; + } + + @Override + public void readFromNBT(NBTTagCompound jObj) { + this.qInfo.readFromNBT(jObj.getCompoundTag("properties")); + this.tasks.readFromNBT(jObj.getTagList("tasks", 10), false); + this.rewards.readFromNBT(jObj.getTagList("rewards", 10), false); + + if (jObj.getTagId("preRequisites") == 11) // Native NBT { - return qInfo.getProperty(prop, def); - } - - @Override - public boolean hasProperty(IPropertyType prop) + setRequirements(jObj.getIntArray("preRequisites")); + } else // Probably an NBTTagList { - return qInfo.hasProperty(prop); + NBTTagList rList = jObj.getTagList("preRequisites", 4); + int[] req = new int[rList.tagCount()]; + for (int i = 0; i < rList.tagCount(); i++) { + NBTBase pTag = rList.get(i); + req[i] = pTag instanceof NBTPrimitive ? ((NBTPrimitive) pTag).getInt() : -1; + } + setRequirements(req); } - - @Override - public void setProperty(IPropertyType prop, T value) - { - qInfo.setProperty(prop, value); + + this.setupProps(); + } + + @Override + public NBTTagCompound writeProgressToNBT(NBTTagCompound json, @Nullable List users) { + synchronized (completeUsers) { + NBTTagList comJson = new NBTTagList(); + for (Entry entry : completeUsers.entrySet()) { + if (users != null && !users.contains(entry.getKey())) { continue; } + NBTTagCompound tags = entry.getValue().copy(); + tags.setString("uuid", entry.getKey().toString()); + comJson.appendTag(tags); + } + json.setTag("completed", comJson); + + NBTTagList tskJson = tasks.writeProgressToNBT(new NBTTagList(), users); + json.setTag("tasks", tskJson); + + return json; } - - @Override - public void removeProperty(IPropertyType prop) - { - qInfo.removeProperty(prop); + } + + @Override + public void readProgressFromNBT(NBTTagCompound json, boolean merge) { + synchronized (completeUsers) { + if (!merge) { completeUsers.clear(); } + NBTTagList comList = json.getTagList("completed", 10); + for (int i = 0; i < comList.tagCount(); i++) { + NBTTagCompound entry = comList.getCompoundTagAt(i).copy(); + + try { + UUID uuid = UUID.fromString(entry.getString("uuid")); + completeUsers.put(uuid, entry); + } catch (Exception e) { + BetterQuesting.logger.log(Level.ERROR, "Unable to load UUID for quest", e); + } + } + + tasks.readProgressFromNBT(json.getTagList("tasks", 10), merge); } - - @Override - public void removeAllProps() - { - qInfo.removeAllProps(); + } + + @Override + public void setClaimed(UUID uuid, long timestamp) { + synchronized (completeUsers) { + NBTTagCompound entry = this.getCompletionInfo(uuid); + + if (entry != null) { + entry.setBoolean("claimed", true); + entry.setLong("timestamp", timestamp); + } else { + entry = new NBTTagCompound(); + entry.setBoolean("claimed", true); + entry.setLong("timestamp", timestamp); + completeUsers.put(uuid, entry); + } } + } + + @Override + public T getProperty(IPropertyType prop) { + return qInfo.getProperty(prop); + } + + @Override + public T getProperty(IPropertyType prop, T def) { + return qInfo.getProperty(prop, def); + } + + @Override + public boolean hasProperty(IPropertyType prop) { + return qInfo.hasProperty(prop); + } + + @Override + public void setProperty(IPropertyType prop, T value) { + qInfo.setProperty(prop, value); + } + + @Override + public void removeProperty(IPropertyType prop) { + qInfo.removeProperty(prop); + } + + @Override + public void removeAllProps() { + qInfo.removeAllProps(); + } } diff --git a/src/main/java/betterquesting/questing/QuestLine.java b/src/main/java/betterquesting/questing/QuestLine.java index 337ef6133..83121fd15 100644 --- a/src/main/java/betterquesting/questing/QuestLine.java +++ b/src/main/java/betterquesting/questing/QuestLine.java @@ -16,163 +16,140 @@ import javax.annotation.Nullable; import java.util.List; -public class QuestLine extends SimpleDatabase implements IQuestLine -{ - private PropertyContainer info = new PropertyContainer(); - - public QuestLine() - { - setupProps(); - } - - private void setupProps() - { - this.setupValue(NativeProps.NAME, "New Quest Line"); - this.setupValue(NativeProps.DESC, "No Description"); - this.setupValue(NativeProps.ICON, new BigItemStack(Items.BOOK)); - this.setupValue(NativeProps.VISIBILITY, EnumQuestVisibility.NORMAL); - this.setupValue(NativeProps.BG_IMAGE); - this.setupValue(NativeProps.BG_SIZE); - } - - private void setupValue(IPropertyType prop) - { - this.setupValue(prop, prop.getDefault()); - } - - private void setupValue(IPropertyType prop, T def) - { - info.setProperty(prop, info.getProperty(prop, def)); - } - - @Override - public IQuestLineEntry createNew(int id) - { - IQuestLineEntry qle = new QuestLineEntry(0, 0, 24, 24); - this.add(id, qle); - return qle; - } - - @Override - public String getUnlocalisedName() - { - String def = "New Quest Line"; - - if(!info.hasProperty(NativeProps.NAME)) - { - info.setProperty(NativeProps.NAME, def); - return def; - } - - return info.getProperty(NativeProps.NAME, def); - } - - @Override - public String getUnlocalisedDescription() - { - String def = "No Description"; - - if(!info.hasProperty(NativeProps.DESC)) - { - info.setProperty(NativeProps.DESC, def); - return def; - } - - return info.getProperty(NativeProps.DESC, def); - } - - @Override - public DBEntry getEntryAt(int x, int y) - { - for(DBEntry entry : getEntries()) - { - int i1 = entry.getValue().getPosX(); - int j1 = entry.getValue().getPosY(); - int i2 = i1 + entry.getValue().getSizeX(); - int j2 = j1 + entry.getValue().getSizeY(); - - if(x >= i1 && x < i2 && y >= j1 && y < j2) - { - return entry; - } - } - - return null; - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound json, @Nullable List subset) - { - json.setTag("properties", info.writeToNBT(new NBTTagCompound())); - - NBTTagList jArr = new NBTTagList(); - - for(DBEntry entry : getEntries()) - { - if(subset != null && !subset.contains(entry.getID())) continue; - NBTTagCompound qle = entry.getValue().writeToNBT(new NBTTagCompound()); - qle.setInteger("id", entry.getID()); - jArr.appendTag(qle); - } - - json.setTag("quests", jArr); - return json; - } - - @Override - public void readFromNBT(NBTTagCompound json, boolean merge) - { - info.readFromNBT(json.getCompoundTag("properties")); - - if(!merge) reset(); - - NBTTagList qList = json.getTagList("quests", 10); - for(int i = 0; i < qList.tagCount(); i++) - { - NBTTagCompound qTag = qList.getCompoundTagAt(i); - - int id = qTag.hasKey("id", 99) ? qTag.getInteger("id") : -1; - if(id< 0) continue; - - add(id, new QuestLineEntry(qTag)); - } - - this.setupProps(); - } - - @Override - public T getProperty(IPropertyType prop) - { - return info.getProperty(prop); - } - - @Override - public T getProperty(IPropertyType prop, T def) - { - return info.getProperty(prop, def); +public class QuestLine extends SimpleDatabase implements IQuestLine { + private final PropertyContainer info = new PropertyContainer(); + + public QuestLine() { + setupProps(); + } + + private void setupProps() { + this.setupValue(NativeProps.NAME, "New Quest Line"); + this.setupValue(NativeProps.DESC, "No Description"); + this.setupValue(NativeProps.ICON, new BigItemStack(Items.BOOK)); + this.setupValue(NativeProps.VISIBILITY, EnumQuestVisibility.NORMAL); + this.setupValue(NativeProps.BG_IMAGE); + this.setupValue(NativeProps.BG_SIZE); + } + + private void setupValue(IPropertyType prop) { + this.setupValue(prop, prop.getDefault()); + } + + private void setupValue(IPropertyType prop, T def) { + info.setProperty(prop, info.getProperty(prop, def)); + } + + @Override + public IQuestLineEntry createNew(int id) { + IQuestLineEntry qle = new QuestLineEntry(0, 0, 24, 24); + this.add(id, qle); + return qle; + } + + @Override + public String getUnlocalisedName() { + String def = "New Quest Line"; + + if (!info.hasProperty(NativeProps.NAME)) { + info.setProperty(NativeProps.NAME, def); + return def; } - - @Override - public boolean hasProperty(IPropertyType prop) - { - return info.hasProperty(prop); + + return info.getProperty(NativeProps.NAME, def); + } + + @Override + public String getUnlocalisedDescription() { + String def = "No Description"; + + if (!info.hasProperty(NativeProps.DESC)) { + info.setProperty(NativeProps.DESC, def); + return def; } - - @Override - public void setProperty(IPropertyType prop, T value) - { - info.setProperty(prop, value); + + return info.getProperty(NativeProps.DESC, def); + } + + @Override + public DBEntry getEntryAt(int x, int y) { + for (DBEntry entry : getEntries()) { + int i1 = entry.getValue().getPosX(); + int j1 = entry.getValue().getPosY(); + int i2 = i1 + entry.getValue().getSizeX(); + int j2 = j1 + entry.getValue().getSizeY(); + + if (x >= i1 && x < i2 && y >= j1 && y < j2) { + return entry; + } } - - @Override - public void removeProperty(IPropertyType prop) - { - info.removeProperty(prop); + + return null; + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound json, @Nullable List subset) { + json.setTag("properties", info.writeToNBT(new NBTTagCompound())); + + NBTTagList jArr = new NBTTagList(); + + for (DBEntry entry : getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { continue; } + NBTTagCompound qle = entry.getValue().writeToNBT(new NBTTagCompound()); + qle.setInteger("id", entry.getID()); + jArr.appendTag(qle); } - - @Override - public void removeAllProps() - { - info.removeAllProps(); + + json.setTag("quests", jArr); + return json; + } + + @Override + public void readFromNBT(NBTTagCompound json, boolean merge) { + info.readFromNBT(json.getCompoundTag("properties")); + + if (!merge) { reset(); } + + NBTTagList qList = json.getTagList("quests", 10); + for (int i = 0; i < qList.tagCount(); i++) { + NBTTagCompound qTag = qList.getCompoundTagAt(i); + + int id = qTag.hasKey("id", 99) ? qTag.getInteger("id") : -1; + if (id < 0) { continue; } + + add(id, new QuestLineEntry(qTag)); } + + this.setupProps(); + } + + @Override + public T getProperty(IPropertyType prop) { + return info.getProperty(prop); + } + + @Override + public T getProperty(IPropertyType prop, T def) { + return info.getProperty(prop, def); + } + + @Override + public boolean hasProperty(IPropertyType prop) { + return info.hasProperty(prop); + } + + @Override + public void setProperty(IPropertyType prop, T value) { + info.setProperty(prop, value); + } + + @Override + public void removeProperty(IPropertyType prop) { + info.removeProperty(prop); + } + + @Override + public void removeAllProps() { + info.removeAllProps(); + } } diff --git a/src/main/java/betterquesting/questing/QuestLineDatabase.java b/src/main/java/betterquesting/questing/QuestLineDatabase.java index 03a40c3d2..c9a3e1cd5 100644 --- a/src/main/java/betterquesting/questing/QuestLineDatabase.java +++ b/src/main/java/betterquesting/questing/QuestLineDatabase.java @@ -15,115 +15,101 @@ import java.util.HashMap; import java.util.List; -public final class QuestLineDatabase extends SimpleDatabase implements IQuestLineDatabase -{ - public static final QuestLineDatabase INSTANCE = new QuestLineDatabase(); - - private final List lineOrder = new ArrayList<>(); - private final QuestLineSorter SORTER = new QuestLineSorter(this); - - @Override - public synchronized int getOrderIndex(int lineID) - { - int order = lineOrder.indexOf(lineID); - if(order >= 0) return order; - if(getValue(lineID) == null) return -1; - - lineOrder.add(lineID); - return lineOrder.size() - 1; - } - - @Override - public synchronized void setOrderIndex(int lineID, int index) - { - lineOrder.remove((Integer)lineID); - lineOrder.add(MathHelper.clamp(index, 0, lineOrder.size()), lineID); - } - - @Override - public synchronized List> getSortedEntries() - { - List> list = new ArrayList<>(this.getEntries()); - list.sort(SORTER); - return list; - } - - @Override - public synchronized IQuestLine createNew(int id) - { - IQuestLine ql = new QuestLine(); - if(id >= 0) this.add(id, ql); - return ql; - } - - @Override - public synchronized void removeQuest(int questID) - { - for(DBEntry ql : getEntries()) - { - ql.getValue().removeID(questID); - } - } - - @Override - public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) - { - for(DBEntry entry : getEntries()) - { - if(subset != null && !subset.contains(entry.getID())) continue; - NBTTagCompound jObj = entry.getValue().writeToNBT(new NBTTagCompound(), null); - jObj.setInteger("lineID", entry.getID()); - jObj.setInteger("order", getOrderIndex(entry.getID())); - json.appendTag(jObj); - } - - return json; - } - - @Override - public synchronized void readFromNBT(NBTTagList json, boolean merge) - { - if(!merge) reset(); - - List unassigned = new ArrayList<>(); - HashMap orderMap = new HashMap<>(); - - for(int i = 0; i < json.tagCount(); i++) - { - NBTTagCompound jql = json.getCompoundTagAt(i); - - int id = jql.hasKey("lineID", 99) ? jql.getInteger("lineID") : -1; - int order = jql.hasKey("order", 99) ? jql.getInteger("order") : -1; - - IQuestLine line = getValue(id); - if(line == null) line = new QuestLine(); - line.readFromNBT(jql, false); - - if(id >= 0) - { - add(id, line); - } else - { - unassigned.add(line); - } - - if(order >= 0) orderMap.put(order, id); - } - - // Legacy support ONLY - for(IQuestLine q : unassigned) add(nextID(), q); - - List orderKeys = new ArrayList<>(orderMap.keySet()); - Collections.sort(orderKeys); - - lineOrder.clear(); - for(int o : orderKeys) lineOrder.add(orderMap.get(o)); - } - - @Override - public synchronized void reset() - { - super.reset(); - lineOrder.clear(); +public final class QuestLineDatabase extends SimpleDatabase implements IQuestLineDatabase { + public static final QuestLineDatabase INSTANCE = new QuestLineDatabase(); + + private final List lineOrder = new ArrayList<>(); + private final QuestLineSorter SORTER = new QuestLineSorter(this); + + @Override + public synchronized int getOrderIndex(int lineID) { + int order = lineOrder.indexOf(lineID); + if (order >= 0) { return order; } + if (getValue(lineID) == null) { return -1; } + + lineOrder.add(lineID); + return lineOrder.size() - 1; + } + + @Override + public synchronized void setOrderIndex(int lineID, int index) { + lineOrder.remove((Integer) lineID); + lineOrder.add(MathHelper.clamp(index, 0, lineOrder.size()), lineID); + } + + @Override + public synchronized List> getSortedEntries() { + List> list = new ArrayList<>(this.getEntries()); + list.sort(SORTER); + return list; + } + + @Override + public synchronized IQuestLine createNew(int id) { + IQuestLine ql = new QuestLine(); + if (id >= 0) { this.add(id, ql); } + return ql; + } + + @Override + public synchronized void removeQuest(int questID) { + for (DBEntry ql : getEntries()) { + ql.getValue().removeID(questID); + } + } + + @Override + public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { + for (DBEntry entry : getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { continue; } + NBTTagCompound jObj = entry.getValue().writeToNBT(new NBTTagCompound(), null); + jObj.setInteger("lineID", entry.getID()); + jObj.setInteger("order", getOrderIndex(entry.getID())); + json.appendTag(jObj); + } + + return json; + } + + @Override + public synchronized void readFromNBT(NBTTagList json, boolean merge) { + if (!merge) { reset(); } + + List unassigned = new ArrayList<>(); + HashMap orderMap = new HashMap<>(); + + for (int i = 0; i < json.tagCount(); i++) { + NBTTagCompound jql = json.getCompoundTagAt(i); + + int id = jql.hasKey("lineID", 99) ? jql.getInteger("lineID") : -1; + int order = jql.hasKey("order", 99) ? jql.getInteger("order") : -1; + + IQuestLine line = getValue(id); + if (line == null) { line = new QuestLine(); } + line.readFromNBT(jql, false); + + if (id >= 0) { + add(id, line); + } else { + unassigned.add(line); + } + + if (order >= 0) { orderMap.put(order, id); } } + + // Legacy support ONLY + for (IQuestLine q : unassigned) { add(nextID(), q); } + + List orderKeys = new ArrayList<>(orderMap.keySet()); + Collections.sort(orderKeys); + + lineOrder.clear(); + for (int o : orderKeys) { lineOrder.add(orderMap.get(o)); } + } + + @Override + public synchronized void reset() { + super.reset(); + lineOrder.clear(); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/questing/QuestLineEntry.java b/src/main/java/betterquesting/questing/QuestLineEntry.java index 072e6924c..752b3f57a 100644 --- a/src/main/java/betterquesting/questing/QuestLineEntry.java +++ b/src/main/java/betterquesting/questing/QuestLineEntry.java @@ -3,117 +3,100 @@ import betterquesting.api.questing.IQuestLineEntry; import net.minecraft.nbt.NBTTagCompound; -public class QuestLineEntry implements IQuestLineEntry -{ - private int sizeX = 0; - private int sizeY = 0; - private int posX = 0; - private int posY = 0; - - public QuestLineEntry(NBTTagCompound json) - { - this.readFromNBT(json); - } - - public QuestLineEntry(int x, int y) - { - this(x, y, 24, 24); - } - - @Deprecated - public QuestLineEntry(int x, int y, int size) - { - this.sizeX = size; - this.sizeY = size; - this.posX = x; - this.posY = y; - } - - public QuestLineEntry(int x, int y, int sizeX, int sizeY) - { - this.sizeX = sizeX; - this.sizeY = sizeY; - this.posX = x; - this.posY = y; - } - - @Override - @Deprecated - public int getSize() - { - return Math.max(getSizeX(), getSizeY()); - } - - @Override - public int getSizeX() - { - return this.sizeX; - } - - @Override - public int getSizeY() - { - return this.sizeY; - } - - @Override - public int getPosX() - { - return posX; - } - - @Override - public int getPosY() - { - return posY; - } - - @Override - public void setPosition(int posX, int posY) - { - this.posX = posX; - this.posY = posY; - } - - @Override - @Deprecated - public void setSize(int size) - { - this.sizeX = size; - this.sizeY = size; - } - - @Override - public void setSize(int sizeX, int sizeY) - { - this.sizeX = sizeX; - this.sizeY = sizeY; +public class QuestLineEntry implements IQuestLineEntry { + private int sizeX = 0; + private int sizeY = 0; + private int posX = 0; + private int posY = 0; + + public QuestLineEntry(NBTTagCompound json) { + this.readFromNBT(json); + } + + public QuestLineEntry(int x, int y) { + this(x, y, 24, 24); + } + + @Deprecated + public QuestLineEntry(int x, int y, int size) { + this.sizeX = size; + this.sizeY = size; + this.posX = x; + this.posY = y; + } + + public QuestLineEntry(int x, int y, int sizeX, int sizeY) { + this.sizeX = sizeX; + this.sizeY = sizeY; + this.posX = x; + this.posY = y; + } + + @Override + @Deprecated + public int getSize() { + return Math.max(getSizeX(), getSizeY()); + } + + @Override + public int getSizeX() { + return this.sizeX; + } + + @Override + public int getSizeY() { + return this.sizeY; + } + + @Override + public int getPosX() { + return posX; + } + + @Override + public int getPosY() { + return posY; + } + + @Override + public void setPosition(int posX, int posY) { + this.posX = posX; + this.posY = posY; + } + + @Override + @Deprecated + public void setSize(int size) { + this.sizeX = size; + this.sizeY = size; + } + + @Override + public void setSize(int sizeX, int sizeY) { + this.sizeX = sizeX; + this.sizeY = sizeY; + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound json) { + json.setInteger("sizeX", sizeX); + json.setInteger("sizeY", sizeY); + json.setInteger("x", posX); + json.setInteger("y", posY); + return json; + } + + @Override + public void readFromNBT(NBTTagCompound json) { + if (json.hasKey("size", 99)) { + sizeX = json.getInteger("size"); + sizeY = sizeX; + } else { + sizeX = json.getInteger("sizeX"); + sizeY = json.getInteger("sizeY"); } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound json) - { - json.setInteger("sizeX", sizeX); - json.setInteger("sizeY", sizeY); - json.setInteger("x", posX); - json.setInteger("y", posY); - return json; - } - - @Override - public void readFromNBT(NBTTagCompound json) - { - if(json.hasKey("size", 99)) - { - sizeX = json.getInteger("size"); - sizeY = sizeX; - } else - { - sizeX = json.getInteger("sizeX"); - sizeY = json.getInteger("sizeY"); - } - posX = json.getInteger("x"); - posY = json.getInteger("y"); - } - + posX = json.getInteger("x"); + posY = json.getInteger("y"); + } + } diff --git a/src/main/java/betterquesting/questing/party/PartyInstance.java b/src/main/java/betterquesting/questing/party/PartyInstance.java index 61feb520d..d86f9309d 100644 --- a/src/main/java/betterquesting/questing/party/PartyInstance.java +++ b/src/main/java/betterquesting/questing/party/PartyInstance.java @@ -14,212 +14,178 @@ import java.util.*; import java.util.Map.Entry; -public class PartyInstance implements IParty -{ - private final HashMap members = new HashMap<>(); - private List memCache = null; - - private final PropertyContainer pInfo = new PropertyContainer(); - - public PartyInstance() - { - this.setupProps(); - } - - private void setupProps() - { - setupValue(NativeProps.NAME, "New Party"); - } - - private void setupValue(IPropertyType prop) - { - this.setupValue(prop, prop.getDefault()); - } - - private void setupValue(IPropertyType prop, T def) - { - pInfo.setProperty(prop, pInfo.getProperty(prop, def)); - } - - private void refreshCache() +public class PartyInstance implements IParty { + private final HashMap members = new HashMap<>(); + private List memCache = null; + + private final PropertyContainer pInfo = new PropertyContainer(); + + public PartyInstance() { + this.setupProps(); + } + + private void setupProps() { + setupValue(NativeProps.NAME, "New Party"); + } + + private void setupValue(IPropertyType prop) { + this.setupValue(prop, prop.getDefault()); + } + + private void setupValue(IPropertyType prop, T def) { + pInfo.setProperty(prop, pInfo.getProperty(prop, def)); + } + + private void refreshCache() { + memCache = Collections.unmodifiableList(new ArrayList<>(members.keySet())); + } + + @Override + public IPropertyContainer getProperties() { + return pInfo; + } + + @Override + public void kickUser(@Nonnull UUID uuid) { + if (!members.containsKey(uuid)) { return; } + + EnumPartyStatus old = members.get(uuid); + members.remove(uuid); + + if (old == EnumPartyStatus.OWNER && !members.isEmpty()) { hostMigrate(); } + refreshCache(); + } + + @Override + public void setStatus(@Nonnull UUID uuid, @Nonnull EnumPartyStatus priv) { + EnumPartyStatus old = members.get(uuid); + if (old == priv) { return; } + + members.put(uuid, priv); + + if (priv == EnumPartyStatus.OWNER) // Check and drop previous owner(s) { - memCache = Collections.unmodifiableList(new ArrayList<>(members.keySet())); - } - - @Override - public IPropertyContainer getProperties() - { - return pInfo; - } - - @Override - public void kickUser(@Nonnull UUID uuid) - { - if(!members.containsKey(uuid)) return; - - EnumPartyStatus old = members.get(uuid); - members.remove(uuid); - - if(old == EnumPartyStatus.OWNER && members.size() > 0) hostMigrate(); - refreshCache(); - } - - @Override - public void setStatus(@Nonnull UUID uuid, @Nonnull EnumPartyStatus priv) - { - EnumPartyStatus old = members.get(uuid); - if(old == priv) return; - - members.put(uuid, priv); - - if(priv == EnumPartyStatus.OWNER) // Check and drop previous owner(s) - { - for(UUID mem : getMembers()) - { - if(mem != uuid && members.get(mem) == EnumPartyStatus.OWNER) - { - members.put(mem, EnumPartyStatus.ADMIN); - } - } - } else if(old == EnumPartyStatus.OWNER) - { - UUID migrate = null; - - // Find new owner - for(UUID mem : getMembers()) - { - if(mem == uuid) continue; - - if(members.get(mem) == EnumPartyStatus.ADMIN) - { - migrate = mem; - break; - } else if(migrate == null) - { - migrate = mem; - } - } - - // No other valid owners found - if(migrate == null) - { - members.put(uuid, old); - return; - } else - { - members.put(migrate, EnumPartyStatus.OWNER); - } - } - - refreshCache(); - } - - @Override - public EnumPartyStatus getStatus(@Nonnull UUID uuid) - { - return members.get(uuid); - } - - @Override - public List getMembers() - { - if(memCache == null) refreshCache(); - return memCache; - } - - private void hostMigrate() - { - // Pre check for existing owners - for(Entry entry : members.entrySet()) - { - if(entry.getValue() == EnumPartyStatus.OWNER) - { - return; - } - } - - UUID migrate = null; - - for(Entry entry : members.entrySet()) - { - EnumPartyStatus status = entry.getValue(); - - if(status == EnumPartyStatus.ADMIN || status == EnumPartyStatus.OWNER) - { - migrate = entry.getKey(); - break; - } else if(migrate == null) - { - migrate = entry.getKey(); - } - } - - if(migrate != null) - { - members.put(migrate, EnumPartyStatus.OWNER); - } else - { - BetterQuesting.logger.error("Failed to find suitable host to migrate party " + this.pInfo.getProperty(NativeProps.NAME)); + for (UUID mem : getMembers()) { + if (mem != uuid && members.get(mem) == EnumPartyStatus.OWNER) { + members.put(mem, EnumPartyStatus.ADMIN); } - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound json) - { - NBTTagList memJson = new NBTTagList(); - for(Entry mem : members.entrySet()) - { - NBTTagCompound jm = new NBTTagCompound(); - jm.setString("uuid", mem.getKey().toString()); - jm.setString("status", mem.getValue().toString()); - memJson.appendTag(jm); - } - json.setTag("members", memJson); - - json.setTag("properties", pInfo.writeToNBT(new NBTTagCompound())); - - return json; - } - - @Override - public void readFromNBT(NBTTagCompound jObj) - { - if(jObj.hasKey("properties", 10)) - { - pInfo.readFromNBT(jObj.getCompoundTag("properties")); - } else // Legacy stuff - { - pInfo.readFromNBT(new NBTTagCompound()); - pInfo.setProperty(NativeProps.NAME, jObj.getString("name")); - } - - members.clear(); - NBTTagList memList = jObj.getTagList("members", 10); - for(int i = 0; i < memList.tagCount(); i++) - { - try - { - NBTTagCompound jMem = memList.getCompoundTagAt(i); - if(!jMem.hasKey("uuid", 8) || !jMem.hasKey("status")) continue; - UUID uuid = UUID.fromString(jMem.getString("uuid")); - EnumPartyStatus priv = EnumPartyStatus.valueOf(jMem.getString("status")); - members.put(uuid, priv); - } catch(Exception ignored){} - } - - refreshCache(); - this.setupProps(); - } - - @Override - public NBTTagCompound writeProperties(NBTTagCompound nbt) - { - return pInfo.writeToNBT(nbt); + } + } else if (old == EnumPartyStatus.OWNER) { + UUID migrate = null; + + // Find new owner + for (UUID mem : getMembers()) { + if (mem == uuid) { continue; } + + if (members.get(mem) == EnumPartyStatus.ADMIN) { + migrate = mem; + break; + } else if (migrate == null) { + migrate = mem; + } + } + + // No other valid owners found + if (migrate == null) { + members.put(uuid, old); + return; + } else { + members.put(migrate, EnumPartyStatus.OWNER); + } + } + + refreshCache(); + } + + @Override + public EnumPartyStatus getStatus(@Nonnull UUID uuid) { + return members.get(uuid); + } + + @Override + public List getMembers() { + if (memCache == null) { refreshCache(); } + return memCache; + } + + private void hostMigrate() { + // Pre check for existing owners + for (Entry entry : members.entrySet()) { + if (entry.getValue() == EnumPartyStatus.OWNER) { + return; + } + } + + UUID migrate = null; + + for (Entry entry : members.entrySet()) { + EnumPartyStatus status = entry.getValue(); + + if (status == EnumPartyStatus.ADMIN || status == EnumPartyStatus.OWNER) { + migrate = entry.getKey(); + break; + } else if (migrate == null) { + migrate = entry.getKey(); + } + } + + if (migrate != null) { + members.put(migrate, EnumPartyStatus.OWNER); + } else { + BetterQuesting.logger.error( + "Failed to find suitable host to migrate party " + this.pInfo.getProperty(NativeProps.NAME)); } - - @Override - public void readProperties(NBTTagCompound nbt) + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound json) { + NBTTagList memJson = new NBTTagList(); + for (Entry mem : members.entrySet()) { + NBTTagCompound jm = new NBTTagCompound(); + jm.setString("uuid", mem.getKey().toString()); + jm.setString("status", mem.getValue().toString()); + memJson.appendTag(jm); + } + json.setTag("members", memJson); + + json.setTag("properties", pInfo.writeToNBT(new NBTTagCompound())); + + return json; + } + + @Override + public void readFromNBT(NBTTagCompound jObj) { + if (jObj.hasKey("properties", 10)) { + pInfo.readFromNBT(jObj.getCompoundTag("properties")); + } else // Legacy stuff { - pInfo.readFromNBT(nbt); + pInfo.readFromNBT(new NBTTagCompound()); + pInfo.setProperty(NativeProps.NAME, jObj.getString("name")); } + + members.clear(); + NBTTagList memList = jObj.getTagList("members", 10); + for (int i = 0; i < memList.tagCount(); i++) { + try { + NBTTagCompound jMem = memList.getCompoundTagAt(i); + if (!jMem.hasKey("uuid", 8) || !jMem.hasKey("status")) { continue; } + UUID uuid = UUID.fromString(jMem.getString("uuid")); + EnumPartyStatus priv = EnumPartyStatus.valueOf(jMem.getString("status")); + members.put(uuid, priv); + } catch (Exception ignored) { } + } + + refreshCache(); + this.setupProps(); + } + + @Override + public NBTTagCompound writeProperties(NBTTagCompound nbt) { + return pInfo.writeToNBT(nbt); + } + + @Override + public void readProperties(NBTTagCompound nbt) { + pInfo.readFromNBT(nbt); + } } diff --git a/src/main/java/betterquesting/questing/party/PartyInvitations.java b/src/main/java/betterquesting/questing/party/PartyInvitations.java index 7d19c2fae..4e1cddc08 100644 --- a/src/main/java/betterquesting/questing/party/PartyInvitations.java +++ b/src/main/java/betterquesting/questing/party/PartyInvitations.java @@ -17,177 +17,156 @@ import java.util.Map.Entry; // NOTE: This is in a separate class because it could later be moved to a dedicated inbox system -public class PartyInvitations implements INBTPartial -{ - public static final PartyInvitations INSTANCE = new PartyInvitations(); - - private final HashMap> invites = new HashMap<>(); - - public synchronized void postInvite(@Nonnull UUID uuid, int id, long expiryTime) - { - if(expiryTime <= 0) - { - BetterQuesting.logger.error("Received an invite that has already expired!"); - return; // Can't expire before being issued - } - - IParty party = PartyManager.INSTANCE.getValue(id); - if(party == null || party.getStatus(uuid) != null) return; // Party doesn't exist or user has already joined - - HashMap list = invites.computeIfAbsent(uuid, (key) -> new HashMap<>()); - list.put(id, System.currentTimeMillis() + expiryTime); - } - - public synchronized boolean acceptInvite(@Nonnull UUID uuid, int id) - { - HashMap userInvites = invites.get(uuid); - if(userInvites == null || userInvites.size() <= 0) return false; - - long timestamp = userInvites.get(id); - IParty party = PartyManager.INSTANCE.getValue(id); - boolean valid = timestamp > System.currentTimeMillis(); - - if(valid && party != null) party.setStatus(uuid, EnumPartyStatus.MEMBER); - - userInvites.remove(id); // We still remove it regardless of validity - if(userInvites.size() <= 0) invites.remove(uuid); - - return valid; - } - - public synchronized void revokeInvites(@Nonnull UUID uuid, int... ids) - { - HashMap userInvites = invites.get(uuid); - if(userInvites == null || userInvites.size() <= 0) return; - for(int i : ids) userInvites.remove(i); - if(userInvites.size() <= 0) invites.remove(uuid); +public class PartyInvitations implements INBTPartial { + public static final PartyInvitations INSTANCE = new PartyInvitations(); + + private final HashMap> invites = new HashMap<>(); + + public synchronized void postInvite(@Nonnull UUID uuid, int id, long expiryTime) { + if (expiryTime <= 0) { + BetterQuesting.logger.error("Received an invite that has already expired!"); + return; // Can't expire before being issued } - - public synchronized List> getPartyInvites(@Nonnull UUID uuid) - { - HashMap userInvites = invites.get(uuid); - if(userInvites == null || userInvites.size() <= 0) return Collections.emptyList(); - - List> list = new ArrayList<>(userInvites.entrySet()); - list.sort(Comparator.comparing(Entry::getValue)); // Sort by expiry time - return list; - } - - // Primarily used when deleting parties to ensure that pending invites don't link to newly created parties under the same ID - public synchronized void purgeInvites(int partyID) - { - invites.values().forEach((value) -> value.remove(partyID)); + + IParty party = PartyManager.INSTANCE.getValue(id); + if (party == null || party.getStatus(uuid) != null) { + return; // Party doesn't exist or user has already joined } - - public synchronized void cleanExpired() - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - Iterator>> iterA = invites.entrySet().iterator(); - while(iterA.hasNext()) - { - Entry> userInvites = iterA.next(); - - List revoked = new ArrayList<>(); - Iterator> iterB = userInvites.getValue().entrySet().iterator(); - while(iterB.hasNext()) - { - Entry entry = iterB.next(); - if(entry.getValue() < System.currentTimeMillis()) - { - revoked.add(entry.getKey()); - iterB.remove(); - } - } - EntityPlayerMP player = server.getPlayerList().getPlayerByUUID(userInvites.getKey()); - //noinspection ConstantConditions - if(player != null && revoked.size() >= 0) - { - int[] revAry = new int[revoked.size()]; - for(int i = 0; i < revoked.size(); i++) revAry[i] = revoked.get(i); - NetInviteSync.sendRevoked(player, revAry); // Normally I avoid including networking calls into the database... - } - if(userInvites.getValue().size() <= 0) iterA.remove(); + + HashMap list = invites.computeIfAbsent(uuid, (key) -> new HashMap<>()); + list.put(id, System.currentTimeMillis() + expiryTime); + } + + public synchronized boolean acceptInvite(@Nonnull UUID uuid, int id) { + HashMap userInvites = invites.get(uuid); + if (userInvites == null || userInvites.isEmpty()) { return false; } + + long timestamp = userInvites.get(id); + IParty party = PartyManager.INSTANCE.getValue(id); + boolean valid = timestamp > System.currentTimeMillis(); + + if (valid && party != null) { party.setStatus(uuid, EnumPartyStatus.MEMBER); } + + userInvites.remove(id); // We still remove it regardless of validity + if (userInvites.isEmpty()) { invites.remove(uuid); } + + return valid; + } + + public synchronized void revokeInvites(@Nonnull UUID uuid, int... ids) { + HashMap userInvites = invites.get(uuid); + if (userInvites == null || userInvites.isEmpty()) { return; } + for (int i : ids) { userInvites.remove(i); } + if (userInvites.isEmpty()) { invites.remove(uuid); } + } + + public synchronized List> getPartyInvites(@Nonnull UUID uuid) { + HashMap userInvites = invites.get(uuid); + if (userInvites == null || userInvites.isEmpty()) { return Collections.emptyList(); } + + List> list = new ArrayList<>(userInvites.entrySet()); + list.sort(Entry.comparingByValue()); // Sort by expiry time + return list; + } + + // Primarily used when deleting parties to ensure that pending invites don't link to newly created parties under the same ID + public synchronized void purgeInvites(int partyID) { + invites.values().forEach((value) -> value.remove(partyID)); + } + + public synchronized void cleanExpired() { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + Iterator>> iterA = invites.entrySet().iterator(); + while (iterA.hasNext()) { + Entry> userInvites = iterA.next(); + + List revoked = new ArrayList<>(); + Iterator> iterB = userInvites.getValue().entrySet().iterator(); + while (iterB.hasNext()) { + Entry entry = iterB.next(); + if (entry.getValue() < System.currentTimeMillis()) { + revoked.add(entry.getKey()); + iterB.remove(); } + } + EntityPlayerMP player = server.getPlayerList().getPlayerByUUID(userInvites.getKey()); + //noinspection ConstantConditions + if (player != null && revoked.size() >= 0) { + int[] revAry = new int[revoked.size()]; + for (int i = 0; i < revoked.size(); i++) { revAry[i] = revoked.get(i); } + NetInviteSync.sendRevoked(player, revAry); // Normally I avoid including networking calls into the database... + } + if (userInvites.getValue().isEmpty()) { iterA.remove(); } } - - public synchronized void reset() - { - invites.clear(); - } - - @Override - public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable List subset) // Don't bother saving this to disk. We do need to send packets though - { - if(subset != null) - { - subset.forEach((uuid) -> { - NBTTagCompound userTag = new NBTTagCompound(); - userTag.setString("uuid", uuid.toString()); - - Map userMap = invites.get(uuid); - if(userMap == null) userMap = Collections.emptyMap(); - NBTTagList invList = new NBTTagList(); - - for(Entry invEntry : userMap.entrySet()) - { - NBTTagCompound invTag = new NBTTagCompound(); - invTag.setInteger("partyID", invEntry.getKey()); - invTag.setLong("expiry", invEntry.getValue()); - invList.appendTag(invTag); - } - - userTag.setTag("invites", invList); - nbt.appendTag(userTag); - }); - } else - { - for(Entry> userMap : invites.entrySet()) - { - NBTTagCompound userTag = new NBTTagCompound(); - userTag.setString("uuid", userMap.getKey().toString()); - - NBTTagList invList = new NBTTagList(); - for(Entry invEntry : userMap.getValue().entrySet()) - { - NBTTagCompound invTag = new NBTTagCompound(); - invTag.setInteger("partyID", invEntry.getKey()); - invTag.setLong("expiry", invEntry.getValue()); - invList.appendTag(invTag); - } - userTag.setTag("invites", invList); - nbt.appendTag(userTag); - } + } + + public synchronized void reset() { + invites.clear(); + } + + @Override + public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable + List subset) // Don't bother saving this to disk. We do need to send packets though + { + if (subset != null) { + subset.forEach((uuid) -> { + NBTTagCompound userTag = new NBTTagCompound(); + userTag.setString("uuid", uuid.toString()); + + Map userMap = invites.get(uuid); + if (userMap == null) { userMap = Collections.emptyMap(); } + NBTTagList invList = new NBTTagList(); + + for (Entry invEntry : userMap.entrySet()) { + NBTTagCompound invTag = new NBTTagCompound(); + invTag.setInteger("partyID", invEntry.getKey()); + invTag.setLong("expiry", invEntry.getValue()); + invList.appendTag(invTag); } - return nbt; - } - - @Override - public synchronized void readFromNBT(NBTTagList nbt, boolean merge) - { - if(!merge) invites.clear(); - for(int i = 0; i < nbt.tagCount(); i++) - { - NBTTagCompound userEntry = nbt.getCompoundTagAt(i); - UUID uuid; - try - { - uuid = UUID.fromString(userEntry.getString("uuid")); - } catch(Exception e) - { - continue; - } - - NBTTagList invList = userEntry.getTagList("invites", 10); - HashMap map = invites.compute(uuid, (key, old) -> new HashMap<>()); - map.clear(); - for(int n = 0; n < invList.tagCount(); n++) - { - NBTTagCompound invEntry = invList.getCompoundTagAt(n); - int partyID = invEntry.hasKey("partyID", 99) ? invEntry.getInteger("partyID") : -1; - long timestamp = invEntry.hasKey("expiry", 99) ? invEntry.getLong("expiry") : -1; - if(partyID < 0) continue; - map.put(partyID, timestamp); - } + + userTag.setTag("invites", invList); + nbt.appendTag(userTag); + }); + } else { + for (Entry> userMap : invites.entrySet()) { + NBTTagCompound userTag = new NBTTagCompound(); + userTag.setString("uuid", userMap.getKey().toString()); + + NBTTagList invList = new NBTTagList(); + for (Entry invEntry : userMap.getValue().entrySet()) { + NBTTagCompound invTag = new NBTTagCompound(); + invTag.setInteger("partyID", invEntry.getKey()); + invTag.setLong("expiry", invEntry.getValue()); + invList.appendTag(invTag); } + userTag.setTag("invites", invList); + nbt.appendTag(userTag); + } + } + return nbt; + } + + @Override + public synchronized void readFromNBT(NBTTagList nbt, boolean merge) { + if (!merge) { invites.clear(); } + for (int i = 0; i < nbt.tagCount(); i++) { + NBTTagCompound userEntry = nbt.getCompoundTagAt(i); + UUID uuid; + try { + uuid = UUID.fromString(userEntry.getString("uuid")); + } catch (Exception e) { + continue; + } + + NBTTagList invList = userEntry.getTagList("invites", 10); + HashMap map = invites.compute(uuid, (key, old) -> new HashMap<>()); + for (int n = 0; n < invList.tagCount(); n++) { + NBTTagCompound invEntry = invList.getCompoundTagAt(n); + int partyID = invEntry.hasKey("partyID", 99) ? invEntry.getInteger("partyID") : -1; + long timestamp = invEntry.hasKey("expiry", 99) ? invEntry.getLong("expiry") : -1; + if (partyID < 0) { continue; } + map.put(partyID, timestamp); + } } + } } diff --git a/src/main/java/betterquesting/questing/party/PartyManager.java b/src/main/java/betterquesting/questing/party/PartyManager.java index b9247cdaf..a3434d5fd 100644 --- a/src/main/java/betterquesting/questing/party/PartyManager.java +++ b/src/main/java/betterquesting/questing/party/PartyManager.java @@ -16,94 +16,85 @@ import java.util.List; import java.util.UUID; -public class PartyManager extends SimpleDatabase implements IPartyDatabase -{ - public static final PartyManager INSTANCE = new PartyManager(); - - private final HashMap partyCache = new HashMap<>(); - - @Override - public synchronized IParty createNew(int id) - { - IParty party = new PartyInstance(); - if(id >= 0) this.add(id, party); - return party; +public class PartyManager extends SimpleDatabase implements IPartyDatabase { + public static final PartyManager INSTANCE = new PartyManager(); + + private final HashMap partyCache = new HashMap<>(); + + @Override + public synchronized IParty createNew(int id) { + IParty party = new PartyInstance(); + if (id >= 0) { this.add(id, party); } + return party; + } + + @Nullable + @Override + public synchronized DBEntry getParty(@Nonnull UUID uuid) { + if (!QuestSettings.INSTANCE.getProperty(NativeProps.PARTY_ENABLE)) { + return null; // We're merely preventing access. Not erasing data } - - @Nullable - @Override - public synchronized DBEntry getParty(@Nonnull UUID uuid) - { - if(!QuestSettings.INSTANCE.getProperty(NativeProps.PARTY_ENABLE)) return null; // We're merely preventing access. Not erasing data - - Integer cachedID = partyCache.get(uuid); - IParty cachedParty = cachedID == null ? null : getValue(cachedID); - - if(cachedID != null && cachedParty == null) // Disbanded party - { - partyCache.remove(uuid); - } else if(cachedParty != null) // Active party. Check validity... - { - EnumPartyStatus status = cachedParty.getStatus(uuid); - if(status != null) return new DBEntry<>(cachedID, cachedParty); - partyCache.remove(uuid); // User isn't a party member anymore - } - - // NOTE: A server with a lot of solo players may still hammer this loop. Optimise further? - for(DBEntry entry : getEntries()) - { - EnumPartyStatus status = entry.getValue().getStatus(uuid); - - if(status != null) - { - partyCache.put(uuid, entry.getID()); - return entry; - } - } - - return null; - } - - @Override - public synchronized NBTTagList writeToNBT(NBTTagList json, List subset) - { - for(DBEntry entry : getEntries()) - { - if(subset != null && !subset.contains(entry.getID())) continue; - NBTTagCompound jp = entry.getValue().writeToNBT(new NBTTagCompound()); - jp.setInteger("partyID", entry.getID()); - json.appendTag(jp); - } - - return json; - } - - @Override - public synchronized void readFromNBT(NBTTagList json, boolean merge) - { - if(!merge) reset(); - - for(int i = 0; i < json.tagCount(); i++) - { - NBTTagCompound jp = json.getCompoundTagAt(i); - - int partyID = jp.hasKey("partyID", 99) ? jp.getInteger("partyID") : -1; - if(partyID < 0) continue; - - IParty party = new PartyInstance(); - party.readFromNBT(jp); - - if(party.getMembers().size() > 0) - { - add(partyID, party); - } - } - } - - @Override - public synchronized void reset() + + Integer cachedID = partyCache.get(uuid); + IParty cachedParty = cachedID == null ? null : getValue(cachedID); + + if (cachedID != null && cachedParty == null) // Disbanded party { - super.reset(); - partyCache.clear(); + partyCache.remove(uuid); + } else if (cachedParty != null) // Active party. Check validity... + { + EnumPartyStatus status = cachedParty.getStatus(uuid); + if (status != null) { return new DBEntry<>(cachedID, cachedParty); } + partyCache.remove(uuid); // User isn't a party member anymore } + + // NOTE: A server with a lot of solo players may still hammer this loop. Optimise further? + for (DBEntry entry : getEntries()) { + EnumPartyStatus status = entry.getValue().getStatus(uuid); + + if (status != null) { + partyCache.put(uuid, entry.getID()); + return entry; + } + } + + return null; + } + + @Override + public synchronized NBTTagList writeToNBT(NBTTagList json, List subset) { + for (DBEntry entry : getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { continue; } + NBTTagCompound jp = entry.getValue().writeToNBT(new NBTTagCompound()); + jp.setInteger("partyID", entry.getID()); + json.appendTag(jp); + } + + return json; + } + + @Override + public synchronized void readFromNBT(NBTTagList json, boolean merge) { + if (!merge) { reset(); } + + for (int i = 0; i < json.tagCount(); i++) { + NBTTagCompound jp = json.getCompoundTagAt(i); + + int partyID = jp.hasKey("partyID", 99) ? jp.getInteger("partyID") : -1; + if (partyID < 0) { continue; } + + IParty party = new PartyInstance(); + party.readFromNBT(jp); + + if (!party.getMembers().isEmpty()) { + add(partyID, party); + } + } + } + + @Override + public synchronized void reset() { + super.reset(); + partyCache.clear(); + } } diff --git a/src/main/java/betterquesting/questing/rewards/RewardRegistry.java b/src/main/java/betterquesting/questing/rewards/RewardRegistry.java index 676217019..9048db570 100644 --- a/src/main/java/betterquesting/questing/rewards/RewardRegistry.java +++ b/src/main/java/betterquesting/questing/rewards/RewardRegistry.java @@ -13,69 +13,57 @@ import java.util.HashMap; import java.util.List; -public class RewardRegistry implements IRegistry, IReward> -{ - public static final RewardRegistry INSTANCE = new RewardRegistry(); - - private final HashMap> rewardRegistry = new HashMap<>(); - - @Override - public void register(IFactoryData factory) - { - if(factory == null) - { - throw new NullPointerException("Tried to register null reward"); - } else if(factory.getRegistryName() == null) - { - throw new IllegalArgumentException("Tried to register a reward with a null name: " + factory.getClass()); - } - - if(rewardRegistry.containsKey(factory.getRegistryName()) || rewardRegistry.containsValue(factory)) - { - throw new IllegalArgumentException("Cannot register dupliate reward type: " + factory.getRegistryName()); - } - - rewardRegistry.put(factory.getRegistryName(), factory); - } - - @Override - public IFactoryData getFactory(ResourceLocation registryName) - { - return rewardRegistry.get(registryName); - } - - @Override - public List> getAll() - { - return new ArrayList<>(rewardRegistry.values()); - } - - @Override - public IReward createNew(ResourceLocation registryName) - { - try - { - IFactoryData factory; - - if(FactoryRewardPlaceholder.INSTANCE.getRegistryName().equals(registryName)) - { - factory = FactoryRewardPlaceholder.INSTANCE; - } else - { - factory = getFactory(registryName); - } - - if(factory == null) - { - BetterQuesting.logger.log(Level.ERROR, "Tried to load missing reward type '" + registryName + "'! Are you missing an expansion pack?"); - return null; - } - - return factory.createNew(); - } catch(Exception e) - { - BetterQuesting.logger.log(Level.ERROR, "Unable to instatiate reward: " + registryName, e); - return null; - } - } +public class RewardRegistry implements IRegistry, IReward> { + public static final RewardRegistry INSTANCE = new RewardRegistry(); + + private final HashMap> rewardRegistry = new HashMap<>(); + + @Override + public void register(IFactoryData factory) { + if (factory == null) { + throw new NullPointerException("Tried to register null reward"); + } else if (factory.getRegistryName() == null) { + throw new IllegalArgumentException("Tried to register a reward with a null name: " + factory.getClass()); + } + + if (rewardRegistry.containsKey(factory.getRegistryName()) || rewardRegistry.containsValue(factory)) { + throw new IllegalArgumentException("Cannot register dupliate reward type: " + factory.getRegistryName()); + } + + rewardRegistry.put(factory.getRegistryName(), factory); + } + + @Override + public IFactoryData getFactory(ResourceLocation registryName) { + return rewardRegistry.get(registryName); + } + + @Override + public List> getAll() { + return new ArrayList<>(rewardRegistry.values()); + } + + @Override + public IReward createNew(ResourceLocation registryName) { + try { + IFactoryData factory; + + if (FactoryRewardPlaceholder.INSTANCE.getRegistryName().equals(registryName)) { + factory = FactoryRewardPlaceholder.INSTANCE; + } else { + factory = getFactory(registryName); + } + + if (factory == null) { + BetterQuesting.logger.log(Level.ERROR, "Tried to load missing reward type '" + registryName + + "'! Are you missing an expansion pack?"); + return null; + } + + return factory.createNew(); + } catch (Exception e) { + BetterQuesting.logger.log(Level.ERROR, "Unable to instatiate reward: " + registryName, e); + return null; + } + } } diff --git a/src/main/java/betterquesting/questing/rewards/RewardStorage.java b/src/main/java/betterquesting/questing/rewards/RewardStorage.java index 4bf40b9f4..f392d175f 100644 --- a/src/main/java/betterquesting/questing/rewards/RewardStorage.java +++ b/src/main/java/betterquesting/questing/rewards/RewardStorage.java @@ -14,92 +14,76 @@ import java.util.List; import java.util.UUID; -public class RewardStorage extends SimpleDatabase implements IDatabaseNBT -{ - @Override - public NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) - { - for(DBEntry rew : getEntries()) - { - if(subset != null && !subset.contains(rew.getID())) continue; - ResourceLocation rewardID = rew.getValue().getFactoryID(); - NBTTagCompound rJson = rew.getValue().writeToNBT(new NBTTagCompound()); - rJson.setString("rewardID", rewardID.toString()); - rJson.setInteger("index", rew.getID()); - json.appendTag(rJson); - } - - return json; - } - - @Override - public void readFromNBT(NBTTagList json, boolean merge) - { - if(!merge) reset(); - List unassigned = new ArrayList<>(); - - for(int i = 0; i < json.tagCount(); i++) - { - NBTTagCompound jsonReward = json.getCompoundTagAt(i); - ResourceLocation loc = new ResourceLocation(jsonReward.getString("rewardID")); - int index = jsonReward.hasKey("index", 99) ? jsonReward.getInteger("index") : -1; - IReward reward = RewardRegistry.INSTANCE.createNew(loc); - - if(reward instanceof RewardPlaceholder) - { - NBTTagCompound jr2 = jsonReward.getCompoundTag("orig_data"); - ResourceLocation loc2 = new ResourceLocation(jr2.getString("rewardID")); - IReward r2 = RewardRegistry.INSTANCE.createNew(loc2); - - if(r2 != null) - { - jsonReward = jr2; - reward = r2; - } - } - - if(reward != null) - { - reward.readFromNBT(jsonReward); - - if(index >= 0) - { - add(index, reward); - } else - { - unassigned.add(reward); - } - } else - { - RewardPlaceholder rph = new RewardPlaceholder(); - rph.setRewardConfigData(jsonReward); - - if(index >= 0) - { - add(index, rph); - } else - { - unassigned.add(rph); - } - } - } - - for(IReward r : unassigned) - { - add(nextID(), r); - } - } - - // === Future support === - - @Override - public NBTTagList writeProgressToNBT(NBTTagList nbt, @Nullable List user) - { - return nbt; +public class RewardStorage extends SimpleDatabase implements IDatabaseNBT { + @Override + public NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { + for (DBEntry rew : getEntries()) { + if (subset != null && !subset.contains(rew.getID())) { continue; } + ResourceLocation rewardID = rew.getValue().getFactoryID(); + NBTTagCompound rJson = rew.getValue().writeToNBT(new NBTTagCompound()); + rJson.setString("rewardID", rewardID.toString()); + rJson.setInteger("index", rew.getID()); + json.appendTag(rJson); } - - @Override - public void readProgressFromNBT(NBTTagList nbt, boolean merge) - { + + return json; + } + + @Override + public void readFromNBT(NBTTagList json, boolean merge) { + if (!merge) { reset(); } + List unassigned = new ArrayList<>(); + + for (int i = 0; i < json.tagCount(); i++) { + NBTTagCompound jsonReward = json.getCompoundTagAt(i); + ResourceLocation loc = new ResourceLocation(jsonReward.getString("rewardID")); + int index = jsonReward.hasKey("index", 99) ? jsonReward.getInteger("index") : -1; + IReward reward = RewardRegistry.INSTANCE.createNew(loc); + + if (reward instanceof RewardPlaceholder) { + NBTTagCompound jr2 = jsonReward.getCompoundTag("orig_data"); + ResourceLocation loc2 = new ResourceLocation(jr2.getString("rewardID")); + IReward r2 = RewardRegistry.INSTANCE.createNew(loc2); + + if (r2 != null) { + jsonReward = jr2; + reward = r2; + } + } + + if (reward != null) { + reward.readFromNBT(jsonReward); + + if (index >= 0) { + add(index, reward); + } else { + unassigned.add(reward); + } + } else { + RewardPlaceholder rph = new RewardPlaceholder(); + rph.setRewardConfigData(jsonReward); + + if (index >= 0) { + add(index, rph); + } else { + unassigned.add(rph); + } + } + } + + for (IReward r : unassigned) { + add(nextID(), r); } + } + + // === Future support === + + @Override + public NBTTagList writeProgressToNBT(NBTTagList nbt, @Nullable List user) { + return nbt; + } + + @Override + public void readProgressFromNBT(NBTTagList nbt, boolean merge) { + } } diff --git a/src/main/java/betterquesting/questing/tasks/TaskRegistry.java b/src/main/java/betterquesting/questing/tasks/TaskRegistry.java index 4ab874e62..efafa1f23 100644 --- a/src/main/java/betterquesting/questing/tasks/TaskRegistry.java +++ b/src/main/java/betterquesting/questing/tasks/TaskRegistry.java @@ -16,69 +16,57 @@ /** * Registry for all known task types. Questing packs should register their custom types here for proper saving/loading */ -public class TaskRegistry implements IRegistry, ITask> -{ - public static final TaskRegistry INSTANCE = new TaskRegistry(); - - private final HashMap> taskRegistry = new HashMap<>(); - - @Override - public void register(IFactoryData factory) - { - if(factory == null) - { - throw new NullPointerException("Tried to register null task"); - } else if(factory.getRegistryName() == null) - { - throw new IllegalArgumentException("Tried to register a task with a null name: " + factory.getClass()); - } - - if(taskRegistry.containsKey(factory.getRegistryName()) || taskRegistry.containsValue(factory)) - { - throw new IllegalArgumentException("Cannot register dupliate task type: " + factory.getRegistryName()); - } - - taskRegistry.put(factory.getRegistryName(), factory); - } - - @Override - public IFactoryData getFactory(ResourceLocation registryName) - { - return taskRegistry.get(registryName); - } - - @Override - public List> getAll() - { - return new ArrayList<>(taskRegistry.values()); - } - - @Override - public ITask createNew(ResourceLocation registryName) - { - try - { - IFactoryData factory; - - if(FactoryTaskPlaceholder.INSTANCE.getRegistryName().equals(registryName)) - { - factory = FactoryTaskPlaceholder.INSTANCE; - } else - { - factory = getFactory(registryName); - } - - if(factory == null) - { - BetterQuesting.logger.log(Level.ERROR, "Tried to load missing task type '" + registryName + "'! Are you missing an expansion pack?"); - return null; - } - - return factory.createNew(); - } catch(Exception e) - { - BetterQuesting.logger.log(Level.ERROR, "Unable to instatiate task: " + registryName, e); - return null; - } - } +public class TaskRegistry implements IRegistry, ITask> { + public static final TaskRegistry INSTANCE = new TaskRegistry(); + + private final HashMap> taskRegistry = new HashMap<>(); + + @Override + public void register(IFactoryData factory) { + if (factory == null) { + throw new NullPointerException("Tried to register null task"); + } else if (factory.getRegistryName() == null) { + throw new IllegalArgumentException("Tried to register a task with a null name: " + factory.getClass()); + } + + if (taskRegistry.containsKey(factory.getRegistryName()) || taskRegistry.containsValue(factory)) { + throw new IllegalArgumentException("Cannot register dupliate task type: " + factory.getRegistryName()); + } + + taskRegistry.put(factory.getRegistryName(), factory); + } + + @Override + public IFactoryData getFactory(ResourceLocation registryName) { + return taskRegistry.get(registryName); + } + + @Override + public List> getAll() { + return new ArrayList<>(taskRegistry.values()); + } + + @Override + public ITask createNew(ResourceLocation registryName) { + try { + IFactoryData factory; + + if (FactoryTaskPlaceholder.INSTANCE.getRegistryName().equals(registryName)) { + factory = FactoryTaskPlaceholder.INSTANCE; + } else { + factory = getFactory(registryName); + } + + if (factory == null) { + BetterQuesting.logger.log(Level.ERROR, "Tried to load missing task type '" + registryName + + "'! Are you missing an expansion pack?"); + return null; + } + + return factory.createNew(); + } catch (Exception e) { + BetterQuesting.logger.log(Level.ERROR, "Unable to instatiate task: " + registryName, e); + return null; + } + } } diff --git a/src/main/java/betterquesting/questing/tasks/TaskStorage.java b/src/main/java/betterquesting/questing/tasks/TaskStorage.java index 45d3f6e4e..d59dabee4 100644 --- a/src/main/java/betterquesting/questing/tasks/TaskStorage.java +++ b/src/main/java/betterquesting/questing/tasks/TaskStorage.java @@ -15,114 +15,95 @@ import java.util.List; import java.util.UUID; -public class TaskStorage extends SimpleDatabase implements IDatabaseNBT -{ - @Override - public NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) - { - for(DBEntry entry : getEntries()) - { - if(subset != null && !subset.contains(entry.getID())) continue; - ResourceLocation taskID = entry.getValue().getFactoryID(); - NBTTagCompound qJson = entry.getValue().writeToNBT(new NBTTagCompound()); - qJson.setString("taskID", taskID.toString()); - qJson.setInteger("index", entry.getID()); - json.appendTag(qJson); - } - return json; - } - - @Override - public void readFromNBT(NBTTagList json, boolean merge) - { - if(!merge) reset(); - List unassigned = new ArrayList<>(); - - for(int i = 0; i < json.tagCount(); i++) - { - NBTTagCompound jsonTask = json.getCompoundTagAt(i); - ResourceLocation loc = new ResourceLocation(jsonTask.getString("taskID")); - int index = jsonTask.hasKey("index", 99) ? jsonTask.getInteger("index") : -1; - ITask task = TaskRegistry.INSTANCE.createNew(loc); - - if(task instanceof TaskPlaceholder) - { - NBTTagCompound jt2 = jsonTask.getCompoundTag("orig_data"); - ResourceLocation loc2 = new ResourceLocation(jt2.getString("taskID")); - ITask t2 = TaskRegistry.INSTANCE.createNew(loc2); - - if(t2 != null) // Restored original task - { - jsonTask = jt2; - task = t2; - } - } - - if(task != null) - { - task.readFromNBT(jsonTask); - } else - { - task = new TaskPlaceholder(); - ((TaskPlaceholder)task).setTaskConfigData(jsonTask); - } - - if(index >= 0) - { - add(index, task); - } else - { - unassigned.add(task); - } - } - - for(ITask t : unassigned) add(nextID(), t); - } - - @Override - public NBTTagList writeProgressToNBT(NBTTagList json, @Nullable List user) - { - for(DBEntry entry : getEntries()) - { - ResourceLocation taskID = entry.getValue().getFactoryID(); - - NBTTagCompound qJson = entry.getValue().writeProgressToNBT(new NBTTagCompound(), user); - qJson.setString("taskID", taskID.toString()); - qJson.setInteger("index", entry.getID()); - json.appendTag(qJson); - } - return json; - } - - @Override - public void readProgressFromNBT(NBTTagList json, boolean merge) - { - for(int i = 0; i < json.tagCount(); i++) - { - NBTTagCompound jsonTask = json.getCompoundTagAt(i); - int index = jsonTask.hasKey("index", 99) ? jsonTask.getInteger("index") : -1; - ResourceLocation loc = new ResourceLocation(jsonTask.getString("taskID")); - ITask task = getValue(index); - - if(task instanceof TaskPlaceholder) - { - if(!task.getFactoryID().equals(loc)) - { - ((TaskPlaceholder)task).setTaskProgressData(jsonTask); - } else - { - task.readProgressFromNBT(jsonTask, merge); - } - } else if(task != null) - { - if(task.getFactoryID().equals(loc)) - { - task.readProgressFromNBT(jsonTask, merge); - } else if(FactoryTaskPlaceholder.INSTANCE.getRegistryName().equals(loc)) // Restored placeholder progress - { - task.readProgressFromNBT(jsonTask.getCompoundTag("orig_prog"), merge); - } - } - } - } +public class TaskStorage extends SimpleDatabase implements IDatabaseNBT { + @Override + public NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { + for (DBEntry entry : getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { continue; } + ResourceLocation taskID = entry.getValue().getFactoryID(); + NBTTagCompound qJson = entry.getValue().writeToNBT(new NBTTagCompound()); + qJson.setString("taskID", taskID.toString()); + qJson.setInteger("index", entry.getID()); + json.appendTag(qJson); + } + return json; + } + + @Override + public void readFromNBT(NBTTagList json, boolean merge) { + if (!merge) { reset(); } + List unassigned = new ArrayList<>(); + + for (int i = 0; i < json.tagCount(); i++) { + NBTTagCompound jsonTask = json.getCompoundTagAt(i); + ResourceLocation loc = new ResourceLocation(jsonTask.getString("taskID")); + int index = jsonTask.hasKey("index", 99) ? jsonTask.getInteger("index") : -1; + ITask task = TaskRegistry.INSTANCE.createNew(loc); + + if (task instanceof TaskPlaceholder) { + NBTTagCompound jt2 = jsonTask.getCompoundTag("orig_data"); + ResourceLocation loc2 = new ResourceLocation(jt2.getString("taskID")); + ITask t2 = TaskRegistry.INSTANCE.createNew(loc2); + + if (t2 != null) // Restored original task + { + jsonTask = jt2; + task = t2; + } + } + + if (task != null) { + task.readFromNBT(jsonTask); + } else { + task = new TaskPlaceholder(); + ((TaskPlaceholder) task).setTaskConfigData(jsonTask); + } + + if (index >= 0) { + add(index, task); + } else { + unassigned.add(task); + } + } + + for (ITask t : unassigned) { add(nextID(), t); } + } + + @Override + public NBTTagList writeProgressToNBT(NBTTagList json, @Nullable List user) { + for (DBEntry entry : getEntries()) { + ResourceLocation taskID = entry.getValue().getFactoryID(); + + NBTTagCompound qJson = entry.getValue().writeProgressToNBT(new NBTTagCompound(), user); + qJson.setString("taskID", taskID.toString()); + qJson.setInteger("index", entry.getID()); + json.appendTag(qJson); + } + return json; + } + + @Override + public void readProgressFromNBT(NBTTagList json, boolean merge) { + for (int i = 0; i < json.tagCount(); i++) { + NBTTagCompound jsonTask = json.getCompoundTagAt(i); + int index = jsonTask.hasKey("index", 99) ? jsonTask.getInteger("index") : -1; + ResourceLocation loc = new ResourceLocation(jsonTask.getString("taskID")); + ITask task = getValue(index); + + if (task instanceof TaskPlaceholder) { + if (!task.getFactoryID().equals(loc)) { + ((TaskPlaceholder) task).setTaskProgressData(jsonTask); + } else { + task.readProgressFromNBT(jsonTask, merge); + } + } else if (task != null) { + if (task.getFactoryID().equals(loc)) { + task.readProgressFromNBT(jsonTask, merge); + } else if (FactoryTaskPlaceholder.INSTANCE.getRegistryName().equals(loc)) // Restored placeholder progress + { + task.readProgressFromNBT(jsonTask.getCompoundTag("orig_prog"), merge); + } + } + } + } } diff --git a/src/main/java/betterquesting/storage/LifeDatabase.java b/src/main/java/betterquesting/storage/LifeDatabase.java index 934e09317..c5f19209e 100644 --- a/src/main/java/betterquesting/storage/LifeDatabase.java +++ b/src/main/java/betterquesting/storage/LifeDatabase.java @@ -13,62 +13,53 @@ import java.util.Map.Entry; import java.util.UUID; -public final class LifeDatabase implements ILifeDatabase -{ - public static final LifeDatabase INSTANCE = new LifeDatabase(); - - private final HashMap playerLives = new HashMap<>(); - - @Override - public synchronized int getLives(@Nonnull UUID uuid) - { - return playerLives.computeIfAbsent(uuid, (k) -> QuestSettings.INSTANCE.getProperty(NativeProps.LIVES_DEF)); - } - - @Override - public synchronized void setLives(@Nonnull UUID uuid, int value) - { - playerLives.put(uuid, MathHelper.clamp(value, 0, QuestSettings.INSTANCE.getProperty(NativeProps.LIVES_MAX))); - } - - @Override - public synchronized NBTTagCompound writeToNBT(NBTTagCompound nbt, @Nullable List users) - { - NBTTagList jul = new NBTTagList(); - for(Entry entry : playerLives.entrySet()) - { - if(users != null && !users.contains(entry.getKey())) continue; - NBTTagCompound j = new NBTTagCompound(); - j.setString("uuid", entry.getKey().toString()); - j.setInteger("lives", entry.getValue()); - jul.appendTag(j); - } - nbt.setTag("playerLives", jul); - - return nbt; - } - - @Override - public synchronized void readFromNBT(NBTTagCompound nbt, boolean merge) - { - if(!merge) playerLives.clear(); - NBTTagList tagList = nbt.getTagList("playerLives", 10); - for(int i = 0; i < tagList.tagCount(); i++) - { - NBTTagCompound j = tagList.getCompoundTagAt(i); - - try - { - UUID uuid = UUID.fromString(j.getString("uuid")); - int lives = j.getInteger("lives"); - playerLives.put(uuid, lives); - } catch(Exception ignored){} - } - } - - @Override - public synchronized void reset() - { - playerLives.clear(); - } +public final class LifeDatabase implements ILifeDatabase { + public static final LifeDatabase INSTANCE = new LifeDatabase(); + + private final HashMap playerLives = new HashMap<>(); + + @Override + public synchronized int getLives(@Nonnull UUID uuid) { + return playerLives.computeIfAbsent(uuid, (k) -> QuestSettings.INSTANCE.getProperty(NativeProps.LIVES_DEF)); + } + + @Override + public synchronized void setLives(@Nonnull UUID uuid, int value) { + playerLives.put(uuid, MathHelper.clamp(value, 0, QuestSettings.INSTANCE.getProperty(NativeProps.LIVES_MAX))); + } + + @Override + public synchronized NBTTagCompound writeToNBT(NBTTagCompound nbt, @Nullable List users) { + NBTTagList jul = new NBTTagList(); + for (Entry entry : playerLives.entrySet()) { + if (users != null && !users.contains(entry.getKey())) { continue; } + NBTTagCompound j = new NBTTagCompound(); + j.setString("uuid", entry.getKey().toString()); + j.setInteger("lives", entry.getValue()); + jul.appendTag(j); + } + nbt.setTag("playerLives", jul); + + return nbt; + } + + @Override + public synchronized void readFromNBT(NBTTagCompound nbt, boolean merge) { + if (!merge) { playerLives.clear(); } + NBTTagList tagList = nbt.getTagList("playerLives", 10); + for (int i = 0; i < tagList.tagCount(); i++) { + NBTTagCompound j = tagList.getCompoundTagAt(i); + + try { + UUID uuid = UUID.fromString(j.getString("uuid")); + int lives = j.getInteger("lives"); + playerLives.put(uuid, lives); + } catch (Exception ignored) { } + } + } + + @Override + public synchronized void reset() { + playerLives.clear(); + } } \ No newline at end of file diff --git a/src/main/java/betterquesting/storage/NameCache.java b/src/main/java/betterquesting/storage/NameCache.java index 40c7a751f..3a795dbfe 100644 --- a/src/main/java/betterquesting/storage/NameCache.java +++ b/src/main/java/betterquesting/storage/NameCache.java @@ -12,128 +12,110 @@ import java.util.*; import java.util.Map.Entry; -public final class NameCache implements INameCache -{ - public static final NameCache INSTANCE = new NameCache(); - - // TODO: Label known names as offline/online and convert accordingly? - private final HashMap cache = new HashMap<>(); - - @Override - public synchronized boolean updateName(@Nonnull EntityPlayerMP player) - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - NBTTagCompound tag = cache.computeIfAbsent(player.getGameProfile().getId(), (key) -> new NBTTagCompound()); - - String name = player.getGameProfile().getName(); - boolean isOP = server.getPlayerList().canSendCommands(player.getGameProfile()); - - if(!tag.getString("name").equals(name) || tag.getBoolean("isOP") != isOP) - { - tag.setString("name", name); - tag.setBoolean("isOP", isOP); - return true; - } - - return false; +public final class NameCache implements INameCache { + public static final NameCache INSTANCE = new NameCache(); + + // TODO: Label known names as offline/online and convert accordingly? + private final HashMap cache = new HashMap<>(); + + @Override + public synchronized boolean updateName(@Nonnull EntityPlayerMP player) { + MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + NBTTagCompound tag = cache.computeIfAbsent(player.getGameProfile().getId(), (key) -> new NBTTagCompound()); + + String name = player.getGameProfile().getName(); + boolean isOP = server.getPlayerList().canSendCommands(player.getGameProfile()); + + if (!tag.getString("name").equals(name) || tag.getBoolean("isOP") != isOP) { + tag.setString("name", name); + tag.setBoolean("isOP", isOP); + return true; + } + + return false; + } + + @Override + public synchronized String getName(@Nonnull UUID uuid) { + NBTTagCompound tag = cache.get(uuid); + return tag == null ? uuid.toString() : tag.getString("name"); + } + + @Override + public synchronized UUID getUUID(@Nonnull String name) { + for (Entry entry : cache.entrySet()) { + if (entry.getValue().getString("name").equalsIgnoreCase(name)) { + return entry.getKey(); + } + } + + return null; + } + + @Override + public synchronized boolean isOP(@Nonnull UUID uuid) { + NBTTagCompound tag = cache.get(uuid); + return tag != null && tag.getBoolean("isOP"); + } + + @Override + public synchronized int size() { + return cache.size(); + } + + @Override + public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable List users) { + for (Entry entry : cache.entrySet()) { + if (users != null && !users.contains(entry.getKey())) { continue; } + NBTTagCompound jn = new NBTTagCompound(); + jn.setString("uuid", entry.getKey().toString()); + jn.setString("name", entry.getValue().getString("name")); + jn.setBoolean("isOP", entry.getValue().getBoolean("isOP")); + nbt.appendTag(jn); } - - @Override - public synchronized String getName(@Nonnull UUID uuid) - { - NBTTagCompound tag = cache.get(uuid); - return tag == null ? uuid.toString() : tag.getString("name"); - } - - @Override - public synchronized UUID getUUID(@Nonnull String name) - { - for(Entry entry : cache.entrySet()) - { - if(entry.getValue().getString("name").equalsIgnoreCase(name)) - { - return entry.getKey(); - } - } - - return null; - } - - @Override - public synchronized boolean isOP(@Nonnull UUID uuid) - { - NBTTagCompound tag = cache.get(uuid); - return tag != null && tag.getBoolean("isOP"); - } - - @Override - public synchronized int size() - { - return cache.size(); - } - - @Override - public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable List users) - { - for(Entry entry : cache.entrySet()) - { - if(users != null && !users.contains(entry.getKey())) continue; - NBTTagCompound jn = new NBTTagCompound(); - jn.setString("uuid", entry.getKey().toString()); - jn.setString("name", entry.getValue().getString("name")); - jn.setBoolean("isOP", entry.getValue().getBoolean("isOP")); - nbt.appendTag(jn); - } - - return nbt; - } - - @Override - public synchronized void readFromNBT(NBTTagList nbt, boolean merge) - { - if(!merge) cache.clear(); - for(int i = 0; i < nbt.tagCount(); i++) - { - NBTTagCompound jn = nbt.getCompoundTagAt(i); - - try - { - UUID uuid = UUID.fromString(jn.getString("uuid")); - String name = jn.getString("name"); - boolean isOP = jn.getBoolean("isOP"); - - NBTTagCompound j2 = new NBTTagCompound(); - j2.setString("name", name); - j2.setBoolean("isOP", isOP); - cache.put(uuid, j2); - } catch(Exception ignored){} - } - } - - @Override - public synchronized void reset() - { - cache.clear(); - nameCache = null; - } - - private List nameCache = null; - - @Override - public synchronized List getAllNames() - { - if(nameCache != null) return nameCache; - - nameCache = new ArrayList<>(); - - for(NBTTagCompound tag : cache.values()) - { - if(tag != null && tag.hasKey("name", 8)) - { - nameCache.add(tag.getString("name")); - } - } - - return Collections.unmodifiableList(nameCache); - } + + return nbt; + } + + @Override + public synchronized void readFromNBT(NBTTagList nbt, boolean merge) { + if (!merge) { cache.clear(); } + for (int i = 0; i < nbt.tagCount(); i++) { + NBTTagCompound jn = nbt.getCompoundTagAt(i); + + try { + UUID uuid = UUID.fromString(jn.getString("uuid")); + String name = jn.getString("name"); + boolean isOP = jn.getBoolean("isOP"); + + NBTTagCompound j2 = new NBTTagCompound(); + j2.setString("name", name); + j2.setBoolean("isOP", isOP); + cache.put(uuid, j2); + } catch (Exception ignored) { } + } + } + + @Override + public synchronized void reset() { + cache.clear(); + nameCache = null; + } + + private List nameCache = null; + + @Override + public synchronized List getAllNames() { + if (nameCache != null) { return nameCache; } + + nameCache = new ArrayList<>(); + + for (NBTTagCompound tag : cache.values()) { + if (tag != null && tag.hasKey("name", 8)) { + nameCache.add(tag.getString("name")); + } + } + + return Collections.unmodifiableList(nameCache); + } } diff --git a/src/main/java/betterquesting/storage/PropertyContainer.java b/src/main/java/betterquesting/storage/PropertyContainer.java index 56ab05a45..3e0a4cab2 100644 --- a/src/main/java/betterquesting/storage/PropertyContainer.java +++ b/src/main/java/betterquesting/storage/PropertyContainer.java @@ -9,89 +9,79 @@ import java.util.ArrayList; import java.util.List; -public class PropertyContainer implements IPropertyContainer, INBTSaveLoad -{ - private final NBTTagCompound nbtInfo = new NBTTagCompound(); - - @Override - public synchronized T getProperty(IPropertyType prop) - { - if(prop == null) return null; - - return getProperty(prop, prop.getDefault()); - } - - @Override - public synchronized T getProperty(IPropertyType prop, T def) - { - if(prop == null) return def; - - NBTTagCompound jProp = getDomain(prop.getKey()); - - if(!jProp.hasKey(prop.getKey().getPath())) return def; - - return prop.readValue(jProp.getTag(prop.getKey().getPath())); - } - - @Override - public synchronized boolean hasProperty(IPropertyType prop) - { - if(prop == null) return false; - return getDomain(prop.getKey()).hasKey(prop.getKey().getPath()); - } - - @Override - public synchronized void removeProperty(IPropertyType prop) - { - if(prop == null) return; - NBTTagCompound jProp = getDomain(prop.getKey()); - - if(!jProp.hasKey(prop.getKey().getPath())) return; - - jProp.removeTag(prop.getKey().getPath()); - - if(jProp.isEmpty()) nbtInfo.removeTag(prop.getKey().getNamespace()); - } - - @Override - public synchronized void setProperty(IPropertyType prop, T value) - { - if(prop == null || value == null) return; - NBTTagCompound dom = getDomain(prop.getKey()); - dom.setTag(prop.getKey().getPath(), prop.writeValue(value)); - nbtInfo.setTag(prop.getKey().getNamespace(), dom); - } - - @Override - public synchronized void removeAllProps() - { - List keys = new ArrayList<>(nbtInfo.getKeySet()); - for(String key : keys) nbtInfo.removeTag(key); - } - - @Override - public synchronized NBTTagCompound writeToNBT(NBTTagCompound nbt) - { - nbt.merge(nbtInfo); - return nbt; - } - - @Override - public synchronized void readFromNBT(NBTTagCompound nbt) - { - for(String key : nbtInfo.getKeySet()) nbtInfo.removeTag(key); - nbtInfo.merge(nbt); - - // TODO: FIX CASING +public class PropertyContainer implements IPropertyContainer, INBTSaveLoad { + private final NBTTagCompound nbtInfo = new NBTTagCompound(); + + @Override + public synchronized T getProperty(IPropertyType prop) { + if (prop == null) { return null; } + + return getProperty(prop, prop.getDefault()); + } + + @Override + public synchronized T getProperty(IPropertyType prop, T def) { + if (prop == null) { return def; } + + NBTTagCompound jProp = getDomain(prop.getKey()); + + if (!jProp.hasKey(prop.getKey().getPath())) { return def; } + + return prop.readValue(jProp.getTag(prop.getKey().getPath())); + } + + @Override + public synchronized boolean hasProperty(IPropertyType prop) { + if (prop == null) { return false; } + return getDomain(prop.getKey()).hasKey(prop.getKey().getPath()); + } + + @Override + public synchronized void removeProperty(IPropertyType prop) { + if (prop == null) { return; } + NBTTagCompound jProp = getDomain(prop.getKey()); + + if (!jProp.hasKey(prop.getKey().getPath())) { return; } + + jProp.removeTag(prop.getKey().getPath()); + + if (jProp.isEmpty()) { nbtInfo.removeTag(prop.getKey().getNamespace()); } + } + + @Override + public synchronized void setProperty(IPropertyType prop, T value) { + if (prop == null || value == null) { return; } + NBTTagCompound dom = getDomain(prop.getKey()); + dom.setTag(prop.getKey().getPath(), prop.writeValue(value)); + nbtInfo.setTag(prop.getKey().getNamespace(), dom); + } + + @Override + public synchronized void removeAllProps() { + List keys = new ArrayList<>(nbtInfo.getKeySet()); + for (String key : keys) { nbtInfo.removeTag(key); } + } + + @Override + public synchronized NBTTagCompound writeToNBT(NBTTagCompound nbt) { + nbt.merge(nbtInfo); + return nbt; + } + + @Override + public synchronized void readFromNBT(NBTTagCompound nbt) { + for (String key : nbtInfo.getKeySet()) { nbtInfo.removeTag(key); } + nbtInfo.merge(nbt); + + // TODO: FIX CASING /*List keys = new ArrayList<>(nbtInfo.getKeySet()); for(nbt) { }*/ - } - - private NBTTagCompound getDomain(ResourceLocation res) - { - return nbtInfo.getCompoundTag(res.getNamespace()); - } + } + + private NBTTagCompound getDomain(ResourceLocation res) { + return nbtInfo.getCompoundTag(res.getNamespace()); + } } diff --git a/src/main/java/betterquesting/storage/QuestSettings.java b/src/main/java/betterquesting/storage/QuestSettings.java index 11e5c4322..75cade719 100644 --- a/src/main/java/betterquesting/storage/QuestSettings.java +++ b/src/main/java/betterquesting/storage/QuestSettings.java @@ -7,61 +7,53 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; -public class QuestSettings extends PropertyContainer implements IQuestSettings -{ - public static final QuestSettings INSTANCE = new QuestSettings(); - - public QuestSettings() - { - this.setupProps(); - } - - @Override - public boolean canUserEdit(EntityPlayer player) - { - if(player == null) return false; - return this.getProperty(NativeProps.EDIT_MODE) && NameCache.INSTANCE.isOP(QuestingAPI.getQuestingUUID(player)); - } - - @Override - public void readFromNBT(NBTTagCompound nbt) - { - super.readFromNBT(nbt); - - this.setupProps(); - } - - @Override - public void reset() - { - this.readFromNBT(new NBTTagCompound()); - } - - private void setupProps() - { - this.setupValue(NativeProps.PACK_NAME); - this.setupValue(NativeProps.PACK_VER); - - this.setupValue(NativeProps.PARTY_ENABLE); - this.setupValue(NativeProps.EDIT_MODE); - this.setupValue(NativeProps.HARDCORE); - this.setupValue(NativeProps.LIVES_DEF); - this.setupValue(NativeProps.LIVES_MAX); - - this.setupValue(NativeProps.HOME_IMAGE); - this.setupValue(NativeProps.HOME_ANC_X); - this.setupValue(NativeProps.HOME_ANC_Y); - this.setupValue(NativeProps.HOME_OFF_X); - this.setupValue(NativeProps.HOME_OFF_Y); - } - - private void setupValue(IPropertyType prop) - { - this.setupValue(prop, prop.getDefault()); - } - - private void setupValue(IPropertyType prop, T def) - { - this.setProperty(prop, this.getProperty(prop, def)); - } +public class QuestSettings extends PropertyContainer implements IQuestSettings { + public static final QuestSettings INSTANCE = new QuestSettings(); + + public QuestSettings() { + this.setupProps(); + } + + @Override + public boolean canUserEdit(EntityPlayer player) { + if (player == null) { return false; } + return this.getProperty(NativeProps.EDIT_MODE) && NameCache.INSTANCE.isOP(QuestingAPI.getQuestingUUID(player)); + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + super.readFromNBT(nbt); + + this.setupProps(); + } + + @Override + public void reset() { + this.readFromNBT(new NBTTagCompound()); + } + + private void setupProps() { + this.setupValue(NativeProps.PACK_NAME); + this.setupValue(NativeProps.PACK_VER); + + this.setupValue(NativeProps.PARTY_ENABLE); + this.setupValue(NativeProps.EDIT_MODE); + this.setupValue(NativeProps.HARDCORE); + this.setupValue(NativeProps.LIVES_DEF); + this.setupValue(NativeProps.LIVES_MAX); + + this.setupValue(NativeProps.HOME_IMAGE); + this.setupValue(NativeProps.HOME_ANC_X); + this.setupValue(NativeProps.HOME_ANC_Y); + this.setupValue(NativeProps.HOME_OFF_X); + this.setupValue(NativeProps.HOME_OFF_Y); + } + + private void setupValue(IPropertyType prop) { + this.setupValue(prop, prop.getDefault()); + } + + private void setupValue(IPropertyType prop, T def) { + this.setProperty(prop, this.getProperty(prop, def)); + } } diff --git a/src/main/resources/assets/betterquesting/lang/en_US.lang b/src/main/resources/assets/betterquesting/lang/en_US.lang index dfb270dbe..d1b11e8af 100644 --- a/src/main/resources/assets/betterquesting/lang/en_US.lang +++ b/src/main/resources/assets/betterquesting/lang/en_US.lang @@ -107,6 +107,7 @@ itemGroup.betterquesting=Better Questing fluid.betterquesting.placeholder=Placeholder item.betterquesting.placeholder.name=Item Placeholder +item.betterquesting.extra_life.name=Extra Life item.betterquesting.extra_life.full.name=Extra Life item.betterquesting.extra_life.half.name=Half Heart item.betterquesting.extra_life.quarter.name=Quarter Heart From 970164f8d384279ae3eeb30177935654113e73be Mon Sep 17 00:00:00 2001 From: Olexy Date: Mon, 4 Sep 2023 17:08:41 +0300 Subject: [PATCH 03/10] Fixed lang files not loading from resource folder sometimes. --- .../core/proxies/ClientProxy.java | 30 +++++++------------ 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/src/main/java/betterquesting/core/proxies/ClientProxy.java b/src/main/java/betterquesting/core/proxies/ClientProxy.java index b00290b62..caf5b67c4 100644 --- a/src/main/java/betterquesting/core/proxies/ClientProxy.java +++ b/src/main/java/betterquesting/core/proxies/ClientProxy.java @@ -17,7 +17,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.client.resources.SimpleReloadableResourceManager; +import net.minecraft.client.resources.IResourcePack; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.ModelLoader; @@ -27,16 +27,23 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import java.util.ArrayList; +import java.util.List; public class ClientProxy extends CommonProxy { + //This should be done very early during loading, before lang files are being loaded. + static { + List list = ObfuscationReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), + "field_110449_ao"); + list.add(new QuestResourcesFolder()); + list.add(new QuestResourcesFile()); + } + @Override public boolean isClient() { return true; } @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) public void registerHandlers() { super.registerHandlers(); @@ -53,23 +60,6 @@ public void registerHandlers() { MinecraftForge.EVENT_BUS.register(new QuestNotification()); BQ_Keybindings.RegisterKeys(); - try { - //String tmp = "defaultResourcePacks"; - ArrayList list = - ObfuscationReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "field_110449_ao", - "defaultResourcePacks"); - QuestResourcesFolder qRes1 = new QuestResourcesFolder(); - QuestResourcesFile qRes2 = new QuestResourcesFile(); - list.add(qRes1); - list.add(qRes2); - ((SimpleReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).reloadResourcePack( - qRes1); // Make sure the pack(s) are visible to everything - ((SimpleReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).reloadResourcePack( - qRes2); // Make sure the pack(s) are visible to everything - } catch (Exception e) { - BetterQuesting.logger.error("Unable to install questing resource loaders", e); - } - RenderingRegistry.registerEntityRenderingHandler(EntityPlaceholder.class, new PlaceholderRenderFactory()); ToolboxRegistry.INSTANCE.registerToolTab(new ResourceLocation(BetterQuesting.MODID, "main"), From 74e42c0854b3df7cb64525429e42a07c0c0c1fc1 Mon Sep 17 00:00:00 2001 From: Olexy Date: Tue, 5 Sep 2023 22:20:36 +0300 Subject: [PATCH 04/10] Returned block and item selection buttons. --- gradle.properties | 2 +- .../java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index ba1562011..f384e5777 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,3 +1,3 @@ -version=3.6.0 +version=3.6.2 minecraftVersion=1.12.2 forgeVersion=14.23.5.2860 \ No newline at end of file diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java index aa80ddceb..49fbd536b 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java @@ -118,7 +118,7 @@ public void initPanel() { QuestTranslation.translate("betterquesting.btn.item"), JsonHelper.ItemStackToJson(new BigItemStack(Blocks.STONE), new NBTTagCompound()))); - options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 100, 0, 92, 16, 0), 2, + options.add(new PanelButtonStorage<>(new GuiTransform(GuiAlign.MID_CENTER, 100, n++ * 16, 92, 16, 0), 2, QuestTranslation.translate("betterquesting.btn.fluid"), JsonHelper.FluidStackToJson(new FluidStack(FluidRegistry.WATER, 1000), new NBTTagCompound()))); From e343200770abd463d2f406451ede1b2e8f4217ca Mon Sep 17 00:00:00 2001 From: Olexy Date: Thu, 5 Oct 2023 18:57:31 +0300 Subject: [PATCH 05/10] Made ids random. Cleaned up code a bit. --- .../betterquesting/api/questing/IQuest.java | 5 +- .../betterquesting/api2/cache/QuestCache.java | 177 +++++++++--------- .../client/gui/controls/PanelButtonQuest.java | 33 ++-- .../api2/storage/SimpleDatabase.java | 13 +- .../betterquesting/handlers/EventHandler.java | 38 ++-- src/main/java/betterquesting/misc/Util.java | 10 + .../questing/CompletionInfo.java | 27 +++ .../questing/QuestDatabase.java | 10 +- .../questing/QuestInstance.java | 141 ++++++++------ .../questing/QuestLineEntry.java | 4 +- .../questing/tasks/TaskStorage.java | 8 +- 11 files changed, 264 insertions(+), 202 deletions(-) create mode 100644 src/main/java/betterquesting/questing/CompletionInfo.java diff --git a/src/main/java/betterquesting/api/questing/IQuest.java b/src/main/java/betterquesting/api/questing/IQuest.java index dfbdb42e1..3c65f2ebd 100644 --- a/src/main/java/betterquesting/api/questing/IQuest.java +++ b/src/main/java/betterquesting/api/questing/IQuest.java @@ -7,6 +7,7 @@ import betterquesting.api2.storage.IDatabaseNBT; import betterquesting.api2.storage.INBTProgress; import betterquesting.api2.storage.INBTSaveLoad; +import betterquesting.questing.CompletionInfo; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -19,9 +20,9 @@ public interface IQuest extends INBTSaveLoad, INBTProgress { // Quests that are visible to the player - private final TreeSet visibleQuests = new TreeSet<>(); + private final Set visibleQuests = new HashSet<>(); // Quests that are currently being undertaken. NOTE: Quests can be locked but still processing data if configured to do so - private final TreeSet activeQuests = new TreeSet<>(); + private final Set activeQuests = new HashSet<>(); // Quests and their scheduled time of being reset - private final TreeSet resetSchedule = - new TreeSet<>((o1, o2) -> o1.questID == o2.questID ? 0 : Long.compare(o1.time, o2.time)); + private final Set resetSchedule = + new TreeSet<>((a, b) -> a.questID == b.questID ? 0 : Long.compare(a.time, b.time)); // Quests with pending auto claims (usually should be empty unless a condition needs to be met) - private final TreeSet autoClaims = new TreeSet<>(); + private final Set autoClaims = new HashSet<>(); // Quests that need to be sent to the client to update progression (NOT for edits. Handle that elsewhere) - private final TreeSet markedDirty = new TreeSet<>(); + private final Set markedDirty = new HashSet<>(); public synchronized int[] getActiveQuests() { - // Probably a better way of doing this but this will do for now - int i = 0; - int[] aryAct = new int[activeQuests.size()]; - for (Integer q : activeQuests) { aryAct[i++] = q; } - return aryAct; + return Util.toIntArray(activeQuests); } public synchronized int[] getVisibleQuests() { - // Probably a better way of doing this but this will do for now - int i = 0; - int[] aryVis = new int[visibleQuests.size()]; - for (Integer q : visibleQuests) { aryVis[i++] = q; } - return aryVis; + return Util.toIntArray(visibleQuests); } public synchronized int[] getPendingAutoClaims() { - // Probably a better way of doing this but this will do for now - int i = 0; - int[] aryAC = new int[autoClaims.size()]; - for (Integer q : autoClaims) { aryAC[i++] = q; } - return aryAC; + return Util.toIntArray(autoClaims); } public synchronized QResetTime[] getScheduledResets() // Already sorted by time @@ -66,15 +54,12 @@ public synchronized QResetTime[] getScheduledResets() // Already sorted by time } public synchronized void markQuestDirty(int questID) { - if (questID < 0) { return; } + if (questID < 0) { + return; + } markedDirty.add(questID); } - public synchronized void markQuestClean(int questID) { - if (questID < 0) { return; } - markedDirty.remove(questID); - } - public synchronized void cleanAllQuests() { markedDirty.clear(); } @@ -83,14 +68,18 @@ public int[] getDirtyQuests() { // Probably a better way of doing this but this will do for now int i = 0; int[] aryMD = new int[markedDirty.size()]; - for (Integer q : markedDirty) { aryMD[i++] = q; } + for (Integer q : markedDirty) { + aryMD[i++] = q; + } return aryMD; } // TODO: Ensure this is thread safe because we're likely going to run this in the background // NOTE: Only run this when the quests completion and claim states change. Use markQuestDirty() for progression changes that need syncing public synchronized void updateCache(EntityPlayer player) { - if (player == null) { return; } + if (player == null) { + return; + } UUID uuid = QuestingAPI.getQuestingUUID(player); List> questDB = QuestingAPI.getAPI(ApiReference.QUEST_DB).getEntries(); @@ -101,32 +90,35 @@ public synchronized void updateCache(EntityPlayer player) { NonNullList tmpAutoClaim = NonNullList.create(); for (DBEntry entry : questDB) { - if (entry.getValue().isUnlocked(uuid) || entry.getValue().isComplete(uuid) || - entry.getValue().getProperty(NativeProps.LOCKED_PROGRESS)) // Unlocked or actively processing progression data - { - int repeat = entry.getValue().getProperty(NativeProps.REPEAT_TIME); - NBTTagCompound ue = entry.getValue().getCompletionInfo(uuid); - - if ((ue == null && entry.getValue().getTasks().size() <= 0) || entry.getValue().canSubmit( - player)) // Can be active without completion in the case of locked progress. Also account for taskless quests - { - tmpActive.add(entry.getID()); - } else if (ue != null) // These conditions only trigger after first completion - { - if (repeat >= 0 && entry.getValue().hasClaimed(uuid)) { - long altTime = ue.getLong("timestamp"); - if (repeat > 1 && !entry.getValue().getProperty(NativeProps.REPEAT_REL)) { altTime -= (altTime % repeat); } - tmpReset.add(new QResetTime(entry.getID(), altTime + (repeat * 50L))); + IQuest quest = entry.getValue(); + int id = entry.getID(); + // Unlocked or actively processing progression data + if (quest.isUnlocked(uuid) || quest.isComplete(uuid) || quest.getProperty(NativeProps.LOCKED_PROGRESS)) { + int repeat = quest.getProperty(NativeProps.REPEAT_TIME); + CompletionInfo ue = quest.getCompletionInfo(uuid); + + // Can be active without completion in the case of locked progress. Also account for taskless quests + if ((ue == null && quest.getTasks().size() <= 0) || quest.canSubmit(player)) { + tmpActive.add(id); + } + // These conditions only trigger after first completion + else if (ue != null) { + if (repeat >= 0 && quest.hasClaimed(uuid)) { + long altTime = ue.getTimestamp(); + if (repeat > 1 && !quest.getProperty(NativeProps.REPEAT_REL)) { + altTime -= (altTime % repeat); + } + tmpReset.add(new QResetTime(id, altTime + (repeat * 50L))); } - if (!entry.getValue().hasClaimed(uuid) && entry.getValue().getProperty(NativeProps.AUTO_CLAIM)) { - tmpAutoClaim.add(entry.getID()); + if (!quest.hasClaimed(uuid) && quest.getProperty(NativeProps.AUTO_CLAIM)) { + tmpAutoClaim.add(id); } } } - if (isQuestShown(entry.getValue(), uuid, player)) { - tmpVisible.add(entry.getID()); + if (isQuestShown(quest, uuid, player)) { + tmpVisible.add(id); } } @@ -142,7 +134,9 @@ public synchronized void updateCache(EntityPlayer player) { autoClaims.clear(); autoClaims.addAll(tmpAutoClaim); - if (player instanceof EntityPlayerMP) { NetCacheSync.sendSync((EntityPlayerMP) player); } + if (player instanceof EntityPlayerMP) { + NetCacheSync.sendSync((EntityPlayerMP) player); + } } @Override @@ -174,10 +168,18 @@ public synchronized void deserializeNBT(NBTTagCompound nbt) { autoClaims.clear(); markedDirty.clear(); - for (int i : nbt.getIntArray("visibleQuests")) { visibleQuests.add(i); } - for (int i : nbt.getIntArray("activeQuests")) { activeQuests.add(i); } - for (int i : nbt.getIntArray("autoClaims")) { autoClaims.add(i); } - for (int i : nbt.getIntArray("markedDirty")) { markedDirty.add(i); } + for (int i : nbt.getIntArray("visibleQuests")) { + visibleQuests.add(i); + } + for (int i : nbt.getIntArray("activeQuests")) { + activeQuests.add(i); + } + for (int i : nbt.getIntArray("autoClaims")) { + autoClaims.add(i); + } + for (int i : nbt.getIntArray("markedDirty")) { + markedDirty.add(i); + } NBTTagList tagList = nbt.getTagList("resetSchedule", 10); for (int i = 0; i < tagList.tagCount(); i++) { @@ -218,46 +220,37 @@ public static boolean isQuestShown(IQuest quest, UUID uuid, EntityPlayer player) EnumQuestVisibility vis = quest.getProperty(NativeProps.VISIBILITY); - if (QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(player) || - vis == EnumQuestVisibility.ALWAYS) // Always shown or in edit mode - { + // Always shown or in edit mode + if (QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(player) || vis == EnumQuestVisibility.ALWAYS) { return true; - } else if (vis == EnumQuestVisibility.HIDDEN) { - return false; - } else if (vis == EnumQuestVisibility.UNLOCKED) { - return quest.isComplete(uuid) || quest.isUnlocked(uuid); - } else if (vis == EnumQuestVisibility.NORMAL) { - if (quest.isComplete(uuid) || quest.isUnlocked(uuid)) // Complete or pending - { - return true; - } - - // Previous quest is underway and this one is visible but still locked (foreshadowing) - for (DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) { - if (!q.getValue().isUnlocked(uuid)) { - return false; + } + switch (vis) { + case HIDDEN: + return false; + case UNLOCKED: + return quest.isComplete(uuid) || quest.isUnlocked(uuid); + case NORMAL: + // Complete or pending + if (quest.isComplete(uuid) || quest.isUnlocked(uuid)) { + return true; + } + // Previous quest is underway and this one is visible but still locked (foreshadowing) + for (DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) { + if (!q.getValue().isUnlocked(uuid)) { + return false; + } } - } - - return true; - } else if (vis == EnumQuestVisibility.COMPLETED) { - return quest.isComplete(uuid); - } else if (vis == EnumQuestVisibility.CHAIN) { - if (quest.getRequirements().length == 0) { return true; - } - - for (DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) { - if (q == null) { return true; } - - if (isQuestShown(q.getValue(), uuid, player)) { - return true; + case COMPLETED: + return quest.isComplete(uuid); + case CHAIN: + for (DBEntry q : QuestDatabase.INSTANCE.bulkLookup(quest.getRequirements())) { + if (isQuestShown(q.getValue(), uuid, player)) { + return true; + } } - } - - return false; + return false; } - return true; } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java index 1255c18b9..163aa57b9 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java @@ -16,12 +16,12 @@ import betterquesting.api2.client.gui.themes.presets.PresetTexture; import betterquesting.api2.storage.DBEntry; import betterquesting.api2.utils.QuestTranslation; +import betterquesting.questing.CompletionInfo; import betterquesting.questing.QuestDatabase; import betterquesting.storage.QuestSettings; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; -import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextFormatting; import java.text.DecimalFormat; @@ -153,19 +153,13 @@ private List getStandardTooltip(IQuest quest, EntityPlayer player, int q private List getAdvancedTooltip(IQuest quest, EntityPlayer player, int qID) { List list = new ArrayList<>(); - list.add(TextFormatting.GRAY + - QuestTranslation.translate("betterquesting.tooltip.global_quest", quest.getProperty(NativeProps.GLOBAL))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_quest", quest.getProperty(NativeProps.GLOBAL))); if (quest.getProperty(NativeProps.GLOBAL)) { - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_share", - quest.getProperty(NativeProps.GLOBAL_SHARE))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_share", quest.getProperty(NativeProps.GLOBAL_SHARE))); } - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.quest_logic", - quest.getProperty(NativeProps.LOGIC_QUEST).toString() - .toUpperCase())); - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.simultaneous", - quest.getProperty(NativeProps.SIMULTANEOUS))); - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.auto_claim", - quest.getProperty(NativeProps.AUTO_CLAIM))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.quest_logic", quest.getProperty(NativeProps.LOGIC_QUEST).toString().toUpperCase())); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.simultaneous", quest.getProperty(NativeProps.SIMULTANEOUS))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.auto_claim", quest.getProperty(NativeProps.AUTO_CLAIM))); if (quest.getProperty(NativeProps.REPEAT_TIME) >= 0) { long time = quest.getProperty(NativeProps.REPEAT_TIME) / 20; DecimalFormat df = new DecimalFormat("00"); @@ -188,13 +182,14 @@ private List getAdvancedTooltip(IQuest quest, EntityPlayer player, int q } private long getRepeatSeconds(IQuest quest, EntityPlayer player) { - if (quest.getProperty(NativeProps.REPEAT_TIME) < 0) { return -1; } - - NBTTagCompound ue = quest.getCompletionInfo(QuestingAPI.getQuestingUUID(player)); - if (ue == null) { return 0; } + if (quest.getProperty(NativeProps.REPEAT_TIME) < 0) { + return -1; + } - return - ((quest.getProperty(NativeProps.REPEAT_TIME) * 50L) - (System.currentTimeMillis() - ue.getLong("timestamp"))) / - 1000L; + CompletionInfo ue = quest.getCompletionInfo(QuestingAPI.getQuestingUUID(player)); + if (ue == null) { + return 0; + } + return (ue.getTimestamp() + quest.getProperty(NativeProps.REPEAT_TIME) * 50L - System.currentTimeMillis()) / 1000L; } } diff --git a/src/main/java/betterquesting/api2/storage/SimpleDatabase.java b/src/main/java/betterquesting/api2/storage/SimpleDatabase.java index 8e415f424..e70fb50e7 100644 --- a/src/main/java/betterquesting/api2/storage/SimpleDatabase.java +++ b/src/main/java/betterquesting/api2/storage/SimpleDatabase.java @@ -6,6 +6,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import java.util.*; +import java.util.concurrent.ThreadLocalRandom; public class SimpleDatabase implements IDatabase { private final Int2ObjectMap map = new Int2ObjectOpenHashMap<>(); @@ -15,12 +16,15 @@ public class SimpleDatabase implements IDatabase { inverseMap.defaultReturnValue(-1); } - private final BitSet idMap = new BitSet(); private List> refCache = null; @Override public synchronized int nextID() { - return idMap.nextClearBit(0); + int nextID; + do { + nextID = ThreadLocalRandom.current().nextInt() & Integer.MAX_VALUE; + } while (map.containsKey(nextID)); + return nextID; } @Override @@ -30,7 +34,6 @@ public synchronized DBEntry add(int id, T value) { throw new IllegalArgumentException("ID cannot be negative"); } if (map.putIfAbsent(id, value) == null && inverseMap.putIfAbsent(value, id) == null) { - idMap.set(id); refCache = null; return new DBEntry<>(id, value); } else { @@ -48,7 +51,6 @@ public synchronized boolean removeID(int key) { return false; } inverseMap.removeInt(removed); - idMap.clear(key); refCache = null; return true; } @@ -63,7 +65,6 @@ public synchronized boolean removeValue(T value) { return false; } map.remove(removed); - idMap.clear(removed); refCache = null; return true; } @@ -86,7 +87,7 @@ public synchronized int size() { @Override public synchronized void reset() { map.clear(); - idMap.clear(); + inverseMap.clear(); refCache = Collections.emptyList(); } diff --git a/src/main/java/betterquesting/handlers/EventHandler.java b/src/main/java/betterquesting/handlers/EventHandler.java index 353bfdcf2..d6488853d 100644 --- a/src/main/java/betterquesting/handlers/EventHandler.java +++ b/src/main/java/betterquesting/handlers/EventHandler.java @@ -11,6 +11,7 @@ import betterquesting.api.questing.party.IParty; import betterquesting.api.storage.BQ_Settings; import betterquesting.api2.cache.CapabilityProviderQuestCache; +import betterquesting.api2.cache.QuestCache; import betterquesting.api2.cache.QuestCache.QResetTime; import betterquesting.api2.client.gui.GuiScreenTest; import betterquesting.api2.client.gui.themes.gui_args.GArgsNone; @@ -45,7 +46,6 @@ import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.CommandEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; -import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.player.PlayerEvent.Clone; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent; @@ -54,6 +54,7 @@ import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.common.gameevent.TickEvent.ServerTickEvent; import net.minecraftforge.fml.relauncher.Side; @@ -96,28 +97,27 @@ public void onCapabilityPlayer(AttachCapabilitiesEvent event) { @SubscribeEvent public void onPlayerClone(Clone event) { - betterquesting.api2.cache.QuestCache oCache = + QuestCache oCache = event.getOriginal().getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - betterquesting.api2.cache.QuestCache nCache = + QuestCache nCache = event.getEntityPlayer().getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); if (oCache != null && nCache != null) { nCache.deserializeNBT(oCache.serializeNBT()); } } @SubscribeEvent - public void onLivingUpdate(LivingUpdateEvent event) { - if (event.getEntityLiving().world.isRemote) { return; } - if (!(event.getEntityLiving() instanceof EntityPlayerMP)) { return; } - if (event.getEntityLiving().ticksExisted % 20 != 0) { - return; // Only triggers once per second + public void onLivingUpdate(TickEvent.PlayerTickEvent event) { + if (event.side.isClient() || event.player.ticksExisted % 20 != 0) { + return; } - EntityPlayerMP player = (EntityPlayerMP) event.getEntityLiving(); - betterquesting.api2.cache.QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); - - if (qc == null) { return; } + EntityPlayerMP player = (EntityPlayerMP) event.player; + QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); + if (qc == null) { + return; + } + boolean editMode = QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE); List> activeQuests = QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests()); List> pendingAutoClaims = QuestDatabase.INSTANCE.bulkLookup(qc.getPendingAutoClaims()); QResetTime[] pendingResets = qc.getScheduledResets(); @@ -134,7 +134,9 @@ public void onLivingUpdate(LivingUpdateEvent event) { continue; // Although it IS active, it cannot be completed yet } - if (quest.getValue().canSubmit(player)) { quest.getValue().update(player); } + if (quest.getValue().canSubmit(player)) { + quest.getValue().update(player); + } if (quest.getValue().isComplete(uuid) && !quest.getValue().canSubmit(player)) { refreshCache = true; @@ -188,12 +190,14 @@ public void onLivingUpdate(LivingUpdateEvent event) { } } - if (refreshCache || player.ticksExisted % 200 == 0) // Refresh the cache if something changed or every 10 seconds - { + // Refresh the cache if something changed or every 10 seconds + if (refreshCache || player.ticksExisted % 200 == 0) { qc.updateCache(player); } - if (qc.getDirtyQuests().length > 0) { NetQuestSync.sendSync(player, qc.getDirtyQuests(), false, true); } + if (qc.getDirtyQuests().length > 0) { + NetQuestSync.sendSync(player, qc.getDirtyQuests(), false, true); + } qc.cleanAllQuests(); } diff --git a/src/main/java/betterquesting/misc/Util.java b/src/main/java/betterquesting/misc/Util.java index a8f1886fc..8ada0b9e3 100644 --- a/src/main/java/betterquesting/misc/Util.java +++ b/src/main/java/betterquesting/misc/Util.java @@ -1,5 +1,6 @@ package betterquesting.misc; +import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; @@ -37,4 +38,13 @@ public Integer next() { } }; } + + public static int[] toIntArray(Collection collection) { + int i = 0; + int[] aryAct = new int[collection.size()]; + for (Integer q : collection) { + aryAct[i++] = q; + } + return aryAct; + } } diff --git a/src/main/java/betterquesting/questing/CompletionInfo.java b/src/main/java/betterquesting/questing/CompletionInfo.java new file mode 100644 index 000000000..23bb3afc6 --- /dev/null +++ b/src/main/java/betterquesting/questing/CompletionInfo.java @@ -0,0 +1,27 @@ +package betterquesting.questing; + +public class CompletionInfo { + private long timestamp; + private boolean claimed; + + public CompletionInfo(long timestamp, boolean claimed) { + this.timestamp = timestamp; + this.claimed = claimed; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long time) { + this.timestamp = time; + } + + public boolean isClaimed() { + return claimed; + } + + public void setClaimed(boolean claimed) { + this.claimed = claimed; + } +} diff --git a/src/main/java/betterquesting/questing/QuestDatabase.java b/src/main/java/betterquesting/questing/QuestDatabase.java index f194acddb..370dbc95b 100644 --- a/src/main/java/betterquesting/questing/QuestDatabase.java +++ b/src/main/java/betterquesting/questing/QuestDatabase.java @@ -17,14 +17,20 @@ public final class QuestDatabase extends SimpleDatabase implements IQues @Override public synchronized IQuest createNew(int id) { IQuest quest = new QuestInstance(); - if (id >= 0) { this.add(id, quest); } + if (id >= 0) { + this.add(id, quest); + } return quest; } @Override public synchronized boolean removeID(int id) { boolean success = super.removeID(id); - if (success) { for (DBEntry entry : getEntries()) { removeReq(entry.getValue(), id); } } + if (success) { + for (DBEntry entry : getEntries()) { + removeReq(entry.getValue(), id); + } + } return success; } diff --git a/src/main/java/betterquesting/questing/QuestInstance.java b/src/main/java/betterquesting/questing/QuestInstance.java index 3947b694c..e2e96c287 100644 --- a/src/main/java/betterquesting/questing/QuestInstance.java +++ b/src/main/java/betterquesting/questing/QuestInstance.java @@ -36,7 +36,7 @@ public class QuestInstance implements IQuest { private final TaskStorage tasks = new TaskStorage(); private final RewardStorage rewards = new RewardStorage(); - private final HashMap completeUsers = new HashMap<>(); + private final HashMap completeUsers = new HashMap<>(); private int[] preRequisites = new int[0]; private final PropertyContainer qInfo = new PropertyContainer(); @@ -105,7 +105,9 @@ public void update(EntityPlayer player) { public void detect(EntityPlayer player) { UUID playerID = QuestingAPI.getQuestingUUID(player); QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (qc == null) { return; } + if (qc == null) { + return; + } int questID = QuestDatabase.INSTANCE.getID(this); if (isComplete(playerID) && (qInfo.getProperty(NativeProps.REPEAT_TIME) < 0 || rewards.size() <= 0)) { @@ -135,7 +137,7 @@ public void detect(EntityPlayer player) { } // Note: Tasks can mark the quest dirty themselves if progress changed but hasn't fully completed. if (tasks.size() <= 0 || qInfo.getProperty(NativeProps.LOGIC_TASK).getResult(done, tasks.size())) { - // State won't be auto updated in edit mode so we force change it here and mark it for re-sync + // State won't be auto updated in edit mode, so we force change it here and mark it for re-sync if (QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) { setComplete(playerID, System.currentTimeMillis()); } @@ -151,39 +153,40 @@ public void detect(EntityPlayer player) { @Override public boolean hasClaimed(UUID uuid) { - if (rewards.size() <= 0) { return true; } + if (rewards.size() <= 0) { + return true; + } synchronized (completeUsers) { if (qInfo.getProperty(NativeProps.GLOBAL) && !qInfo.getProperty(NativeProps.GLOBAL_SHARE)) { // TODO: Figure out some replacement to track participation - for (NBTTagCompound entry : completeUsers.values()) { - if (entry.getBoolean("claimed")) { return true; } + for (CompletionInfo entry : completeUsers.values()) { + if (entry.isClaimed()) { + return true; + } } return false; } - NBTTagCompound entry = getCompletionInfo(uuid); - return entry != null && entry.getBoolean("claimed"); + CompletionInfo entry = getCompletionInfo(uuid); + return entry != null && entry.isClaimed(); } } @Override public boolean canClaim(EntityPlayer player) { UUID pID = QuestingAPI.getQuestingUUID(player); - NBTTagCompound entry = getCompletionInfo(pID); - if (entry == null || hasClaimed(pID) || canSubmit(player)) { + if (getCompletionInfo(pID) == null || hasClaimed(pID) || canSubmit(player)) { return false; - } else { - DBEntry dbe = new DBEntry<>(QuestDatabase.INSTANCE.getID(this), this); - for (DBEntry rew : rewards.getEntries()) { - if (!rew.getValue().canClaim(player, dbe)) { - return false; - } + } + DBEntry dbe = new DBEntry<>(QuestDatabase.INSTANCE.getID(this), this); + for (DBEntry rew : rewards.getEntries()) { + if (!rew.getValue().canClaim(player, dbe)) { + return false; } } - return true; } @@ -199,18 +202,20 @@ public void claimReward(EntityPlayer player) { QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); synchronized (completeUsers) { - NBTTagCompound entry = getCompletionInfo(pID); + CompletionInfo entry = getCompletionInfo(pID); if (entry == null) { - entry = new NBTTagCompound(); + entry = new CompletionInfo(System.currentTimeMillis(), true); this.completeUsers.put(pID, entry); + } else { + entry.setClaimed(true); + entry.setTimestamp(System.currentTimeMillis()); } - - entry.setBoolean("claimed", true); - entry.setLong("timestamp", System.currentTimeMillis()); } - if (qc != null) { qc.markQuestDirty(questID); } + if (qc != null) { + qc.markQuestDirty(questID); + } } @Override @@ -218,10 +223,12 @@ public boolean canSubmit(@Nonnull EntityPlayer player) { UUID playerID = QuestingAPI.getQuestingUUID(player); synchronized (completeUsers) { - NBTTagCompound entry = this.getCompletionInfo(playerID); - if (entry == null) { return true; } + CompletionInfo entry = this.getCompletionInfo(playerID); + if (entry == null) { + return true; + } - if (!entry.getBoolean("claimed") && getProperty(NativeProps.REPEAT_TIME) >= 0) // Complete but repeatable + if (!entry.isClaimed() && getProperty(NativeProps.REPEAT_TIME) >= 0) // Complete but repeatable { if (tasks.size() <= 0) { return true; } @@ -242,7 +249,9 @@ public boolean canSubmit(@Nonnull EntityPlayer player) { @Override public boolean isUnlocked(UUID uuid) { - if (preRequisites.length == 0) { return true; } + if (preRequisites.length == 0) { + return true; + } int A = 0; int B = preRequisites.length; @@ -258,18 +267,20 @@ public boolean isUnlocked(UUID uuid) { @Override public void setComplete(UUID uuid, long timestamp) { - if (uuid == null) { return; } + if (uuid == null) { + return; + } synchronized (completeUsers) { - NBTTagCompound entry = this.getCompletionInfo(uuid); + CompletionInfo entry = this.getCompletionInfo(uuid); if (entry == null) { - entry = new NBTTagCompound(); + entry = new CompletionInfo(timestamp, false); completeUsers.put(uuid, entry); + } else { + entry.setTimestamp(timestamp); + entry.setClaimed(false); } - - entry.setBoolean("claimed", false); - entry.setLong("timestamp", timestamp); } } @@ -301,21 +312,23 @@ public EnumQuestState getState(UUID uuid) { } @Override - public NBTTagCompound getCompletionInfo(UUID uuid) { + public CompletionInfo getCompletionInfo(UUID uuid) { synchronized (completeUsers) { return completeUsers.get(uuid); } } @Override - public void setCompletionInfo(UUID uuid, NBTTagCompound nbt) { - if (uuid == null) { return; } + public void setCompletionInfo(UUID uuid, CompletionInfo completionInfo) { + if (uuid == null) { + return; + } synchronized (completeUsers) { - if (nbt == null) { + if (completionInfo == null) { completeUsers.remove(uuid); } else { - completeUsers.put(uuid, nbt); + completeUsers.put(uuid, completionInfo); } } } @@ -335,14 +348,14 @@ public void resetUser(@Nullable UUID uuid, boolean fullReset) { } else { if (uuid == null) { completeUsers.forEach((key, value) -> { - value.setBoolean("claimed", false); - value.setLong("timestamp", 0); + value.setClaimed(false); + value.setTimestamp(0); }); } else { - NBTTagCompound entry = getCompletionInfo(uuid); + CompletionInfo entry = getCompletionInfo(uuid); if (entry != null) { - entry.setBoolean("claimed", false); - entry.setLong("timestamp", 0); + entry.setTimestamp(0); + entry.setClaimed(false); } } } @@ -408,11 +421,23 @@ public void readFromNBT(NBTTagCompound jObj) { public NBTTagCompound writeProgressToNBT(NBTTagCompound json, @Nullable List users) { synchronized (completeUsers) { NBTTagList comJson = new NBTTagList(); - for (Entry entry : completeUsers.entrySet()) { - if (users != null && !users.contains(entry.getKey())) { continue; } - NBTTagCompound tags = entry.getValue().copy(); - tags.setString("uuid", entry.getKey().toString()); - comJson.appendTag(tags); + if (users == null) { + for (Entry entry : completeUsers.entrySet()) { + NBTTagCompound tags = new NBTTagCompound(); + tags.setLong("timestamp", entry.getValue().getTimestamp()); + tags.setBoolean("claimed", entry.getValue().isClaimed()); + tags.setString("uuid", entry.getKey().toString()); + comJson.appendTag(tags); + } + } else { + for (UUID key : users) { + CompletionInfo value = completeUsers.get(key); + NBTTagCompound tags = new NBTTagCompound(); + tags.setLong("timestamp", value.getTimestamp()); + tags.setBoolean("claimed", value.isClaimed()); + tags.setString("uuid", value.toString()); + comJson.appendTag(tags); + } } json.setTag("completed", comJson); @@ -426,14 +451,16 @@ public NBTTagCompound writeProgressToNBT(NBTTagCompound json, @Nullable List implements IDatabaseNBT subset) { for (DBEntry entry : getEntries()) { - if (subset != null && !subset.contains(entry.getID())) { continue; } + if (subset != null && !subset.contains(entry.getID())) { + continue; + } ResourceLocation taskID = entry.getValue().getFactoryID(); NBTTagCompound qJson = entry.getValue().writeToNBT(new NBTTagCompound()); qJson.setString("taskID", taskID.toString()); @@ -31,7 +33,9 @@ public NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { @Override public void readFromNBT(NBTTagList json, boolean merge) { - if (!merge) { reset(); } + if (!merge) { + reset(); + } List unassigned = new ArrayList<>(); for (int i = 0; i < json.tagCount(); i++) { From 33e2aa332783a4930c87e16676230e0dba3c902a Mon Sep 17 00:00:00 2001 From: Olexy Date: Thu, 5 Oct 2023 19:32:16 +0300 Subject: [PATCH 06/10] Version bump --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index f384e5777..07c2017a7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,3 +1,3 @@ -version=3.6.2 +version=3.6.3 minecraftVersion=1.12.2 forgeVersion=14.23.5.2860 \ No newline at end of file From 454a80c26d5f64822cc065c7573c9bd8aebadbb9 Mon Sep 17 00:00:00 2001 From: Olexy Date: Sat, 7 Oct 2023 00:22:05 +0300 Subject: [PATCH 07/10] Fixed an NPE during quest synchronisation. --- gradle.properties | 2 +- src/main/java/betterquesting/questing/QuestInstance.java | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 07c2017a7..bbce34437 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,3 +1,3 @@ -version=3.6.3 +version=3.6.4 minecraftVersion=1.12.2 forgeVersion=14.23.5.2860 \ No newline at end of file diff --git a/src/main/java/betterquesting/questing/QuestInstance.java b/src/main/java/betterquesting/questing/QuestInstance.java index e2e96c287..6ab4c7524 100644 --- a/src/main/java/betterquesting/questing/QuestInstance.java +++ b/src/main/java/betterquesting/questing/QuestInstance.java @@ -432,6 +432,9 @@ public NBTTagCompound writeProgressToNBT(NBTTagCompound json, @Nullable List Date: Sun, 8 Oct 2023 20:53:41 +0300 Subject: [PATCH 08/10] Fixed ClassCastException during quest deserialization. --- gradle.properties | 2 +- src/main/java/betterquesting/questing/QuestInstance.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index bbce34437..5df5afe05 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,3 +1,3 @@ -version=3.6.4 +version=3.6.5 minecraftVersion=1.12.2 forgeVersion=14.23.5.2860 \ No newline at end of file diff --git a/src/main/java/betterquesting/questing/QuestInstance.java b/src/main/java/betterquesting/questing/QuestInstance.java index 6ab4c7524..e0d008add 100644 --- a/src/main/java/betterquesting/questing/QuestInstance.java +++ b/src/main/java/betterquesting/questing/QuestInstance.java @@ -438,7 +438,7 @@ public NBTTagCompound writeProgressToNBT(NBTTagCompound json, @Nullable List Date: Mon, 16 Oct 2023 16:47:05 +0300 Subject: [PATCH 09/10] Reformatted everything again. --- .../api/events/DatabaseEvent.java | 4 +- .../api/events/NbtDocEvent.java | 2 +- .../betterquesting/api/events/QuestEvent.java | 8 +- .../api/placeholders/EntityPlaceholder.java | 9 +- .../api/placeholders/ItemPlaceholder.java | 2 +- .../placeholders/PlaceholderConverter.java | 24 +- .../rewards/FactoryRewardPlaceholder.java | 3 +- .../rewards/RewardPlaceholder.java | 3 +- .../tasks/FactoryTaskPlaceholder.java | 3 +- .../placeholders/tasks/TaskPlaceholder.java | 9 +- .../properties/basic/PropertyTypeBoolean.java | 6 +- .../properties/basic/PropertyTypeByte.java | 4 +- .../properties/basic/PropertyTypeDouble.java | 4 +- .../properties/basic/PropertyTypeEnum.java | 6 +- .../properties/basic/PropertyTypeFloat.java | 4 +- .../properties/basic/PropertyTypeInteger.java | 4 +- .../basic/PropertyTypeItemStack.java | 2 +- .../properties/basic/PropertyTypeLong.java | 4 +- .../properties/basic/PropertyTypeString.java | 4 +- .../api/utils/BigItemStack.java | 30 +-- .../api/utils/ItemComparison.java | 8 +- .../betterquesting/api/utils/JsonHelper.java | 32 ++- .../api/utils/NBTConverter.java | 4 +- .../betterquesting/api/utils/RenderUtils.java | 12 +- .../cache/CapabilityProviderQuestCache.java | 4 +- .../betterquesting/api2/cache/QuestCache.java | 4 +- .../api2/client/gui/GuiContainerCanvas.java | 92 ++++---- .../api2/client/gui/GuiScreenCanvas.java | 79 ++++--- .../api2/client/gui/GuiScreenTest.java | 4 +- .../api2/client/gui/controls/PanelButton.java | 81 ++++--- .../client/gui/controls/PanelButtonQuest.java | 24 +- .../gui/controls/PanelButtonStorage.java | 10 +- .../client/gui/controls/PanelTextField.java | 206 +++++++++--------- .../callbacks/CallbackNBTPrimitive.java | 12 +- .../callbacks/CallbackNBTTagString.java | 8 +- .../client/gui/controls/io/FloatSimpleIO.java | 24 +- .../client/gui/controls/io/ValueFuncIO.java | 2 +- .../client/gui/events/PEventBroadcaster.java | 4 +- .../api2/client/gui/events/PEventEntry.java | 10 +- .../api2/client/gui/events/PanelEvent.java | 6 +- .../client/gui/events/types/PEventButton.java | 2 +- .../client/gui/events/types/PEventParty.java | 4 +- .../client/gui/events/types/PEventQuest.java | 4 +- .../api2/client/gui/help/HelpRegistry.java | 4 +- .../api2/client/gui/help/HelpTopic.java | 6 +- .../api2/client/gui/misc/GuiAlign.java | 2 +- .../api2/client/gui/misc/GuiPadding.java | 10 +- .../api2/client/gui/misc/GuiRectLerp.java | 34 +-- .../api2/client/gui/misc/GuiRectangle.java | 12 +- .../api2/client/gui/misc/GuiTransform.java | 22 +- .../api2/client/gui/misc/ProxyRect.java | 8 +- .../api2/client/gui/panels/CanvasEmpty.java | 10 +- .../client/gui/panels/CanvasResizeable.java | 36 +-- .../client/gui/panels/CanvasTextured.java | 6 +- .../client/gui/panels/bars/PanelHBarFill.java | 25 +-- .../gui/panels/bars/PanelHScrollBar.java | 47 ++-- .../client/gui/panels/bars/PanelVBarFill.java | 25 +-- .../gui/panels/bars/PanelVScrollBar.java | 47 ++-- .../panels/content/PanelEntityPreview.java | 29 ++- .../gui/panels/content/PanelFluidSlot.java | 18 +- .../gui/panels/content/PanelGeneric.java | 9 +- .../gui/panels/content/PanelItemSlot.java | 26 ++- .../client/gui/panels/content/PanelLine.java | 11 +- .../panels/content/PanelPlayerPortrait.java | 29 ++- .../gui/panels/content/PanelTextBox.java | 42 ++-- .../panels/lists/CanvasCullingManager.java | 4 +- .../panels/lists/CanvasEntityDatabase.java | 8 +- .../gui/panels/lists/CanvasFileDirectory.java | 18 +- .../gui/panels/lists/CanvasFluidDatabase.java | 4 +- .../gui/panels/lists/CanvasHoverTray.java | 28 ++- .../gui/panels/lists/CanvasItemDatabase.java | 8 +- .../gui/panels/lists/CanvasQuestLine.java | 50 +++-- .../gui/panels/lists/CanvasScrolling.java | 86 +++++--- .../client/gui/panels/lists/CanvasSearch.java | 18 +- .../api2/client/gui/popups/PopChoice.java | 14 +- .../client/gui/popups/PopContextMenu.java | 12 +- .../api2/client/gui/popups/PopMessage.java | 14 +- .../gui/resources/colors/GuiColorPulse.java | 4 +- .../resources/colors/GuiColorSequence.java | 6 +- .../gui/resources/colors/GuiColorStatic.java | 4 +- .../resources/colors/GuiColorTransition.java | 2 +- .../factories/colors/FactoryColorPulse.java | 8 +- .../colors/FactoryColorSequence.java | 4 +- .../textures/FactoryColorTexture.java | 8 +- .../textures/FactoryLayeredTexture.java | 4 +- .../textures/FactoryPolyTextureC.java | 12 +- .../textures/FactoryPolyTextureR.java | 8 +- .../textures/FactorySimpleTexture.java | 4 +- .../textures/FactorySlicedTexture.java | 8 +- .../textures/FactorySlideShowTexture.java | 7 +- .../client/gui/resources/lines/BoxLine.java | 4 +- .../gui/resources/lines/SimpleLine.java | 4 +- .../gui/resources/textures/ColorTexture.java | 6 +- .../gui/resources/textures/EmptyTexture.java | 6 +- .../gui/resources/textures/FluidTexture.java | 8 +- .../resources/textures/GuiTextureColored.java | 8 +- .../gui/resources/textures/ItemTexture.java | 6 +- .../resources/textures/LayeredTexture.java | 8 +- .../gui/resources/textures/PolyTexture.java | 16 +- .../gui/resources/textures/SimpleTexture.java | 12 +- .../gui/resources/textures/SlicedTexture.java | 22 +- .../resources/textures/SlideShowTexture.java | 20 +- .../api2/client/gui/themes/GuiKey.java | 4 +- .../gui/themes/presets/PresetColor.java | 4 +- .../client/gui/themes/presets/PresetIcon.java | 4 +- .../client/gui/themes/presets/PresetLine.java | 4 +- .../gui/themes/presets/PresetTexture.java | 4 +- .../api2/registry/FunctionRegistry.java | 4 +- .../betterquesting/api2/storage/DBEntry.java | 4 +- .../api2/supporter/MCLinkAPI.java | 8 +- .../api2/supporter/RgbTexture.java | 5 +- .../api2/supporter/SupporterAPI.java | 57 +++-- .../api2/supporter/SupporterEntry.java | 6 +- .../supporter/mc_link/McLinkEndpoint.java | 2 +- .../supporter/theme_dlc/CatalogueEntry.java | 20 +- .../supporter/theme_dlc/ThemeCatalogue.java | 8 +- .../supporter/theme_dlc/ThemeRepository.java | 2 +- .../api2/utils/BQThreadedIO.java | 2 +- .../api2/utils/BqFontRenderer.java | 36 +-- .../api2/utils/EntityPlayerPreview.java | 6 +- .../api2/utils/ParticipantInfo.java | 34 ++- .../api2/utils/QuestLineSorter.java | 2 +- .../blocks/BlockSubmitStation.java | 6 +- .../blocks/TileSubmitStation.java | 13 +- .../client/CreativeTabQuesting.java | 2 +- .../client/QuestNotification.java | 14 +- .../betterquesting/client/gui2/GuiHome.java | 8 +- .../betterquesting/client/gui2/GuiQuest.java | 22 +- .../client/gui2/GuiQuestHelp.java | 2 +- .../client/gui2/GuiQuestLines.java | 80 +++++-- .../betterquesting/client/gui2/GuiThemes.java | 4 +- .../client/gui2/editors/GuiFileBrowser.java | 32 ++- .../client/gui2/editors/GuiImporters.java | 4 +- .../gui2/editors/GuiPrerequisiteEditor.java | 34 ++- .../client/gui2/editors/GuiQuestEditor.java | 16 +- .../gui2/editors/GuiQuestLineAddRemove.java | 20 +- .../gui2/editors/GuiQuestLinesEditor.java | 42 +++- .../client/gui2/editors/GuiRewardEditor.java | 18 +- .../client/gui2/editors/GuiTaskEditor.java | 18 +- .../client/gui2/editors/GuiTextEditor.java | 4 +- .../gui2/editors/designer/GuiDesigner.java | 32 ++- .../editors/designer/PanelToolController.java | 85 +++++--- .../gui2/editors/nbt/GuiEntitySelection.java | 12 +- .../gui2/editors/nbt/GuiFluidSelection.java | 12 +- .../gui2/editors/nbt/GuiItemSelection.java | 12 +- .../client/gui2/editors/nbt/GuiNbtAdd.java | 12 +- .../client/gui2/editors/nbt/GuiNbtEditor.java | 16 +- .../client/gui2/editors/nbt/GuiNbtType.java | 12 +- .../gui2/editors/nbt/PanelScrollingNBT.java | 92 ++++---- .../inventory/ContainerSubmitStation.java | 20 +- .../gui2/inventory/GuiSubmitStation.java | 46 ++-- .../client/gui2/party/GuiPartyCreate.java | 8 +- .../client/gui2/party/GuiPartyInvite.java | 4 +- .../client/gui2/party/GuiPartyManage.java | 8 +- .../betterquesting/client/gui3/GuiStatus.java | 2 +- .../client/importers/ImportedQuestLines.java | 16 +- .../client/importers/ImportedQuests.java | 29 ++- .../renderer/EntityPlaceholderRenderer.java | 2 +- .../client/themes/ResourceTheme.java | 66 ++++-- .../client/themes/ThemeRegistry.java | 72 ++++-- .../client/toolbox/PanelTabMain.java | 8 +- .../client/toolbox/ToolboxTabMain.java | 4 +- .../toolbox/tools/ToolboxToolComplete.java | 31 +-- .../client/toolbox/tools/ToolboxToolCopy.java | 23 +- .../toolbox/tools/ToolboxToolDelete.java | 19 +- .../toolbox/tools/ToolboxToolFrame.java | 35 ++- .../client/toolbox/tools/ToolboxToolGrab.java | 23 +- .../client/toolbox/tools/ToolboxToolIcon.java | 19 +- .../client/toolbox/tools/ToolboxToolLink.java | 52 +++-- .../client/toolbox/tools/ToolboxToolNew.java | 10 +- .../client/toolbox/tools/ToolboxToolOpen.java | 15 +- .../toolbox/tools/ToolboxToolRemove.java | 27 +-- .../toolbox/tools/ToolboxToolReset.java | 23 +- .../toolbox/tools/ToolboxToolScale.java | 7 +- .../client/ui_builder/ComponentPanel.java | 2 +- .../client/ui_builder/GuiBuilderMain.java | 114 ++++++---- .../commands/BQ_CommandAdmin.java | 10 +- .../commands/BQ_CommandUser.java | 10 +- .../commands/QuestCommandBase.java | 4 +- .../commands/admin/QuestCommandComplete.java | 14 +- .../commands/admin/QuestCommandEdit.java | 2 +- .../commands/admin/QuestCommandHardcore.java | 2 +- .../commands/admin/QuestCommandLives.java | 10 +- .../commands/admin/QuestCommandPurge.java | 12 +- .../commands/admin/QuestCommandReset.java | 4 +- .../commands/user/QuestCommandRefresh.java | 8 +- .../betterquesting/core/BetterQuesting.java | 5 +- .../core/proxies/CommonProxy.java | 3 +- .../betterquesting/handlers/EventHandler.java | 36 ++- .../handlers/SaveLoadHandler.java | 10 +- .../betterquesting/items/ItemExtraLife.java | 14 +- .../betterquesting/items/ItemGuideBook.java | 4 +- .../legacy/v0/LegacyLoader_v0.java | 7 +- .../misc/QuestResourcesFile.java | 16 +- .../misc/QuestResourcesFolder.java | 11 +- .../network/PacketQuesting.java | 3 +- .../network/PacketSetupStation.java | 3 +- .../network/handlers/NetBulkSync.java | 4 +- .../network/handlers/NetCacheSync.java | 8 +- .../network/handlers/NetChapterEdit.java | 16 +- .../network/handlers/NetChapterSync.java | 20 +- .../network/handlers/NetImport.java | 8 +- .../network/handlers/NetNameSync.java | 24 +- .../network/handlers/NetNotices.java | 12 +- .../network/handlers/NetPartyAction.java | 40 +++- .../network/handlers/NetPartySync.java | 32 ++- .../network/handlers/NetQuestAction.java | 12 +- .../network/handlers/NetQuestEdit.java | 24 +- .../network/handlers/NetQuestSync.java | 40 +++- .../questing/CompletionInfo.java | 2 +- .../questing/QuestDatabase.java | 60 +++-- .../questing/QuestInstance.java | 32 +-- .../betterquesting/questing/QuestLine.java | 30 ++- .../questing/QuestLineDatabase.java | 38 +++- .../questing/QuestLineEntry.java | 22 +- .../questing/party/PartyInstance.java | 32 ++- .../questing/party/PartyInvitations.java | 48 +++- .../questing/party/PartyManager.java | 20 +- .../questing/rewards/RewardStorage.java | 11 +- .../questing/tasks/TaskStorage.java | 4 +- .../betterquesting/storage/LifeDatabase.java | 8 +- .../betterquesting/storage/NameCache.java | 12 +- .../storage/PropertyContainer.java | 47 ++-- .../betterquesting/storage/QuestSettings.java | 44 ++-- 224 files changed, 2462 insertions(+), 1593 deletions(-) diff --git a/src/main/java/betterquesting/api/events/DatabaseEvent.java b/src/main/java/betterquesting/api/events/DatabaseEvent.java index 73b4b0a08..e9dbaf0c9 100644 --- a/src/main/java/betterquesting/api/events/DatabaseEvent.java +++ b/src/main/java/betterquesting/api/events/DatabaseEvent.java @@ -12,11 +12,11 @@ public abstract class DatabaseEvent extends Event { private final DBType TYPE; public DatabaseEvent(DBType type) { - this.TYPE = type; + TYPE = type; } public DBType getType() { - return this.TYPE; + return TYPE; } @Deprecated diff --git a/src/main/java/betterquesting/api/events/NbtDocEvent.java b/src/main/java/betterquesting/api/events/NbtDocEvent.java index 58c7d2b25..d883de687 100644 --- a/src/main/java/betterquesting/api/events/NbtDocEvent.java +++ b/src/main/java/betterquesting/api/events/NbtDocEvent.java @@ -20,7 +20,7 @@ public INbtDoc getNbtDoc() { } public void setNewDoc(INbtDoc jdoc) { - this.outJdoc = jdoc; + outJdoc = jdoc; } public INbtDoc getNbtDocResult() { diff --git a/src/main/java/betterquesting/api/events/QuestEvent.java b/src/main/java/betterquesting/api/events/QuestEvent.java index 7152284c8..a265e6cc6 100644 --- a/src/main/java/betterquesting/api/events/QuestEvent.java +++ b/src/main/java/betterquesting/api/events/QuestEvent.java @@ -10,21 +10,21 @@ public class QuestEvent extends Event { private final Set questIDs; public Set getQuestIDs() { - return this.questIDs; + return questIDs; } public UUID getPlayerID() { - return this.playerID; + return playerID; } public Type getType() { - return this.type; + return type; } public QuestEvent(Type type, UUID playerID, int questID) { this.type = type; this.playerID = playerID; - this.questIDs = Collections.singleton(questID); + questIDs = Collections.singleton(questID); } public QuestEvent(Type type, UUID playerID, Collection questIDs) { diff --git a/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java b/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java index 9c11b194a..0cf043352 100644 --- a/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/EntityPlaceholder.java @@ -17,12 +17,12 @@ public EntityPlaceholder(World world) { } public EntityPlaceholder SetOriginalTags(NBTTagCompound tags) { - this.original = tags; + original = tags; return this; } public NBTTagCompound GetOriginalTags() { - return this.original; + return original; } public EntityItem GetItemEntity() { @@ -30,8 +30,7 @@ public EntityItem GetItemEntity() { } @Override - protected void entityInit() { - } + protected void entityInit() { } @Override protected void readEntityFromNBT(NBTTagCompound tags) { @@ -40,6 +39,6 @@ protected void readEntityFromNBT(NBTTagCompound tags) { @Override protected void writeEntityToNBT(NBTTagCompound tags) { - tags.setTag("original", this.original); + tags.setTag("original", original); } } diff --git a/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java b/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java index 533fc23ae..7c0d742f2 100644 --- a/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/ItemPlaceholder.java @@ -20,7 +20,7 @@ public class ItemPlaceholder extends Item { // Used solely for retaining info to missing items public ItemPlaceholder() { - this.setTranslationKey("betterquesting.placeholder"); + setTranslationKey("betterquesting.placeholder"); } /** diff --git a/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java b/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java index bc7cd66f0..e38151ba6 100644 --- a/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java +++ b/src/main/java/betterquesting/api/placeholders/PlaceholderConverter.java @@ -36,7 +36,9 @@ public static BigItemStack convertItem(Item item, String name, int count, int da stack.SetTagCompound(new NBTTagCompound()); stack.GetTagCompound().setString("orig_id", name); stack.GetTagCompound().setInteger("orig_meta", damage); - if (nbt != null) { stack.GetTagCompound().setTag("orig_tag", nbt); } + if (nbt != null) { + stack.GetTagCompound().setTag("orig_tag", nbt); + } return stack; } else if (item == ItemPlaceholder.placeholder) { if (nbt != null) { @@ -45,7 +47,9 @@ public static BigItemStack convertItem(Item item, String name, int count, int da if (restored != null) { BigItemStack stack = new BigItemStack(restored, count, nbt.hasKey("orig_meta") ? nbt.getInteger("orig_meta") : damage).setOreDict(oreDict); - if (nbt.hasKey("orig_tag")) { stack.SetTagCompound(nbt.getCompoundTag("orig_tag")); } + if (nbt.hasKey("orig_tag")) { + stack.SetTagCompound(nbt.getCompoundTag("orig_tag")); + } return stack; } else if (damage > 0 && !nbt.hasKey("orig_meta")) { @@ -56,7 +60,9 @@ public static BigItemStack convertItem(Item item, String name, int count, int da } BigItemStack stack = new BigItemStack(item, count, damage).setOreDict(oreDict); - if (nbt != null) { stack.SetTagCompound(nbt); } + if (nbt != null) { + stack.SetTagCompound(nbt); + } return stack; } @@ -66,7 +72,9 @@ public static FluidStack convertFluid(Fluid fluid, String name, int amount, NBTT FluidStack stack = new FluidStack(FluidPlaceholder.fluidPlaceholder, amount); NBTTagCompound orig = new NBTTagCompound(); orig.setString("orig_id", name); - if (nbt != null) { orig.setTag("orig_tag", nbt); } + if (nbt != null) { + orig.setTag("orig_tag", nbt); + } stack.tag = orig; return stack; } else if (fluid == FluidPlaceholder.fluidPlaceholder && nbt != null) { @@ -74,13 +82,17 @@ public static FluidStack convertFluid(Fluid fluid, String name, int amount, NBTT if (restored != null) { FluidStack stack = new FluidStack(restored, amount); - if (nbt.hasKey("orig_tag")) { stack.tag = nbt.getCompoundTag("orig_tag"); } + if (nbt.hasKey("orig_tag")) { + stack.tag = nbt.getCompoundTag("orig_tag"); + } return stack; } } FluidStack stack = new FluidStack(fluid, amount); - if (nbt != null) { stack.tag = nbt; } + if (nbt != null) { + stack.tag = nbt; + } return stack; } diff --git a/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java b/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java index b44032311..55768d0fd 100644 --- a/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/rewards/FactoryRewardPlaceholder.java @@ -9,8 +9,7 @@ public class FactoryRewardPlaceholder implements IFactoryData quest) { } @Override - public void claimReward(EntityPlayer player, DBEntry quest) { - } + public void claimReward(EntityPlayer player, DBEntry quest) { } @Override public IGuiPanel getRewardGui(IGuiRect rect, DBEntry quest) { diff --git a/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java b/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java index adf14fa02..3444c8ef3 100644 --- a/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java +++ b/src/main/java/betterquesting/api/placeholders/tasks/FactoryTaskPlaceholder.java @@ -9,8 +9,7 @@ public class FactoryTaskPlaceholder implements IFactoryData quest) { - } + public void detect(ParticipantInfo participant, DBEntry quest) { } @Override public boolean isComplete(UUID uuid) { @@ -75,12 +74,10 @@ public boolean isComplete(UUID uuid) { } @Override - public void setComplete(UUID uuid) { - } + public void setComplete(UUID uuid) { } @Override - public void resetUser(UUID uuid) { - } + public void resetUser(UUID uuid) { } @Override public IGuiPanel getTaskGui(IGuiRect rect, DBEntry quest) { diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java index d5f448f31..e0afddc99 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeBoolean.java @@ -13,20 +13,20 @@ public PropertyTypeBoolean(ResourceLocation key, Boolean def) { @Override public Boolean readValue(NBTBase nbt) { if (nbt == null || nbt.getId() < 1 || nbt.getId() > 6) { - return this.getDefault(); + return getDefault(); } try { return ((NBTPrimitive) nbt).getByte() > 0; } catch (Exception e) { - return this.getDefault(); + return getDefault(); } } @Override public NBTBase writeValue(Boolean value) { if (value == null) { - return new NBTTagByte(this.getDefault() ? (byte) 1 : (byte) 0); + return new NBTTagByte(getDefault() ? (byte) 1 : (byte) 0); } return new NBTTagByte(value ? (byte) 1 : (byte) 0); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java index 7de8c7ca2..e2a2b5662 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeByte.java @@ -13,7 +13,7 @@ public PropertyTypeByte(ResourceLocation key, Byte def) { @Override public Byte readValue(NBTBase nbt) { if (!(nbt instanceof NBTPrimitive)) { - return this.getDefault(); + return getDefault(); } return ((NBTPrimitive) nbt).getByte(); @@ -22,7 +22,7 @@ public Byte readValue(NBTBase nbt) { @Override public NBTBase writeValue(Byte value) { if (value == null) { - return new NBTTagByte(this.getDefault()); + return new NBTTagByte(getDefault()); } return new NBTTagByte(value); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java index eeed6ef03..a714012e9 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeDouble.java @@ -13,7 +13,7 @@ public PropertyTypeDouble(ResourceLocation key, Double def) { @Override public Double readValue(NBTBase nbt) { if (!(nbt instanceof NBTPrimitive)) { - return this.getDefault(); + return getDefault(); } return ((NBTPrimitive) nbt).getDouble(); @@ -22,7 +22,7 @@ public Double readValue(NBTBase nbt) { @Override public NBTBase writeValue(Double value) { if (value == null) { - return new NBTTagDouble(this.getDefault()); + return new NBTTagDouble(getDefault()); } return new NBTTagDouble(value); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java index 36fb6fa2a..34d639b48 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeEnum.java @@ -16,20 +16,20 @@ public PropertyTypeEnum(ResourceLocation key, E def) { @Override public E readValue(NBTBase nbt) { if (nbt == null || nbt.getId() != 8) { - return this.getDefault(); + return getDefault(); } try { return Enum.valueOf(eClazz, ((NBTTagString) nbt).getString()); } catch (Exception e) { - return this.getDefault(); + return getDefault(); } } @Override public NBTBase writeValue(E value) { if (value == null) { - return new NBTTagString(this.getDefault().toString()); + return new NBTTagString(getDefault().toString()); } return new NBTTagString(value.toString()); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java index 52301f3e8..127acf9d5 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeFloat.java @@ -13,7 +13,7 @@ public PropertyTypeFloat(ResourceLocation key, Float def) { @Override public Float readValue(NBTBase nbt) { if (!(nbt instanceof NBTPrimitive)) { - return this.getDefault(); + return getDefault(); } return ((NBTPrimitive) nbt).getFloat(); @@ -22,7 +22,7 @@ public Float readValue(NBTBase nbt) { @Override public NBTBase writeValue(Float value) { if (value == null) { - return new NBTTagFloat(this.getDefault()); + return new NBTTagFloat(getDefault()); } return new NBTTagFloat(value); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java index 366cfd8b3..756458230 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeInteger.java @@ -13,7 +13,7 @@ public PropertyTypeInteger(ResourceLocation key, Integer def) { @Override public Integer readValue(NBTBase nbt) { if (!(nbt instanceof NBTPrimitive)) { - return this.getDefault(); + return getDefault(); } return ((NBTPrimitive) nbt).getInt(); @@ -22,7 +22,7 @@ public Integer readValue(NBTBase nbt) { @Override public NBTBase writeValue(Integer value) { if (value == null) { - return new NBTTagInt(this.getDefault()); + return new NBTTagInt(getDefault()); } return new NBTTagInt(value); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java index e0fd6ed35..0f9216ea0 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeItemStack.java @@ -14,7 +14,7 @@ public PropertyTypeItemStack(ResourceLocation key, BigItemStack def) { @Override public BigItemStack readValue(NBTBase nbt) { if (nbt == null || nbt.getId() != 10) { - return this.getDefault(); + return getDefault(); } return JsonHelper.JsonToItemStack((NBTTagCompound) nbt); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java index 740763599..a2a68620b 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeLong.java @@ -13,7 +13,7 @@ public PropertyTypeLong(ResourceLocation key, Long def) { @Override public Long readValue(NBTBase nbt) { if (!(nbt instanceof NBTPrimitive)) { - return this.getDefault(); + return getDefault(); } return ((NBTPrimitive) nbt).getLong(); @@ -22,7 +22,7 @@ public Long readValue(NBTBase nbt) { @Override public NBTBase writeValue(Long value) { if (value == null) { - return new NBTTagLong(this.getDefault()); + return new NBTTagLong(getDefault()); } return new NBTTagLong(value); diff --git a/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java b/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java index f4f92cade..a2795bd60 100644 --- a/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java +++ b/src/main/java/betterquesting/api/properties/basic/PropertyTypeString.java @@ -12,7 +12,7 @@ public PropertyTypeString(ResourceLocation key, String def) { @Override public String readValue(NBTBase nbt) { if (nbt == null || nbt.getId() != 8) { - return this.getDefault(); + return getDefault(); } return ((NBTTagString) nbt).getString(); @@ -21,7 +21,7 @@ public String readValue(NBTBase nbt) { @Override public NBTBase writeValue(String value) { if (value == null) { - return new NBTTagString(this.getDefault()); + return new NBTTagString(getDefault()); } return new NBTTagString(value); diff --git a/src/main/java/betterquesting/api/utils/BigItemStack.java b/src/main/java/betterquesting/api/utils/BigItemStack.java index b13c717cd..94a27de3a 100644 --- a/src/main/java/betterquesting/api/utils/BigItemStack.java +++ b/src/main/java/betterquesting/api/utils/BigItemStack.java @@ -25,7 +25,7 @@ public class BigItemStack { public BigItemStack(ItemStack stack) { baseStack = stack.copy(); - this.stackSize = baseStack.getCount(); + stackSize = baseStack.getCount(); baseStack.setCount(1); } @@ -51,7 +51,7 @@ public BigItemStack(@Nonnull Item item, int amount) { public BigItemStack(@Nonnull Item item, int amount, int damage) { baseStack = new ItemStack(item, 1, damage); - this.stackSize = amount; + stackSize = amount; } /** @@ -62,22 +62,22 @@ public ItemStack getBaseStack() { } public boolean hasOreDict() { - return !StringUtils.isNullOrEmpty(this.oreDict) && this.oreIng.getMatchingStacks().length > 0; + return !StringUtils.isNullOrEmpty(oreDict) && oreIng.getMatchingStacks().length > 0; } @Nonnull public String getOreDict() { - return this.oreDict; + return oreDict; } @Nonnull public OreIngredient getOreIngredient() { - return this.oreIng; + return oreIng; } public BigItemStack setOreDict(@Nonnull String ore) { - this.oreDict = ore; - this.oreIng = ore.isEmpty() ? NO_ORE : new OreIngredient(ore); + oreDict = ore; + oreIng = ore.isEmpty() ? NO_ORE : new OreIngredient(ore); return this; } @@ -122,9 +122,9 @@ public List getCombinedStacks() { public BigItemStack copy() { BigItemStack stack = new BigItemStack(baseStack.copy()); - stack.stackSize = this.stackSize; - stack.oreDict = this.oreDict; - stack.oreIng = this.oreIng; + stack.stackSize = stackSize; + stack.oreDict = oreDict; + stack.oreIng = oreIng; return stack; } @@ -144,10 +144,12 @@ public BigItemStack(@Nonnull NBTTagCompound tags) // Can load normal ItemStack N if (tags.hasKey("id", 99)) { itemNBT.setString("id", "" + tags.getShort("id")); } - this.stackSize = tags.getInteger("Count"); - this.setOreDict(tags.getString("OreDict")); - this.baseStack = new ItemStack(itemNBT); // Minecraft does the ID conversions for me - if (tags.getShort("Damage") < 0) { this.baseStack.setItemDamage(OreDictionary.WILDCARD_VALUE); } + stackSize = tags.getInteger("Count"); + setOreDict(tags.getString("OreDict")); + baseStack = new ItemStack(itemNBT); // Minecraft does the ID conversions for me + if (tags.getShort("Damage") < 0) { + baseStack.setItemDamage(OreDictionary.WILDCARD_VALUE); + } } public NBTTagCompound writeToNBT(NBTTagCompound tags) { diff --git a/src/main/java/betterquesting/api/utils/ItemComparison.java b/src/main/java/betterquesting/api/utils/ItemComparison.java index 9d9d7e88d..bc0245e3d 100644 --- a/src/main/java/betterquesting/api/utils/ItemComparison.java +++ b/src/main/java/betterquesting/api/utils/ItemComparison.java @@ -195,7 +195,9 @@ public static boolean OreDictionaryMatch(String name, ItemStack stack) { @Deprecated public static boolean OreDictionaryMatch(String name, NBTTagCompound tags, ItemStack stack, boolean nbtCheck, boolean partialNBT) { - if (!nbtCheck) { return stack != null && !StringUtils.isNullOrEmpty(name) && new OreIngredient(name).apply(stack); } + if (!nbtCheck) { + return stack != null && !StringUtils.isNullOrEmpty(name) && new OreIngredient(name).apply(stack); + } return OreDictionaryMatch(new OreIngredient(name), tags, stack, true, partialNBT); } @@ -204,7 +206,9 @@ public static boolean OreDictionaryMatch(String name, NBTTagCompound tags, ItemS */ public static boolean OreDictionaryMatch(OreIngredient ore, NBTTagCompound tags, ItemStack stack, boolean nbtCheck, boolean partialNBT) { - if (stack == null || ore == null) { return false; } + if (stack == null || ore == null) { + return false; + } return ore.apply(stack) && (!nbtCheck || CompareNBTTagCompound(stack.getTagCompound(), tags, partialNBT)); } diff --git a/src/main/java/betterquesting/api/utils/JsonHelper.java b/src/main/java/betterquesting/api/utils/JsonHelper.java index 5a60bc8c7..97a00cf57 100644 --- a/src/main/java/betterquesting/api/utils/JsonHelper.java +++ b/src/main/java/betterquesting/api/utils/JsonHelper.java @@ -103,7 +103,9 @@ public static void ClearCompoundTag(@Nonnull NBTTagCompound tag) { } public static JsonObject ReadFromFile(File file) { - if (file == null || !file.exists()) { return new JsonObject(); } + if (file == null || !file.exists()) { + return new JsonObject(); + } Future task = BQThreadedIO.INSTANCE.enqueue(() -> { // NOTE: These are now split due to an edge case in the previous implementation where resource leaking can occur should the outer constructor fail @@ -177,7 +179,9 @@ public static void WriteToFile(File file, JsonObject jObj) { } try { - if (file.exists()) { file.delete(); } + if (file.exists()) { + file.delete(); + } tmp.renameTo(file); } catch (Exception e) { QuestingAPI.getLogger().error("An error occured while saving JSON to file (Temp copy):", e); @@ -187,10 +191,14 @@ public static void WriteToFile(File file, JsonObject jObj) { @SuppressWarnings("ResultOfMethodCallIgnored") public static void CopyPaste(File fileIn, File fileOut) { - if (!fileIn.exists()) { return; } + if (!fileIn.exists()) { + return; + } try { - if (fileOut.getParentFile() != null) { fileOut.getParentFile().mkdirs(); } + if (fileOut.getParentFile() != null) { + fileOut.getParentFile().mkdirs(); + } Files.copy(fileIn.toPath(), fileOut.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { QuestingAPI.getLogger().log(Level.ERROR, "Failed copy paste", e); @@ -232,7 +240,9 @@ public static boolean isEntity(NBTTagCompound tags) { */ public static BigItemStack JsonToItemStack(NBTTagCompound nbt) { Item preCheck = Item.getByNameOrId(nbt.hasKey("id", 99) ? "" + nbt.getShort("id") : nbt.getString("id")); - if (preCheck != null && preCheck != ItemPlaceholder.placeholder) { return new BigItemStack(nbt); } + if (preCheck != null && preCheck != ItemPlaceholder.placeholder) { + return new BigItemStack(nbt); + } return PlaceholderConverter.convertItem(preCheck, nbt.getString("id"), nbt.getInteger("Count"), nbt.getShort("Damage"), nbt.getString("OreDict"), !nbt.hasKey("tag", 10) ? null : nbt.getCompoundTag("tag")); @@ -242,7 +252,9 @@ public static BigItemStack JsonToItemStack(NBTTagCompound nbt) { * Use this for quests instead of converter NBT because this doesn't use ID numbers */ public static NBTTagCompound ItemStackToJson(BigItemStack stack, NBTTagCompound nbt) { - if (stack != null) { stack.writeToNBT(nbt); } + if (stack != null) { + stack.writeToNBT(nbt); + } return nbt; } @@ -256,10 +268,14 @@ public static FluidStack JsonToFluidStack(NBTTagCompound json) { } public static NBTTagCompound FluidStackToJson(FluidStack stack, NBTTagCompound json) { - if (stack == null) { return json; } + if (stack == null) { + return json; + } json.setString("FluidName", FluidRegistry.getFluidName(stack)); json.setInteger("Amount", stack.amount); - if (stack.tag != null) { json.setTag("Tag", stack.tag); } + if (stack.tag != null) { + json.setTag("Tag", stack.tag); + } return json; } diff --git a/src/main/java/betterquesting/api/utils/NBTConverter.java b/src/main/java/betterquesting/api/utils/NBTConverter.java index bf1c0b6a8..f6999c32b 100644 --- a/src/main/java/betterquesting/api/utils/NBTConverter.java +++ b/src/main/java/betterquesting/api/utils/NBTConverter.java @@ -80,7 +80,9 @@ private static JsonElement NBTtoJSON_Base(NBTBase tag, boolean format) { // The fact that this is necessary is so dumb @SuppressWarnings("WeakerAccess") public static long[] readLongArray(NBTTagLongArray tag) { - if (tag == null) { return new long[0]; } + if (tag == null) { + return new long[0]; + } String[] entry = tag.toString().replaceAll("[\\[\\]L;]", "") .split(","); // Cut off square braces and "L;" before splitting elements diff --git a/src/main/java/betterquesting/api/utils/RenderUtils.java b/src/main/java/betterquesting/api/utils/RenderUtils.java index 197728610..d5d58c19f 100644 --- a/src/main/java/betterquesting/api/utils/RenderUtils.java +++ b/src/main/java/betterquesting/api/utils/RenderUtils.java @@ -65,7 +65,9 @@ public static void RenderItemStack(Minecraft mc, ItemStack stack, int x, int y, itemRender.zLevel = -150F; // Counters internal Z depth change so that GL translation makes sense FontRenderer font = stack.getItem().getFontRenderer(stack); - if (font == null) { font = mc.fontRenderer; } + if (font == null) { + font = mc.fontRenderer; + } try { itemRender.renderItemAndEffectIntoGUI(stack, x, y); @@ -678,11 +680,15 @@ public static void drawHoveringText(List textLines, int mouseX, int mous */ public static void drawHoveringText(@Nonnull final ItemStack stack, List textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, int maxTextWidth, FontRenderer font) { - if (textLines == null || textLines.isEmpty()) { return; } + if (textLines == null || textLines.isEmpty()) { + return; + } RenderTooltipEvent.Pre event = new RenderTooltipEvent.Pre(stack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, font); - if (MinecraftForge.EVENT_BUS.post(event)) { return; } + if (MinecraftForge.EVENT_BUS.post(event)) { + return; + } mouseX = event.getX(); mouseY = event.getY(); diff --git a/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java b/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java index 83161feb5..183a8e37f 100644 --- a/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java +++ b/src/main/java/betterquesting/api2/cache/CapabilityProviderQuestCache.java @@ -48,7 +48,9 @@ public NBTBase writeNBT(Capability capability, QuestCache instance, @Override public void readNBT(Capability capability, QuestCache instance, EnumFacing side, NBTBase nbt) { - if (nbt instanceof NBTTagCompound) { instance.deserializeNBT((NBTTagCompound) nbt); } + if (nbt instanceof NBTTagCompound) { + instance.deserializeNBT((NBTTagCompound) nbt); + } } }, QuestCache::new); } diff --git a/src/main/java/betterquesting/api2/cache/QuestCache.java b/src/main/java/betterquesting/api2/cache/QuestCache.java index b628abf06..a521727f8 100644 --- a/src/main/java/betterquesting/api2/cache/QuestCache.java +++ b/src/main/java/betterquesting/api2/cache/QuestCache.java @@ -206,7 +206,9 @@ public int compareTo(QResetTime o) { @Override public boolean equals(Object o) { - if (!(o instanceof QResetTime)) { return false; } + if (!(o instanceof QResetTime)) { + return false; + } return ((QResetTime) o).questID == questID; } } diff --git a/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java b/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java index 10cd5dd3d..818ac1270 100644 --- a/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java +++ b/src/main/java/betterquesting/api2/client/gui/GuiContainerCanvas.java @@ -49,12 +49,12 @@ public GuiContainerCanvas(GuiScreen parent, Container container) { @Override public void openPopup(@Nonnull IGuiPanel panel) { - this.popup = panel; + popup = panel; } @Override public void closePopup() { - this.popup = null; + popup = null; } @Override @@ -65,21 +65,21 @@ public IGuiRect getTransform() { @Nonnull @Override public List getChildren() { - return this.guiPanels; + return guiPanels; } public GuiContainerCanvas useMargins(boolean enable) { - this.useMargins = enable; + useMargins = enable; return this; } public GuiContainerCanvas useDefaultBG(boolean enable) { - this.useDefaultBG = enable; + useDefaultBG = enable; return this; } public GuiContainerCanvas setVolatile(boolean state) { - this.isVolatile = state; + isVolatile = state; return this; } @@ -91,10 +91,10 @@ public final void initGui() { super.initGui(); // Make the container somewhat behave using the root transform bounds - this.guiLeft = 0; - this.guiTop = 0; - this.xSize = width; - this.ySize = height; + guiLeft = 0; + guiTop = 0; + xSize = width; + ySize = height; initPanel(); } @@ -108,41 +108,43 @@ public void onGuiClosed() { @Override public void initPanel() { - rootTransform.w = this.width; - rootTransform.h = this.height; + rootTransform.w = width; + rootTransform.h = height; transform.setParent(rootTransform); if (useMargins) { - int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); - int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); + int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (width - BQ_Settings.guiWidth) / 2); + int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (height - BQ_Settings.guiHeight) / 2); transform.getPadding().setPadding(marginX, marginY, marginX, marginY); } else { transform.getPadding().setPadding(0, 0, 0, 0); } - this.guiPanels.clear(); + guiPanels.clear(); } @Override public void setEnabled(boolean state) { // Technically supported if you wanted something like a multiscreen where this isn't actually the root screen - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override protected void drawGuiContainerBackgroundLayer(float partialTick, int mx, int my) { - if (useDefaultBG) { this.drawDefaultBackground(); } + if (useDefaultBG) { + drawDefaultBackground(); + } GlStateManager.pushMatrix(); GlStateManager.color(1F, 1F, 1F, 1F); GlStateManager.disableDepth(); - this.drawPanel(mx, my, partialTick); + drawPanel(mx, my, partialTick); GlStateManager.enableDepth(); GlStateManager.popMatrix(); @@ -152,8 +154,10 @@ protected void drawGuiContainerBackgroundLayer(float partialTick, int mx, int my public void drawScreen(int mx, int my, float partialTick) { super.drawScreen(mx, my, partialTick); - List tt = this.getTooltip(mx, my); - if (tt != null && !tt.isEmpty()) { this.drawHoveringText(tt, mx, my); } + List tt = getTooltip(mx, my); + if (tt != null && !tt.isEmpty()) { + drawHoveringText(tt, mx, my); + } } /** @@ -178,35 +182,37 @@ public void handleMouseInput() throws IOException { if (k >= 0 && k < 3 && mBtnState[k] != flag) { if (flag) { - this.onMouseClick(i, j, k); + onMouseClick(i, j, k); } else { - this.onMouseRelease(i, j, k); + onMouseRelease(i, j, k); } mBtnState[k] = flag; } if (SDX != 0) { - this.onMouseScroll(i, j, SDX); + onMouseScroll(i, j, SDX); } } @Override public void keyTyped(char c, int keyCode) { if (keyCode == 1) { - if (this.isVolatile || this instanceof IVolatileScreen) { + if (isVolatile || this instanceof IVolatileScreen) { openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); } else { - this.mc.displayGuiScreen(null); - if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + mc.displayGuiScreen(null); + if (mc.currentScreen == null) { + mc.setIngameFocus(); + } } return; } - this.onKeyTyped(c, keyCode); + onKeyTyped(c, keyCode); } @Override @@ -317,14 +323,16 @@ public boolean onKeyTyped(char c, int keycode) { if (!used && (BQ_Keybindings.openQuests.getKeyCode() == keycode || mc.gameSettings.keyBindInventory.getKeyCode() == keycode)) { - if (this.isVolatile || this instanceof IVolatileScreen) { + if (isVolatile || this instanceof IVolatileScreen) { openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); } else { - this.mc.displayGuiScreen(null); - if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + mc.displayGuiScreen(null); + if (mc.currentScreen == null) { + mc.setIngameFocus(); + } } } @@ -338,19 +346,25 @@ public List getTooltip(int mx, int my) { if (popup != null && popup.isEnabled()) { tt = popup.getTooltip(mx, my); - if (tt != null) { return tt; } + if (tt != null) { + return tt; + } } while (pnIter.hasPrevious()) { IGuiPanel entry = pnIter.previous(); - if (!entry.isEnabled()) { continue; } + if (!entry.isEnabled()) { + continue; + } tt = entry.getTooltip(mx, my); - if (tt != null && !tt.isEmpty()) { return tt; } + if (tt != null && !tt.isEmpty()) { + return tt; + } } if (tt == null) { - for (Slot slot : this.inventorySlots.inventorySlots) { + for (Slot slot : inventorySlots.inventorySlots) { if (slot.isEnabled() && slot.getHasStack() && isPointInRegion(slot.xPos, slot.yPos, 16, 16, mx, my)) { tt = slot.getStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED : TooltipFlags.NORMAL); @@ -402,7 +416,7 @@ public T addButton(@Nonnull T button) { @Override protected void renderToolTip(ItemStack stack, int x, int y) { FontRenderer font = stack.getItem().getFontRenderer(stack); - RenderUtils.drawHoveringText(stack, this.getItemToolTip(stack), x, y, width, height, -1, + RenderUtils.drawHoveringText(stack, getItemToolTip(stack), x, y, width, height, -1, (font == null ? fontRenderer : font)); } @@ -413,8 +427,10 @@ protected void drawHoveringText(@Nonnull List textLines, int x, int y, @ public void confirmClose(int id) { if (id == 0) { - this.mc.displayGuiScreen(null); - if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + mc.displayGuiScreen(null); + if (mc.currentScreen == null) { + mc.setIngameFocus(); + } } } } diff --git a/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java b/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java index 8a9b56504..c408537e4 100644 --- a/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java +++ b/src/main/java/betterquesting/api2/client/gui/GuiScreenCanvas.java @@ -58,27 +58,27 @@ public void closePopup() { @Override public IGuiRect getTransform() { - return this.transform; + return transform; } @Nonnull @Override public List getChildren() { - return this.guiPanels; + return guiPanels; } public GuiScreenCanvas useMargins(boolean enable) { - this.useMargins = enable; + useMargins = enable; return this; } public GuiScreenCanvas useDefaultBG(boolean enable) { - this.useDefaultBG = enable; + useDefaultBG = enable; return this; } public GuiScreenCanvas setVolatile(boolean state) { - this.isVolatile = state; + isVolatile = state; return this; } @@ -101,19 +101,19 @@ public void onGuiClosed() { @Override public void initPanel() { - rootTransform.w = this.width; - rootTransform.h = this.height; + rootTransform.w = width; + rootTransform.h = height; transform.setParent(rootTransform); if (useMargins) { - int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); - int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); + int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (width - BQ_Settings.guiWidth) / 2); + int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (height - BQ_Settings.guiHeight) / 2); transform.getPadding().setPadding(marginX, marginY, marginX, marginY); } else { transform.getPadding().setPadding(0, 0, 0, 0); } - this.guiPanels.clear(); + guiPanels.clear(); Arrays.fill(mBtnState, false); // Reset mouse states // TODO: See if I can just make this static across all GUIs if (popup != null) { @@ -124,12 +124,12 @@ public void initPanel() { @Override public void setEnabled(boolean state) { // Technically supported if you wanted something like a multiscreen where this isn't actually the root screen - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } /** @@ -139,18 +139,20 @@ public boolean isEnabled() { public final void drawScreen(int mx, int my, float partialTick) { super.drawScreen(mx, my, partialTick); - if (useDefaultBG) { this.drawDefaultBackground(); } + if (useDefaultBG) { + drawDefaultBackground(); + } GlStateManager.pushMatrix(); GlStateManager.color(1F, 1F, 1F, 1F); GlStateManager.disableDepth(); - this.drawPanel(mx, my, partialTick); + drawPanel(mx, my, partialTick); List tt = getTooltip(mx, my); if (tt != null && !tt.isEmpty()) { - this.drawHoveringText(tt, mx, my); + drawHoveringText(tt, mx, my); } GlStateManager.enableDepth(); @@ -162,8 +164,7 @@ public final void drawScreen(int mx, int my, float partialTick) { */ @Override @Deprecated - public void actionPerformed(@Nonnull GuiButton button) { - } + public void actionPerformed(@Nonnull GuiButton button) { } // Remembers the last mouse buttons states. Required to fire release events private final boolean[] mBtnState = new boolean[3]; @@ -180,35 +181,37 @@ public void handleMouseInput() throws IOException { if (k >= 0 && k < 3 && mBtnState[k] != flag) { if (flag) { - this.onMouseClick(i, j, k); + onMouseClick(i, j, k); } else { - this.onMouseRelease(i, j, k); + onMouseRelease(i, j, k); } mBtnState[k] = flag; } if (SDX != 0) { - this.onMouseScroll(i, j, SDX); + onMouseScroll(i, j, SDX); } } @Override public void keyTyped(char c, int keyCode) { if (keyCode == 1) { - if (this.isVolatile || this instanceof IVolatileScreen) { + if (isVolatile || this instanceof IVolatileScreen) { openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); } else { - this.mc.displayGuiScreen(null); - if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + mc.displayGuiScreen(null); + if (mc.currentScreen == null) { + mc.setIngameFocus(); + } } return; } - this.onKeyTyped(c, keyCode); + onKeyTyped(c, keyCode); } @Override @@ -317,14 +320,16 @@ public boolean onKeyTyped(char c, int keycode) { if (!used && (BQ_Keybindings.openQuests.getKeyCode() == keycode || mc.gameSettings.keyBindInventory.getKeyCode() == keycode)) { - if (this.isVolatile || this instanceof IVolatileScreen) { + if (isVolatile || this instanceof IVolatileScreen) { openPopup(new PopChoice(QuestTranslation.translate("betterquesting.gui.closing_warning") + "\n\n" + QuestTranslation.translate("betterquesting.gui.closing_confirm"), PresetIcon.ICON_NOTICE.getTexture(), this::confirmClose, QuestTranslation.translate("gui.yes"), QuestTranslation.translate("gui.no"))); } else { - this.mc.displayGuiScreen(null); - if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + mc.displayGuiScreen(null); + if (mc.currentScreen == null) { + mc.setIngameFocus(); + } } } @@ -338,15 +343,21 @@ public List getTooltip(int mx, int my) { if (popup != null && popup.isEnabled()) { tt = popup.getTooltip(mx, my); - if (tt != null) { return tt; } + if (tt != null) { + return tt; + } } while (pnIter.hasPrevious()) { IGuiPanel entry = pnIter.previous(); - if (!entry.isEnabled()) { continue; } + if (!entry.isEnabled()) { + continue; + } tt = entry.getTooltip(mx, my); - if (tt != null) { return tt; } + if (tt != null) { + return tt; + } } return null; @@ -382,7 +393,7 @@ public boolean doesGuiPauseGame() { @Override protected void renderToolTip(ItemStack stack, int x, int y) { FontRenderer font = stack.getItem().getFontRenderer(stack); - RenderUtils.drawHoveringText(stack, this.getItemToolTip(stack), x, y, width, height, -1, + RenderUtils.drawHoveringText(stack, getItemToolTip(stack), x, y, width, height, -1, (font == null ? fontRenderer : font)); } @@ -393,8 +404,10 @@ protected void drawHoveringText(@Nonnull List textLines, int x, int y, @ private void confirmClose(int id) { if (id == 0) { - this.mc.displayGuiScreen(null); - if (this.mc.currentScreen == null) { this.mc.setIngameFocus(); } + mc.displayGuiScreen(null); + if (mc.currentScreen == null) { + mc.setIngameFocus(); + } } } } diff --git a/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java b/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java index c4145abac..db45ab37a 100644 --- a/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java +++ b/src/main/java/betterquesting/api2/client/gui/GuiScreenTest.java @@ -23,7 +23,7 @@ public void initPanel() { super.initPanel(); CanvasTextured cvt1 = new CanvasTextured(new GuiTransform(), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvt1); + addPanel(cvt1); PanelHBarFill phf = new PanelHBarFill(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(72, 16, 72, -32), 0)); phf.setFillColor( @@ -54,7 +54,7 @@ public void initPanel() { @Override public void drawPanel(int mx, int my, float partialTick) { - this.drawDefaultBackground(); + drawDefaultBackground(); super.drawPanel(mx, my, partialTick); } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java index 23c725df9..44a4cdbcd 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelButton.java @@ -28,9 +28,9 @@ public class PanelButton implements IPanelButton, IGuiPanel, INBTSaveLoad clickAction = null; public PanelButton(IGuiRect rect, int id, String txt) { - this.transform = rect; - this.btnText = txt; - this.btnID = id; - - this.setTextures(PresetTexture.BTN_NORMAL_0.getTexture(), PresetTexture.BTN_NORMAL_1.getTexture(), - PresetTexture.BTN_NORMAL_2.getTexture()); - this.setTextHighlight(PresetColor.BTN_DISABLED.getColor(), PresetColor.BTN_IDLE.getColor(), - PresetColor.BTN_HOVER.getColor()); + transform = rect; + btnText = txt; + btnID = id; + + setTextures(PresetTexture.BTN_NORMAL_0.getTexture(), PresetTexture.BTN_NORMAL_1.getTexture(), + PresetTexture.BTN_NORMAL_2.getTexture()); + setTextHighlight(PresetColor.BTN_DISABLED.getColor(), PresetColor.BTN_IDLE.getColor(), + PresetColor.BTN_HOVER.getColor()); } public PanelButton setClickAction(Consumer action) { - this.clickAction = action; + clickAction = action; return this; } public PanelButton setTextHighlight(IGuiColor disabled, IGuiColor idle, IGuiColor hover) { - this.colStates[0] = disabled; - this.colStates[1] = idle; - this.colStates[2] = hover; + colStates[0] = disabled; + colStates[1] = idle; + colStates[2] = hover; return this; } public PanelButton setTextShadow(boolean enabled) { - this.txtShadow = enabled; + txtShadow = enabled; return this; } public PanelButton setTextAlignment(int align) { - this.textAlign = MathHelper.clamp(align, 0, 2); + textAlign = MathHelper.clamp(align, 0, 2); return this; } public PanelButton setTextures(IGuiTexture disabled, IGuiTexture idle, IGuiTexture hover) { - this.texStates[0] = disabled; - this.texStates[1] = idle; - this.texStates[2] = hover; + texStates[0] = disabled; + texStates[1] = idle; + texStates[2] = hover; return this; } public PanelButton setIcon(IGuiTexture icon) { - return this.setIcon(icon, 0); + return setIcon(icon, 0); } public PanelButton setIcon(IGuiTexture icon, int padding) { @@ -94,9 +94,9 @@ public PanelButton setIcon(IGuiTexture icon, int padding) { } public PanelButton setIcon(IGuiTexture icon, IGuiColor color, int padding) { - this.texIcon = icon; - this.colIcon = color; - this.icoPadding = padding * 2; + texIcon = icon; + colIcon = color; + icoPadding = padding * 2; return this; } @@ -106,36 +106,36 @@ public PanelButton setTooltip(List tooltip) { } public void setText(String text) { - this.btnText = text; + btnText = text; } public String getText() { - return this.btnText; + return btnText; } @Override public int getButtonID() { - return this.btnID; + return btnID; } @Override public boolean isActive() { - return this.isActive; + return isActive; } @Override public void setActive(boolean state) { - this.isActive = state; + isActive = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override @@ -144,12 +144,11 @@ public IGuiRect getTransform() { } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void drawPanel(int mx, int my, float partialTick) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); GlStateManager.pushMatrix(); GlStateManager.color(1F, 1F, 1F, 1F); int curState = !isActive() ? 0 : (bounds.contains(mx, my) ? 2 : 1); @@ -208,7 +207,7 @@ private static void drawCenteredString(FontRenderer font, String text, int x, in @Override public boolean onMouseClick(int mx, int my, int click) { - boolean contains = this.getTransform().contains(mx, my); + boolean contains = getTransform().contains(mx, my); pendingRelease = isActive() && click == 0 && contains; return (click == 0 || click == 1) && contains; @@ -222,7 +221,7 @@ public boolean onMouseRelease(int mx, int my, int click) { pendingRelease = false; - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); boolean clicked = isActive() && click == 0 && bounds.contains(mx, my) && !PEventBroadcaster.INSTANCE.postEvent(new PEventButton(this)); @@ -247,7 +246,7 @@ public boolean onKeyTyped(char c, int keycode) { @Override public List getTooltip(int mx, int my) { - if (this.getTransform().contains(mx, my)) { + if (getTransform().contains(mx, my)) { return tooltip; } @@ -256,7 +255,9 @@ public List getTooltip(int mx, int my) { @Override public void onButtonClick() { - if (clickAction != null) { clickAction.accept(this); } + if (clickAction != null) { + clickAction.accept(this); + } } @Override @@ -266,7 +267,5 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { } @Override - public void readFromNBT(NBTTagCompound nbt) { - - } + public void readFromNBT(NBTTagCompound nbt) { } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java index 163aa57b9..c627bc4e2 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonQuest.java @@ -76,9 +76,11 @@ public PanelButtonQuest(GuiRectangle rect, int id, String txt, DBEntry v @Override public List getTooltip(int mx, int my) { - if (!this.getTransform().contains(mx, my)) { return null; } + if (!getTransform().contains(mx, my)) { + return null; + } - DBEntry value = this.getStoredValue(); + DBEntry value = getStoredValue(); return value == null ? Collections.emptyList() : getQuestTooltip(value.getValue(), player, value.getID()); } @@ -88,7 +90,7 @@ private List getQuestTooltip(IQuest quest, EntityPlayer player, int qID) if (Minecraft.getMinecraft().gameSettings.advancedItemTooltips && QuestSettings.INSTANCE.getProperty(NativeProps.EDIT_MODE)) { tooltip.add(""); - tooltip.addAll(this.getAdvancedTooltip(quest, player, qID)); + tooltip.addAll(getAdvancedTooltip(quest, player, qID)); } return tooltip; @@ -153,13 +155,19 @@ private List getStandardTooltip(IQuest quest, EntityPlayer player, int q private List getAdvancedTooltip(IQuest quest, EntityPlayer player, int qID) { List list = new ArrayList<>(); - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_quest", quest.getProperty(NativeProps.GLOBAL))); + list.add(TextFormatting.GRAY + + QuestTranslation.translate("betterquesting.tooltip.global_quest", quest.getProperty(NativeProps.GLOBAL))); if (quest.getProperty(NativeProps.GLOBAL)) { - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_share", quest.getProperty(NativeProps.GLOBAL_SHARE))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.global_share", + quest.getProperty(NativeProps.GLOBAL_SHARE))); } - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.quest_logic", quest.getProperty(NativeProps.LOGIC_QUEST).toString().toUpperCase())); - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.simultaneous", quest.getProperty(NativeProps.SIMULTANEOUS))); - list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.auto_claim", quest.getProperty(NativeProps.AUTO_CLAIM))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.quest_logic", + quest.getProperty(NativeProps.LOGIC_QUEST).toString() + .toUpperCase())); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.simultaneous", + quest.getProperty(NativeProps.SIMULTANEOUS))); + list.add(TextFormatting.GRAY + QuestTranslation.translate("betterquesting.tooltip.auto_claim", + quest.getProperty(NativeProps.AUTO_CLAIM))); if (quest.getProperty(NativeProps.REPEAT_TIME) >= 0) { long time = quest.getProperty(NativeProps.REPEAT_TIME) / 20; DecimalFormat df = new DecimalFormat("00"); diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java index 07615c48f..cc2ce4e8d 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelButtonStorage.java @@ -9,11 +9,11 @@ public class PanelButtonStorage extends PanelButton { public PanelButtonStorage(IGuiRect rect, int id, String txt, T value) { super(rect, id, txt); - this.setStoredValue(value); + setStoredValue(value); } public PanelButtonStorage setStoredValue(T value) { - this.stored = value; + stored = value; return this; } @@ -27,11 +27,13 @@ public PanelButtonStorage setCallback(ICallback callback) { } public ICallback getCallback() { - return this.callback; + return callback; } @Override public void onButtonClick() { - if (callback != null) { this.callback.setValue(this.getStoredValue()); } + if (callback != null) { + callback.setValue(getStoredValue()); + } } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java b/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java index ae2d2ad32..2dab5b9f6 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/PanelTextField.java @@ -53,22 +53,22 @@ public class PanelTextField implements IGuiPanel { private ICallback callback; public PanelTextField(IGuiRect rect, String text, IFieldFilter filter) { - this.transform = rect; - cursorLine.setParent(this.transform); + transform = rect; + cursorLine.setParent(transform); this.filter = filter; - this.setTextures(PresetTexture.TEXT_BOX_0.getTexture(), PresetTexture.TEXT_BOX_1.getTexture(), - PresetTexture.TEXT_BOX_2.getTexture()); - this.setMainColors(PresetColor.TEXT_AUX_0.getColor(), PresetColor.TEXT_AUX_0.getColor(), - PresetColor.TEXT_AUX_0.getColor()); - this.setAuxColors(PresetColor.TEXT_WATERMARK.getColor(), PresetColor.TEXT_HIGHLIGHT.getColor()); + setTextures(PresetTexture.TEXT_BOX_0.getTexture(), PresetTexture.TEXT_BOX_1.getTexture(), + PresetTexture.TEXT_BOX_2.getTexture()); + setMainColors(PresetColor.TEXT_AUX_0.getColor(), PresetColor.TEXT_AUX_0.getColor(), + PresetColor.TEXT_AUX_0.getColor()); + setAuxColors(PresetColor.TEXT_WATERMARK.getColor(), PresetColor.TEXT_HIGHLIGHT.getColor()); // Dummy value drivers scrollX = new FloatSimpleIO(); scrollY = new FloatSimpleIO(); - this.setText(text); + setText(text); } public PanelTextField setCallback(ICallback callback) { @@ -77,27 +77,27 @@ public PanelTextField setCallback(ICallback callback) { } public PanelTextField setTextures(IGuiTexture disabled, IGuiTexture idle, IGuiTexture focused) { - this.texState[0] = disabled; - this.texState[1] = idle; - this.texState[2] = focused; + texState[0] = disabled; + texState[1] = idle; + texState[2] = focused; return this; } public PanelTextField setMainColors(IGuiColor disabled, IGuiColor idle, IGuiColor focused) { - this.colStates[0] = disabled; - this.colStates[1] = idle; - this.colStates[2] = focused; + colStates[0] = disabled; + colStates[1] = idle; + colStates[2] = focused; return this; } public PanelTextField setAuxColors(IGuiColor watermark, IGuiColor highlight) { - this.colWatermark = watermark; - this.colHighlight = highlight; + colWatermark = watermark; + colHighlight = highlight; return this; } public PanelTextField setMaxLength(int size) { - this.maxLength = size; + maxLength = size; return this; } @@ -105,26 +105,26 @@ public PanelTextField setMaxLength(int size) { * Enables text wrapping for multi-line editing */ public PanelTextField enableWrapping(boolean state) { - this.canWrap = state; + canWrap = state; updateScrollBounds(); return this; } public void lockFocus(boolean state) { - this.lockFocus = state; + lockFocus = state; if (state) { - this.isFocused = true; + isFocused = true; } } public PanelTextField setScrollDriverX(IValueIO driver) { - this.scrollX = driver; + scrollX = driver; return this; } public PanelTextField setScrollDriverY(IValueIO driver) { - this.scrollY = driver; + scrollY = driver; return this; } @@ -163,19 +163,19 @@ public void setScrollY(int value) { } public void setActive(boolean state) { - this.isActive = state; + isActive = state; } public boolean isActive() { - return this.isActive; + return isActive; } public boolean isFocused() { - return this.isFocused; + return isFocused; } public PanelTextField setWatermark(String text) { - this.watermark = text; + watermark = text; return this; } @@ -186,11 +186,11 @@ public void setText(String text) { } public String getRawText() { - return this.text; + return text; } public T getValue() { - return this.filter.parseValue(getRawText()); + return filter.parseValue(getRawText()); } public String getSelectedText() { @@ -206,7 +206,7 @@ public void writeText(String in) { StringBuilder out = new StringBuilder(); int l = Math.min(selectStart, selectEnd); int r = Math.max(selectStart, selectEnd); - int space = this.maxLength - text.length() - (l - r); + int space = maxLength - text.length() - (l - r); if (!text.isEmpty()) { out.append(text, 0, l); @@ -232,13 +232,13 @@ public void writeText(String in) { //if(filter.isValid(text)) { - this.text = filter.filterText(out.toString()); + text = filter.filterText(out.toString()); updateScrollBounds(); moveCursorBy(l - selectEnd + used); // Broadcast changes if (callback != null) { - callback.setValue(filter.parseValue(this.text)); + callback.setValue(filter.parseValue(text)); } } } @@ -248,11 +248,11 @@ public void writeText(String in) { * which case the selection is deleted instead. */ public void deleteWords(int num) { - if (!this.text.isEmpty()) { - if (this.selectEnd != this.selectStart) { - this.writeText(""); + if (!text.isEmpty()) { + if (selectEnd != selectStart) { + writeText(""); } else { - this.deleteFromCursor(this.getNthWordFromCursor(num) - this.selectStart); + deleteFromCursor(getNthWordFromCursor(num) - selectStart); } } } @@ -262,36 +262,36 @@ public void deleteWords(int num) { * in which case the selection is deleted instead. */ public void deleteFromCursor(int num) { - if (!this.text.isEmpty()) { - if (this.selectEnd != this.selectStart) { - this.writeText(""); + if (!text.isEmpty()) { + if (selectEnd != selectStart) { + writeText(""); } else { boolean flag = num < 0; - int i = flag ? this.selectStart + num : this.selectStart; - int j = flag ? this.selectStart : this.selectStart + num; + int i = flag ? selectStart + num : selectStart; + int j = flag ? selectStart : selectStart + num; String s = ""; if (i >= 0) { - s = this.text.substring(0, i); + s = text.substring(0, i); } - if (j < this.text.length()) { - s = s + this.text.substring(j); + if (j < text.length()) { + s = s + text.substring(j); } //if(filter.isValid(s)) { - this.text = filter.filterText(s); + text = filter.filterText(s); updateScrollBounds(); if (flag) { - this.moveCursorBy(num); + moveCursorBy(num); } // Broadcast changes if (callback != null) { - callback.setValue(filter.parseValue(this.text)); + callback.setValue(filter.parseValue(text)); } } } @@ -302,14 +302,14 @@ public void deleteFromCursor(int num) { * Gets the starting index of the word at the specified number of words away from the cursor position. */ public int getNthWordFromCursor(int numWords) { - return this.getNthWordFromPos(numWords, this.selectStart); + return getNthWordFromPos(numWords, selectStart); } /** * Gets the starting index of the word at a distance of the specified number of words away from the given position. */ public int getNthWordFromPos(int n, int pos) { - return this.getNthWordFromPosWS(n, pos, true); + return getNthWordFromPosWS(n, pos, true); } /** @@ -322,22 +322,22 @@ public int getNthWordFromPosWS(int n, int pos, boolean skipWs) { for (int k = 0; k < j; ++k) { if (!flag) { - int l = this.text.length(); - i = this.text.indexOf(32, i); + int l = text.length(); + i = text.indexOf(32, i); if (i == -1) { i = l; } else { - while (skipWs && i < l && this.text.charAt(i) == ' ') { + while (skipWs && i < l && text.charAt(i) == ' ') { ++i; } } } else { - while (skipWs && i > 0 && this.text.charAt(i - 1) == ' ') { + while (skipWs && i > 0 && text.charAt(i - 1) == ' ') { --i; } - while (i > 0 && this.text.charAt(i - 1) != ' ') { + while (i > 0 && text.charAt(i - 1) != ' ') { --i; } } @@ -350,17 +350,17 @@ public int getNthWordFromPosWS(int n, int pos, boolean skipWs) { * Moves the text cursor by a specified number of characters and clears the selection */ public void moveCursorBy(int num) { - this.setCursorPosition(this.selectEnd + num); + setCursorPosition(selectEnd + num); } /** * Sets the current position of the cursor. */ public void setCursorPosition(int pos) { - this.selectStart = pos; - int i = this.text.length(); - this.selectStart = MathHelper.clamp(this.selectStart, 0, i); - this.setSelectionPos(this.selectStart); + selectStart = pos; + int i = text.length(); + selectStart = MathHelper.clamp(selectStart, 0, i); + setSelectionPos(selectStart); } /** @@ -368,26 +368,26 @@ public void setCursorPosition(int pos) { */ @Override public boolean onKeyTyped(char typedChar, int keyCode) { - if (!this.isFocused) { + if (!isFocused) { return false; } else if (GuiScreen.isKeyComboCtrlA(keyCode)) { - this.setCursorPosition(text.length()); - this.setSelectionPos(0); + setCursorPosition(text.length()); + setSelectionPos(0); return true; } else if (GuiScreen.isKeyComboCtrlC(keyCode)) { - GuiScreen.setClipboardString(this.getSelectedText()); + GuiScreen.setClipboardString(getSelectedText()); return true; } else if (GuiScreen.isKeyComboCtrlV(keyCode)) { - if (this.isActive) { - this.writeText(GuiScreen.getClipboardString()); + if (isActive) { + writeText(GuiScreen.getClipboardString()); } return true; } else if (GuiScreen.isKeyComboCtrlX(keyCode)) { - GuiScreen.setClipboardString(this.getSelectedText()); + GuiScreen.setClipboardString(getSelectedText()); - if (this.isActive) { - this.writeText(""); + if (isActive) { + writeText(""); } return true; @@ -396,11 +396,11 @@ public boolean onKeyTyped(char typedChar, int keyCode) { case 14: // Backspace { if (GuiScreen.isCtrlKeyDown()) { - if (this.isActive) { - this.deleteWords(-1); + if (isActive) { + deleteWords(-1); } - } else if (this.isActive) { - this.deleteFromCursor(-1); + } else if (isActive) { + deleteFromCursor(-1); } return true; @@ -408,7 +408,7 @@ public boolean onKeyTyped(char typedChar, int keyCode) { case 28: // Enter { if (canWrap) { - this.writeText("\n"); + writeText("\n"); } return true; @@ -416,9 +416,9 @@ public boolean onKeyTyped(char typedChar, int keyCode) { case 199: // Home { if (GuiScreen.isShiftKeyDown()) { - this.setSelectionPos(0); + setSelectionPos(0); } else { - this.setCursorPosition(0); + setCursorPosition(0); } return true; @@ -427,14 +427,14 @@ public boolean onKeyTyped(char typedChar, int keyCode) { { if (GuiScreen.isShiftKeyDown()) { if (GuiScreen.isCtrlKeyDown()) { - this.setSelectionPos(this.getNthWordFromPos(-1, selectEnd)); + setSelectionPos(getNthWordFromPos(-1, selectEnd)); } else { - this.setSelectionPos(selectEnd - 1); + setSelectionPos(selectEnd - 1); } } else if (GuiScreen.isCtrlKeyDown()) { - this.setCursorPosition(this.getNthWordFromCursor(-1)); + setCursorPosition(getNthWordFromCursor(-1)); } else { - this.moveCursorBy(-1); + moveCursorBy(-1); } return true; @@ -443,14 +443,14 @@ public boolean onKeyTyped(char typedChar, int keyCode) { { if (GuiScreen.isShiftKeyDown()) { if (GuiScreen.isCtrlKeyDown()) { - this.setSelectionPos(this.getNthWordFromPos(1, selectEnd)); + setSelectionPos(getNthWordFromPos(1, selectEnd)); } else { - this.setSelectionPos(selectEnd + 1); + setSelectionPos(selectEnd + 1); } } else if (GuiScreen.isCtrlKeyDown()) { - this.setCursorPosition(this.getNthWordFromCursor(1)); + setCursorPosition(getNthWordFromCursor(1)); } else { - this.moveCursorBy(1); + moveCursorBy(1); } return true; @@ -458,9 +458,9 @@ public boolean onKeyTyped(char typedChar, int keyCode) { case 207: // End { if (GuiScreen.isShiftKeyDown()) { - this.setSelectionPos(this.text.length()); + setSelectionPos(text.length()); } else { - this.setCursorPosition(text.length()); + setCursorPosition(text.length()); } return true; @@ -478,19 +478,19 @@ public boolean onKeyTyped(char typedChar, int keyCode) { case 211: // Delete { if (GuiScreen.isCtrlKeyDown()) { - if (this.isActive) { - this.deleteWords(1); + if (isActive) { + deleteWords(1); } - } else if (this.isActive) { - this.deleteFromCursor(1); + } else if (isActive) { + deleteFromCursor(1); } return true; } default: { if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) { - if (this.isActive) { - this.writeText(Character.toString(typedChar)); + if (isActive) { + writeText(Character.toString(typedChar)); } return true; @@ -507,7 +507,7 @@ public boolean onKeyTyped(char typedChar, int keyCode) { * selection). If the anchor is set beyond the bounds of the current text, it will be put back inside. */ public void setSelectionPos(int position) { - int i = this.text.length(); + int i = text.length(); if (position > i) { position = i; @@ -518,7 +518,7 @@ public void setSelectionPos(int position) { } if (selectEnd != position) { - this.selectEnd = position; + selectEnd = position; FontRenderer font = Minecraft.getMinecraft().fontRenderer; @@ -595,18 +595,16 @@ public IGuiRect getTransform() { } @Override - public void initPanel() { - - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override @@ -624,8 +622,8 @@ public void drawPanel(int mx, int my, float partialTick) { dragging = false; } - IGuiRect bounds = this.getTransform(); - int state = !this.isActive() ? 0 : (isFocused ? 2 : 1); + IGuiRect bounds = getTransform(); + int state = !isActive() ? 0 : (isFocused ? 2 : 1); Minecraft mc = Minecraft.getMinecraft(); IGuiTexture t = texState[state]; GlStateManager.pushMatrix(); @@ -666,8 +664,8 @@ public void drawPanel(int mx, int my, float partialTick) { @Override public boolean onMouseClick(int mx, int my, int button) { if (transform.contains(mx, my)) { - if (!this.isFocused) { - this.isFocused = true; + if (!isFocused) { + isFocused = true; updateScrollBounds(); // Just in case } @@ -682,9 +680,9 @@ public boolean onMouseClick(int mx, int my, int button) { dragging = true; //return true; - } else if (this.isFocused && !lockFocus) { - this.isFocused = false; - this.text = filter.parseValue(this.text).toString(); + } else if (isFocused && !lockFocus) { + isFocused = false; + text = filter.parseValue(text).toString(); //setCursorPosition(0); } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java index 0c1c14519..23ea4fbbd 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTPrimitive.java @@ -11,16 +11,16 @@ public class CallbackNBTPrimitive implements ICallback { public CallbackNBTPrimitive(NBTTagCompound tag, String key, Class c) { this.tag = tag; - this.sKey = key; - this.iKey = -1; - this.tagID = getTagID(c); + sKey = key; + iKey = -1; + tagID = getTagID(c); } public CallbackNBTPrimitive(NBTTagList tag, int key, Class c) { this.tag = tag; - this.sKey = null; - this.iKey = key; - this.tagID = getTagID(c); + sKey = null; + iKey = key; + tagID = getTagID(c); } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java index 1293007c8..238f2a2da 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/callbacks/CallbackNBTTagString.java @@ -13,14 +13,14 @@ public class CallbackNBTTagString implements ICallback { public CallbackNBTTagString(NBTTagCompound tag, String key) { this.tag = tag; - this.sKey = key; - this.iKey = -1; + sKey = key; + iKey = -1; } public CallbackNBTTagString(NBTTagList tag, int key) { this.tag = tag; - this.sKey = null; - this.iKey = key; + sKey = null; + iKey = key; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java b/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java index f04170f20..a7fa2946c 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/io/FloatSimpleIO.java @@ -21,21 +21,21 @@ public FloatSimpleIO() { } public FloatSimpleIO(float startVal, float min, float max) { - this.v = startVal; - this.s = startVal; + v = startVal; + s = startVal; this.min = min; this.max = max; - this.t = System.currentTimeMillis(); // Added precaution for lerp math + t = System.currentTimeMillis(); // Added precaution for lerp math } public FloatSimpleIO setClamp(boolean enable) { - this.clamp = enable; + clamp = enable; return this; } public FloatSimpleIO setLerp(boolean enable, float speed) { - this.lerp = enable; - this.lerpSpd = speed; + lerp = enable; + lerpSpd = speed; return this; } @@ -60,18 +60,20 @@ public Float readValue() { @Override public void writeValue(Float value) { - if (s == v) { t = System.currentTimeMillis(); } - this.v = clamp ? MathHelper.clamp(value, min, max) : value; + if (s == v) { + t = System.currentTimeMillis(); + } + v = clamp ? MathHelper.clamp(value, min, max) : value; } @Override public Float readValueRaw() { - return this.v; + return v; } @Override public void writeValueRaw(Float value) { - this.v = clamp ? MathHelper.clamp(value, min, max) : value; - this.s = v; + v = clamp ? MathHelper.clamp(value, min, max) : value; + s = v; } } diff --git a/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java b/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java index 91d2678d8..7ad55005e 100644 --- a/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java +++ b/src/main/java/betterquesting/api2/client/gui/controls/io/ValueFuncIO.java @@ -9,7 +9,7 @@ public class ValueFuncIO implements IValueIO { private final Callable v; public ValueFuncIO(Callable value) { - this.v = value; + v = value; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java b/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java index b9a9b936b..d245f06a5 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java +++ b/src/main/java/betterquesting/api2/client/gui/events/PEventBroadcaster.java @@ -46,7 +46,9 @@ public void unregister(@Nonnull Consumer consumer) { public boolean postEvent(@Nonnull PanelEvent event) { // We cycle over all entries incase we need to fire events for parent class types for (Entry, PEventEntry> e : entryList.entrySet()) { - if (!e.getKey().isAssignableFrom(event.getClass())) { continue; } + if (!e.getKey().isAssignableFrom(event.getClass())) { + continue; + } e.getValue().fire(event); } diff --git a/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java b/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java index cdd764367..e3da1e317 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java +++ b/src/main/java/betterquesting/api2/client/gui/events/PEventEntry.java @@ -10,11 +10,13 @@ public class PEventEntry { private final Class cType; public PEventEntry(Class type) { - this.cType = type; + cType = type; } public void registerListener(@Nonnull Consumer consumer) { - if (listeners.contains(consumer)) { return; } + if (listeners.contains(consumer)) { + return; + } listeners.add(consumer); } @@ -23,7 +25,9 @@ public void unregisterListener(@Nonnull Consumer consumer) { } public void fire(@Nonnull PanelEvent event) { - if (!cType.isAssignableFrom(event.getClass())) { return; } + if (!cType.isAssignableFrom(event.getClass())) { + return; + } listeners.forEach((l) -> l.accept(event)); } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java b/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java index 263f2578a..5b556c37f 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java +++ b/src/main/java/betterquesting/api2/client/gui/events/PanelEvent.java @@ -6,14 +6,14 @@ public abstract class PanelEvent { public abstract boolean canCancel(); public boolean isCancelled() { - return this.cancelled; + return cancelled; } public void setCancelled(boolean state) { - if (!this.canCancel()) { + if (!canCancel()) { throw new IllegalStateException("Attempted to cancel a non cancellable panel event"); } - this.cancelled = state; + cancelled = state; } } diff --git a/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java b/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java index 973e07dab..14003e6de 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java +++ b/src/main/java/betterquesting/api2/client/gui/events/types/PEventButton.java @@ -12,7 +12,7 @@ public PEventButton(IPanelButton btn) { } public IPanelButton getButton() { - return this.btn; + return btn; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java b/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java index 7f08f940b..b3e3d8343 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java +++ b/src/main/java/betterquesting/api2/client/gui/events/types/PEventParty.java @@ -12,7 +12,7 @@ public class PEventParty extends PanelEvent { private final Set partyIDs; public PEventParty(int partyID) { - this.partyIDs = Collections.singleton(partyID); + partyIDs = Collections.singleton(partyID); } public PEventParty(Collection partyIDs) { @@ -20,7 +20,7 @@ public PEventParty(Collection partyIDs) { } public Set getPartyIDs() { - return this.partyIDs; + return partyIDs; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java b/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java index 8e9efd326..ddbb75908 100644 --- a/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java +++ b/src/main/java/betterquesting/api2/client/gui/events/types/PEventQuest.java @@ -12,7 +12,7 @@ public class PEventQuest extends PanelEvent { private final Set questIDs; public PEventQuest(int questID) { - this.questIDs = Collections.singleton(questID); + questIDs = Collections.singleton(questID); } public PEventQuest(Collection questIDs) { @@ -20,7 +20,7 @@ public PEventQuest(Collection questIDs) { } public Set getQuestID() { - return this.questIDs; + return questIDs; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java b/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java index 6897d79f6..6d4f8f038 100644 --- a/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java +++ b/src/main/java/betterquesting/api2/client/gui/help/HelpRegistry.java @@ -21,7 +21,9 @@ public HelpRegistry() { } public boolean registerTopic(HelpTopic topic) { - if (topicList.contains(topic)) { return false; } + if (topicList.contains(topic)) { + return false; + } return topicList.add(topic); } diff --git a/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java b/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java index b32559e6a..0ca582530 100644 --- a/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java +++ b/src/main/java/betterquesting/api2/client/gui/help/HelpTopic.java @@ -23,10 +23,12 @@ public String getDescription() { @Override public boolean equals(Object o) { - if (!(o instanceof HelpTopic)) { return false; } + if (!(o instanceof HelpTopic)) { + return false; + } HelpTopic ht = (HelpTopic) o; - return ht.title.equals(this.title) && ht.description.equals(this.description); + return ht.title.equals(title) && ht.description.equals(description); } } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java index 51434f615..6f6aada0d 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiAlign.java @@ -50,7 +50,7 @@ private static class ImmutableVec4f implements ReadableVector4f { private final ReadableVector4f v4f; public ImmutableVec4f(float x, float y, float z, float w) { - this.v4f = new Vector4f(x, y, z, w); + v4f = new Vector4f(x, y, z, w); } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java index 41975a9c2..f4f3b9726 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiPadding.java @@ -8,7 +8,7 @@ public GuiPadding() { } public GuiPadding(int left, int top, int right, int bottom) { - this.setPadding(left, top, right, bottom); + setPadding(left, top, right, bottom); } public GuiPadding copy() { @@ -16,11 +16,11 @@ public GuiPadding copy() { } public GuiPadding setPadding(int left, int top, int right, int bottom) { - this.l = left; - this.t = top; + l = left; + t = top; - this.r = right; - this.b = bottom; + r = right; + b = bottom; return this; } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java index 19c2371e4..39d249bcf 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectLerp.java @@ -13,26 +13,28 @@ public class GuiRectLerp implements IGuiRect { private final ProxyRect pxRect; public GuiRectLerp(@Nonnull IGuiRect start) { - this.startRect = start; - this.targetRect = start; - this.pxRect = new ProxyRect(start); - this.et = System.currentTimeMillis(); + startRect = start; + targetRect = start; + pxRect = new ProxyRect(start); + et = System.currentTimeMillis(); } public void lerpTo(@Nonnull IGuiRect target, long time) { - if (time <= 0) { return; } + if (time <= 0) { + return; + } - this.targetRect = target; - this.duration = time; - this.et = System.currentTimeMillis(); - this.pxRect.changeReference(target); + targetRect = target; + duration = time; + et = System.currentTimeMillis(); + pxRect.changeReference(target); } public void snapTo(@Nonnull IGuiRect target) { - this.startRect = target; - this.targetRect = target; - this.et = System.currentTimeMillis(); - this.pxRect.changeReference(target); + startRect = target; + targetRect = target; + et = System.currentTimeMillis(); + pxRect.changeReference(target); } // Allows other transforms to snap to new destinations even if the targetRect variable changes instance @@ -41,9 +43,11 @@ public IGuiRect getProxyRect() { } public boolean isIdle() { - if (startRect == targetRect) { return true; } + if (startRect == targetRect) { + return true; + } if (System.currentTimeMillis() - et >= duration) { - this.startRect = this.targetRect; + startRect = targetRect; return true; } return false; diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java index 6cd26cb18..a3ecfde3a 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiRectangle.java @@ -54,20 +54,20 @@ public int getDepth() { @Override public IGuiRect getParent() { - return this.parent; + return parent; } @Override public void setParent(IGuiRect rect) { - this.parent = rect; + parent = rect; } @Override public boolean contains(int x, int y) { - int x1 = this.getX(); - int x2 = x1 + this.getWidth(); - int y1 = this.getY(); - int y2 = y1 + this.getHeight(); + int x1 = getX(); + int x2 = x1 + getWidth(); + int y1 = getY(); + int y2 = y1 + getHeight(); return x >= x1 && x < x2 && y >= y1 && y < y2; } diff --git a/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java b/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java index a811bd0fe..972e1cbd2 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/GuiTransform.java @@ -29,7 +29,7 @@ public GuiTransform(ReadableVector4f anchor, GuiPadding padding, int depth) { public GuiTransform(Vector4f anchor, GuiPadding padding, int depth) { this.anchor = anchor; this.padding = padding; - this.drawOrder = depth; + drawOrder = depth; float l = Math.min(anchor.x, anchor.z); float r = Math.max(anchor.x, anchor.z); @@ -44,49 +44,49 @@ public GuiTransform(Vector4f anchor, GuiPadding padding, int depth) { public GuiTransform copy() { GuiTransform trans = new GuiTransform(new Vector4f(anchor), padding.copy(), drawOrder); - trans.setParent(this.parent); + trans.setParent(parent); return trans; } public GuiPadding getPadding() { - return this.padding; + return padding; } public Vector4f getAnchor() { - return this.anchor; + return anchor; } public void setDrawDepth(int order) { - this.drawOrder = order; + drawOrder = order; } @Override public int getX() { - int i = parent == null ? 0 : (parent.getX() + (int) Math.ceil(parent.getWidth() * this.anchor.x)); + int i = parent == null ? 0 : (parent.getX() + (int) Math.ceil(parent.getWidth() * anchor.x)); return i + padding.getLeft(); } @Override public int getY() { - int i = parent == null ? 0 : (parent.getY() + (int) Math.ceil(parent.getHeight() * this.anchor.y)); + int i = parent == null ? 0 : (parent.getY() + (int) Math.ceil(parent.getHeight() * anchor.y)); return i + padding.getTop(); } @Override public int getWidth() { - int i = parent == null ? 0 : (int) Math.ceil(parent.getWidth() * (this.anchor.z - this.anchor.x)); + int i = parent == null ? 0 : (int) Math.ceil(parent.getWidth() * (anchor.z - anchor.x)); return i - (padding.getRight() + padding.getLeft()); } @Override public int getHeight() { - int i = parent == null ? 0 : (int) Math.ceil(parent.getHeight() * (this.anchor.w - this.anchor.y)); + int i = parent == null ? 0 : (int) Math.ceil(parent.getHeight() * (anchor.w - anchor.y)); return i - (padding.getBottom() + padding.getTop()); } @Override public int getDepth() { - return this.drawOrder; + return drawOrder; } @Override @@ -96,7 +96,7 @@ public IGuiRect getParent() { @Override public void setParent(IGuiRect rect) { - this.parent = rect; + parent = rect; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java b/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java index 94c3055d8..201fa2da8 100644 --- a/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java +++ b/src/main/java/betterquesting/api2/client/gui/misc/ProxyRect.java @@ -7,11 +7,11 @@ public class ProxyRect implements IGuiRect { private IGuiRect ref; public ProxyRect(IGuiRect refRect) { - this.ref = refRect; + ref = refRect; } public void changeReference(IGuiRect refRect) { - this.ref = refRect; + ref = refRect; } @Override @@ -46,7 +46,9 @@ public IGuiRect getParent() { @Override public void setParent(IGuiRect rect) { - if (ref != null) { ref.setParent(rect); } + if (ref != null) { + ref.setParent(rect); + } } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java b/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java index 804aebd5e..04ee93b81 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/CanvasEmpty.java @@ -14,7 +14,7 @@ public class CanvasEmpty implements IGuiCanvas { private boolean enabled = true; public CanvasEmpty(IGuiRect rect) { - this.transform = rect; + transform = rect; } @Override @@ -25,22 +25,22 @@ public IGuiRect getTransform() { @Nonnull @Override public List getChildren() { - return this.guiPanels; + return guiPanels; } @Override public void initPanel() { - this.guiPanels.clear(); + guiPanels.clear(); } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java b/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java index b4e2ce8d3..de2712aa3 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/CanvasResizeable.java @@ -27,13 +27,13 @@ public CanvasResizeable(IGuiRect rect, IGuiTexture texture) { } public CanvasResizeable(IGuiRect rect, IGuiTexture texture, boolean crop) { - this.bgTexture = texture; - this.rectLerp = new GuiRectLerp(rect); + bgTexture = texture; + rectLerp = new GuiRectLerp(rect); this.crop = crop; } public void changeBG(@Nullable IGuiTexture texture) { - this.bgTexture = texture; + bgTexture = texture; } @Override @@ -42,43 +42,49 @@ public IGuiRect getTransform() { } public GuiRectLerp getRectLerp() { - return this.rectLerp; + return rectLerp; } @Nonnull @Override public List getChildren() { - return this.guiPanels; + return guiPanels; } @Override public void initPanel() { - this.guiPanels.clear(); + guiPanels.clear(); } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } public void lerpToRect(@Nonnull IGuiRect rect, long time, boolean inheritParent) { - if (inheritParent) { rect.setParent(rectLerp.getParent()); } + if (inheritParent) { + rect.setParent(rectLerp.getParent()); + } rectLerp.lerpTo(rect, time); } public void snapToRect(@Nonnull IGuiRect rect, boolean inheritParent) { - if (inheritParent) { rect.setParent(rectLerp.getParent()); } + if (inheritParent) { + rect.setParent(rectLerp.getParent()); + } rectLerp.snapTo(rect); } @Override public void drawPanel(int mx, int my, float partialTick) { - if (crop) { RenderUtils.startScissor(rectLerp); } + if (crop) { + RenderUtils.startScissor(rectLerp); + } if (bgTexture != null) { IGuiRect bounds = rectLerp; @@ -89,10 +95,14 @@ public void drawPanel(int mx, int my, float partialTick) { } for (IGuiPanel entry : guiPanels) { - if (entry.isEnabled()) { entry.drawPanel(mx, my, partialTick); } + if (entry.isEnabled()) { + entry.drawPanel(mx, my, partialTick); + } } - if (crop) { RenderUtils.endScissor(); } + if (crop) { + RenderUtils.endScissor(); + } } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java b/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java index e9ff388c6..9a102fff6 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/CanvasTextured.java @@ -12,17 +12,17 @@ public class CanvasTextured extends CanvasEmpty { public CanvasTextured(IGuiRect rect, IGuiTexture texture) { super(rect); - this.bgTexture = texture; + bgTexture = texture; } public void changeBG(@Nullable IGuiTexture texture) { - this.bgTexture = texture; + bgTexture = texture; } @Override public void drawPanel(int mx, int my, float partialTick) { if (bgTexture != null) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); GlStateManager.pushMatrix(); GlStateManager.color(1F, 1F, 1F, 1F); bgTexture.drawTexture(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(), 0F, partialTick); diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java index 4b27affde..aefb68c70 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHBarFill.java @@ -24,21 +24,21 @@ public class PanelHBarFill implements IBarFill { private IGuiColor color = new GuiColorStatic(0xFFFFFFFF); public PanelHBarFill(IGuiRect rect) { - this.texBack = PresetTexture.METER_H_0.getTexture(); - this.texFill = PresetTexture.METER_H_1.getTexture(); + texBack = PresetTexture.METER_H_0.getTexture(); + texFill = PresetTexture.METER_H_1.getTexture(); - this.transform = rect; + transform = rect; } @Override public PanelHBarFill setFillDriver(IValueIO driver) { - this.fillDriver = driver; + fillDriver = driver; return this; } @Override public PanelHBarFill setFlipped(boolean flipped) { - this.flipBar = flipped; + flipBar = flipped; return this; } @@ -50,23 +50,22 @@ public PanelHBarFill setFillColor(IGuiColor color) { @Override public PanelHBarFill setBarTexture(IGuiTexture back, IGuiTexture front) { - this.texBack = back; - this.texFill = front; + texBack = back; + texFill = front; return this; } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override @@ -76,7 +75,7 @@ public IGuiRect getTransform() { @Override public void drawPanel(int mx, int my, float partialTick) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); GlStateManager.pushMatrix(); GlStateManager.color(1F, 1F, 1F, 1F); @@ -87,7 +86,7 @@ public void drawPanel(int mx, int my, float partialTick) { float f = MathHelper.clamp(fillDriver.readValue(), 0F, 1F); - if (this.flipBar) { + if (flipBar) { RenderUtils.startScissor( new GuiRectangle(bounds.getX() + (int) (bounds.getWidth() - (bounds.getWidth() * f)), bounds.getY(), (int) (bounds.getWidth() * f), bounds.getHeight(), 0)); diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java index 4bdaa2036..03fbe620d 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelHScrollBar.java @@ -24,14 +24,14 @@ public class PanelHScrollBar implements IScrollBar { private boolean isDragging = false; public PanelHScrollBar(IGuiRect rect) { - this.transform = rect; - this.setBarTexture(PresetTexture.SCROLL_H_BG.getTexture(), PresetTexture.SCROLL_H_0.getTexture(), - PresetTexture.SCROLL_H_1.getTexture(), PresetTexture.SCROLL_H_2.getTexture()); + transform = rect; + setBarTexture(PresetTexture.SCROLL_H_BG.getTexture(), PresetTexture.SCROLL_H_0.getTexture(), + PresetTexture.SCROLL_H_1.getTexture(), PresetTexture.SCROLL_H_2.getTexture()); } @Override public PanelHScrollBar setHandleSize(int size, int inset) { - this.hSize = size; + hSize = size; this.inset = inset; return this; } @@ -39,41 +39,40 @@ public PanelHScrollBar setHandleSize(int size, int inset) { @Override public PanelHScrollBar setBarTexture(IGuiTexture back, IGuiTexture handleDisabled, IGuiTexture handleIdle, IGuiTexture handleHover) { - this.texBack = back; - this.texHandleState[0] = handleDisabled; - this.texHandleState[1] = handleIdle; - this.texHandleState[2] = handleHover; + texBack = back; + texHandleState[0] = handleDisabled; + texHandleState[1] = handleIdle; + texHandleState[2] = handleHover; return this; } @Override public PanelHScrollBar setScrollSpeed(float f) { - this.speed = f; + speed = f; return this; } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override public void setActive(boolean state) { - this.active = state; + active = state; } @Override public boolean isActive() { - return this.active; + return active; } @Override @@ -83,13 +82,13 @@ public IGuiRect getTransform() { @Override public void drawPanel(int mx, int my, float partialTick) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); if (active && isDragging && (Mouse.isButtonDown(0) || Mouse.isButtonDown(2))) { float cx = (float) (mx - (bounds.getX() + hSize / 2)) / (float) (bounds.getWidth() - hSize); - this.writeValue(cx); + writeValue(cx); } else if (isDragging) { - this.isDragging = false; + isDragging = false; } GlStateManager.pushMatrix(); @@ -113,7 +112,7 @@ public void drawPanel(int mx, int my, float partialTick) { @Override public boolean onMouseClick(int mx, int my, int click) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); if (!active || !bounds.contains(mx, my)) { return false; @@ -134,7 +133,7 @@ public boolean onMouseRelease(int mx, int my, int click) { @Override public boolean onMouseScroll(int mx, int my, int sdx) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); if (!active || sdx == 0 || !bounds.contains(mx, my)) { return false; } @@ -144,7 +143,7 @@ public boolean onMouseScroll(int mx, int my, int sdx) { if ((dx < 0 && scroll <= 0F) || (dx > 0 && scroll >= 1)) { return false; } else { - this.writeValue(dx + scroll); + writeValue(dx + scroll); return true; } } @@ -161,12 +160,12 @@ public List getTooltip(int mx, int my) { @Override public Float readValue() { - return this.scroll; + return scroll; } @Override public void writeValue(Float value) { - this.scroll = MathHelper.clamp(value, 0F, 1F); + scroll = MathHelper.clamp(value, 0F, 1F); } @Override @@ -176,6 +175,6 @@ public Float readValueRaw() { @Override public void writeValueRaw(Float value) { - this.scroll = value; + scroll = value; } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java index 15c5b1952..dedbfaf3f 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVBarFill.java @@ -23,21 +23,21 @@ public class PanelVBarFill implements IBarFill { private IGuiColor color; public PanelVBarFill(IGuiRect rect) { - this.texBack = PresetTexture.METER_V_0.getTexture(); - this.texFill = PresetTexture.METER_V_1.getTexture(); + texBack = PresetTexture.METER_V_0.getTexture(); + texFill = PresetTexture.METER_V_1.getTexture(); - this.transform = rect; + transform = rect; } @Override public PanelVBarFill setFillDriver(IValueIO driver) { - this.fillDriver = driver; + fillDriver = driver; return this; } @Override public PanelVBarFill setFlipped(boolean flipped) { - this.flipBar = flipped; + flipBar = flipped; return this; } @@ -49,23 +49,22 @@ public PanelVBarFill setFillColor(IGuiColor color) { @Override public PanelVBarFill setBarTexture(IGuiTexture back, IGuiTexture front) { - this.texBack = back; - this.texFill = front; + texBack = back; + texFill = front; return this; } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override @@ -75,7 +74,7 @@ public IGuiRect getTransform() { @Override public void drawPanel(int mx, int my, float partialTick) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); GlStateManager.pushMatrix(); GlStateManager.color(1F, 1F, 1F, 1F); @@ -86,7 +85,7 @@ public void drawPanel(int mx, int my, float partialTick) { float f = MathHelper.clamp(fillDriver.readValue(), 0F, 1F); - if (this.flipBar) { + if (flipBar) { RenderUtils.startScissor( new GuiRectangle(bounds.getX(), bounds.getY(), bounds.getWidth(), (int) (bounds.getHeight() * f), 0)); } else { diff --git a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java index f7b2c6b6b..9ee0145be 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/bars/PanelVScrollBar.java @@ -24,14 +24,14 @@ public class PanelVScrollBar implements IScrollBar { private boolean isDragging = false; public PanelVScrollBar(IGuiRect rect) { - this.transform = rect; - this.setBarTexture(PresetTexture.SCROLL_V_BG.getTexture(), PresetTexture.SCROLL_V_0.getTexture(), - PresetTexture.SCROLL_V_1.getTexture(), PresetTexture.SCROLL_V_2.getTexture()); + transform = rect; + setBarTexture(PresetTexture.SCROLL_V_BG.getTexture(), PresetTexture.SCROLL_V_0.getTexture(), + PresetTexture.SCROLL_V_1.getTexture(), PresetTexture.SCROLL_V_2.getTexture()); } @Override public PanelVScrollBar setHandleSize(int size, int inset) { - this.hSize = size; + hSize = size; this.inset = inset; return this; } @@ -39,40 +39,39 @@ public PanelVScrollBar setHandleSize(int size, int inset) { @Override public PanelVScrollBar setBarTexture(IGuiTexture back, IGuiTexture handleDisabled, IGuiTexture handleIdle, IGuiTexture handleHover) { - this.texBack = back; - this.texHandleState[0] = handleDisabled; - this.texHandleState[1] = handleIdle; - this.texHandleState[2] = handleHover; + texBack = back; + texHandleState[0] = handleDisabled; + texHandleState[1] = handleIdle; + texHandleState[2] = handleHover; return this; } public PanelVScrollBar setScrollSpeed(float f) { - this.speed = f; + speed = f; return this; } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override public void setActive(boolean state) { - this.active = state; + active = state; } @Override public boolean isActive() { - return this.active; + return active; } @Override @@ -82,13 +81,13 @@ public IGuiRect getTransform() { @Override public void drawPanel(int mx, int my, float partialTick) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); if (active && isDragging && (Mouse.isButtonDown(0) || Mouse.isButtonDown(2))) { float cy = (float) (my - (bounds.getY() + hSize / 2)) / (float) (bounds.getHeight() - hSize); - this.writeValue(cy); + writeValue(cy); } else if (isDragging) { - this.isDragging = false; + isDragging = false; } GlStateManager.pushMatrix(); @@ -112,7 +111,7 @@ public void drawPanel(int mx, int my, float partialTick) { @Override public boolean onMouseClick(int mx, int my, int click) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); if (!active || !bounds.contains(mx, my)) { return false; } @@ -132,7 +131,7 @@ public boolean onMouseRelease(int mx, int my, int click) { @Override public boolean onMouseScroll(int mx, int my, int sdx) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); if (!active || sdx == 0 || !bounds.contains(mx, my)) { return false; } @@ -142,7 +141,7 @@ public boolean onMouseScroll(int mx, int my, int sdx) { if ((dy < 0F && scroll <= 0F) || (dy > 0F && scroll >= 1F)) { return false; } else { - this.writeValue(dy + scroll); + writeValue(dy + scroll); return true; } } @@ -159,12 +158,12 @@ public List getTooltip(int mx, int my) { @Override public Float readValue() { - return this.scroll; + return scroll; } @Override public void writeValue(Float value) { - this.scroll = MathHelper.clamp(value, 0F, 1F); + scroll = MathHelper.clamp(value, 0F, 1F); } @Override @@ -174,6 +173,6 @@ public Float readValueRaw() { @Override public void writeValueRaw(Float value) { - this.scroll = value; + scroll = value; } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java index 6fa604582..f932d244a 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelEntityPreview.java @@ -26,32 +26,32 @@ public class PanelEntityPreview implements IGuiPanel { private float zDepth = 100F; public PanelEntityPreview(IGuiRect rect, Entity entity) { - this.transform = rect; + transform = rect; this.entity = entity; - this.basePitch = new ValueFuncIO<>(() -> 15F); - this.pitchDriver = basePitch; + basePitch = new ValueFuncIO<>(() -> 15F); + pitchDriver = basePitch; - this.baseYaw = new ValueFuncIO<>(() -> -30F); - this.yawDriver = baseYaw; + baseYaw = new ValueFuncIO<>(() -> -30F); + yawDriver = baseYaw; } public PanelEntityPreview setRotationFixed(float pitch, float yaw) { - this.pitchDriver = basePitch; - this.yawDriver = baseYaw; + pitchDriver = basePitch; + yawDriver = baseYaw; basePitch.writeValue(pitch); baseYaw.writeValue(yaw); return this; } public PanelEntityPreview setRotationDriven(IValueIO pitch, IValueIO yaw) { - this.pitchDriver = pitch == null ? basePitch : pitch; - this.yawDriver = yaw == null ? baseYaw : yaw; + pitchDriver = pitch == null ? basePitch : pitch; + yawDriver = yaw == null ? baseYaw : yaw; return this; } public PanelEntityPreview setDepth(float z) { - this.zDepth = z; + zDepth = z; return this; } @@ -60,17 +60,16 @@ public void setEntity(Entity entity) { } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override @@ -84,7 +83,7 @@ public void drawPanel(int mx, int my, float partialTick) { return; } - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); GlStateManager.pushMatrix(); RenderUtils.startScissor(new GuiRectangle(bounds)); diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java index ca375ff70..3731787f9 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelFluidSlot.java @@ -25,11 +25,11 @@ public PanelFluidSlot(IGuiRect rect, int id, FluidStack value, boolean showCount super(rect, id, "", value); this.showCount = showCount; - this.setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), - new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), - new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), - new GuiPadding(1, 1, 1, 1)))); - this.setStoredValue(value); // Need to run this again because of the instatiation order of showCount + setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), + new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), + new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), + new GuiPadding(1, 1, 1, 1)))); + setStoredValue(value); // Need to run this again because of the instatiation order of showCount } @@ -38,14 +38,14 @@ public PanelFluidSlot setStoredValue(FluidStack value) { super.setStoredValue(value); if (value != null) { - this.setIcon(new FluidTexture(value, showCount, true), 1); + setIcon(new FluidTexture(value, showCount, true), 1); List tooltip = new ArrayList<>(); tooltip.add(value.getLocalizedName()); tooltip.add(TextFormatting.GRAY.toString() + value.amount + "mB"); - this.setTooltip(tooltip); + setTooltip(tooltip); } else { - this.setIcon(null); - this.setTooltip(null); + setIcon(null); + setTooltip(null); } return this; diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java index d50b33ad7..16010f869 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelGeneric.java @@ -25,7 +25,7 @@ public PanelGeneric(IGuiRect rect, IGuiTexture texture) { } public PanelGeneric(IGuiRect rect, IGuiTexture texture, IGuiColor color) { - this.transform = rect; + transform = rect; this.texture = texture; this.color = color; } @@ -45,17 +45,16 @@ public IGuiRect getTransform() { } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java index 9527d4ef5..e8a93683b 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java @@ -39,11 +39,11 @@ public PanelItemSlot(IGuiRect rect, int id, BigItemStack value, boolean showCoun this.showCount = showCount; this.oreDict = oreDict; - this.setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), - new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), - new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), - new GuiPadding(1, 1, 1, 1)))); - this.setStoredValue(value); // Need to run this again because of the instatiation order of showCount + setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), + new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), + new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), + new GuiPadding(1, 1, 1, 1)))); + setStoredValue(value); // Need to run this again because of the instatiation order of showCount } @Override @@ -52,7 +52,7 @@ public PanelItemSlot setStoredValue(BigItemStack value) { if (value != null) { Minecraft mc = Minecraft.getMinecraft(); - this.setIcon( + setIcon( oreDict || value.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE ? new OreDictTexture(1F, value, showCount, @@ -60,12 +60,12 @@ public PanelItemSlot setStoredValue(BigItemStack value) { : new ItemTexture(value, showCount, true), 1); - this.setTooltip(value.getBaseStack().getTooltip(mc.player, - mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED - : TooltipFlags.NORMAL)); + setTooltip(value.getBaseStack().getTooltip(mc.player, + mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED + : TooltipFlags.NORMAL)); } else { - this.setIcon(null); - this.setTooltip(null); + setIcon(null); + setTooltip(null); } updateOreStacks(); @@ -99,7 +99,9 @@ private void updateOreStacks() { oreVariants.clear(); BigItemStack stack = getStoredValue(); - if (stack == null) { return; } + if (stack == null) { + return; + } if (!stack.hasOreDict()) { if (stack.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE) { diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java index a0edf1bd6..4795a7bd8 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelLine.java @@ -28,8 +28,8 @@ public PanelLine(IGuiRect start, IGuiRect end, IGuiLine line, int width, IGuiCol this.line = line; this.width = width; this.color = color; - this.bounds = new GuiRectangle(0, 0, 0, 0, drawOrder); - this.bounds.setParent(start); + bounds = new GuiRectangle(0, 0, 0, 0, drawOrder); + bounds.setParent(start); } @Override @@ -38,17 +38,16 @@ public IGuiRect getTransform() { } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java index f3d6755bf..6ca6b43c9 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelPlayerPortrait.java @@ -34,7 +34,7 @@ public PanelPlayerPortrait(IGuiRect rect, UUID playerID, String username) { } public PanelPlayerPortrait(IGuiRect rect, AbstractClientPlayer player) { - this.transform = rect; + transform = rect; this.player = new EntityPlayerPreview(player.world, player.getGameProfile()); this.player.limbSwing = 0F; this.player.limbSwingAmount = 0F; @@ -44,44 +44,43 @@ public PanelPlayerPortrait(IGuiRect rect, AbstractClientPlayer player) { Minecraft.getMinecraft().getTextureManager().getTexture(resource); - this.basePitch = new ValueFuncIO<>(() -> 15F); - this.pitchDriver = basePitch; + basePitch = new ValueFuncIO<>(() -> 15F); + pitchDriver = basePitch; - this.baseYaw = new ValueFuncIO<>(() -> -30F); - this.yawDriver = baseYaw; + baseYaw = new ValueFuncIO<>(() -> -30F); + yawDriver = baseYaw; } public PanelPlayerPortrait setRotationFixed(float pitch, float yaw) { - this.pitchDriver = basePitch; - this.yawDriver = baseYaw; + pitchDriver = basePitch; + yawDriver = baseYaw; basePitch.writeValue(pitch); baseYaw.writeValue(yaw); return this; } public PanelPlayerPortrait setRotationDriven(IValueIO pitch, IValueIO yaw) { - this.pitchDriver = pitch == null ? basePitch : pitch; - this.yawDriver = yaw == null ? baseYaw : yaw; + pitchDriver = pitch == null ? basePitch : pitch; + yawDriver = yaw == null ? baseYaw : yaw; return this; } public PanelPlayerPortrait setDepth(float z) { - this.zDepth = z; + zDepth = z; return this; } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override @@ -91,7 +90,7 @@ public IGuiRect getTransform() { @Override public void drawPanel(int mx, int my, float partialTick) { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); GlStateManager.pushMatrix(); RenderUtils.startScissor(new GuiRectangle(bounds)); diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java index 7e8c6af2d..e09be6c06 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelTextBox.java @@ -35,8 +35,8 @@ public PanelTextBox(IGuiRect rect, String text) { } public PanelTextBox(IGuiRect rect, String text, boolean autoFit) { - this.transform = new GuiRectText(rect, autoFit); - this.setText(text); + transform = new GuiRectText(rect, autoFit); + setText(text); this.autoFit = autoFit; } @@ -59,17 +59,17 @@ public PanelTextBox setAlignment(int align) { } public PanelTextBox setFontSize(int size) { - this.fontScale = size; + fontScale = size; return this; } public PanelTextBox enableShadow(boolean enable) { - this.shadow = enable; + shadow = enable; return this; } private void refreshText() { - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); FontRenderer fr = Minecraft.getMinecraft().fontRenderer; float scale = fontScale / relScale; @@ -82,7 +82,7 @@ private void refreshText() { List sl = w > 8 ? fr.listFormattedStringToWidth(text, w) : Collections.emptyList(); lines = sl.size() - 1; - this.transform.h = (int) Math.floor(fr.FONT_HEIGHT * sl.size() * scale); + transform.h = (int) Math.floor(fr.FONT_HEIGHT * sl.size() * scale); refRect.x = bounds.getX(); refRect.y = bounds.getY(); @@ -102,12 +102,12 @@ public void initPanel() { @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override @@ -115,9 +115,11 @@ public void drawPanel(int mx, int my, float partialTick) { if (!isRectEqual(refRect, getTransform())) { refreshText(); // Makes this panel work with resizable canvases without having to update every frame } - if (lines < 0) { return; } + if (lines < 0) { + return; + } - IGuiRect bounds = this.getTransform(); + IGuiRect bounds = getTransform(); FontRenderer fr = Minecraft.getMinecraft().fontRenderer; //FontRenderer fr = BqFontRenderer.FONT_UNICODE; //FontRenderer fr = BqFontRenderer.FONT_STANDARD; @@ -126,12 +128,18 @@ public void drawPanel(int mx, int my, float partialTick) { int bw = (int) Math.ceil(bounds.getWidth() / s); double w = Math.min(bw, RenderUtils.getStringWidth(text, fr) * s); - if (bw <= 0) { return; } + if (bw <= 0) { + return; + } GlStateManager.pushMatrix(); GlStateManager.translate(bounds.getX(), bounds.getY(), 1); - if (align == 1) { GlStateManager.translate(bounds.getWidth() / 2D - w / 2D, 0D, 0D); } - if (align == 2) { GlStateManager.translate(bounds.getWidth() - w, 0D, 0D); } + if (align == 1) { + GlStateManager.translate(bounds.getWidth() / 2D - w / 2D, 0D, 0D); + } + if (align == 2) { + GlStateManager.translate(bounds.getWidth() - w, 0D, 0D); + } GlStateManager.scale(s, s, 1D); if (align == 2) { @@ -217,10 +225,10 @@ public void setParent(IGuiRect rect) { @Override public boolean contains(int x, int y) { - int x1 = this.getX(); - int x2 = x1 + this.getWidth(); - int y1 = this.getY(); - int y2 = y1 + this.getHeight(); + int x1 = getX(); + int x2 = x1 + getWidth(); + int y1 = getY(); + int y2 = y1 + getHeight(); return x >= x1 && x < x2 && y >= y1 && y < y2; } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java index b1055d575..c75974867 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasCullingManager.java @@ -144,10 +144,10 @@ private static class RegionInfo { private boolean enabled = false; // Starts disabled so that the cache can be populated on initial checks private final GuiRectangle rect; - // Needs to be updated with the min-max bounds (doesn't actually conform to any grid) + // Needs to be updated with the min-max bounds (doesn't actually conform to any grid) private RegionInfo(int blockX, int blockY, int gridSize) { - this.rect = new GuiRectangle(blockX * gridSize, blockY * gridSize, gridSize, gridSize); + rect = new GuiRectangle(blockX * gridSize, blockY * gridSize, gridSize, gridSize); } private void refreshBounds() { diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java index bf2a005f8..deaa4a114 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasEntityDatabase.java @@ -16,7 +16,7 @@ public class CanvasEntityDatabase extends CanvasSearch public CanvasEntityDatabase(IGuiRect rect, int buttonId) { super(rect); - this.btnId = buttonId; + btnId = buttonId; } @Override @@ -28,7 +28,9 @@ protected Iterator getIterator() { @Override protected void queryMatches(EntityEntry ee, String query, final ArrayDeque results) { - if (ee == null || ee.getRegistryName() == null) { return; } + if (ee == null || ee.getRegistryName() == null) { + return; + } String qlc = query.toLowerCase(); @@ -43,7 +45,7 @@ protected boolean addResult(EntityEntry ee, int index, int cachedWidth) { return false; } - this.addPanel( + addPanel( new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), btnId, ee.getName(), ee)); return true; diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java index 6d689451c..b8aea0ed3 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFileDirectory.java @@ -15,15 +15,17 @@ public abstract class CanvasFileDirectory extends CanvasSearch { public CanvasFileDirectory(IGuiRect rect, File dirStart, FileFilter filter) { super(rect); this.filter = filter; - this.curDir = dirStart; + curDir = dirStart; - if (curDir != null && !curDir.isDirectory()) { curDir = curDir.getParentFile(); } + if (curDir != null && !curDir.isDirectory()) { + curDir = curDir.getParentFile(); + } } public void setCurDirectory(File file) { curDir = file; - this.refreshSearch(); - this.scrollY.writeValue(0F); + refreshSearch(); + scrollY.writeValue(0F); } @Override @@ -34,7 +36,9 @@ protected Iterator getIterator() { } else { files = !curDir.isDirectory() ? new File[0] : curDir.listFiles(filter); } - if (files == null) { files = new File[0]; } + if (files == null) { + files = new File[0]; + } List fList = Arrays.asList(files); fList.sort(sorter); return fList.iterator(); @@ -42,7 +46,9 @@ protected Iterator getIterator() { @Override protected void queryMatches(File value, String query, ArrayDeque results) { - if (value.getName().toLowerCase().contains(query.toLowerCase())) { results.add(value); } + if (value.getName().toLowerCase().contains(query.toLowerCase())) { + results.add(value); + } } private static class FileSort implements Comparator { diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java index af3b8ebab..0dfb7ab92 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasFluidDatabase.java @@ -17,7 +17,7 @@ public class CanvasFluidDatabase extends CanvasSearch { public CanvasFluidDatabase(IGuiRect rect, int buttonId) { super(rect); - this.btnId = buttonId; + btnId = buttonId; } @Override @@ -54,7 +54,7 @@ protected boolean addResult(FluidStack stack, int index, int cachedWidth) { int x = (index % (cachedWidth / 18)) * 18; int y = (index / (cachedWidth / 18)) * 18; - this.addPanel(new PanelFluidSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, stack)); + addPanel(new PanelFluidSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, stack)); return true; } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java index c0845ec87..e8fea30bd 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasHoverTray.java @@ -28,7 +28,7 @@ public CanvasHoverTray(IGuiRect rectClosed, IGuiRect rectOpen, IGuiTexture textu this.rectOpen = rectOpen; GuiTransform trans = new GuiTransform(GuiAlign.FULL_BOX); - trans.setParent(this.getRectLerp()); + trans.setParent(getRectLerp()); cvOpen = new CanvasEmpty(trans); cvClosed = new CanvasEmpty(trans); } @@ -46,31 +46,35 @@ public boolean isTrayOpen() { } public CanvasHoverTray setManualOpen(boolean state) { - this.manualOpen = state; + manualOpen = state; return this; } public CanvasHoverTray setCloseAction(Runnable action) { - this.actionClose = action; + actionClose = action; return this; } public CanvasHoverTray setOpenAction(Runnable action) { - this.actionOpen = action; + actionOpen = action; return this; } public void setTrayState(boolean open, long time) { if (!open && isTrayOpen()) { - this.lerpToRect(rectClosed, time, true); + lerpToRect(rectClosed, time, true); cvOpen.setEnabled(false); cvClosed.setEnabled(true); - if (actionClose != null) { actionClose.run(); } + if (actionClose != null) { + actionClose.run(); + } } else if (open && !isTrayOpen()) { - this.lerpToRect(rectOpen, time, true); + lerpToRect(rectOpen, time, true); cvOpen.setEnabled(true); cvClosed.setEnabled(false); - if (actionOpen != null) { actionOpen.run(); } + if (actionOpen != null) { + actionOpen.run(); + } } } @@ -94,8 +98,8 @@ public void resetCanvas() { cvOpen.resetCanvas(); cvClosed.resetCanvas(); - this.addPanel(cvOpen); - this.addPanel(cvClosed); + addPanel(cvOpen); + addPanel(cvClosed); cvOpen.setEnabled(false); cvClosed.setEnabled(true); } @@ -104,8 +108,8 @@ public void resetCanvas() { public void initPanel() { super.initPanel(); - this.addPanel(cvOpen); - this.addPanel(cvClosed); + addPanel(cvOpen); + addPanel(cvClosed); cvOpen.setEnabled(false); cvClosed.setEnabled(true); diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java index 90ba02518..b8d031a9d 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasItemDatabase.java @@ -23,7 +23,7 @@ public class CanvasItemDatabase extends CanvasSearch { public CanvasItemDatabase(IGuiRect rect, int buttonId) { super(rect); - this.btnId = buttonId; + btnId = buttonId; } @Override @@ -86,12 +86,14 @@ protected void queryMatches(Item item, String query, final ArrayDeque @Override public boolean addResult(ItemStack stack, int index, int cachedWidth) { - if (stack == null) { return false; } + if (stack == null) { + return false; + } int x = (index % (cachedWidth / 18)) * 18; int y = (index / (cachedWidth / 18)) * 18; - this.addPanel(new PanelItemSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, new BigItemStack(stack))); + addPanel(new PanelItemSlot(new GuiRectangle(x, y, 18, 18, 0), btnId, new BigItemStack(stack))); return true; } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java index d2a0efc1f..244442f71 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasQuestLine.java @@ -38,13 +38,13 @@ public class CanvasQuestLine extends CanvasScrolling { public CanvasQuestLine(IGuiRect rect, int buttonId) { super(rect); - this.setupAdvanceScroll(true, true, 24); - this.enableBlocking(false); + setupAdvanceScroll(true, true, 24); + enableBlocking(false); this.buttonId = buttonId; } public Collection getQuestButtons() { - return Collections.unmodifiableCollection(this.btnList); + return Collections.unmodifiableCollection(btnList); } public PanelButtonQuest getButtonAt(int mx, int my) { @@ -55,7 +55,9 @@ public PanelButtonQuest getButtonAt(int mx, int my) { int smy = (int) ((my - ty) / zs) + lsy; for (PanelButtonQuest btn : btnList) { - if (btn.rect.contains(smx, smy)) { return btn; } + if (btn.rect.contains(smx, smy)) { + return btn; + } } return null; @@ -76,11 +78,13 @@ public void refreshQuestLine() { */ public void setQuestLine(IQuestLine line) { // Rest contents - this.resetCanvas(); - this.btnList.clear(); + resetCanvas(); + btnList.clear(); lastQL = line; - if (line == null) { return; } + if (line == null) { + return; + } EntityPlayer player = Minecraft.getMinecraft().player; UUID pid = QuestingAPI.getQuestingUUID(player); @@ -89,9 +93,9 @@ public void setQuestLine(IQuestLine line) { if (!StringUtils.isNullOrEmpty(bgString)) { int bgSize = line.getProperty(NativeProps.BG_SIZE); - this.addPanel(new PanelGeneric(new GuiRectangle(0, 0, bgSize, bgSize, 1), - new SimpleTexture(new ResourceLocation(bgString), - new GuiRectangle(0, 0, 256, 256)))); + addPanel(new PanelGeneric(new GuiRectangle(0, 0, bgSize, bgSize, 1), + new SimpleTexture(new ResourceLocation(bgString), + new GuiRectangle(0, 0, 256, 256)))); } HashMap questBtns = new HashMap<>(); @@ -99,15 +103,17 @@ public void setQuestLine(IQuestLine line) { for (DBEntry qle : line.getEntries()) { IQuest quest = QuestingAPI.getAPI(ApiReference.QUEST_DB).getValue(qle.getID()); - if (!QuestCache.isQuestShown(quest, pid, player)) { continue; } + if (!QuestCache.isQuestShown(quest, pid, player)) { + continue; + } GuiRectangle rect = new GuiRectangle(qle.getValue().getPosX(), qle.getValue().getPosY(), qle.getValue().getSizeX(), qle.getValue().getSizeY()); PanelButtonQuest paBtn = new PanelButtonQuest(rect, buttonId, "", new DBEntry<>(qle.getID(), quest)); - this.addPanel(paBtn); - this.btnList.add(paBtn); + addPanel(paBtn); + btnList.add(paBtn); questBtns.put(qle.getID(), paBtn); } @@ -117,7 +123,9 @@ public void setQuestLine(IQuestLine line) { List> reqList = QuestingAPI.getAPI(ApiReference.QUEST_DB).bulkLookup(quest.getValue().getRequirements()); - if (reqList.isEmpty()) { continue; } + if (reqList.isEmpty()) { + continue; + } boolean main = quest.getValue().getProperty(NativeProps.MAIN); EnumQuestState qState = quest.getValue().getState(pid); @@ -150,7 +158,7 @@ public void setQuestLine(IQuestLine line) { PanelLine prLine = new PanelLine(parBtn.getTransform(), entry.getValue().getTransform(), lineRender, main ? 8 : 4, txLineCol, 1); - this.addPanel(prLine); + addPanel(prLine); } } } @@ -188,13 +196,13 @@ public void fitToWindow() { maxX += margin; maxY += margin; - this.setZoom(Math.min(getTransform().getWidth() / (float) (maxX - minX), - getTransform().getHeight() / (float) (maxY - minY))); - this.refreshScrollBounds(); + setZoom(Math.min(getTransform().getWidth() / (float) (maxX - minX), + getTransform().getHeight() / (float) (maxY - minY))); + refreshScrollBounds(); IGuiRect bounds = getScrollBounds(); - this.setScrollX(bounds.getX() + bounds.getWidth() / 2); - this.setScrollY(bounds.getY() + bounds.getHeight() / 2); - this.updatePanelScroll(); + setScrollX(bounds.getX() + bounds.getWidth() / 2); + setScrollY(bounds.getY() + bounds.getHeight() / 2); + updatePanelScroll(); } } diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java index bfcabc156..af3831bb2 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasScrolling.java @@ -53,7 +53,7 @@ public class CanvasScrolling implements IGuiCanvas { private final GuiRectangle refRect = new GuiRectangle(0, 0, 0, 0); public CanvasScrolling(IGuiRect rect) { - this.transform = rect; + transform = rect; // Dummy value drivers @@ -63,39 +63,39 @@ public CanvasScrolling(IGuiRect rect) { } public CanvasScrolling setScrollDriverX(IValueIO driver) { - this.scrollX = driver; + scrollX = driver; return this; } public CanvasScrolling setScrollDriverY(IValueIO driver) { - this.scrollY = driver; + scrollY = driver; return this; } public CanvasScrolling setZoomDriver(IValueIO driver) { - this.zoomScale = driver; + zoomScale = driver; return this; } public CanvasScrolling setScrollSpeed(int dx) { - this.scrollSpeed = dx; + scrollSpeed = dx; return this; } public CanvasScrolling setupAdvanceScroll(boolean scrollToZoom, boolean extendedScroll, int scrollMargin) { - this.zoomMode = scrollToZoom; + zoomMode = scrollToZoom; this.extendedScroll = extendedScroll; - this.margin = scrollMargin; + margin = scrollMargin; return this; } public CanvasScrolling enableBlocking(boolean state) { - this.useBlocking = state; + useBlocking = state; return this; } public IGuiRect getScrollBounds() { - return this.scrollBounds; + return scrollBounds; } public int getScrollX() { @@ -111,37 +111,41 @@ public float getZoom() { } public void setScrollX(int sx) { - if (scrollBounds.getWidth() <= 0) { return; } + if (scrollBounds.getWidth() <= 0) { + return; + } scrollX.writeValueRaw((sx - scrollBounds.getX()) / (float) scrollBounds.getWidth()); - lsx = this.getScrollX(); + lsx = getScrollX(); } public void setScrollY(int sy) { - if (scrollBounds.getHeight() <= 0) { return; } + if (scrollBounds.getHeight() <= 0) { + return; + } scrollY.writeValueRaw((sy - scrollBounds.getY()) / (float) scrollBounds.getHeight()); - lsy = this.getScrollY(); + lsy = getScrollY(); } public void setZoom(float z) { zoomScale.writeValueRaw(z); lsz = zoomScale.readValue(); - this.refreshScrollBounds(); + refreshScrollBounds(); } @Override public void initPanel() { - this.guiPanels.clear(); - this.cullingManager.reset(); + guiPanels.clear(); + cullingManager.reset(); } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override public boolean isEnabled() { - return this.enabled; + return enabled; } @Override @@ -152,12 +156,14 @@ public IGuiRect getTransform() { @Nonnull @Override public List getChildren() { - return this.guiPanels; + return guiPanels; } @Override public void drawPanel(int mx, int my, float partialTick) { - if (!isRectEqual(refRect, transform)) { refreshScrollBounds(); } + if (!isRectEqual(refRect, transform)) { + refreshScrollBounds(); + } float zs = zoomScale.readValue(); @@ -203,7 +209,7 @@ public void drawPanel(int mx, int my, float partialTick) { swcx -= swcx / change; swcy -= swcy / change; - this.refreshScrollBounds(); // NOTE: This runs updatePanelPcroll() too. Hence why the math above is done first before the scroll bounds are changed + refreshScrollBounds(); // NOTE: This runs updatePanelPcroll() too. Hence why the math above is done first before the scroll bounds are changed if (scrollBounds.getWidth() > 0) { scrollX.writeValue(((csx + swcx) - scrollBounds.getX()) / (float) scrollBounds.getWidth()); @@ -216,7 +222,7 @@ public void drawPanel(int mx, int my, float partialTick) { lsz = zs; } else if (lsx != getScrollX() || lsy != getScrollY()) // We can skip this if the above case ran { - this.updatePanelScroll(); + updatePanelScroll(); } GlStateManager.pushMatrix(); @@ -281,7 +287,9 @@ public boolean onMouseRelease(int mx, int my, int click) { boolean used = false; if (!hasDragged) { - if (!transform.contains(mx, my)) { return false; } + if (!transform.contains(mx, my)) { + return false; + } float zs = zoomScale.readValue(); int tx = transform.getX(); @@ -300,7 +308,9 @@ public boolean onMouseRelease(int mx, int my, int click) { } if (isDragging) { - if (!Mouse.isButtonDown(0) && !Mouse.isButtonDown(2)) { isDragging = false; } + if (!Mouse.isButtonDown(0) && !Mouse.isButtonDown(2)) { + isDragging = false; + } return true; } @@ -309,7 +319,9 @@ public boolean onMouseRelease(int mx, int my, int click) { @Override public boolean onMouseScroll(int mx, int my, int scroll) { - if (scroll == 0 || !transform.contains(mx, my)) { return false; } + if (scroll == 0 || !transform.contains(mx, my)) { + return false; + } float zs = zoomScale.readValue(); int tx = transform.getX(); @@ -344,7 +356,7 @@ public boolean onMouseScroll(int mx, int my, int scroll) { if (!((dy < 0F && cs <= 0F) || (dy > 0F && cs >= 1F))) { scrollY.writeValue(cs + dy); - this.updatePanelScroll(); + updatePanelScroll(); used = true; } } else if (scrollBounds.getWidth() > 0) // H scroll @@ -354,7 +366,7 @@ public boolean onMouseScroll(int mx, int my, int scroll) { if (!((dy < 0F && cs <= 0F) || (dy > 0F && cs >= 1F))) { scrollX.writeValue(cs + dy); - this.updatePanelScroll(); + updatePanelScroll(); used = true; } } @@ -389,7 +401,9 @@ public boolean onKeyTyped(char c, int keycode) { @Override public List getTooltip(int mx, int my) { - if (!transform.contains(mx, my) || isDragging) { return null; } + if (!transform.contains(mx, my) || isDragging) { + return null; + } float zs = zoomScale.readValue(); int tx = transform.getX(); @@ -424,7 +438,9 @@ public void addPanel(IGuiPanel panel) { } public void addCulledPanel(IGuiPanel panel, boolean useCulling) { - if (panel == null || guiPanels.contains(panel)) { return; } + if (panel == null || guiPanels.contains(panel)) { + return; + } guiPanels.add(panel); guiPanels.sort(ComparatorGuiDepth.INSTANCE); @@ -433,7 +449,7 @@ public void addCulledPanel(IGuiPanel panel, boolean useCulling) { panel.initPanel(); - this.refreshScrollBounds(); + refreshScrollBounds(); } @Override @@ -442,7 +458,7 @@ public boolean removePanel(IGuiPanel panel) { if (b) { cullingManager.removePanel(panel); - this.refreshScrollBounds(); + refreshScrollBounds(); } return b; @@ -477,8 +493,8 @@ public void refreshScrollBounds() { top -= margin; bottom += margin; - right -= (int) Math.ceil(this.getTransform().getWidth() / zs); - bottom -= (int) Math.ceil(this.getTransform().getHeight() / zs); + right -= (int) Math.ceil(getTransform().getWidth() / zs); + bottom -= (int) Math.ceil(getTransform().getHeight() / zs); if (extendedScroll) { scrollBounds.x = Math.min(left, right); @@ -501,8 +517,8 @@ public void refreshScrollBounds() { } public void updatePanelScroll() { - lsx = this.getScrollX(); - lsy = this.getScrollY(); + lsx = getScrollX(); + lsy = getScrollY(); float zs = zoomScale.readValue(); diff --git a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java index 307f79043..04b88ed2f 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/lists/CanvasSearch.java @@ -20,7 +20,7 @@ public CanvasSearch(IGuiRect rect) { } public void setSearchFilter(String text) { - this.searchTerm = text.toLowerCase(); + searchTerm = text.toLowerCase(); refreshSearch(); } @@ -39,12 +39,12 @@ public void drawPanel(int mx, int my, float partialTick) { } public void refreshSearch() { - this.resetCanvas(); - this.searchIdx = 0; - this.searching = getIterator(); - this.resultWidth = this.getTransform().getWidth(); - this.pendingResults.clear(); - this.savedResults.clear(); + resetCanvas(); + searchIdx = 0; + searching = getIterator(); + resultWidth = getTransform().getWidth(); + pendingResults.clear(); + savedResults.clear(); } private void updateSearch() { @@ -80,7 +80,9 @@ private void updateResults() { searchTime.reset().start(); while (!pendingResults.isEmpty() && searchTime.elapsed(TimeUnit.MILLISECONDS) < 100) { - if (addResult(pendingResults.poll(), searchIdx, resultWidth)) { searchIdx++; } + if (addResult(pendingResults.poll(), searchIdx, resultWidth)) { + searchIdx++; + } } searchTime.stop(); diff --git a/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java b/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java index fb22f141c..9643aad8e 100644 --- a/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java +++ b/src/main/java/betterquesting/api2/client/gui/popups/PopChoice.java @@ -43,19 +43,19 @@ public PopChoice(@Nonnull String message, @Nullable IGuiTexture icon, @Nonnull C public void initPanel() { super.initPanel(); - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), - new ColorTexture(new GuiColorStatic(0x80000000)))); + addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), + new ColorTexture(new GuiColorStatic(0x80000000)))); CanvasResizeable cvBox = new CanvasResizeable(new GuiTransform(new Vector4f(0.5F, 0.45F, 0.5F, 0.45F)), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBox); + addPanel(cvBox); cvBox.lerpToRect(new GuiTransform(new Vector4f(0.2F, 0.3F, 0.8F, 0.6F)), 200L, true); if (icon != null) { CanvasTextured icoFrame = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0.3F, 0.5F, 0.3F), -16, -40, 32, 32, 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(icoFrame); + addPanel(icoFrame); icoFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), icon)); } @@ -75,9 +75,11 @@ public void initPanel() { options[i]); btn.setClickAction((b) -> { callback.accept(index); - if (SceneController.getActiveScene() != null) { SceneController.getActiveScene().closePopup(); } + if (SceneController.getActiveScene() != null) { + SceneController.getActiveScene().closePopup(); + } }); - this.addPanel(btn); + addPanel(btn); } } diff --git a/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java b/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java index a92fce28c..3157497c2 100644 --- a/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java +++ b/src/main/java/betterquesting/api2/client/gui/popups/PopContextMenu.java @@ -32,7 +32,7 @@ public PopContextMenu(GuiRectangle rect, boolean autoClose) { } public ContextCategory getRootCategory() { - return this.catRoot; + return catRoot; } public void addButton(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) { @@ -44,7 +44,7 @@ public ContextCategory addCateogry(@Nonnull String text) { } public void openCategory(@Nonnull ContextCategory category) { - this.resetCanvas(); + resetCanvas(); int listH = Math.min(category.entries.size() * 16, rect.getHeight()); @@ -57,14 +57,14 @@ public void openCategory(@Nonnull ContextCategory category) { CanvasResizeable cvBG = new CanvasResizeable(new GuiRectangle(0, 0, 0, 0, 0), PresetTexture.PANEL_INNER.getTexture()); - this.addPanel(cvBG); + addPanel(cvBG); cvBG.lerpToRect(new GuiRectangle(0, 0, rect.w - 8, listH, 0), 100, true); CanvasScrolling cvScroll = new CanvasScrolling(new GuiTransform(GuiAlign.FULL_BOX)); cvBG.addPanel(cvScroll); PanelVScrollBar scrollBar = new PanelVScrollBar(new GuiRectangle(rect.w - 8, 0, 8, listH, 0)); - this.addPanel(scrollBar); + addPanel(scrollBar); cvScroll.setScrollDriverY(scrollBar); for (int i = 0; i < category.entries.size(); i++) { @@ -122,7 +122,9 @@ private ContextCategory(@Nullable ContextCategory parent, @Nonnull String name) this.parent = parent; this.name = name; - if (this.parent != null) { addButton("<", null, () -> openCategory(this.parent)); } + if (this.parent != null) { + addButton("<", null, () -> openCategory(this.parent)); + } } public void addButton(@Nonnull String text, @Nullable IGuiTexture icon, @Nullable Runnable action) { diff --git a/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java b/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java index 929067f5a..44a46d54a 100644 --- a/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java +++ b/src/main/java/betterquesting/api2/client/gui/popups/PopMessage.java @@ -37,18 +37,18 @@ public PopMessage(@Nonnull String message, @Nullable IGuiTexture icon) { public void initPanel() { super.initPanel(); - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), - new ColorTexture(new GuiColorStatic(0x80000000)))); + addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 1), + new ColorTexture(new GuiColorStatic(0x80000000)))); CanvasTextured cvBox = new CanvasTextured(new GuiTransform(new Vector4f(0.2F, 0.3F, 0.8F, 0.6F)), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBox); + addPanel(cvBox); if (icon != null) { CanvasTextured icoFrame = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0.3F, 0.5F, 0.3F), -16, -40, 32, 32, 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(icoFrame); + addPanel(icoFrame); icoFrame.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(8, 8, 8, 8), 0), icon)); } @@ -58,9 +58,11 @@ public void initPanel() { PanelButton btn = new PanelButton(new GuiTransform(new Vector4f(0.5F, 0.6F, 0.5F, 0.6F), -48, 8, 96, 16, 0), -1, QuestTranslation.translate("gui.back")); btn.setClickAction((b) -> { - if (SceneController.getActiveScene() != null) { SceneController.getActiveScene().closePopup(); } + if (SceneController.getActiveScene() != null) { + SceneController.getActiveScene().closePopup(); + } }); - this.addPanel(btn); + addPanel(btn); } // == TRAP ALL UI USAGE UNTIL CLOSED === diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java index 35a2a6f06..4d57eafbb 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorPulse.java @@ -18,8 +18,8 @@ public GuiColorPulse(int color1, int color2, double period, float phase) { } public GuiColorPulse(IGuiColor color1, IGuiColor color2, double period, float phase) { - this.c1 = color1; - this.c2 = color2; + c1 = color1; + c2 = color2; this.period = period; this.phase = phase; diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java index 15c158f39..9eedd562e 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorSequence.java @@ -40,11 +40,13 @@ public void applyGlColor() { } public IGuiColor getCurrentColor() { - if (colors.length == 0) { return null; } + if (colors.length == 0) { + return null; + } return colors[(int) Math.floor((System.currentTimeMillis() / 1000D) % (colors.length * interval) / interval)]; } public IGuiColor[] getAllColors() { - return this.colors; + return colors; } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java index 506a4342c..edc29f773 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorStatic.java @@ -8,11 +8,11 @@ public class GuiColorStatic implements IGuiColor { private final int argb; public GuiColorStatic(int color) { - this.argb = color; + argb = color; } public GuiColorStatic(int red, int green, int blue, int alpha) { - this.argb = ((alpha & 255) << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255); + argb = ((alpha & 255) << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255); } public GuiColorStatic(float red, float green, float blue, float alpha) { diff --git a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java index 0892ba8dd..bff4d3ccc 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/colors/GuiColorTransition.java @@ -18,7 +18,7 @@ public GuiColorTransition(IGuiColor cNorm, IGuiColor cLow) { } public GuiColorTransition setupBlending(boolean enable, float threshold) { - this.useLerp = enable; + useLerp = enable; this.threshold = threshold; return this; } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java index 1db11ee67..be8b5ef36 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorPulse.java @@ -25,12 +25,16 @@ public GuiColorPulse loadFromData(JsonObject data) { JsonObject jo1 = JsonHelper.GetObject(data, "color1"); color1 = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() .createNew(new ResourceLocation(JsonHelper.GetString(jo1, "colorType", "null")), jo1); - if (color1 == null) { color1 = new GuiColorStatic(0xFFFFFFFF); } + if (color1 == null) { + color1 = new GuiColorStatic(0xFFFFFFFF); + } JsonObject jo2 = JsonHelper.GetObject(data, "color2"); color2 = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() .createNew(new ResourceLocation(JsonHelper.GetString(jo2, "colorType", "null")), jo2); - if (color2 == null) { color2 = new GuiColorStatic(0xFFFFFFFF); } + if (color2 == null) { + color2 = new GuiColorStatic(0xFFFFFFFF); + } return new GuiColorPulse(color1, color2, period, phase); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java index 71e926b26..f5b6c9d81 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/colors/FactoryColorSequence.java @@ -29,7 +29,9 @@ public GuiColorSequence loadFromData(JsonObject data) { JsonArray jAry = JsonHelper.GetArray(data, "colors"); for (JsonElement je : jAry) { - if (!je.isJsonObject()) { continue; } + if (!je.isJsonObject()) { + continue; + } JsonObject jo = je.getAsJsonObject(); try { diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java index 5b0b0e3a5..8c24ee157 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryColorTexture.java @@ -23,7 +23,9 @@ public ColorTexture loadFromData(JsonObject data) { int[] bounds = new int[] { 0, 0, 0, 0 }; JsonArray jAry = JsonHelper.GetArray(data, "padding"); for (int i = 0; i < jAry.size() && i < bounds.length; i++) { - if (!(jAry.get(i).isJsonPrimitive())) { continue; } + if (!(jAry.get(i).isJsonPrimitive())) { + continue; + } try { bounds[i] = jAry.get(i).getAsInt(); } catch (Exception ignored) { } @@ -34,7 +36,9 @@ public ColorTexture loadFromData(JsonObject data) { try { color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if (color == null) { color = new GuiColorStatic(0xFFFFFFFF); } + if (color == null) { + color = new GuiColorStatic(0xFFFFFFFF); + } } catch (Exception ignored) { color = new GuiColorStatic(0xFFFFFFFF); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java index 88f5dcc27..dfe01d0db 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryLayeredTexture.java @@ -30,7 +30,9 @@ public LayeredTexture loadFromData(JsonObject data) { JsonArray jAry = JsonHelper.GetArray(data, "layers"); for (JsonElement je : jAry) { - if (!je.isJsonObject()) { continue; } + if (!je.isJsonObject()) { + continue; + } JsonObject jo = je.getAsJsonObject(); try { diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java index b8031d8f3..029ba7c0d 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureC.java @@ -22,7 +22,9 @@ public IGuiTexture loadFromData(JsonObject data) { JsonArray jAry = JsonHelper.GetArray(data, "verts"); double[] verts = new double[jAry.size()]; for (int i = 0; i < jAry.size() && i < verts.length; i++) { - if (!(jAry.get(i).isJsonPrimitive())) { continue; } + if (!(jAry.get(i).isJsonPrimitive())) { + continue; + } try { verts[i] = jAry.get(i).getAsDouble(); } catch (Exception ignored) { } @@ -35,7 +37,9 @@ public IGuiTexture loadFromData(JsonObject data) { try { color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if (color == null) { color = new GuiColorStatic(0xFFFFFFFF); } + if (color == null) { + color = new GuiColorStatic(0xFFFFFFFF); + } } catch (Exception ignored) { color = new GuiColorStatic(0xFFFFFFFF); } @@ -46,7 +50,9 @@ public IGuiTexture loadFromData(JsonObject data) { try { borColor = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if (borColor == null) { borColor = new GuiColorStatic(0xFFFFFFFF); } + if (borColor == null) { + borColor = new GuiColorStatic(0xFFFFFFFF); + } } catch (Exception ignored) { borColor = new GuiColorStatic(0xFFFFFFFF); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java index 86565950f..127fa329b 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactoryPolyTextureR.java @@ -27,7 +27,9 @@ public IGuiTexture loadFromData(JsonObject data) { try { color = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if (color == null) { color = new GuiColorStatic(0xFFFFFFFF); } + if (color == null) { + color = new GuiColorStatic(0xFFFFFFFF); + } } catch (Exception ignored) { color = new GuiColorStatic(0xFFFFFFFF); } @@ -38,7 +40,9 @@ public IGuiTexture loadFromData(JsonObject data) { try { borColor = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getColorReg() .createNew(new ResourceLocation(JsonHelper.GetString(jCol, "colorType", "null")), jCol); - if (borColor == null) { borColor = new GuiColorStatic(0xFFFFFFFF); } + if (borColor == null) { + borColor = new GuiColorStatic(0xFFFFFFFF); + } } catch (Exception ignored) { borColor = new GuiColorStatic(0xFFFFFFFF); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java index bb32004f5..e32715c7f 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySimpleTexture.java @@ -24,7 +24,9 @@ public SimpleTexture loadFromData(JsonObject data) { int[] bounds = new int[] { 0, 0, 16, 16 }; JsonArray jAry = JsonHelper.GetArray(data, "bounds"); for (int i = 0; i < jAry.size() && i < bounds.length; i++) { - if (!(jAry.get(i).isJsonPrimitive())) { continue; } + if (!(jAry.get(i).isJsonPrimitive())) { + continue; + } try { bounds[i] = jAry.get(i).getAsInt(); } catch (Exception ignored) { } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java index ebf0480b4..aa386ac0d 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlicedTexture.java @@ -28,7 +28,9 @@ public SlicedTexture loadFromData(JsonObject data) { int[] bounds = new int[] { 0, 0, 16, 16 }; JsonArray jAry = JsonHelper.GetArray(data, "bounds"); for (int i = 0; i < jAry.size() && i < bounds.length; i++) { - if (!(jAry.get(i).isJsonPrimitive())) { continue; } + if (!(jAry.get(i).isJsonPrimitive())) { + continue; + } try { bounds[i] = jAry.get(i).getAsInt(); } catch (Exception ignored) { } @@ -37,7 +39,9 @@ public SlicedTexture loadFromData(JsonObject data) { int[] padding = new int[] { 0, 0, 16, 16 }; JsonArray jAry2 = JsonHelper.GetArray(data, "padding"); for (int i = 0; i < jAry.size() && i < padding.length; i++) { - if (!(jAry2.get(i).isJsonPrimitive())) { continue; } + if (!(jAry2.get(i).isJsonPrimitive())) { + continue; + } try { padding[i] = jAry2.get(i).getAsInt(); } catch (Exception ignored) { } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java index e129d4394..53a5e113d 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/factories/textures/FactorySlideShowTexture.java @@ -32,12 +32,15 @@ public SlideShowTexture loadFromData(JsonObject data) { JsonArray jAry = JsonHelper.GetArray(data, "slides"); for (JsonElement je : jAry) { - if (!je.isJsonObject()) { continue; } + if (!je.isJsonObject()) { + continue; + } JsonObject jo = je.getAsJsonObject(); try { IGuiTexture tFact = QuestingAPI.getAPI(ApiReference.RESOURCE_REG).getTexReg() - .createNew(new ResourceLocation(JsonHelper.GetString(jo, "textureType", "null")), jo); + .createNew(new ResourceLocation(JsonHelper.GetString(jo, "textureType", "null")), + jo); layers.add(tFact); } catch (Exception ignored) { layers.add(NULL_TX); diff --git a/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java b/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java index dc5a6ac7a..38c810d2a 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/lines/BoxLine.java @@ -14,8 +14,8 @@ public BoxLine() { } public BoxLine(int stippleScale, short stipplePattern) { - this.pattern = stipplePattern; - this.scale = stippleScale; + pattern = stipplePattern; + scale = stippleScale; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java b/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java index 791bcee09..fb3d731a7 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/lines/SimpleLine.java @@ -14,8 +14,8 @@ public SimpleLine() { } public SimpleLine(int stippleScale, short stipplePattern) { - this.pattern = stipplePattern; - this.scale = stippleScale; + pattern = stipplePattern; + scale = stippleScale; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java index 45effb44e..d967059d9 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/ColorTexture.java @@ -23,7 +23,7 @@ public ColorTexture(IGuiColor baseColor) { // Really only used for item slot highlighting but could be used elsewhere public ColorTexture(IGuiColor baseColor, GuiPadding padding) { this.baseColor = baseColor; - this.pad = padding; + pad = padding; } @Override @@ -33,7 +33,9 @@ public void drawTexture(int x, int y, int width, int height, float zDepth, float @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } GlStateManager.pushMatrix(); diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java index 9cdf9ed85..bbcd18b89 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/EmptyTexture.java @@ -7,12 +7,10 @@ // Literally does nothing... public class EmptyTexture implements IGuiTexture { @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { - } + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { } @Override - public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { - } + public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { } @Override public ResourceLocation getTexture() { diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java index 149ad40ed..1f1104e5b 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/FluidTexture.java @@ -38,12 +38,14 @@ public FluidTexture(FluidStack fluid, boolean showCount, boolean keepAspect) { @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { - this.drawTexture(x, y, width, height, zDepth, partialTick, defColor); + drawTexture(x, y, width, height, zDepth, partialTick, defColor); } @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } float sx = width / 16F; float sy = height / 16F; @@ -85,7 +87,7 @@ public void drawTexture(int x, int y, int width, int height, float zDepth, float Minecraft mc = Minecraft.getMinecraft(); mc.renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); TextureAtlasSprite fluidTx = mc.getTextureMapBlocks().getAtlasSprite(fluid.getFluid().getStill().toString()); - this.drawTexturedModalRect(0, 0, 0, fluidTx, 16, 16); + drawTexturedModalRect(0, 0, 0, fluidTx, 16, 16); GlStateManager.popMatrix(); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java index 3799c7883..838ae6c48 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/GuiTextureColored.java @@ -18,7 +18,9 @@ public GuiTextureColored(IGuiTexture texture, IGuiColor color) { @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } texture.drawTexture(x, y, width, height, zDepth, partialTick, color); } @@ -26,7 +28,9 @@ public void drawTexture(int x, int y, int width, int height, float zDepth, float @Override @Deprecated public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor c) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } texture.drawTexture(x, y, width, height, zDepth, partialTick, c); } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java index 2535c0ccf..2ef53ad8a 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/ItemTexture.java @@ -35,7 +35,7 @@ public ItemTexture(BigItemStack stack, boolean showCount, boolean keepAspect) { } public ItemTexture setDepth(float z) { - this.zDepth = z; + zDepth = z; return this; } @@ -46,7 +46,9 @@ public void drawTexture(int x, int y, int width, int height, float zLevel, float @Override public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } float sx = width / 16F; float sy = height / 16F; diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java index 7f6ed3b5a..902b20e4c 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/LayeredTexture.java @@ -13,7 +13,9 @@ public LayeredTexture(IGuiTexture... layers) { @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } for (IGuiTexture tex : layers) { tex.drawTexture(x, y, width, height, zDepth, partialTick); @@ -22,7 +24,9 @@ public void drawTexture(int x, int y, int width, int height, float zDepth, float @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } for (IGuiTexture tex : layers) { tex.drawTexture(x, y, width, height, zDepth, partialTick, color); diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java index fb08071a1..52f8d222c 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/PolyTexture.java @@ -21,10 +21,12 @@ public class PolyTexture implements IGuiTexture { private IGuiColor borColor = new GuiColorStatic(0xFFFFFFFF); public PolyTexture(int points, double rotation, boolean shadow, @Nonnull IGuiColor color) { - this.defColor = color; + defColor = color; this.shadow = shadow; - if (points <= 0) { points = 32; } + if (points <= 0) { + points = 32; + } verts = new double[points * 2]; // XY positions of all outer verticies double min = 0.0001D; @@ -48,15 +50,15 @@ public PolyTexture(int points, double rotation, boolean shadow, @Nonnull IGuiCol } public PolyTexture(@Nonnull double[] verts, boolean shadow, IGuiColor color) { - this.defColor = color; + defColor = color; this.shadow = shadow; this.verts = new double[verts.length]; System.arraycopy(verts, 0, this.verts, 0, verts.length); } public IGuiTexture setBorder(int size, IGuiColor color) { - this.borderSize = size; - this.borColor = color; + borderSize = size; + borColor = color; return this; } @@ -67,7 +69,9 @@ public void drawTexture(int x, int y, int width, int height, float zDepth, float @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } GlStateManager.pushMatrix(); diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java index 4cca1d45c..fc3fddbe6 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/SimpleTexture.java @@ -18,11 +18,11 @@ public class SimpleTexture implements IGuiTexture { public SimpleTexture(ResourceLocation texture, IGuiRect bounds) { this.texture = texture; - this.texBounds = bounds; + texBounds = bounds; } public SimpleTexture maintainAspect(boolean enable) { - this.maintainAspect = enable; + maintainAspect = enable; return this; } @@ -33,7 +33,9 @@ public void drawTexture(int x, int y, int width, int height, float zLevel, float @Override public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } GlStateManager.pushMatrix(); @@ -66,11 +68,11 @@ public void drawTexture(int x, int y, int width, int height, float zLevel, float @Override public ResourceLocation getTexture() { - return this.texture; + return texture; } @Override public IGuiRect getBounds() { - return this.texBounds; + return texBounds; } } diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java index 58e62d651..23ff1c3c8 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlicedTexture.java @@ -22,9 +22,9 @@ public class SlicedTexture implements IGuiTexture { private SliceMode sliceMode = SliceMode.SLICED_TILE; public SlicedTexture(ResourceLocation tex, IGuiRect bounds, GuiPadding border) { - this.texture = tex; - this.texBounds = bounds; - this.texBorder = border; + texture = tex; + texBounds = bounds; + texBorder = border; } @Override @@ -34,7 +34,9 @@ public void drawTexture(int x, int y, int width, int height, float zLevel, float @Override public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0) { return; } + if (width <= 0 || height <= 0) { + return; + } int w = Math.max(width, texBorder.getLeft() + texBorder.getRight()); int h = Math.max(height, texBorder.getTop() + texBorder.getBottom()); @@ -155,23 +157,23 @@ public void drawTexture(int x, int y, int width, int height, float zLevel, float @Override public ResourceLocation getTexture() { - return this.texture; + return texture; } @Override public IGuiRect getBounds() { - return this.texBounds; + return texBounds; } public GuiPadding getBorder() { - return this.texBorder; + return texBorder; } /** * Enables texture slicing. Will stretch to fit if disabled */ public SlicedTexture setSliceMode(SliceMode mode) { - this.sliceMode = mode; + sliceMode = mode; return this; } @@ -206,7 +208,9 @@ private static void drawContinuousTexturedBox(ResourceLocation res, int x, int y int fillerWidth = textureWidth - leftBorder - rightBorder; int fillerHeight = textureHeight - topBorder - bottomBorder; - if (fillerWidth <= 0 || fillerHeight <= 0) { return; } + if (fillerWidth <= 0 || fillerHeight <= 0) { + return; + } int canvasWidth = width - leftBorder - rightBorder; int canvasHeight = height - topBorder - bottomBorder; int xPasses = canvasWidth / fillerWidth; diff --git a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java index c9353dd23..bdaf10b39 100644 --- a/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/resources/textures/SlideShowTexture.java @@ -17,18 +17,26 @@ public SlideShowTexture(float interval, IGuiTexture... slides) { @Override public void drawTexture(int x, int y, int width, int height, float zLevel, float partialTick) { - if (width <= 0 || height <= 0 || slides.length == 0) { return; } + if (width <= 0 || height <= 0 || slides.length == 0) { + return; + } IGuiTexture tex = getCurrentFrame(); - if (tex != null) { tex.drawTexture(x, y, width, height, zLevel, partialTick); } + if (tex != null) { + tex.drawTexture(x, y, width, height, zLevel, partialTick); + } } @Override public void drawTexture(int x, int y, int width, int height, float zDepth, float partialTick, IGuiColor color) { - if (width <= 0 || height <= 0 || slides.length == 0) { return; } + if (width <= 0 || height <= 0 || slides.length == 0) { + return; + } IGuiTexture tex = getCurrentFrame(); - if (tex != null) { tex.drawTexture(x, y, width, height, zDepth, partialTick, color); } + if (tex != null) { + tex.drawTexture(x, y, width, height, zDepth, partialTick, color); + } } @Override @@ -47,7 +55,9 @@ public IGuiRect getBounds() { @Nullable public IGuiTexture getCurrentFrame() { - if (slides.length == 0) { return null; } + if (slides.length == 0) { + return null; + } return slides[(int) Math.floor((System.currentTimeMillis() / 1000D) % (slides.length * interval) / interval)]; } diff --git a/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java b/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java index 2ab5137cb..91acfecb5 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/GuiKey.java @@ -9,12 +9,12 @@ public class GuiKey { private final ResourceLocation ID; public GuiKey(@Nonnull ResourceLocation id) { - this.ID = id; + ID = id; } @Nonnull public ResourceLocation getID() { - return this.ID; + return ID; } @Override diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java index 873827800..a63821dc1 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetColor.java @@ -47,11 +47,11 @@ public enum PresetColor { } public IGuiColor getColor() { - return ThemeRegistry.INSTANCE.getColor(this.key); + return ThemeRegistry.INSTANCE.getColor(key); } public ResourceLocation getKey() { - return this.key; + return key; } public static void registerColors(IThemeRegistry reg) { diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java index 1df2a3513..fc02c19a1 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetIcon.java @@ -108,11 +108,11 @@ public enum PresetIcon { } public IGuiTexture getTexture() { - return ThemeRegistry.INSTANCE.getTexture(this.key); + return ThemeRegistry.INSTANCE.getTexture(key); } public ResourceLocation getKey() { - return this.key; + return key; } public static void registerIcons(IThemeRegistry reg) { diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java index bb8e5b587..a0ab53e30 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetLine.java @@ -25,11 +25,11 @@ public enum PresetLine { } public IGuiLine getLine() { - return ThemeRegistry.INSTANCE.getLine(this.key); + return ThemeRegistry.INSTANCE.getLine(key); } public ResourceLocation getKey() { - return this.key; + return key; } public static void registerLines(IThemeRegistry reg) { diff --git a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java index 73bb1811e..d91dd390a 100644 --- a/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java +++ b/src/main/java/betterquesting/api2/client/gui/themes/presets/PresetTexture.java @@ -88,11 +88,11 @@ public enum PresetTexture { } public IGuiTexture getTexture() { - return ThemeRegistry.INSTANCE.getTexture(this.key); + return ThemeRegistry.INSTANCE.getTexture(key); } public ResourceLocation getKey() { - return this.key; + return key; } public static void registerTextures(IThemeRegistry reg) { diff --git a/src/main/java/betterquesting/api2/registry/FunctionRegistry.java b/src/main/java/betterquesting/api2/registry/FunctionRegistry.java index 3f0d51041..760c72e25 100644 --- a/src/main/java/betterquesting/api2/registry/FunctionRegistry.java +++ b/src/main/java/betterquesting/api2/registry/FunctionRegistry.java @@ -26,7 +26,9 @@ public void register(@Nonnull ResourceLocation idname, @Nonnull Function f @Nullable public T createNew(@Nonnull ResourceLocation idName) { E arg = def_args.get(idName); - if (arg != null) { return createNew(idName, arg); } + if (arg != null) { + return createNew(idName, arg); + } BetterQuesting.logger.error("Registry failed to instantiate new object with ID: " + idName); return null; diff --git a/src/main/java/betterquesting/api2/storage/DBEntry.java b/src/main/java/betterquesting/api2/storage/DBEntry.java index f3ba653b9..1ec9032af 100644 --- a/src/main/java/betterquesting/api2/storage/DBEntry.java +++ b/src/main/java/betterquesting/api2/storage/DBEntry.java @@ -17,7 +17,7 @@ public DBEntry(int id, @Nonnull T obj) { } public int getID() { - return this.id; + return id; } @Nonnull @@ -38,6 +38,6 @@ public boolean equals(Object obj) { DBEntry entry = (DBEntry) obj; - return this.getID() == entry.getID() && this.getValue().equals(entry.getValue()); + return getID() == entry.getID() && getValue().equals(entry.getValue()); } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java b/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java index a36b80b63..a1cd20691 100644 --- a/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java +++ b/src/main/java/betterquesting/api2/supporter/MCLinkAPI.java @@ -54,7 +54,9 @@ public void updateSupporterInfo(@Nonnull Collection playerIDs, Collection< } private static JsonElement sendJsonPost(String endpoint, JsonElement json) throws IOException { - if (userAgent == null) { setupMetadata(); } + if (userAgent == null) { + setupMetadata(); + } URL url = new URL(endpoint); String redirect = url.toString(); @@ -84,7 +86,9 @@ private static JsonElement sendJsonPost(String endpoint, JsonElement json) throw //TODO: Flag the JSON response as an error when necessary so it can be handled as such InputStream is = con.getErrorStream(); - if (is == null) { is = con.getInputStream(); } + if (is == null) { + is = con.getInputStream(); + } try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) { JsonElement jsonOut = JsonHelper.GSON.fromJson(isr, JsonElement.class); diff --git a/src/main/java/betterquesting/api2/supporter/RgbTexture.java b/src/main/java/betterquesting/api2/supporter/RgbTexture.java index 1ba217007..06dccf765 100644 --- a/src/main/java/betterquesting/api2/supporter/RgbTexture.java +++ b/src/main/java/betterquesting/api2/supporter/RgbTexture.java @@ -7,7 +7,6 @@ import javax.annotation.Nonnull; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; -import java.io.IOException; public class RgbTexture extends AbstractTexture { private final int[] rgbAry; @@ -23,11 +22,11 @@ public RgbTexture(int w, int h, int[] rgbAry) { @Override public void loadTexture(@Nonnull IResourceManager resourceManager) { - this.deleteGlTexture(); + deleteGlTexture(); BufferedImage bufImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); final int[] imgData = ((DataBufferInt) bufImg.getRaster().getDataBuffer()).getData(); System.arraycopy(rgbAry, 0, imgData, 0, imgData.length); - TextureUtil.uploadTextureImageAllocate(this.getGlTextureId(), bufImg, false, false); + TextureUtil.uploadTextureImageAllocate(getGlTextureId(), bufImg, false, false); } } diff --git a/src/main/java/betterquesting/api2/supporter/SupporterAPI.java b/src/main/java/betterquesting/api2/supporter/SupporterAPI.java index bc438199e..5268724e3 100644 --- a/src/main/java/betterquesting/api2/supporter/SupporterAPI.java +++ b/src/main/java/betterquesting/api2/supporter/SupporterAPI.java @@ -17,7 +17,10 @@ import javax.annotation.Nullable; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; -import java.io.*; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.*; @@ -33,7 +36,9 @@ public class SupporterAPI { public static JsonObject readManifest(File loc) { try (DataInputStream dis = new DataInputStream(new GZIPInputStream(Files.newInputStream(loc.toPath())))) { return GSON.fromJson(new String(Base64.getDecoder().decode(dis.readUTF())), JsonObject.class); - } catch (Exception ignored) { return null; } + } catch (Exception ignored) { + return null; + } } public static ResourceTheme readCompressedFile(File loc) { @@ -139,7 +144,9 @@ private static String decode(String s, byte[] key) { private static byte[] flipBytes(@Nonnull byte[] input, @Nonnull byte[] key) { byte[] output = new byte[input.length]; - for (int i = 0; i < input.length; i++) { output[i] = (byte) (input[i] ^ key[i % key.length]); } + for (int i = 0; i < input.length; i++) { + output[i] = (byte) (input[i] ^ key[i % key.length]); + } return output; } @@ -156,7 +163,9 @@ private static byte[] makeFormat_1(@Nonnull DataOutputStream dos, @Nonnull Strin list.add(new Tuple<>(true, token)); for (int i = 0; i < salts; i++) { StringBuilder sb = new StringBuilder(); - for (int j = rand.nextInt(9) + 16; j >= 0; j--) { sb.append(charSet.charAt(rand.nextInt(charSet.length()))); } + for (int j = rand.nextInt(9) + 16; j >= 0; j--) { + sb.append(charSet.charAt(rand.nextInt(charSet.length()))); + } list.add(new Tuple<>(false, sb.toString())); } Collections.shuffle(list, rand); @@ -170,9 +179,13 @@ private static byte[] makeFormat_1(@Nonnull DataOutputStream dos, @Nonnull Colle Set l = new HashSet<>(); for (Tuple t : tokens) { byte[] b = t.getFirst() ? t.getSecond().getBytes(StandardCharsets.UTF_8) : new byte[16]; - if (!t.getFirst()) { new Random(t.getSecond().hashCode()).nextBytes(b); } + if (!t.getFirst()) { + new Random(t.getSecond().hashCode()).nextBytes(b); + } l.add(b); - if (s < b.length) { s = b.length; } + if (s < b.length) { + s = b.length; + } dos.writeUTF(Base64.getEncoder().encodeToString(t.getSecond().getBytes(StandardCharsets.UTF_8))); } @@ -180,7 +193,11 @@ private static byte[] makeFormat_1(@Nonnull DataOutputStream dos, @Nonnull Colle dos.writeInt(threshold); byte[] k = new byte[s]; - for (int i = 0; i < s; i++) { for (byte[] e : l) { k[i] ^= e[i % e.length]; } } + for (int i = 0; i < s; i++) { + for (byte[] e : l) { + k[i] ^= e[i % e.length]; + } + } return k; } @@ -204,14 +221,18 @@ private static byte[] readFormat_0(@Nonnull DataInputStream dis) { long seed = dis.readLong(); new Random(seed).nextBytes(b); return b; - } catch (Exception ignored) { return new byte[] { 127 }; } + } catch (Exception ignored) { + return new byte[] { 127 }; + } } @SideOnly(Side.CLIENT) private static byte[] readFormat_1(@Nonnull DataInputStream dis) { try { String[] tokens = new String[dis.readInt()]; - for (int n = 0; n < tokens.length; n++) { tokens[n] = new String(Base64.getDecoder().decode(dis.readUTF())); } + for (int n = 0; n < tokens.length; n++) { + tokens[n] = new String(Base64.getDecoder().decode(dis.readUTF())); + } String service = new String(Base64.getDecoder().decode(dis.readUTF())); int threshold = dis.readInt(); @@ -224,14 +245,24 @@ private static byte[] readFormat_1(@Nonnull DataInputStream dis) { boolean c = entry != null && entry.getServices(k).entrySet().stream() .anyMatch((v) -> v.getKey().equals(service) && v.getValue() >= threshold); byte[] b = c ? k.getBytes(StandardCharsets.UTF_8) : new byte[16]; - if (c) { new Random(k.hashCode()).nextBytes(b); } + if (c) { + new Random(k.hashCode()).nextBytes(b); + } encoded.add(b); - if (b.length > m) { m = b.length; } + if (b.length > m) { + m = b.length; + } } byte[] merged = new byte[m]; - for (int i = 0; i < m; i++) { for (byte[] e : encoded) { merged[i] ^= e[i % e.length]; } } + for (int i = 0; i < m; i++) { + for (byte[] e : encoded) { + merged[i] ^= e[i % e.length]; + } + } return merged; - } catch (Exception ignored) { return new byte[] { 127 }; } + } catch (Exception ignored) { + return new byte[] { 127 }; + } } } diff --git a/src/main/java/betterquesting/api2/supporter/SupporterEntry.java b/src/main/java/betterquesting/api2/supporter/SupporterEntry.java index b9161b18c..c850fea66 100644 --- a/src/main/java/betterquesting/api2/supporter/SupporterEntry.java +++ b/src/main/java/betterquesting/api2/supporter/SupporterEntry.java @@ -11,7 +11,7 @@ public class SupporterEntry implements INBTSaveLoad { @Nonnull public HashMap getServices(@Nonnull String token) { - return this.services.computeIfAbsent(token, (t) -> new HashMap<>()); + return services.computeIfAbsent(token, (t) -> new HashMap<>()); } @Override @@ -20,7 +20,5 @@ public NBTTagCompound writeToNBT(NBTTagCompound nbt) { } @Override - public void readFromNBT(NBTTagCompound nbt) { - - } + public void readFromNBT(NBTTagCompound nbt) { } } \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java b/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java index 3ae335e54..e8f2c0730 100644 --- a/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java +++ b/src/main/java/betterquesting/api2/supporter/mc_link/McLinkEndpoint.java @@ -10,6 +10,6 @@ public enum McLinkEndpoint { public final String URL; McLinkEndpoint(@Nonnull String url) { - this.URL = url; + URL = url; } } diff --git a/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java b/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java index 649644920..beac2298b 100644 --- a/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java +++ b/src/main/java/betterquesting/api2/supporter/theme_dlc/CatalogueEntry.java @@ -28,7 +28,7 @@ public class CatalogueEntry { public CatalogueEntry(String author, String themeName, String themeID, String downloadLink, String subLink) { this.author = author; - this.name = themeName; + name = themeName; this.themeID = new ResourceLocation(themeID); this.downloadLink = downloadLink; this.subLink = subLink; @@ -38,28 +38,32 @@ public CatalogueEntry setRequirement(@Nonnull String token, @Nonnull String serv @Nonnull String subLink) { this.token = token; this.service = service; - this.subTier = amount; + subTier = amount; this.subLink = subLink; return this; } public CatalogueEntry(@Nonnull JsonObject json) { - this.author = JsonHelper.GetString(json, "author", "Unknown"); - this.name = JsonHelper.GetString(json, "themeName", "Untitled"); - this.themeID = new ResourceLocation(JsonHelper.GetString(json, "themeID", "minecraft:untitled")); - this.downloadLink = JsonHelper.GetString(json, "themeID", "127.0.0.1"); + author = JsonHelper.GetString(json, "author", "Unknown"); + name = JsonHelper.GetString(json, "themeName", "Untitled"); + themeID = new ResourceLocation(JsonHelper.GetString(json, "themeID", "minecraft:untitled")); + downloadLink = JsonHelper.GetString(json, "themeID", "127.0.0.1"); reqMods.clear(); JsonArray aryMods = JsonHelper.GetArray(json, "reqMods"); for (JsonElement je : aryMods) { - if (!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) { continue; } + if (!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) { + continue; + } reqMods.add(je.getAsString()); } reqMods.clear(); JsonArray aryThms = JsonHelper.GetArray(json, "reqThemes"); for (JsonElement je : aryThms) { - if (!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) { continue; } + if (!je.isJsonPrimitive() || !je.getAsJsonPrimitive().isString()) { + continue; + } reqThemes.add(je.getAsString()); } } diff --git a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java index 29d8a4899..764293822 100644 --- a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java +++ b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeCatalogue.java @@ -8,12 +8,8 @@ public class ThemeCatalogue { // Download database of DLC themes - public static void refreshCatalogue() { - - } + public static void refreshCatalogue() { } // Update the refresh the local DLC themes - public static void refreshManifests() { - - } + public static void refreshManifests() { } } diff --git a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java index c2c967e7a..ced2d74e2 100644 --- a/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java +++ b/src/main/java/betterquesting/api2/supporter/theme_dlc/ThemeRepository.java @@ -19,7 +19,7 @@ public ThemeRepository(@Nonnull String address) { } public String getAddress() { - return this.repoAddress; + return repoAddress; } public List getEntries() { diff --git a/src/main/java/betterquesting/api2/utils/BQThreadedIO.java b/src/main/java/betterquesting/api2/utils/BQThreadedIO.java index 6e5274238..e68acb462 100644 --- a/src/main/java/betterquesting/api2/utils/BQThreadedIO.java +++ b/src/main/java/betterquesting/api2/utils/BQThreadedIO.java @@ -11,7 +11,7 @@ public class BQThreadedIO { private ExecutorService exService; public BQThreadedIO() { - this.init(); + init(); } public void init() { diff --git a/src/main/java/betterquesting/api2/utils/BqFontRenderer.java b/src/main/java/betterquesting/api2/utils/BqFontRenderer.java index 0cd6543d4..e61c515cd 100644 --- a/src/main/java/betterquesting/api2/utils/BqFontRenderer.java +++ b/src/main/java/betterquesting/api2/utils/BqFontRenderer.java @@ -29,7 +29,9 @@ public int drawString(@Nonnull String text, float x, float y, int color, boolean } public int drawStringScaled(String text, float x, float y, int color, boolean shadow, float scale) { - if (scale <= 0F) { return 0; } + if (scale <= 0F) { + return 0; + } Minecraft mc = Minecraft.getMinecraft(); @@ -53,19 +55,19 @@ public int drawStringScaled(String text, float x, float y, int color, boolean sh @Override protected float renderUnicodeChar(char ch, boolean italic) { - int i = this.glyphWidth[ch] & 255; + int i = glyphWidth[ch] & 255; if (i == 0) { return 0.0F; } else { int j = ch / 256; - this.loadGlyphTexture(j); + loadGlyphTexture(j); int k = i >>> 4; int l = i & 15; double f = k; double f1 = l + 1; double f2 = (double) (ch % 16 * 16) + f; - double f3 = (ch & 255) / 16 * 16; + double f3 = ((ch & 255) >> 4) * 16; double f4 = f1 - f - 0.02D; double f5 = italic ? 1.0D : 0.0D; double ys = 7.99D; @@ -86,13 +88,13 @@ protected float renderUnicodeChar(char ch, boolean italic) { GlStateManager.glBegin(GL11.GL_TRIANGLE_STRIP); GL11.glTexCoord2d(f2 / 256.0D, f3 / 256.0D); - GL11.glVertex3d(this.posX + f5, this.posY, 0.0D); + GL11.glVertex3d(posX + f5, posY, 0.0D); GL11.glTexCoord2d(f2 / 256.0D, (f3 + 15.98D) / 256.0D); - GL11.glVertex3d(this.posX - f5, this.posY + ys, 0.0D); + GL11.glVertex3d(posX - f5, posY + ys, 0.0D); GL11.glTexCoord2d((f2 + f4) / 256.0D, f3 / 256.0D); - GL11.glVertex3d(this.posX + f4 / 2.0D + f5, this.posY, 0.0D); + GL11.glVertex3d(posX + f4 / 2.0D + f5, posY, 0.0D); GL11.glTexCoord2d((f2 + f4) / 256.0D, (f3 + 15.98D) / 256.0D); - GL11.glVertex3d(this.posX + f4 / 2.0D - f5, this.posY + ys, 0.0D); + GL11.glVertex3d(posX + f4 / 2.0D - f5, posY + ys, 0.0D); GlStateManager.glEnd(); if (isSmall) { @@ -109,8 +111,8 @@ protected float renderDefaultChar(int ch, boolean italic) { int i = ch % 16 * 8; int j = ch / 16 * 8; int k = italic ? 1 : 0; - bindTexture(this.locationFontTexture); - int l = this.charWidth[ch]; + bindTexture(locationFontTexture); + int l = charWidth[ch]; float f = (float) l - 0.01F; if (isSmall) { @@ -120,13 +122,13 @@ protected float renderDefaultChar(int ch, boolean italic) { GlStateManager.glBegin(GL11.GL_TRIANGLE_STRIP); GlStateManager.glTexCoord2f((float) i / 128.0F, (float) j / 128.0F); - GlStateManager.glVertex3f(this.posX + (float) k, this.posY, 0.0F); + GlStateManager.glVertex3f(posX + (float) k, posY, 0.0F); GlStateManager.glTexCoord2f((float) i / 128.0F, ((float) j + 7.99F) / 128.0F); - GlStateManager.glVertex3f(this.posX - (float) k, this.posY + 7.99F, 0.0F); + GlStateManager.glVertex3f(posX - (float) k, posY + 7.99F, 0.0F); GlStateManager.glTexCoord2f(((float) i + f - 1.0F) / 128.0F, (float) j / 128.0F); - GlStateManager.glVertex3f(this.posX + f - 1.0F + (float) k, this.posY, 0.0F); + GlStateManager.glVertex3f(posX + f - 1.0F + (float) k, posY, 0.0F); GlStateManager.glTexCoord2f(((float) i + f - 1.0F) / 128.0F, ((float) j + 7.99F) / 128.0F); - GlStateManager.glVertex3f(this.posX + f - 1.0F - (float) k, this.posY + 7.99F, 0.0F); + GlStateManager.glVertex3f(posX + f - 1.0F - (float) k, posY + 7.99F, 0.0F); GlStateManager.glEnd(); if (isSmall) { @@ -146,7 +148,7 @@ private ResourceLocation getUnicodePageLocation(int page) { } private void loadGlyphTexture(int page) { - bindTexture(this.getUnicodePageLocation(page)); + bindTexture(getUnicodePageLocation(page)); } // Fixed version of vanilla @@ -162,7 +164,7 @@ public String trimStringToWidth(@Nonnull String text, int width, boolean reverse for (int l = j; l >= 0 && l < text.length() && i < width; l += k) { char c0 = text.charAt(l); - int i1 = this.getCharWidth(c0); + int i1 = getCharWidth(c0); if (flag) { flag = false; @@ -205,7 +207,7 @@ public int getStringWidth(String text) { for (int j = 0; j < text.length(); ++j) { char c0 = text.charAt(j); - int k = this.getCharWidth(c0); + int k = getCharWidth(c0); if (k < 0 && j < text.length() - 1) { ++j; diff --git a/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java b/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java index 7337f5f95..6632bfbe1 100644 --- a/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java +++ b/src/main/java/betterquesting/api2/utils/EntityPlayerPreview.java @@ -25,14 +25,14 @@ public EntityPlayerPreview(World worldIn) { public EntityPlayerPreview(World worldIn, GameProfile gameProfileIn) { super(worldIn, gameProfileIn); - this.resource = new ResourceLocation(BetterQuesting.MODID, "textures/skin_cache/" + gameProfileIn.getName()); - this.getDataManager().set(PLAYER_MODEL_FLAG, (byte) 1); + resource = new ResourceLocation(BetterQuesting.MODID, "textures/skin_cache/" + gameProfileIn.getName()); + getDataManager().set(PLAYER_MODEL_FLAG, (byte) 1); } @Nonnull @Override public ResourceLocation getLocationSkin() { - return this.resource; + return resource; } @Override diff --git a/src/main/java/betterquesting/api2/utils/ParticipantInfo.java b/src/main/java/betterquesting/api2/utils/ParticipantInfo.java index 49f6d8dcb..ab7961bf8 100644 --- a/src/main/java/betterquesting/api2/utils/ParticipantInfo.java +++ b/src/main/java/betterquesting/api2/utils/ParticipantInfo.java @@ -25,9 +25,9 @@ public class ParticipantInfo { public final DBEntry PARTY_INSTANCE; public ParticipantInfo(@Nonnull EntityPlayer player) { - this.PLAYER = player; - this.UUID = QuestingAPI.getQuestingUUID(player); - this.PARTY_INSTANCE = PartyManager.INSTANCE.getParty(this.UUID); + PLAYER = player; + UUID = QuestingAPI.getQuestingUUID(player); + PARTY_INSTANCE = PartyManager.INSTANCE.getParty(UUID); MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); @@ -53,24 +53,30 @@ public ParticipantInfo(@Nonnull EntityPlayer player) { } // Really shouldn't be modifying these lists anyway but just for safety - this.ACTIVE_PLAYERS = Collections.unmodifiableList(actPl); - this.ACTIVE_UUIDS = Collections.unmodifiableList(actID); - this.ALL_UUIDS = Collections.unmodifiableList(allID); + ACTIVE_PLAYERS = Collections.unmodifiableList(actPl); + ACTIVE_UUIDS = Collections.unmodifiableList(actID); + ALL_UUIDS = Collections.unmodifiableList(allID); } public void markDirty( @Nonnull List questIDs) // Only marks quests dirty for the immediate participating player { QuestCache qc = PLAYER.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (qc != null) { questIDs.forEach(qc::markQuestDirty); } + if (qc != null) { + questIDs.forEach(qc::markQuestDirty); + } } public void markDirtyParty(@Nonnull List questIDs) // Marks quests as dirty for the entire (active) party { - if (ACTIVE_PLAYERS.isEmpty() || questIDs.isEmpty()) { return; } + if (ACTIVE_PLAYERS.isEmpty() || questIDs.isEmpty()) { + return; + } ACTIVE_PLAYERS.forEach((value) -> { QuestCache qc = value.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (qc != null) { questIDs.forEach(qc::markQuestDirty); } + if (qc != null) { + questIDs.forEach(qc::markQuestDirty); + } }); } @@ -80,12 +86,18 @@ public int[] getSharedQuests() // Returns an array of all quests which one or mo TreeSet active = new TreeSet<>(); ACTIVE_PLAYERS.forEach((p) -> { QuestCache qc = p.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (qc != null) { for (int value : qc.getActiveQuests()) { active.add(value); } } + if (qc != null) { + for (int value : qc.getActiveQuests()) { + active.add(value); + } + } }); int[] shared = new int[active.size()]; int i = 0; - for (int value : active) { shared[i++] = value; } + for (int value : active) { + shared[i++] = value; + } return shared; } } diff --git a/src/main/java/betterquesting/api2/utils/QuestLineSorter.java b/src/main/java/betterquesting/api2/utils/QuestLineSorter.java index 658ae4652..e7fe458f2 100644 --- a/src/main/java/betterquesting/api2/utils/QuestLineSorter.java +++ b/src/main/java/betterquesting/api2/utils/QuestLineSorter.java @@ -10,7 +10,7 @@ public class QuestLineSorter implements Comparator> { private final IQuestLineDatabase QL_DB; public QuestLineSorter(IQuestLineDatabase database) { - this.QL_DB = database; + QL_DB = database; } @Override diff --git a/src/main/java/betterquesting/blocks/BlockSubmitStation.java b/src/main/java/betterquesting/blocks/BlockSubmitStation.java index 7fe7bca85..a915aba91 100644 --- a/src/main/java/betterquesting/blocks/BlockSubmitStation.java +++ b/src/main/java/betterquesting/blocks/BlockSubmitStation.java @@ -21,9 +21,9 @@ public class BlockSubmitStation extends BlockContainer { public BlockSubmitStation() { super(Material.WOOD); - this.setHardness(1); - this.setTranslationKey("betterquesting.submit_station"); - this.setCreativeTab(BetterQuesting.tabQuesting); + setHardness(1); + setTranslationKey("betterquesting.submit_station"); + setCreativeTab(BetterQuesting.tabQuesting); } @Override diff --git a/src/main/java/betterquesting/blocks/TileSubmitStation.java b/src/main/java/betterquesting/blocks/TileSubmitStation.java index 15608d17b..8a52a4c3a 100644 --- a/src/main/java/betterquesting/blocks/TileSubmitStation.java +++ b/src/main/java/betterquesting/blocks/TileSubmitStation.java @@ -67,7 +67,8 @@ public Tuple, T> getQuestTask(Class taskCla private void syncBlockState() { if (world.getMinecraftServer() != null) { IBlockState state = blockType.getStateFromMeta(getBlockMetadata()); - world.notifyBlockUpdate(pos, state, state, 2); //Per Forge documentation this is the proper way to cause block update. + world.notifyBlockUpdate(pos, state, state, + 2); //Per Forge documentation this is the proper way to cause block update. } } @@ -79,7 +80,7 @@ public void setupTask(UUID owner, int questID, int taskID) { this.questID = questID; this.taskID = taskID; this.owner = owner; - this.markDirty(); + markDirty(); } public boolean isSetup() { @@ -90,7 +91,7 @@ public void reset() { owner = null; questID = -1; taskID = -1; - this.markDirty(); + markDirty(); } @Nonnull @@ -117,7 +118,7 @@ public void readFromNBT(@Nonnull NBTTagCompound tags) { try { owner = UUID.fromString(tags.getString("owner")); } catch (Exception e) { - this.reset(); + reset(); return; } @@ -128,7 +129,7 @@ public void readFromNBT(@Nonnull NBTTagCompound tags) { // All data must be present for this to run correctly if (!isSetup()) { - this.reset(); + reset(); } } @@ -223,7 +224,7 @@ public int getInventoryStackLimit() { @Override public boolean isUsableByPlayer(@Nonnull EntityPlayer player) { - return (owner == null || player.getUniqueID().equals(owner)) && player.getDistanceSq(this.pos) < 256; + return (owner == null || player.getUniqueID().equals(owner)) && player.getDistanceSq(pos) < 256; } @Override diff --git a/src/main/java/betterquesting/client/CreativeTabQuesting.java b/src/main/java/betterquesting/client/CreativeTabQuesting.java index 871beba2e..fb3f1e28a 100644 --- a/src/main/java/betterquesting/client/CreativeTabQuesting.java +++ b/src/main/java/betterquesting/client/CreativeTabQuesting.java @@ -17,7 +17,7 @@ public CreativeTabQuesting() { @Override public ItemStack createIcon() { if (tabStack == null) { - this.tabStack = new ItemStack(BetterQuesting.extraLife); + tabStack = new ItemStack(BetterQuesting.extraLife); } return tabStack; diff --git a/src/main/java/betterquesting/client/QuestNotification.java b/src/main/java/betterquesting/client/QuestNotification.java index e21cb804a..96bbe4938 100644 --- a/src/main/java/betterquesting/client/QuestNotification.java +++ b/src/main/java/betterquesting/client/QuestNotification.java @@ -27,7 +27,9 @@ @SideOnly(Side.CLIENT) public class QuestNotification { public static void ScheduleNotice(String mainTxt, String subTxt, ItemStack icon, String sound) { - if (BQ_Settings.questNotices) { notices.add(new QuestNotice(mainTxt, subTxt, icon, sound)); } + if (BQ_Settings.questNotices) { + notices.add(new QuestNotice(mainTxt, subTxt, icon, sound)); + } } private static final List notices = new ArrayList<>(); @@ -38,8 +40,12 @@ public static void resetNotices() { @SubscribeEvent public void onDrawScreen(RenderGameOverlayEvent.Post event) { - if (event.getType() != ElementType.ALL) { return; } - if (notices.isEmpty()) { return; } + if (event.getType() != ElementType.ALL) { + return; + } + if (notices.isEmpty()) { + return; + } if (notices.size() >= 20 || !BQ_Settings.questNotices) { notices.clear(); @@ -110,7 +116,7 @@ public static class QuestNotice { private final String sound; public QuestNotice(String mainTxt, String subTxt, ItemStack icon, String sound) { - this.startTime = Minecraft.getSystemTime(); + startTime = Minecraft.getSystemTime(); this.mainTxt = mainTxt; this.subTxt = subTxt; this.icon = icon; diff --git a/src/main/java/betterquesting/client/gui2/GuiHome.java b/src/main/java/betterquesting/client/gui2/GuiHome.java index 4544dd2b8..574b816e3 100644 --- a/src/main/java/betterquesting/client/gui2/GuiHome.java +++ b/src/main/java/betterquesting/client/gui2/GuiHome.java @@ -78,7 +78,7 @@ public void initPanel() { // Background panel CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(bgCan); + addPanel(bgCan); // Inner canvas bounds CanvasEmpty inCan = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0)); @@ -139,14 +139,16 @@ public void onButtonClick() { } private void onButtonPress(PanelEvent event) { - if (!(event instanceof PEventButton)) { return; } + if (!(event instanceof PEventButton)) { + return; + } Minecraft mc = Minecraft.getMinecraft(); IPanelButton btn = ((PEventButton) event).getButton(); if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1) // Quests { mc.displayGuiScreen(new GuiQuestLines(this)); diff --git a/src/main/java/betterquesting/client/gui2/GuiQuest.java b/src/main/java/betterquesting/client/gui2/GuiQuest.java index c93b62e2e..6beadb6d9 100644 --- a/src/main/java/betterquesting/client/gui2/GuiQuest.java +++ b/src/main/java/betterquesting/client/gui2/GuiQuest.java @@ -71,10 +71,10 @@ public GuiQuest(GuiScreen parent, int questID) { public void initPanel() { super.initPanel(); - this.quest = QuestDatabase.INSTANCE.getValue(questID); + quest = QuestDatabase.INSTANCE.getValue(questID); if (quest == null) { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); return; } @@ -83,7 +83,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate( @@ -203,15 +203,15 @@ public void initPanel() { @Override public void refreshGui() { - this.refreshTaskPanel(); - this.refreshRewardPanel(); - this.updateButtons(); + refreshTaskPanel(); + refreshRewardPanel(); + updateButtons(); } @Override public boolean onMouseClick(int mx, int my, int click) { if (super.onMouseClick(mx, my, click)) { - this.updateButtons(); + updateButtons(); return true; } @@ -221,7 +221,7 @@ public boolean onMouseClick(int mx, int my, int click) { @Override public boolean onMouseScroll(int mx, int my, int scroll) { if (super.onMouseScroll(mx, my, scroll)) { - this.updateButtons(); + updateButtons(); return true; } @@ -231,7 +231,7 @@ public boolean onMouseScroll(int mx, int my, int scroll) { @Override public boolean onKeyTyped(char c, int keycode) { if (super.onKeyTyped(c, keycode)) { - this.updateButtons(); + updateButtons(); return true; } @@ -250,7 +250,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1) // Edit { mc.displayGuiScreen(new GuiQuestEditor(this, questID)); @@ -293,7 +293,7 @@ private void refreshRewardPanel() { return; } else if (rectReward == null) { - this.initPanel(); + initPanel(); return; } diff --git a/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java b/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java index 8e3be6c26..1f40f0ece 100644 --- a/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java +++ b/src/main/java/betterquesting/client/gui2/GuiQuestHelp.java @@ -30,7 +30,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("item.betterquesting.guide.name")).setAlignment( diff --git a/src/main/java/betterquesting/client/gui2/GuiQuestLines.java b/src/main/java/betterquesting/client/gui2/GuiQuestLines.java index 6dd24d331..863d9e206 100644 --- a/src/main/java/betterquesting/client/gui2/GuiQuestLines.java +++ b/src/main/java/betterquesting/client/gui2/GuiQuestLines.java @@ -96,20 +96,24 @@ public void initPanel() { if (selectedLineId >= 0) { selectedLine = QuestLineDatabase.INSTANCE.getValue(selectedLineId); - if (selectedLine == null) { selectedLineId = -1; } + if (selectedLine == null) { + selectedLineId = -1; + } } else { selectedLine = null; } boolean canEdit = QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player); boolean preOpen = trayLock && cvChapterTray != null && cvChapterTray.isTrayOpen(); - if (trayLock && cvDescTray != null && cvDescTray.isTrayOpen()) { preOpen = true; } + if (trayLock && cvDescTray != null && cvDescTray.isTrayOpen()) { + preOpen = true; + } PEventBroadcaster.INSTANCE.register(this, PEventButton.class); CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelButton btnExit = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 8, -24, 32, 16, 0), -1, "").setIcon( PresetIcon.ICON_PG_PREV.getTexture()); @@ -221,7 +225,9 @@ public void initPanel() { PanelButton fitView = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 72, 32, 16, -2), 5, ""); fitView.setIcon(PresetIcon.ICON_BOX_FIT.getTexture()); fitView.setClickAction((b) -> { - if (cvQuest.getQuestLine() != null) { cvQuest.fitToWindow(); } + if (cvQuest.getQuestLine() != null) { + cvQuest.fitToWindow(); + } }); fitView.setTooltip(Collections.singletonList(QuestTranslation.translate("betterquesting.btn.zoom_fit"))); cvBackground.addPanel(fitView); @@ -229,11 +235,15 @@ public void initPanel() { claimAll = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 8, 56, 32, 16, -2), -1, ""); claimAll.setIcon(PresetIcon.ICON_CHEST_ALL.getTexture()); claimAll.setClickAction((b) -> { - if (cvQuest.getQuestButtons().isEmpty()) { return; } + if (cvQuest.getQuestButtons().isEmpty()) { + return; + } List claimIdList = new ArrayList<>(); for (PanelButtonQuest pbQuest : cvQuest.getQuestButtons()) { IQuest q = pbQuest.getStoredValue().getValue(); - if (q.getRewards().size() > 0 && q.canClaim(mc.player)) { claimIdList.add(pbQuest.getStoredValue().getID()); } + if (q.getRewards().size() > 0 && q.canClaim(mc.player)) { + claimIdList.add(pbQuest.getStoredValue().getID()); + } } int[] cIDs = new int[claimIdList.size()]; @@ -312,13 +322,15 @@ private void onButtonPress(PEventButton event) { private void refreshChapterVisibility() { boolean canEdit = QuestingAPI.getAPI(ApiReference.SETTINGS).canUserEdit(mc.player); List> lineList = QuestLineDatabase.INSTANCE.getSortedEntries(); - this.visChapters.clear(); + visChapters.clear(); UUID playerID = QuestingAPI.getQuestingUUID(mc.player); for (DBEntry dbEntry : lineList) { IQuestLine ql = dbEntry.getValue(); EnumQuestVisibility vis = ql.getProperty(NativeProps.VISIBILITY); - if (!canEdit && vis == EnumQuestVisibility.HIDDEN) { continue; } + if (!canEdit && vis == EnumQuestVisibility.HIDDEN) { + continue; + } boolean show = false; boolean unlocked = false; @@ -334,14 +346,28 @@ private void refreshChapterVisibility() { for (DBEntry qID : ql.getEntries()) { IQuest q = QuestDatabase.INSTANCE.getValue(qID.getID()); - if (q == null) { continue; } - - if (allComplete && !q.isComplete(playerID)) { allComplete = false; } - if (!pendingClaim && q.isComplete(playerID) && !q.hasClaimed(playerID)) { pendingClaim = true; } - if (!unlocked && q.isUnlocked(playerID)) { unlocked = true; } - if (!complete && q.isComplete(playerID)) { complete = true; } - if (!show && QuestCache.isQuestShown(q, playerID, mc.player)) { show = true; } - if (unlocked && complete && show && pendingClaim && !allComplete) { break; } + if (q == null) { + continue; + } + + if (allComplete && !q.isComplete(playerID)) { + allComplete = false; + } + if (!pendingClaim && q.isComplete(playerID) && !q.hasClaimed(playerID)) { + pendingClaim = true; + } + if (!unlocked && q.isUnlocked(playerID)) { + unlocked = true; + } + if (!complete && q.isComplete(playerID)) { + complete = true; + } + if (!show && QuestCache.isQuestShown(q, playerID, mc.player)) { + show = true; + } + if (unlocked && complete && show && pendingClaim && !allComplete) { + break; + } } if (vis == EnumQuestVisibility.COMPLETED && !complete) { @@ -351,13 +377,19 @@ private void refreshChapterVisibility() { } int val = pendingClaim ? 1 : 0; - if (allComplete) { val |= 2; } - if (!show) { val |= 4; } + if (allComplete) { + val |= 2; + } + if (!show) { + val |= 4; + } visChapters.add(new Tuple<>(dbEntry, val)); } - if (cvChapterTray.isTrayOpen()) { buildChapterList(); } + if (cvChapterTray.isTrayOpen()) { + buildChapterList(); + } } private void buildChapterList() { @@ -389,7 +421,11 @@ private void buildChapterList() { btnLine.setTextAlignment(0); btnLine.setActive((vis & 4) == 0 && entry.getID() != selectedLineId); btnLine.setCallback((q) -> { - btnListRef.forEach((b) -> { if (b.getStoredValue().getID() == selectedLineId) { b.setActive(true); } }); + btnListRef.forEach((b) -> { + if (b.getStoredValue().getID() == selectedLineId) { + b.setActive(true); + } + }); btnLine.setActive(false); selectedLine = q.getValue(); selectedLineId = q.getID(); @@ -414,7 +450,9 @@ private void buildChapterList() { private void refreshContent() { if (selectedLineId >= 0) { selectedLine = QuestLineDatabase.INSTANCE.getValue(selectedLineId); - if (selectedLine == null) { selectedLineId = -1; } + if (selectedLine == null) { + selectedLineId = -1; + } } else { selectedLine = null; } diff --git a/src/main/java/betterquesting/client/gui2/GuiThemes.java b/src/main/java/betterquesting/client/gui2/GuiThemes.java index ab55a0437..b752fc777 100644 --- a/src/main/java/betterquesting/client/gui2/GuiThemes.java +++ b/src/main/java/betterquesting/client/gui2/GuiThemes.java @@ -50,7 +50,7 @@ public void initPanel() { // Background panel CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(bgCan); + addPanel(bgCan); // Inner canvas bounds CanvasEmpty inCan = new CanvasEmpty(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(16, 16, 16, 16), 0)); @@ -85,7 +85,7 @@ public void initPanel() { pbs.setCallback((res) -> { float scroll = scrollPanel.readValueRaw(); ThemeRegistry.INSTANCE.setTheme(res); - this.initGui(); + initGui(); scrollPanel.writeValueRaw(scroll); }); canScroll.addPanel(pbs); diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java b/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java index e782ec515..1128e19e4 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiFileBrowser.java @@ -49,7 +49,7 @@ public class GuiFileBrowser extends GuiScreenCanvas implements IPEventListener { public GuiFileBrowser(GuiScreen parent, ICallback callback, File directory, @Nullable FileFilter filter) { super(parent); this.callback = callback; - this.curDirectory = directory == null ? null : directory.getAbsoluteFile(); + curDirectory = directory == null ? null : directory.getAbsoluteFile(); this.filter = filter; } @@ -68,7 +68,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); txtTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), curDirectory == null ? "*" : curDirectory.getAbsolutePath()).setAlignment(1); @@ -123,16 +123,18 @@ protected boolean addResult(File entry, int index, int width) { btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); btnAdd.setActive(!selList.contains(entry)); btnAdd.setCallback(value -> { - if (!multiSelect) { selList.clear(); } + if (!multiSelect) { + selList.clear(); + } selList.add(value); refreshSelected(); refreshSearch(); }); - this.addPanel(btnAdd); + addPanel(btnAdd); } else { // Keeps the scrolling region's left side from auto-cropping when no files are present to select. PanelGeneric pnDummy = new PanelGeneric(new GuiRectangle(0, index * 16, 16, 16, 0), null); - this.addPanel(pnDummy); + addPanel(pnDummy); } PanelButtonStorage btnEdit = @@ -141,15 +143,15 @@ protected boolean addResult(File entry, int index, int width) { btnEdit.setActive(entry.isDirectory()); btnEdit.setCallback(value -> { curDirectory = value; - this.setCurDirectory(curDirectory); + setCurDirectory(curDirectory); txtTitle.setText(curDirectory == null ? "*" : curDirectory.getAbsolutePath()); }); - this.addPanel(btnEdit); + addPanel(btnEdit); PanelGeneric pnIco = new PanelGeneric(new GuiRectangle(width - 16, index * 16, 16, 16, 0), entry.isDirectory() ? PresetIcon.ICON_FOLDER_OPEN.getTexture() : PresetIcon.ICON_FILE.getTexture()); - this.addPanel(pnIco); + addPanel(pnIco); return true; } @@ -159,7 +161,9 @@ protected boolean addResult(File entry, int index, int width) { PanelButton selAll = new PanelButton(new GuiTransform(GuiAlign.TOP_RIGHT, -24, 16, 16, 16, 0), -1, "") { @Override public void onButtonClick() { - if (!multiSelect) { return; } + if (!multiSelect) { + return; + } boolean changed = false; for (File file : cvDirectory.getResults()) { @@ -189,7 +193,9 @@ public void onButtonClick() { PanelButton btnNew = new PanelButton(new GuiTransform(GuiAlign.TOP_LEFT, 0, 16, 16, 16, 0), -1, "") { @Override public void onButtonClick() { - if (curDirectory == null) { return; } + if (curDirectory == null) { + return; + } curDirectory = curDirectory.getParentFile(); cvDirectory.setCurDirectory(curDirectory); txtTitle.setText(curDirectory == null ? "*" : curDirectory.getAbsolutePath()); @@ -222,8 +228,10 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - if (callback != null) { callback.setValue(selList.toArray(new File[0])); } - mc.displayGuiScreen(this.parent); + if (callback != null) { + callback.setValue(selList.toArray(new File[0])); + } + mc.displayGuiScreen(parent); } } diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java b/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java index 0117b51aa..189506f40 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiImporters.java @@ -52,7 +52,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.importers")).setAlignment( @@ -135,7 +135,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1) // Select { IImporter imp = ((PanelButtonStorage) btn).getStoredValue(); diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java index 580c717e0..179fe9457 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiPrerequisiteEditor.java @@ -49,7 +49,7 @@ public class GuiPrerequisiteEditor extends GuiScreenCanvas implements IPEventLis public GuiPrerequisiteEditor(GuiScreen parent, IQuest quest) { super(parent); this.quest = quest; - this.questID = QuestDatabase.INSTANCE.getID(quest); + questID = QuestDatabase.INSTANCE.getID(quest); } @Override @@ -75,7 +75,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate( @@ -110,17 +110,17 @@ protected boolean addResult(DBEntry entry, int index, int width) { new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), 2, "", entry); btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); btnAdd.setActive(!containsReq(quest, entry.getID())); - this.addPanel(btnAdd); + addPanel(btnAdd); PanelButtonStorage> btnEdit = new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), 1, QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)), entry); - this.addPanel(btnEdit); + addPanel(btnEdit); PanelButtonStorage> btnDel = new PanelButtonStorage<>(new GuiRectangle(width - 16, index * 16, 16, 16, 0), 4, "", entry); btnDel.setIcon(PresetIcon.ICON_TRASH.getTexture()); - this.addPanel(btnDel); + addPanel(btnDel); return true; } @@ -200,7 +200,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Edit Quest { DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); @@ -235,29 +235,41 @@ private void onButtonPress(PEventButton event) { } private boolean containsReq(IQuest quest, int id) { - for (int reqID : quest.getRequirements()) { if (id == reqID) { return true; } } + for (int reqID : quest.getRequirements()) { + if (id == reqID) { + return true; + } + } return false; } private void removeReq(IQuest quest, int id) { int[] orig = quest.getRequirements(); - if (orig.length == 0) { return; } + if (orig.length == 0) { + return; + } boolean hasRemoved = false; int[] rem = new int[orig.length - 1]; for (int i = 0; i < orig.length; i++) { if (!hasRemoved && orig[i] == id) { hasRemoved = true; continue; - } else if (!hasRemoved && i >= rem.length) { break; } + } else if (!hasRemoved && i >= rem.length) { + break; + } rem[!hasRemoved ? i : (i - 1)] = orig[i]; } - if (hasRemoved) { quest.setRequirements(rem); } + if (hasRemoved) { + quest.setRequirements(rem); + } } private void addReq(IQuest quest, int id) { - if (containsReq(quest, id)) { return; } + if (containsReq(quest, id)) { + return; + } int[] orig = quest.getRequirements(); int[] added = Arrays.copyOf(orig, orig.length + 1); added[orig.length] = id; diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java index 9e406656c..b6cbd80ed 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiQuestEditor.java @@ -53,12 +53,16 @@ public void refreshGui() { quest = QuestDatabase.INSTANCE.getValue(questID); if (quest == null) { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else { pnTitle.setText(QuestTranslation.translate("betterquesting.title.edit_quest", QuestTranslation.translate(quest.getProperty(NativeProps.NAME)))); - if (!flName.isFocused()) { flName.setText(quest.getProperty(NativeProps.NAME)); } - if (!flDesc.isFocused()) { flDesc.setText(quest.getProperty(NativeProps.DESC)); } + if (!flName.isFocused()) { + flName.setText(quest.getProperty(NativeProps.NAME)); + } + if (!flDesc.isFocused()) { + flDesc.setText(quest.getProperty(NativeProps.DESC)); + } btnLogic.setText( QuestTranslation.translate("betterquesting.btn.logic") + ": " + quest.getProperty(NativeProps.LOGIC_QUEST)); btnVis.setText( @@ -73,7 +77,7 @@ public void initPanel() { quest = QuestDatabase.INSTANCE.getValue(questID); if (quest == null) { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); return; } @@ -83,7 +87,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); pnTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_quest", QuestTranslation.translate( @@ -188,7 +192,7 @@ private void onButtonPress(PEventButton event) { switch (btn.getButtonID()) { case 0: // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); break; } case 1: // Edit tasks diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java index c2f08b7a3..5489103a6 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLineAddRemove.java @@ -55,14 +55,16 @@ public class GuiQuestLineAddRemove extends GuiScreenCanvas implements IPEventLis public GuiQuestLineAddRemove(GuiScreen parent, @Nullable IQuestLine questLine) { super(parent); this.questLine = questLine; - this.lineID = QuestLineDatabase.INSTANCE.getID(questLine); + lineID = QuestLineDatabase.INSTANCE.getID(questLine); } @Override public void refreshGui() { questLine = lineID < 0 ? null : QuestLineDatabase.INSTANCE.getValue(lineID); canvasDB.refreshSearch(); - if (questLine != null) { refreshQuestList(); } + if (questLine != null) { + refreshQuestList(); + } } @Override @@ -75,7 +77,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_line2", @@ -133,17 +135,17 @@ protected boolean addResult(DBEntry entry, int index, int width) { new PanelButtonStorage<>(new GuiRectangle(0, index * 16, 16, 16, 0), 2, "", entry); btnAdd.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); btnAdd.setActive(questLine != null && questLine.getValue(entry.getID()) == null); - this.addPanel(btnAdd); + addPanel(btnAdd); PanelButtonStorage> btnEdit = new PanelButtonStorage<>(new GuiRectangle(16, index * 16, width - 32, 16, 0), 1, QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME)), entry); - this.addPanel(btnEdit); + addPanel(btnEdit); PanelButtonStorage> btnDel = new PanelButtonStorage<>(new GuiRectangle(width - 16, index * 16, 16, 16, 0), 4, "", entry); btnDel.setIcon(PresetIcon.ICON_TRASH.getTexture()); - this.addPanel(btnDel); + addPanel(btnDel); return true; } @@ -186,7 +188,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1) // Edit { DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); @@ -287,7 +289,9 @@ private void refreshQuestList() { } private void SendChanges() { - if (questLine == null) { return; } + if (questLine == null) { + return; + } NBTTagCompound payload = new NBTTagCompound(); NBTTagList dataList = new NBTTagList(); diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java index ef469956b..9bb061241 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiQuestLinesEditor.java @@ -74,8 +74,12 @@ public void refreshGui() { btnVis.setActive(true); btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + selected.getProperty(NativeProps.VISIBILITY)); - if (!tfName.isFocused()) { tfName.setText(selected.getUnlocalisedName()); } - if (!tfDesc.isFocused()) { tfDesc.setText(selected.getUnlocalisedDescription()); } + if (!tfName.isFocused()) { + tfName.setText(selected.getUnlocalisedName()); + } + if (!tfDesc.isFocused()) { + tfDesc.setText(selected.getUnlocalisedDescription()); + } } } @@ -92,7 +96,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_line1")).setAlignment( @@ -151,7 +155,9 @@ public void initPanel() { QuestTranslation.translate("betterquesting.btn.icon")) { @Override public void onButtonClick() { - if (selected == null) { return; } + if (selected == null) { + return; + } mc.displayGuiScreen( new GuiItemSelection(GuiQuestLinesEditor.this, selected.getProperty(NativeProps.ICON), value -> { selected.setProperty(NativeProps.ICON, value); @@ -168,12 +174,14 @@ public void onButtonClick() { : selected.getProperty(NativeProps.VISIBILITY))) { @Override public void onButtonClick() { - if (selected == null) { return; } + if (selected == null) { + return; + } EnumQuestVisibility[] visList = EnumQuestVisibility.values(); EnumQuestVisibility vis = selected.getProperty(NativeProps.VISIBILITY); vis = visList[(vis.ordinal() + 1) % visList.length]; selected.setProperty(NativeProps.VISIBILITY, vis); - this.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + vis); + setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + vis); } }; btnVis.setActive(selected != null); @@ -218,8 +226,12 @@ public void onButtonClick() { btnVis.setActive(true); btnVis.setText(QuestTranslation.translate("betterquesting.btn.show") + ": " + selected.getProperty(NativeProps.VISIBILITY)); - if (!tfName.isFocused()) { tfName.setText(selected.getUnlocalisedName()); } - if (!tfDesc.isFocused()) { tfDesc.setText(selected.getUnlocalisedDescription()); } + if (!tfName.isFocused()) { + tfName.setText(selected.getUnlocalisedName()); + } + if (!tfDesc.isFocused()) { + tfDesc.setText(selected.getUnlocalisedDescription()); + } } } @@ -262,7 +274,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1) // New Quest Line { NBTTagCompound payload = new NBTTagCompound(); @@ -308,7 +320,9 @@ private void onButtonPress(PEventButton event) { { DBEntry entry = ((PanelButtonStorage>) btn).getStoredValue(); int order = QuestLineDatabase.INSTANCE.getOrderIndex(entry.getID()); - if (order > 0) { SendReorder(order); } + if (order > 0) { + SendReorder(order); + } } else if (btn.getButtonID() == 8) // Big Description Editor { mc.displayGuiScreen(new GuiTextEditor(this, tfDesc.getRawText(), value -> { @@ -357,9 +371,13 @@ private void SendChanges(DBEntry chapter) { } private void SendReorder(int indexToShift) { - if (indexToShift <= 0) { return; } + if (indexToShift <= 0) { + return; + } List> entries = QuestLineDatabase.INSTANCE.getSortedEntries(); - if (indexToShift >= entries.size()) { return; } + if (indexToShift >= entries.size()) { + return; + } int[] chapterIDs = new int[entries.size()]; for (int i = 0; i < entries.size(); i++) { chapterIDs[i] = entries.get(i).getID(); diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java index c898586e2..6d3776887 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiRewardEditor.java @@ -52,7 +52,7 @@ public GuiRewardEditor(GuiScreen parent, IQuest quest) { super(parent); this.quest = quest; - this.qID = QuestDatabase.INSTANCE.getID(quest); + qID = QuestDatabase.INSTANCE.getID(quest); } @Override @@ -60,7 +60,7 @@ public void refreshGui() { quest = QuestDatabase.INSTANCE.getValue(qID); if (quest == null) { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); return; } @@ -72,7 +72,7 @@ public void initPanel() { super.initPanel(); if (qID < 0) { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); return; } @@ -81,7 +81,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate( @@ -105,13 +105,15 @@ protected Iterator> getIterator() { @Override protected void queryMatches(IFactoryData value, String query, ArrayDeque> results) { - if (value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) { results.add(value); } + if (value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) { + results.add(value); + } } @Override protected boolean addResult(IFactoryData entry, int index, int cachedWidth) { - this.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, - entry.getRegistryName().toString(), entry)); + addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, + entry.getRegistryName().toString(), entry)); return true; } }; @@ -163,7 +165,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Add { IFactoryData fact = diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java index f9d1e2733..3ed2cd98d 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiTaskEditor.java @@ -52,7 +52,7 @@ public GuiTaskEditor(GuiScreen parent, IQuest quest) { super(parent); this.quest = quest; - this.qID = QuestDatabase.INSTANCE.getID(quest); + qID = QuestDatabase.INSTANCE.getID(quest); } @Override @@ -60,7 +60,7 @@ public void refreshGui() { quest = QuestDatabase.INSTANCE.getValue(qID); if (quest == null) { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); return; } @@ -72,7 +72,7 @@ public void initPanel() { super.initPanel(); if (qID < 0) { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); return; } @@ -81,7 +81,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.edit_tasks")).setAlignment( @@ -105,13 +105,15 @@ protected Iterator> getIterator() { @Override protected void queryMatches(IFactoryData value, String query, ArrayDeque> results) { - if (value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) { results.add(value); } + if (value.getRegistryName().toString().toLowerCase().contains(query.toLowerCase())) { + results.add(value); + } } @Override protected boolean addResult(IFactoryData entry, int index, int cachedWidth) { - this.addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, - entry.getRegistryName().toString(), entry)); + addPanel(new PanelButtonStorage<>(new GuiRectangle(0, index * 16, cachedWidth, 16, 0), 1, + entry.getRegistryName().toString(), entry)); return true; } }; @@ -163,7 +165,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) // Add { IFactoryData fact = diff --git a/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java b/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java index c285feec7..eee0ac567 100644 --- a/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/GuiTextEditor.java @@ -50,7 +50,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); @@ -100,7 +100,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { String format = ((PanelButtonStorage) btn).getStoredValue(); flText.writeText(format); diff --git a/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java b/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java index e50fa0f6b..c3886878a 100644 --- a/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java +++ b/src/main/java/betterquesting/client/gui2/editors/designer/GuiDesigner.java @@ -50,14 +50,14 @@ public class GuiDesigner extends GuiScreenCanvas implements IVolatileScreen, INe public GuiDesigner(GuiScreen parent, IQuestLine line) { super(parent); - this.questLine = line; - this.lineID = QuestLineDatabase.INSTANCE.getID(line); - this.tabList.addAll(ToolboxRegistry.INSTANCE.getAllTabs()); + questLine = line; + lineID = QuestLineDatabase.INSTANCE.getID(line); + tabList.addAll(ToolboxRegistry.INSTANCE.getAllTabs()); } @Override public void refreshGui() { - this.questLine = QuestLineDatabase.INSTANCE.getValue(lineID); + questLine = QuestLineDatabase.INSTANCE.getValue(lineID); if (questLine == null) { mc.displayGuiScreen(parent); @@ -86,11 +86,11 @@ public void initPanel() { CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 96, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvTray = new CanvasTextured(new GuiTransform(GuiAlign.RIGHT_EDGE, new GuiPadding(-96, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvTray); + addPanel(cvTray); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); @@ -148,10 +148,18 @@ public void onButtonClick() { } private void refreshToolTab() { - if (lastTabPanel != null) { cvTray.removePanel(lastTabPanel); } + if (lastTabPanel != null) { + cvTray.removePanel(lastTabPanel); + } - if (tabList.isEmpty()) { return; } - if (tabIdx < 0) { while (tabIdx < 0) { tabIdx += tabList.size(); } } + if (tabList.isEmpty()) { + return; + } + if (tabIdx < 0) { + while (tabIdx < 0) { + tabIdx += tabList.size(); + } + } tabIdx %= tabList.size(); lastTabPanel = tabList.get(tabIdx) @@ -159,7 +167,9 @@ private void refreshToolTab() { toolController); tabTitle.setText(QuestTranslation.translate(tabList.get(tabIdx).getUnlocalisedName())); - if (lastTabPanel != null) { cvTray.addPanel(lastTabPanel); } + if (lastTabPanel != null) { + cvTray.addPanel(lastTabPanel); + } } @Override @@ -174,7 +184,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } } } diff --git a/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java b/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java index 344fc31e9..81d099aa3 100644 --- a/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java +++ b/src/main/java/betterquesting/client/gui2/editors/designer/PanelToolController.java @@ -46,16 +46,16 @@ public class PanelToolController implements IGuiPanel { private final IGuiTexture hTex = new ColorTexture(new GuiColorPulse(0x22FFFFFF, 0x77FFFFFF, 2F, 0F)); public PanelToolController(IGuiRect rect, CanvasQuestLine questLine) { - this.transform = rect; + transform = rect; this.questLine = questLine; scDriverX = new FloatSimpleIO() { @Override public void writeValue(Float value) { if (activeTool != null && !activeTool.clampScrolling()) { - this.v = value; + v = value; } else { - this.v = MathHelper.clamp(value, 0F, 1F); + v = MathHelper.clamp(value, 0F, 1F); } } }.setLerp(true, 0.02F); @@ -64,28 +64,32 @@ public void writeValue(Float value) { @Override public void writeValue(Float value) { if (activeTool != null && !activeTool.clampScrolling()) { - this.v = value; + v = value; } else { - this.v = MathHelper.clamp(value, 0F, 1F); + v = MathHelper.clamp(value, 0F, 1F); } } }.setLerp(true, 0.02F); } public void setActiveTool(IToolboxTool tool) { - if (this.activeTool != null) { activeTool.disableTool(); } - if (tool == null) { return; } + if (activeTool != null) { + activeTool.disableTool(); + } + if (tool == null) { + return; + } activeTool = tool; tool.initTool(questLine); } public IToolboxTool getActiveTool() { - return this.activeTool; + return activeTool; } public void changeCanvas(@Nonnull CanvasQuestLine canvas) { - this.questLine = canvas; + questLine = canvas; refreshCanvas(); setActiveTool(getActiveTool()); } @@ -108,17 +112,17 @@ public void refreshCanvas() { highlights.add(new PanelGeneric(btn.rect, hTex)); } - if (this.activeTool != null) { - activeTool.refresh(this.questLine); + if (activeTool != null) { + activeTool.refresh(questLine); } } public IValueIO getScrollX() { - return this.scDriverX; + return scDriverX; } public IValueIO getScrollY() { - return this.scDriverY; + return scDriverY; } @Override @@ -127,12 +131,11 @@ public IGuiRect getTransform() { } @Override - public void initPanel() { - } + public void initPanel() { } @Override public void setEnabled(boolean state) { - this.enabled = state; + enabled = state; } @Override @@ -142,7 +145,9 @@ public boolean isEnabled() { @Override public void drawPanel(int mx, int my, float partialTick) { - if (!enabled) { return; } + if (!enabled) { + return; + } if (activeTool != null) { float zs = questLine.getZoom(); @@ -166,7 +171,9 @@ public void drawPanel(int mx, int my, float partialTick) { selLine.drawLine(selBounds, selBounds, 2, selCol, partialTick); } - for (IGuiPanel pn : highlights) { pn.drawPanel(smx, smy, partialTick); } + for (IGuiPanel pn : highlights) { + pn.drawPanel(smx, smy, partialTick); + } // Pretending we're on the scrolling canvas (when we're really not) so as not to influence it by hotswapping panels activeTool.drawCanvas(smx, smy, partialTick); @@ -180,8 +187,10 @@ public void drawPanel(int mx, int my, float partialTick) { @Override public boolean onMouseClick(int mx, int my, int button) { - if (activeTool != null && this.getTransform().contains(mx, my)) { - if (activeTool.onMouseClick(mx, my, button)) { return true; } + if (activeTool != null && getTransform().contains(mx, my)) { + if (activeTool.onMouseClick(mx, my, button)) { + return true; + } if (activeTool.useSelection()) { if (button == 1) { selBounds = null; @@ -223,7 +232,9 @@ public boolean onMouseRelease(int mx, int my, int button) { boolean append = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); boolean subtract = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); - if (!append && !subtract) { selected.clear(); } + if (!append && !subtract) { + selected.clear(); + } for (PanelButtonQuest btn : questLine.getQuestButtons()) { if (selBounds.contains(btn.rect.x + btn.rect.w / 2, btn.rect.y + btn.rect.h / 2) || @@ -232,32 +243,44 @@ public boolean onMouseRelease(int mx, int my, int button) { selected.remove(btn); continue; } - if (append && selected.contains(btn)) { continue; } + if (append && selected.contains(btn)) { + continue; + } selected.add(btn); } } highlights.clear(); - for (PanelButtonQuest btn : selected) { highlights.add(new PanelGeneric(btn.rect, hTex)); } + for (PanelButtonQuest btn : selected) { + highlights.add(new PanelGeneric(btn.rect, hTex)); + } selBounds = null; - if (activeTool != null) { activeTool.onSelection(selected); } + if (activeTool != null) { + activeTool.onSelection(selected); + } } - if (activeTool != null) { return activeTool.onMouseRelease(mx, my, button); } + if (activeTool != null) { + return activeTool.onMouseRelease(mx, my, button); + } return false; } @Override public boolean onMouseScroll(int mx, int my, int scroll) { - if (activeTool != null) { return activeTool.onMouseScroll(mx, my, scroll); } + if (activeTool != null) { + return activeTool.onMouseScroll(mx, my, scroll); + } return false; } @Override public boolean onKeyTyped(char c, int keycode) { if (activeTool != null) { - if (activeTool.onKeyPressed(c, keycode)) { return true; } + if (activeTool.onKeyPressed(c, keycode)) { + return true; + } if (activeTool.useSelection() && keycode == Keyboard.KEY_A) { boolean append = Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL); boolean subtract = @@ -289,8 +312,12 @@ public boolean onKeyTyped(char c, int keycode) { @Override public List getTooltip(int mx, int my) { - if (selBounds != null) { return Collections.emptyList(); } - if (activeTool != null) { return activeTool.getTooltip(mx, my); } + if (selBounds != null) { + return Collections.emptyList(); + } + if (activeTool != null) { + return activeTool.getTooltip(mx, my); + } return null; } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java index 8a81e73b5..bf9773218 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiEntitySelection.java @@ -50,7 +50,7 @@ public GuiEntitySelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) { super(parent); - this.selEntity = entity; + selEntity = entity; this.callback = callback; } @@ -63,7 +63,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); @@ -128,15 +128,17 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { try { - if (callback != null) { callback.setValue(selEntity); } + if (callback != null) { + callback.setValue(selEntity); + } } catch (Exception e) { QuestingAPI.getLogger().error("Unable to return entity selection!", e); } - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { Entity e = EntityList.newEntity(((PanelButtonStorage) btn).getStoredValue().getEntityClass(), - this.mc.world); + mc.world); if (e != null) { selEntity = e; diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java index 9aa6c8363..924dfe733 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiFluidSelection.java @@ -54,7 +54,7 @@ public GuiFluidSelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) { super(parent); this.callback = callback; - this.itemStack = stack; + itemStack = stack; } public void initPanel() { @@ -66,7 +66,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); @@ -119,7 +119,11 @@ public void initPanel() { fieldSize = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 16, 0, -32), 0), itemStack == null ? "1" : ("" + itemStack.amount), FieldFilterNumber.INT); cvTopLeft.addPanel(fieldSize); - fieldSize.setCallback(value -> { if (itemStack != null) { itemStack.amount = value; } }); + fieldSize.setCallback(value -> { + if (itemStack != null) { + itemStack.amount = value; + } + }); // === BOTTOM LEFT PANEL === @@ -191,7 +195,7 @@ private void onButtonPress(PEventButton event) { callback.setValue(itemStack); } - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { FluidStack fluid = ((PanelButtonStorage) btn).getStoredValue(); diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java index 4c77d8adf..dec2e2dd2 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiItemSelection.java @@ -55,7 +55,7 @@ public GuiItemSelection(GuiScreen parent, NBTTagCompound tag, ICallback callback) { super(parent); this.callback = callback; - this.itemStack = stack; + itemStack = stack; } public void initPanel() { @@ -67,7 +67,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.done"))); @@ -120,7 +120,11 @@ public void initPanel() { fieldSize = new PanelTextField<>(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(52, 16, 0, -32), 0), itemStack == null ? "1" : ("" + itemStack.stackSize), FieldFilterNumber.INT); cvTopLeft.addPanel(fieldSize); - fieldSize.setCallback(value -> { if (itemStack != null) { itemStack.stackSize = value; } }); + fieldSize.setCallback(value -> { + if (itemStack != null) { + itemStack.stackSize = value; + } + }); String oreName = "NONE"; int oreIdx = -1; @@ -220,7 +224,7 @@ private void onButtonPress(PEventButton event) { callback.setValue(itemStack); } - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && btn instanceof PanelButtonStorage) { BigItemStack tmp = ((PanelButtonStorage) btn).getStoredValue(); diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java index 49fbd536b..6eee4676e 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtAdd.java @@ -48,13 +48,13 @@ public class GuiNbtAdd extends GuiScreenCanvas implements IPEventListener, IVola public GuiNbtAdd(GuiScreen parent, NBTTagCompound compoundTag) { super(parent); - this.nbt = compoundTag; - this.index = -1; + nbt = compoundTag; + index = -1; } public GuiNbtAdd(GuiScreen parent, NBTTagList list, int index) { super(parent); - this.nbt = list; + nbt = list; this.index = index; } @@ -68,7 +68,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 100, 16, 0), 0, QuestTranslation.translate("gui.cancel"))); @@ -180,7 +180,7 @@ private void onButtonPress(PEventButton event) { switch (btn.getButtonID()) { case 0: // Cancel { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); break; } case 1: // Confirm @@ -204,7 +204,7 @@ private void onButtonPress(PEventButton event) { } } - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); break; } case 2: // Select this diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java index 94ae4726e..6210771de 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtEditor.java @@ -35,17 +35,17 @@ public class GuiNbtEditor extends GuiScreenCanvas implements IPEventListener, IV public GuiNbtEditor(GuiScreen parent, NBTTagCompound tag, ICallback callback) { super(parent); - this.nbt = tag; - this.comCallback = callback; - this.lstCallback = null; + nbt = tag; + comCallback = callback; + lstCallback = null; } public GuiNbtEditor(GuiScreen parent, NBTTagList tag, ICallback callback) { super(parent); - this.nbt = tag; - this.comCallback = null; - this.lstCallback = callback; + nbt = tag; + comCallback = null; + lstCallback = callback; } public void initPanel() { @@ -57,7 +57,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); @@ -115,7 +115,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); if (nbt.getId() == 10 && comCallback != null) { comCallback.setValue((NBTTagCompound) nbt); diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java index bc9e98e32..53b6074a7 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/GuiNbtType.java @@ -39,7 +39,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox panTxt = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate("betterquesting.title.json_object")).setAlignment( @@ -73,27 +73,27 @@ private void onButtonPress(PEventButton event) { switch (btn.getButtonID()) { case 0: // Back { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); break; } case 1: // Raw NBT { - mc.displayGuiScreen(new GuiNbtEditor(this.parent, tagCompound, null)); + mc.displayGuiScreen(new GuiNbtEditor(parent, tagCompound, null)); break; } case 2: // Item { - mc.displayGuiScreen(new GuiItemSelection(this.parent, tagCompound, new NbtItemCallback(tagCompound))); + mc.displayGuiScreen(new GuiItemSelection(parent, tagCompound, new NbtItemCallback(tagCompound))); break; } case 3: // Fluid { - mc.displayGuiScreen(new GuiFluidSelection(this.parent, tagCompound, new NbtFluidCallback(tagCompound))); + mc.displayGuiScreen(new GuiFluidSelection(parent, tagCompound, new NbtFluidCallback(tagCompound))); break; } case 4: // Entity { - mc.displayGuiScreen(new GuiEntitySelection(this.parent, tagCompound, new NbtEntityCallback(tagCompound))); + mc.displayGuiScreen(new GuiEntitySelection(parent, tagCompound, new NbtEntityCallback(tagCompound))); break; } } diff --git a/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java b/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java index 353c4676c..3d6843539 100644 --- a/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java +++ b/src/main/java/betterquesting/client/gui2/editors/nbt/PanelScrollingNBT.java @@ -54,13 +54,13 @@ public class PanelScrollingNBT extends CanvasScrolling implements IPEventListene public PanelScrollingNBT(IGuiRect rect, NBTTagCompound tag, int btnEdit, int btnAdv, int btnInsert, int btnDelete) { this(rect, btnEdit, btnAdv, btnInsert, btnDelete); - this.setNBT(tag); + setNBT(tag); } public PanelScrollingNBT(IGuiRect rect, NBTTagList tag, int btnEdit, int btnAdv, int btnInsert, int btnDelete) { this(rect, btnEdit, btnAdv, btnInsert, btnDelete); - this.setNBT(tag); + setNBT(tag); } private PanelScrollingNBT(IGuiRect rect, int btnEdit, int btnAdv, int btnInsert, int btnDelete) { @@ -101,13 +101,13 @@ public List> getHandler(@Nonnull NBTBase tag) }*/ public PanelScrollingNBT setNBT(NBTTagCompound tag) { - this.nbt = tag; + nbt = tag; refreshList(); return this; } public PanelScrollingNBT setNBT(NBTTagList list) { - this.nbt = list; + nbt = list; refreshList(); return this; } @@ -116,14 +116,14 @@ public PanelScrollingNBT setNBT(NBTTagList list) { public void initPanel() { super.initPanel(); - this.refreshList(); + refreshList(); } @SuppressWarnings("unchecked") private void refreshList() { - this.resetCanvas(); + resetCanvas(); - if (this.nbt == null) { + if (nbt == null) { return; } @@ -147,45 +147,45 @@ private void refreshList() { PanelTextBox name = new PanelTextBox(new GuiRectangle(0, i * 16 + 4, lw - 8, 12, 0), k).setAlignment(2); name.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(name); + addPanel(name); if (entry.getId() == 10) // Object { PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), btnEdit, getButtonTitle((NBTTagCompound) entry), k); - this.addPanel(btn); + addPanel(btn); btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnAdv, "...", k); - this.addPanel(btn); + addPanel(btn); } else if (entry.getId() == 9) // List { PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), btnEdit, "List...", k); - this.addPanel(btn); + addPanel(btn); } else if (entry.getId() == 8) // Text { PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), ((NBTTagString) entry).getString(), FieldFilterString.INSTANCE); text.setCallback(new CallbackNBTTagString(tag, k)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnEdit, "Aa", k); - this.addPanel(btn); + addPanel(btn); } else if (entry.getId() == 1) // Byte/Boolean { PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw / 2, 16, 0), "" + ((NBTPrimitive) entry).getByte(), FieldFilterNumber.BYTE); text.setMaxLength(Integer.MAX_VALUE); // Put callback here - this.addPanel(text); + addPanel(text); PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw + rw / 2, i * 16, (int) Math.ceil(rw / 2F) - 32, 16, 0), btnEdit, ((NBTPrimitive) entry).getByte() > 0 ? "true" : "false", k); - this.addPanel(btn); + addPanel(btn); text.setMaxLength(Integer.MAX_VALUE).setCallback( new CallbackMulti<>(new CallbackNBTPrimitive<>(tag, k, Byte.class), @@ -205,7 +205,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getShort(), FieldFilterNumber.SHORT); text.setCallback(new CallbackNBTPrimitive<>(tag, k, Short.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 3: // Integer @@ -214,7 +214,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getInt(), FieldFilterNumber.INT); text.setCallback(new CallbackNBTPrimitive<>(tag, k, Integer.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 4: // Long @@ -223,7 +223,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getLong(), FieldFilterNumber.LONG); text.setCallback(new CallbackNBTPrimitive<>(tag, k, Long.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 5: // Float @@ -232,7 +232,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getFloat(), FieldFilterNumber.FLOAT); text.setCallback(new CallbackNBTPrimitive<>(tag, k, Float.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 6: // Double @@ -241,7 +241,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getDouble(), FieldFilterNumber.DOUBLE); text.setCallback(new CallbackNBTPrimitive<>(tag, k, Double.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } } @@ -249,32 +249,32 @@ private void refreshList() { PanelTextBox err = new PanelTextBox(new GuiRectangle(lw, i * 16 + 4, rw - 48, 12, 0), entry.getClass().getSimpleName() + " Not Supported Yet").setAlignment(1); err.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(err); + addPanel(err); } PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", k); btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); + addPanel(btnI); PanelButtonStorage btnD = new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), btnDelete, "x", k); btnD.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 0, 0, 255), new GuiColorStatic(255, 0, 0, 255)); - this.addPanel(btnD); + addPanel(btnD); i++; } - this.addPanel( + addPanel( new PanelGeneric(new GuiRectangle(0, i * 16, width - 32, 16, 0), null)); // Keeps the list from auto resizing PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", ""); btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); + addPanel(btnI); } else if (nbt.getId() == 9) // NBTTagList { NBTTagList list = (NBTTagList) nbt; @@ -286,44 +286,44 @@ private void refreshList() { PanelTextBox name = new PanelTextBox(new GuiRectangle(0, i * 16 + 4, lw - 8, 16, 0), "#" + i).setAlignment(2); name.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(name); + addPanel(name); if (entry.getId() == 10) // Object { PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), btnEdit, getButtonTitle((NBTTagCompound) entry), i); - this.addPanel(btn); + addPanel(btn); btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnAdv, "...", i); - this.addPanel(btn); + addPanel(btn); } else if (entry.getId() == 9) // List { PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw, i * 16, rw - 32, 16, 0), btnEdit, "List...", i); - this.addPanel(btn); + addPanel(btn); } else if (entry.getId() == 8) // Text { PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw - 48, 16, 0), ((NBTTagString) entry).getString(), FieldFilterString.INSTANCE); text.setCallback(new CallbackNBTTagString(list, i)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(width - 48, i * 16, 16, 16, 0), btnEdit, "Aa", i); - this.addPanel(btn); + addPanel(btn); } else if (entry.getId() == 1) // Byte/Boolean { PanelTextField text = new PanelTextField<>(new GuiRectangle(lw, i * 16, rw / 2, 16, 0), "" + ((NBTPrimitive) entry).getByte(), FieldFilterNumber.BYTE); - this.addPanel(text); + addPanel(text); PanelButtonStorage btn = new PanelButtonStorage<>(new GuiRectangle(lw + rw / 2, i * 16, (int) Math.ceil(rw / 2F) - 32, 16, 0), btnEdit, ((NBTPrimitive) entry).getByte() > 0 ? "true" : "false", i); - this.addPanel(btn); + addPanel(btn); text.setMaxLength(Integer.MAX_VALUE).setCallback( new CallbackMulti<>(new CallbackNBTPrimitive<>(list, i, Byte.class), @@ -343,7 +343,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getShort(), FieldFilterNumber.SHORT); text.setCallback(new CallbackNBTPrimitive<>(list, i, Short.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 3: // Integer @@ -352,7 +352,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getInt(), FieldFilterNumber.INT); text.setCallback(new CallbackNBTPrimitive<>(list, i, Integer.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 4: // Long @@ -361,7 +361,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getLong(), FieldFilterNumber.LONG); text.setCallback(new CallbackNBTPrimitive<>(list, i, Long.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 5: // Float @@ -370,7 +370,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getFloat(), FieldFilterNumber.FLOAT); text.setCallback(new CallbackNBTPrimitive<>(list, i, Float.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } case 6: // Double @@ -379,7 +379,7 @@ private void refreshList() { "" + ((NBTPrimitive) entry).getDouble(), FieldFilterNumber.DOUBLE); text.setCallback(new CallbackNBTPrimitive<>(list, i, Double.class)).setMaxLength(Integer.MAX_VALUE); - this.addPanel(text); + addPanel(text); break; } } @@ -387,34 +387,34 @@ private void refreshList() { PanelTextBox err = new PanelTextBox(new GuiRectangle(lw, i * 16 + 4, rw - 48, 12, 0), entry.getClass().getSimpleName() + " Not Supported Yet").setAlignment(1); err.setColor(PresetColor.TEXT_MAIN.getColor()); - this.addPanel(err); + addPanel(err); } PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", i); btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); + addPanel(btnI); PanelButtonStorage btnD = new PanelButtonStorage<>(new GuiRectangle(width - 16, i * 16, 16, 16, 0), btnDelete, "x", i); btnD.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(255, 0, 0, 255), new GuiColorStatic(255, 0, 0, 255)); - this.addPanel(btnD); + addPanel(btnD); } - this.addPanel( + addPanel( new PanelGeneric(new GuiRectangle(0, i * 16, width - 32, 16, 0), null)); // Keeps the list from auto resizing PanelButtonStorage btnI = new PanelButtonStorage<>(new GuiRectangle(width - 32, i * 16, 16, 16, 0), btnInsert, "+", i); btnI.setTextHighlight(new GuiColorStatic(128, 128, 128, 255), new GuiColorStatic(0, 255, 0, 255), new GuiColorStatic(0, 255, 0, 255)); - this.addPanel(btnI); + addPanel(btnI); } - this.setScrollX(preSX); - this.setScrollY(preSY); + setScrollX(preSX); + setScrollY(preSY); } @Override @@ -519,7 +519,7 @@ private String getButtonTitle(NBTTagCompound tag) { FluidStack fluid = JsonHelper.JsonToFluidStack(tag); return QuestTranslation.translate("betterquesting.btn.fluid") + ": " + fluid.getLocalizedName(); } else if (JsonHelper.isEntity(tag)) { - Entity entity = JsonHelper.JsonToEntity(tag, this.mc.world); + Entity entity = JsonHelper.JsonToEntity(tag, mc.world); return QuestTranslation.translate("betterquesting.btn.entity") + ": " + entity.getName(); } diff --git a/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java b/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java index 5afc3bf99..0c4395f6c 100644 --- a/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java +++ b/src/main/java/betterquesting/client/gui2/inventory/ContainerSubmitStation.java @@ -29,12 +29,12 @@ public ContainerSubmitStation(InventoryPlayer player, TileSubmitStation tile) { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { - this.addSlotToContainer(new Slot(player, j + i * 9 + 9, j * 18, i * 18)); + addSlotToContainer(new Slot(player, j + i * 9 + 9, j * 18, i * 18)); } } for (int i = 0; i < 9; ++i) { - this.addSlotToContainer(new Slot(player, i, i * 18, 58)); + addSlotToContainer(new Slot(player, i, i * 18, 58)); } } @@ -77,7 +77,7 @@ protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, if (stack.isStackable()) { for (int i : range) { - Slot slot = this.inventorySlots.get(i); + Slot slot = inventorySlots.get(i); ItemStack slotStack = slot.getStack(); if (ItemHandlerHelper.canItemStacksStack(stack, slotStack)) { @@ -99,7 +99,7 @@ protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, } for (int i : range) { - Slot slot = this.inventorySlots.get(i); + Slot slot = inventorySlots.get(i); ItemStack slotStack = slot.getStack(); if (slotStack.isEmpty() && slot.isItemValid(stack)) { @@ -125,31 +125,31 @@ public ItemStack transferStackInSlot(@Nonnull EntityPlayer player, int idx) { } ItemStack itemstack = ItemStack.EMPTY; - Slot slot = this.inventorySlots.get(idx); + Slot slot = inventorySlots.get(idx); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (idx == 0) { - if (!this.mergeItemStack(itemstack1, 1, 37, true)) { + if (!mergeItemStack(itemstack1, 1, 37, true)) { return ItemStack.EMPTY; } slot.onSlotChange(itemstack1, itemstack); } else if (slot.isItemValid(itemstack1)) { - if (!this.mergeItemStack(itemstack1, 0, 1, false)) { + if (!mergeItemStack(itemstack1, 0, 1, false)) { return ItemStack.EMPTY; } } else if (idx < 28) { - if (!this.mergeItemStack(itemstack1, 28, 37, false)) { + if (!mergeItemStack(itemstack1, 28, 37, false)) { return ItemStack.EMPTY; } } else if (idx < 37) { - if (!this.mergeItemStack(itemstack1, 1, 28, false)) { + if (!mergeItemStack(itemstack1, 1, 28, false)) { return ItemStack.EMPTY; } - } else if (!this.mergeItemStack(itemstack1, 1, 37, false)) { + } else if (!mergeItemStack(itemstack1, 1, 37, false)) { return ItemStack.EMPTY; } diff --git a/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java b/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java index fdd647b54..bce44946d 100644 --- a/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java +++ b/src/main/java/betterquesting/client/gui2/inventory/GuiSubmitStation.java @@ -64,15 +64,17 @@ public class GuiSubmitStation extends GuiContainerCanvas implements INeedsRefres public GuiSubmitStation(GuiScreen parent, InventoryPlayer playerInvo, TileSubmitStation submitStation) { super(parent, new ContainerSubmitStation(playerInvo, submitStation)); - this.ssContainer = (ContainerSubmitStation) this.inventorySlots; - this.tile = submitStation; + ssContainer = (ContainerSubmitStation) inventorySlots; + tile = submitStation; } @Override public void refreshGui() { quests.clear(); QuestCache qc = mc.player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (qc != null) { quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); } + if (qc != null) { + quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); + } filterQuests(); refreshTaskPanel(); @@ -87,13 +89,15 @@ public void initPanel() { quests.clear(); taskPanel = null; QuestCache qc = mc.player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (qc != null) { quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); } + if (qc != null) { + quests.addAll(QuestDatabase.INSTANCE.bulkLookup(qc.getActiveQuests())); + } filterQuests(); // Background panel cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); PanelTextBox txtTitle = new PanelTextBox(new GuiTransform(GuiAlign.TOP_EDGE, new GuiPadding(0, 16, 0, -32), 0), QuestTranslation.translate( @@ -196,18 +200,20 @@ private void setInventoryPosition(int x, int y) { for (int i = 0; i < 36; i++) { int j = i % 9 * 18; int k = i / 9 * 18; - if (i >= 27) { k += 4; } + if (i >= 27) { + k += 4; + } - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + j, y + k + 22, 18, 18, -1), - PresetTexture.ITEM_FRAME.getTexture())); + addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + j, y + k + 22, 18, 18, -1), + PresetTexture.ITEM_FRAME.getTexture())); } - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 54, y, 18, 18, -1), - PresetTexture.ITEM_FRAME.getTexture())); - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 72, y, 18, 18, -1), - PresetIcon.ICON_RIGHT.getTexture())); - this.addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 90, y, 18, 18, -1), - PresetTexture.ITEM_FRAME.getTexture())); + addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 54, y, 18, 18, -1), + PresetTexture.ITEM_FRAME.getTexture())); + addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 72, y, 18, 18, -1), + PresetIcon.ICON_RIGHT.getTexture())); + addPanel(new PanelGeneric(new GuiTransform(GuiAlign.TOP_LEFT, x + 90, y, 18, 18, -1), + PresetTexture.ITEM_FRAME.getTexture())); } private void filterQuests() { @@ -228,7 +234,9 @@ private void filterQuests() { } private void refreshTaskPanel() { - if (taskPanel != null) { cvBackground.removePanel(taskPanel); } + if (taskPanel != null) { + cvBackground.removePanel(taskPanel); + } if (tile.isSetup()) { DBEntry qdbe = null; @@ -275,7 +283,9 @@ private void refreshTaskPanel() { txtQstTitle.setText(""); txtTskTitle.setText(""); return; - } else { selQuest = lazyPosMod(selQuest, quests.size()); } + } else { + selQuest = lazyPosMod(selQuest, quests.size()); + } DBEntry entry = quests.get(selQuest); txtQstTitle.setText(QuestTranslation.translate(entry.getValue().getProperty(NativeProps.NAME))); @@ -298,7 +308,9 @@ private void refreshTaskPanel() { curTask instanceof IEnergyTask)); taskPanel = curTask.getTaskGui(new GuiTransform(GuiAlign.HALF_RIGHT, new GuiPadding(8, 88, 16, 24), 0), entry); - if (taskPanel != null) { cvBackground.addPanel(taskPanel); } + if (taskPanel != null) { + cvBackground.addPanel(taskPanel); + } } private int lazyPosMod(int a, int b) { diff --git a/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java b/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java index dd9325349..d30450931 100644 --- a/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java +++ b/src/main/java/betterquesting/client/gui2/party/GuiPartyCreate.java @@ -90,7 +90,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); @@ -170,7 +170,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1) // Create { NBTTagCompound payload = new NBTTagCompound(); @@ -194,7 +194,9 @@ private void refreshInvites() { for (int i = 0; i < invites.size(); i++) { int pid = invites.get(i).getKey(); - if (pid < 0) { continue; } + if (pid < 0) { + continue; + } long exp = invites.get(i).getValue(); IParty party = PartyManager.INSTANCE.getValue(pid); diff --git a/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java b/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java index 7fecfef8e..26355f5ab 100644 --- a/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java +++ b/src/main/java/betterquesting/client/gui2/party/GuiPartyInvite.java @@ -68,7 +68,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); @@ -138,7 +138,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 1 && !flName.getRawText().isEmpty()) // Manual Invite { NBTTagCompound payload = new NBTTagCompound(); diff --git a/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java b/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java index a5074fb96..f654df79e 100644 --- a/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java +++ b/src/main/java/betterquesting/client/gui2/party/GuiPartyManage.java @@ -70,7 +70,9 @@ public void refreshGui() { party = tmp.getValue(); partyID = tmp.getID(); - if (!flName.isFocused()) { flName.setText(party.getProperties().getProperty(NativeProps.NAME)); } + if (!flName.isFocused()) { + flName.setText(party.getProperties().getProperty(NativeProps.NAME)); + } initPanel(); } @@ -103,7 +105,7 @@ public void initPanel() { // Background panel CanvasTextured cvBackground = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvBackground); + addPanel(cvBackground); cvBackground.addPanel(new PanelButton(new GuiTransform(GuiAlign.BOTTOM_CENTER, -100, -16, 200, 16, 0), 0, QuestTranslation.translate("gui.back"))); @@ -240,7 +242,7 @@ private void onButtonPress(PEventButton event) { if (btn.getButtonID() == 0) // Exit { - mc.displayGuiScreen(this.parent); + mc.displayGuiScreen(parent); } else if (btn.getButtonID() == 2) // Invite { mc.displayGuiScreen(new GuiPartyInvite(this)); diff --git a/src/main/java/betterquesting/client/gui3/GuiStatus.java b/src/main/java/betterquesting/client/gui3/GuiStatus.java index 6c320552d..ecc149990 100644 --- a/src/main/java/betterquesting/client/gui3/GuiStatus.java +++ b/src/main/java/betterquesting/client/gui3/GuiStatus.java @@ -28,7 +28,7 @@ public void initPanel() { // === BACKGROUND PANEL === CanvasTextured bgCan = new CanvasTextured(new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(0, 0, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(bgCan); + addPanel(bgCan); CanvasHoverTray cvHover = new CanvasHoverTray(new GuiTransform(GuiAlign.MID_CENTER, 16, 16, 16, 16, 0), new GuiTransform(GuiAlign.MID_CENTER, 16, 16, 64, 64, 5), diff --git a/src/main/java/betterquesting/client/importers/ImportedQuestLines.java b/src/main/java/betterquesting/client/importers/ImportedQuestLines.java index 6255a8ecc..93f3b8186 100644 --- a/src/main/java/betterquesting/client/importers/ImportedQuestLines.java +++ b/src/main/java/betterquesting/client/importers/ImportedQuestLines.java @@ -49,7 +49,9 @@ public List> getSortedEntries() { @Override public NBTTagList writeToNBT(NBTTagList json, List subset) { for (DBEntry entry : getEntries()) { - if (subset != null && !subset.contains(entry.getID())) { continue; } + if (subset != null && !subset.contains(entry.getID())) { + continue; + } NBTTagCompound jObj = entry.getValue().writeToNBT(new NBTTagCompound(), null); jObj.setInteger("lineID", entry.getID()); jObj.setInteger("order", getOrderIndex(entry.getID())); @@ -61,7 +63,9 @@ public NBTTagList writeToNBT(NBTTagList json, List subset) { @Override public void readFromNBT(NBTTagList json, boolean merge) { - if (!merge) { reset(); } + if (!merge) { + reset(); + } List unassigned = new ArrayList<>(); HashMap orderMap = new HashMap<>(); @@ -86,14 +90,18 @@ public void readFromNBT(NBTTagList json, boolean merge) { } // Legacy support ONLY - for (IQuestLine q : unassigned) { add(nextID(), q); } + for (IQuestLine q : unassigned) { + add(nextID(), q); + } List orderKeys = new ArrayList<>(orderMap.keySet()); Collections.sort(orderKeys); synchronized (lineOrder) { lineOrder.clear(); - for (int o : orderKeys) { lineOrder.add(orderMap.get(o)); } + for (int o : orderKeys) { + lineOrder.add(orderMap.get(o)); + } } } diff --git a/src/main/java/betterquesting/client/importers/ImportedQuests.java b/src/main/java/betterquesting/client/importers/ImportedQuests.java index ca90c82a0..bc9cbf832 100644 --- a/src/main/java/betterquesting/client/importers/ImportedQuests.java +++ b/src/main/java/betterquesting/client/importers/ImportedQuests.java @@ -17,19 +17,23 @@ public class ImportedQuests extends SimpleDatabase implements IQuestDatabase { @Override public IQuest createNew(int id) { - return this.add(id, new QuestInstance()).getValue(); + return add(id, new QuestInstance()).getValue(); } @Override public List> bulkLookup(int... ids) { - if (ids == null || ids.length == 0) { return Collections.emptyList(); } + if (ids == null || ids.length == 0) { + return Collections.emptyList(); + } List> values = new ArrayList<>(); synchronized (this) { for (int i : ids) { IQuest v = getValue(i); - if (v != null) { values.add(new DBEntry<>(i, v)); } + if (v != null) { + values.add(new DBEntry<>(i, v)); + } } } @@ -38,8 +42,10 @@ public List> bulkLookup(int... ids) { @Override public NBTTagList writeToNBT(NBTTagList nbt, List subset) { - for (DBEntry entry : this.getEntries()) { - if (subset != null && !subset.contains(entry.getID())) { continue; } + for (DBEntry entry : getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { + continue; + } NBTTagCompound jq = new NBTTagCompound(); entry.getValue().writeToNBT(jq); jq.setInteger("questID", entry.getID()); @@ -51,16 +57,20 @@ public NBTTagList writeToNBT(NBTTagList nbt, List subset) { @Override public void readFromNBT(NBTTagList nbt, boolean merge) { - if (!merge) { this.reset(); } + if (!merge) { + reset(); + } for (int i = 0; i < nbt.tagCount(); i++) { NBTTagCompound qTag = nbt.getCompoundTagAt(i); int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; - if (qID < 0) { continue; } + if (qID < 0) { + continue; + } IQuest quest = getValue(qID); - quest = quest != null ? quest : this.createNew(qID); + quest = quest != null ? quest : createNew(qID); quest.readFromNBT(qTag); } } @@ -71,6 +81,5 @@ public NBTTagList writeProgressToNBT(NBTTagList nbt, @Nullable List users) } @Override - public void readProgressFromNBT(NBTTagList nbt, boolean merge) { - } + public void readProgressFromNBT(NBTTagList nbt, boolean merge) { } } diff --git a/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java b/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java index b5054b878..bb38b5c0f 100644 --- a/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java +++ b/src/main/java/betterquesting/client/renderer/EntityPlaceholderRenderer.java @@ -16,7 +16,7 @@ protected EntityPlaceholderRenderer(RenderManager renderManager) { @Override public void doRender(EntityPlaceholder entity, double x, double y, double z, float yaw, float partialTick) { EntityItem item = entity.GetItemEntity(); - this.renderManager.renderEntity(item, x, y + 1D, z, yaw, partialTick, false); + renderManager.renderEntity(item, x, y + 1D, z, yaw, partialTick, false); } @Override diff --git a/src/main/java/betterquesting/client/themes/ResourceTheme.java b/src/main/java/betterquesting/client/themes/ResourceTheme.java index 7e2b42f5c..b55ad7256 100644 --- a/src/main/java/betterquesting/client/themes/ResourceTheme.java +++ b/src/main/java/betterquesting/client/themes/ResourceTheme.java @@ -30,7 +30,7 @@ public class ResourceTheme implements IGuiTheme { private final HashMap LINE_MAP = new HashMap<>(); public ResourceTheme(ResourceLocation parentID, ResourceLocation id, String dispName) { - this.ID = id; + ID = id; this.dispName = dispName; this.parentID = parentID; } @@ -38,7 +38,9 @@ public ResourceTheme(ResourceLocation parentID, ResourceLocation id, String disp public void loadFromJson(JsonObject jThm) { JsonObject jsonTextureRoot = JsonHelper.GetObject(jThm, "textures"); for (Entry entry : jsonTextureRoot.entrySet()) { - if (!entry.getValue().isJsonObject()) { continue; } + if (!entry.getValue().isJsonObject()) { + continue; + } JsonObject joTex = entry.getValue().getAsJsonObject(); ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joTex, "textureType", "")); @@ -49,12 +51,14 @@ public void loadFromJson(JsonObject jThm) { continue; } - this.setTexture(new ResourceLocation(entry.getKey()), gTex); + setTexture(new ResourceLocation(entry.getKey()), gTex); } JsonObject jsonColourRoot = JsonHelper.GetObject(jThm, "colors"); for (Entry entry : jsonColourRoot.entrySet()) { - if (!(entry.getValue() instanceof JsonObject)) { continue; } + if (!(entry.getValue() instanceof JsonObject)) { + continue; + } JsonObject joCol = entry.getValue().getAsJsonObject(); ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joCol, "colorType", "")); @@ -65,12 +69,14 @@ public void loadFromJson(JsonObject jThm) { continue; } - this.setColor(new ResourceLocation(entry.getKey()), gCol); + setColor(new ResourceLocation(entry.getKey()), gCol); } JsonObject jsonLinesRoot = JsonHelper.GetObject(jThm, "lines"); for (Entry entry : jsonLinesRoot.entrySet()) { - if (!(entry.getValue() instanceof JsonObject)) { continue; } + if (!(entry.getValue() instanceof JsonObject)) { + continue; + } JsonObject joLine = entry.getValue().getAsJsonObject(); ResourceLocation typeID = new ResourceLocation(JsonHelper.GetString(joLine, "lineType", "")); @@ -81,12 +87,14 @@ public void loadFromJson(JsonObject jThm) { continue; } - this.setLine(new ResourceLocation(entry.getKey()), gLine); + setLine(new ResourceLocation(entry.getKey()), gLine); } } private IGuiTheme getParent() { - if (cached) { return parentTheme; } + if (cached) { + return parentTheme; + } IGuiTheme parent = ThemeRegistry.INSTANCE.getTheme(parentID); IGuiTheme checking = parent; @@ -94,7 +102,7 @@ private IGuiTheme getParent() { if (checking instanceof ResourceTheme) { if (((ResourceTheme) checking).parentTheme == this) { BetterQuesting.logger.error("Circular reference in resource theme " + ID); - this.parentTheme = null; + parentTheme = null; cached = true; return null; } @@ -104,24 +112,30 @@ private IGuiTheme getParent() { break; } - this.parentTheme = parent; + parentTheme = parent; cached = true; - return this.parentTheme; + return parentTheme; } public void setTexture(ResourceLocation key, IGuiTexture texture) { - if (key == null) { return; } + if (key == null) { + return; + } TEX_MAP.put(key, texture); // Could actually use null here to override the parent } public void setColor(ResourceLocation key, IGuiColor color) { - if (key == null) { return; } + if (key == null) { + return; + } COLOR_MAP.put(key, color); // Could actually use null here to override the parent } public void setLine(ResourceLocation key, IGuiLine line) { - if (key == null) { return; } + if (key == null) { + return; + } LINE_MAP.put(key, line); // Could actually use null here to override the parent } @@ -138,24 +152,36 @@ public ResourceLocation getID() { @Override public IGuiTexture getTexture(ResourceLocation key) { IGuiTexture value = TEX_MAP.get(key); - if (value != null) { return value; } - if (getParent() != null) { return getParent().getTexture(key); } + if (value != null) { + return value; + } + if (getParent() != null) { + return getParent().getTexture(key); + } return null; } @Override public IGuiLine getLine(ResourceLocation key) { IGuiLine value = LINE_MAP.get(key); - if (value != null) { return value; } - if (getParent() != null) { return getParent().getLine(key); } + if (value != null) { + return value; + } + if (getParent() != null) { + return getParent().getLine(key); + } return null; } @Override public IGuiColor getColor(ResourceLocation key) { IGuiColor value = COLOR_MAP.get(key); - if (value != null) { return value; } - if (getParent() != null) { return getParent().getColor(key); } + if (value != null) { + return value; + } + if (getParent() != null) { + return getParent().getColor(key); + } return null; } diff --git a/src/main/java/betterquesting/client/themes/ThemeRegistry.java b/src/main/java/betterquesting/client/themes/ThemeRegistry.java index 08d286661..114f8f097 100644 --- a/src/main/java/betterquesting/client/themes/ThemeRegistry.java +++ b/src/main/java/betterquesting/client/themes/ThemeRegistry.java @@ -160,12 +160,14 @@ public void setTheme(ResourceLocation id) { @Override public IGuiTheme getTheme(ResourceLocation key) { - if (key == null) { return null; } + if (key == null) { + return null; + } return themes.get(key); } private void setTheme(IGuiTheme theme, ResourceLocation id) { - this.activeTheme = theme; + activeTheme = theme; BQ_Settings.curTheme = id == null ? "" : id.toString(); @@ -179,12 +181,12 @@ private void setTheme(IGuiTheme theme, ResourceLocation id) { @Override public IGuiTheme getCurrentTheme() { - if (!setup && this.activeTheme == null) { - this.activeTheme = this.getTheme(new ResourceLocation(BQ_Settings.curTheme)); + if (!setup && activeTheme == null) { + activeTheme = getTheme(new ResourceLocation(BQ_Settings.curTheme)); setup = true; } - return this.activeTheme; + return activeTheme; } @Override @@ -200,7 +202,9 @@ public void loadResourceThemes() { try { list = resManager.getAllResources(res); - } catch (Exception e) { continue; } // Not going to log errors everytime the file isn't found + } catch (Exception e) { + continue; + } // Not going to log errors everytime the file isn't found for (IResource iresource : list) { try (InputStreamReader isr = new InputStreamReader(iresource.getInputStream(), StandardCharsets.UTF_8)) { @@ -230,11 +234,15 @@ public void loadResourceThemes() { String themeName = JsonHelper.GetString(jThm, "themeName", "Unnamed Theme"); String idRaw = JsonHelper.GetString(jThm, "themeID", themeName); idRaw = idRaw.toLowerCase().trim().replaceAll(" ", "_"); - if (!idRaw.contains(":")) { idRaw = domain + ":" + idRaw; } + if (!idRaw.contains(":")) { + idRaw = domain + ":" + idRaw; + } ResourceLocation themeId = new ResourceLocation(idRaw); int n = 0; - while (themes.containsKey(themeId)) { themeId = new ResourceLocation(domain, idRaw + n++); } + while (themes.containsKey(themeId)) { + themeId = new ResourceLocation(domain, idRaw + n++); + } ResourceTheme resTheme; @@ -259,46 +267,70 @@ public void loadResourceThemes() { @Override public IGuiTexture getTexture(ResourceLocation key) { - if (key == null) { return NULL_TEXTURE; } + if (key == null) { + return NULL_TEXTURE; + } IGuiTexture tex = null; - if (getCurrentTheme() != null) { tex = activeTheme.getTexture(key); } - if (tex == null) { tex = defTextures.get(key); } + if (getCurrentTheme() != null) { + tex = activeTheme.getTexture(key); + } + if (tex == null) { + tex = defTextures.get(key); + } return tex == null ? NULL_TEXTURE : tex; } @Override public IGuiLine getLine(ResourceLocation key) { - if (key == null) { return NULL_LINE; } + if (key == null) { + return NULL_LINE; + } IGuiLine line = null; - if (getCurrentTheme() != null) { line = activeTheme.getLine(key); } - if (line == null) { line = defLines.get(key); } + if (getCurrentTheme() != null) { + line = activeTheme.getLine(key); + } + if (line == null) { + line = defLines.get(key); + } return line == null ? NULL_LINE : line; } @Override public IGuiColor getColor(ResourceLocation key) { - if (key == null) { return NULL_COLOR; } + if (key == null) { + return NULL_COLOR; + } IGuiColor color = null; - if (getCurrentTheme() != null) { color = activeTheme.getColor(key); } - if (color == null) { color = defColors.get(key); } + if (getCurrentTheme() != null) { + color = activeTheme.getColor(key); + } + if (color == null) { + color = defColors.get(key); + } return color == null ? NULL_COLOR : color; } @Override @SuppressWarnings("unchecked") public GuiScreen getGui(GuiKey key, T args) { - if (key == null) { return null; } + if (key == null) { + return null; + } Function func = null; - if (getCurrentTheme() != null) { func = activeTheme.getGui(key); } - if (func == null) { func = (Function) defGuis.get(key); } + if (getCurrentTheme() != null) { + func = activeTheme.getGui(key); + } + if (func == null) { + func = (Function) defGuis.get(key); + } return func == null ? null : func.apply(args); } diff --git a/src/main/java/betterquesting/client/toolbox/PanelTabMain.java b/src/main/java/betterquesting/client/toolbox/PanelTabMain.java index 8437ae5c6..cb5fe83e0 100644 --- a/src/main/java/betterquesting/client/toolbox/PanelTabMain.java +++ b/src/main/java/betterquesting/client/toolbox/PanelTabMain.java @@ -44,18 +44,18 @@ public void initPanel() { int w = getTransform().getWidth(); IGuiColor tCol = new GuiColorStatic(0xFF000000); - this.addPanel( + addPanel( new PanelButton(new GuiRectangle(0, 0, w / 2, 16, 0), -1, "" + ToolboxTabMain.INSTANCE.getSnapValue()) { @Override public void onButtonClick() { ToolboxTabMain.INSTANCE.toggleSnap(); - this.setText("" + ToolboxTabMain.INSTANCE.getSnapValue()); + setText("" + ToolboxTabMain.INSTANCE.getSnapValue()); } }.setIcon(PresetIcon.ICON_GRID.getTexture()).setTextShadow(false).setTextHighlight(tCol, tCol, tCol).setTooltip( makeToolTip(QuestTranslation.translate("betterquesting.toolbox.tool.snap.name"), QuestTranslation.translate("betterquesting.toolbox.tool.snap.desc")))); - this.addPanel(new PanelButton(new GuiRectangle(w / 2, 0, w / 2, 16, 0), -1, "") { + addPanel(new PanelButton(new GuiRectangle(w / 2, 0, w / 2, 16, 0), -1, "") { @Override public void onButtonClick() { Minecraft mc = Minecraft.getMinecraft(); @@ -94,7 +94,7 @@ public void onButtonClick() { btn.setActive(false); }); toolBtns.add(btn); - this.addPanel(btn); + addPanel(btn); if (entry.tool instanceof ToolboxToolOpen && toolController.getActiveTool() == null) { toolController.setActiveTool(entry.tool); diff --git a/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java b/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java index d338ae2f3..548bc49f8 100644 --- a/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java +++ b/src/main/java/betterquesting/client/toolbox/ToolboxTabMain.java @@ -40,7 +40,9 @@ public int getSnapIndex() { } public void drawGrid(CanvasQuestLine ui) { - if (getSnapValue() <= 1) { return; } + if (getSnapValue() <= 1) { + return; + } float zs = ui.getZoom(); int snap = getSnapValue(); diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java index 56646f2a4..00622ba9b 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolComplete.java @@ -21,20 +21,16 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void disableTool() { - } + public void disableTool() { } @Override - public void refresh(CanvasQuestLine gui) { - } + public void refresh(CanvasQuestLine gui) { } @Override - public void drawCanvas(int mx, int my, float partialTick) { - } + public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override public List getTooltip(int mx, int my) { @@ -43,12 +39,18 @@ public List getTooltip(int mx, int my) { @Override public boolean onMouseClick(int mx, int my, int click) { - if (click != 0 || !gui.getTransform().contains(mx, my)) { return false; } + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; + } PanelButtonQuest btn = gui.getButtonAt(mx, my); - if (btn == null) { return false; } - if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { return false; } + if (btn == null) { + return false; + } + if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { + return false; + } List btnList = PanelToolController.selected.isEmpty() ? Collections.singletonList(btn) : PanelToolController.selected; @@ -79,7 +81,9 @@ public boolean onMouseScroll(int mx, int my, int scroll) { @Override public boolean onKeyPressed(char c, int key) { - if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { + return false; + } List btnList = PanelToolController.selected; int[] questIDs = new int[btnList.size()]; @@ -103,8 +107,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java index 30b8b5a5c..331d2b760 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolCopy.java @@ -38,7 +38,9 @@ public void disableTool() { @Override public void refresh(CanvasQuestLine gui) { - if (grabList.isEmpty()) { return; } + if (grabList.isEmpty()) { + return; + } List tmp = new ArrayList<>(); @@ -57,7 +59,9 @@ public void refresh(CanvasQuestLine gui) { @Override public void drawCanvas(int mx, int my, float partialTick) { - if (grabList.isEmpty()) { return; } + if (grabList.isEmpty()) { + return; + } int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); int dx = mx; @@ -76,7 +80,9 @@ public void drawCanvas(int mx, int my, float partialTick) { @Override public void drawOverlay(int mx, int my, float partialTick) { - if (!grabList.isEmpty()) { ToolboxTabMain.INSTANCE.drawGrid(gui); } + if (!grabList.isEmpty()) { + ToolboxTabMain.INSTANCE.drawGrid(gui); + } } @Override @@ -99,7 +105,9 @@ public boolean onMouseClick(int mx, int my, int click) { if (btnClicked != null) // Pickup the group or the single one if none are selected { if (!PanelToolController.selected.isEmpty()) { - if (!PanelToolController.selected.contains(btnClicked)) { return false; } + if (!PanelToolController.selected.contains(btnClicked)) { + return false; + } for (PanelButtonQuest btn : PanelToolController.selected) { GuiRectangle rect = new GuiRectangle(btn.rect); @@ -186,7 +194,9 @@ private int[] getNextIDs(int num) { int[] nxtIDs = new int[num]; if (listDB.isEmpty() || listDB.get(listDB.size() - 1).getID() == listDB.size() - 1) { - for (int i = 0; i < num; i++) { nxtIDs[i] = listDB.size() + i; } + for (int i = 0; i < num; i++) { + nxtIDs[i] = listDB.size() + i; + } return nxtIDs; } @@ -225,8 +235,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java index 8ef4cebbc..38b2c3fc3 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolDelete.java @@ -21,20 +21,16 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void disableTool() { - } + public void disableTool() { } @Override - public void refresh(CanvasQuestLine gui) { - } + public void refresh(CanvasQuestLine gui) { } @Override - public void drawCanvas(int mx, int my, float partialTick) { - } + public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override public List getTooltip(int mx, int my) { @@ -84,7 +80,9 @@ public boolean onMouseScroll(int mx, int my, int scroll) { @Override public boolean onKeyPressed(char c, int key) { - if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { + return false; + } List btnList = PanelToolController.selected; int[] questIDs = new int[btnList.size()]; @@ -107,8 +105,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java index 6e1086ac2..e21567c3c 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolFrame.java @@ -23,37 +23,34 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void refresh(CanvasQuestLine gui) { - - } + public void refresh(CanvasQuestLine gui) { } @Override - public void disableTool() { - - } + public void disableTool() { } @Override - public void drawCanvas(int mx, int my, float partialTick) { - - } + public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean onMouseClick(int mx, int my, int click) { - if (click != 0 || !gui.getTransform().contains(mx, my)) { return false; } + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; + } PanelButtonQuest btn = gui.getButtonAt(mx, my); - if (btn == null) { return false; } - if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { return false; } + if (btn == null) { + return false; + } + if (!PanelToolController.selected.isEmpty() && !PanelToolController.selected.contains(btn)) { + return false; + } List btnList = PanelToolController.selected.isEmpty() ? Collections.singletonList(btn) : PanelToolController.selected; @@ -92,7 +89,9 @@ public boolean onMouseScroll(int mx, int my, int scroll) { @Override public boolean onKeyPressed(char c, int key) { - if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { + return false; + } changeFrame(PanelToolController.selected); return true; diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java index 2a417a274..ebf213691 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolGrab.java @@ -44,7 +44,9 @@ public void disableTool() { @Override public void refresh(CanvasQuestLine gui) { - if (grabList.isEmpty()) { return; } + if (grabList.isEmpty()) { + return; + } List tmp = new ArrayList<>(); @@ -63,7 +65,9 @@ public void refresh(CanvasQuestLine gui) { @Override public void drawCanvas(int mx, int my, float partialTick) { - if (grabList.isEmpty()) { return; } + if (grabList.isEmpty()) { + return; + } int snap = Math.max(1, ToolboxTabMain.INSTANCE.getSnapValue()); int dx = mx; @@ -86,7 +90,9 @@ public void drawOverlay(int mx, int my, float partialTick) { @Override public List getTooltip(int mx, int my) { - if (grabList.isEmpty()) { return null; } + if (grabList.isEmpty()) { + return null; + } for (GrabEntry grab : grabList) { if (grab.offX == 0 && grab.offY == 0) { @@ -101,8 +107,7 @@ public List getTooltip(int mx, int my) { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean onMouseClick(int mx, int my, int click) { @@ -130,7 +135,9 @@ public boolean onMouseClick(int mx, int my, int click) { int lID = QuestLineDatabase.INSTANCE.getID(qLine); for (GrabEntry grab : grabList) { IQuestLineEntry qle = gui.getQuestLine().getValue(grab.btn.getStoredValue().getID()); - if (qle != null) { qle.setPosition(grab.btn.rect.x, grab.btn.rect.y); } + if (qle != null) { + qle.setPosition(grab.btn.rect.x, grab.btn.rect.y); + } } // Send quest line edits @@ -153,7 +160,9 @@ public boolean onMouseClick(int mx, int my, int click) { if (btnClicked != null) // Pickup the group or the single one if none are selected { if (!PanelToolController.selected.isEmpty()) { - if (!PanelToolController.selected.contains(btnClicked)) { return false; } + if (!PanelToolController.selected.contains(btnClicked)) { + return false; + } for (PanelButtonQuest btn : PanelToolController.selected) { grabList.add(new GrabEntry(btn, btn.rect.x - btnClicked.rect.x, btn.rect.y - btnClicked.rect.y)); diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java index b9e26883f..6fadaaa4a 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolIcon.java @@ -26,12 +26,10 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void disableTool() { - } + public void disableTool() { } @Override - public void refresh(CanvasQuestLine gui) { - } + public void refresh(CanvasQuestLine gui) { } @Override public boolean onMouseClick(int mx, int my, int click) { @@ -86,19 +84,19 @@ public boolean onMouseScroll(int mx, int my, int scroll) { @Override public boolean onKeyPressed(char c, int key) { - if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { + return false; + } changeIcon(PanelToolController.selected, PanelToolController.selected.get(0).getStoredValue().getValue().getProperty(NativeProps.ICON)); return true; } @Override - public void drawCanvas(int mx, int my, float partialTick) { - } + public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override public List getTooltip(int mx, int my) { @@ -111,8 +109,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java index d01a333d5..61795b10a 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolLink.java @@ -35,13 +35,17 @@ public void disableTool() { @Override public void refresh(CanvasQuestLine gui) { - if (linking.isEmpty()) { return; } + if (linking.isEmpty()) { + return; + } List tmp = new ArrayList<>(); for (PanelButtonQuest b1 : linking) { for (PanelButtonQuest b2 : gui.getQuestButtons()) { - if (b1.getStoredValue().getID() == b2.getStoredValue().getID()) { tmp.add(b2); } + if (b1.getStoredValue().getID() == b2.getStoredValue().getID()) { + tmp.add(b2); + } } } @@ -51,7 +55,9 @@ public void refresh(CanvasQuestLine gui) { @Override public void drawCanvas(int mx, int my, float partialTick) { - if (linking.isEmpty()) { return; } + if (linking.isEmpty()) { + return; + } mouseRect.x = mx; mouseRect.y = my; @@ -63,8 +69,7 @@ public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override public List getTooltip(int mx, int my) { @@ -82,10 +87,14 @@ public boolean onMouseClick(int mx, int my, int click) { if (linking.isEmpty()) { PanelButtonQuest btn = gui.getButtonAt(mx, my); - if (btn == null) { return false; } + if (btn == null) { + return false; + } if (!PanelToolController.selected.isEmpty()) { - if (!PanelToolController.selected.contains(btn)) { return false; } + if (!PanelToolController.selected.contains(btn)) { + return false; + } linking.addAll(PanelToolController.selected); return true; } @@ -95,7 +104,9 @@ public boolean onMouseClick(int mx, int my, int click) { } else { PanelButtonQuest b2 = gui.getButtonAt(mx, my); - if (b2 == null) { return false; } + if (b2 == null) { + return false; + } linking.remove(b2); if (!linking.isEmpty()) { @@ -165,8 +176,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { @@ -174,30 +184,42 @@ public boolean useSelection() { } private boolean containsReq(IQuest quest, int id) { - for (int reqID : quest.getRequirements()) { if (id == reqID) { return true; } } + for (int reqID : quest.getRequirements()) { + if (id == reqID) { + return true; + } + } return false; } private boolean removeReq(IQuest quest, int id) { int[] orig = quest.getRequirements(); - if (orig.length == 0) { return false; } + if (orig.length == 0) { + return false; + } boolean hasRemoved = false; int[] rem = new int[orig.length - 1]; for (int i = 0; i < orig.length; i++) { if (!hasRemoved && orig[i] == id) { hasRemoved = true; continue; - } else if (!hasRemoved && i >= rem.length) { break; } + } else if (!hasRemoved && i >= rem.length) { + break; + } rem[!hasRemoved ? i : (i - 1)] = orig[i]; } - if (hasRemoved) { quest.setRequirements(rem); } + if (hasRemoved) { + quest.setRequirements(rem); + } return hasRemoved; } private boolean addReq(IQuest quest, int id) { - if (containsReq(quest, id)) { return false; } + if (containsReq(quest, id)) { + return false; + } int[] orig = quest.getRequirements(); int[] added = Arrays.copyOf(orig, orig.length + 1); added[orig.length] = id; diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java index f1e262db4..e80b0919f 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolNew.java @@ -31,8 +31,7 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void refresh(CanvasQuestLine gui) { - } + public void refresh(CanvasQuestLine gui) { } @Override public void drawCanvas(int mx, int my, float partialTick) { @@ -63,7 +62,9 @@ public List getTooltip(int mx, int my) { @Override public void disableTool() { - if (nQuest != null) { nQuest = null; } + if (nQuest != null) { + nQuest = null; + } } @Override @@ -132,8 +133,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java index cb8a31dd8..675596c3f 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolOpen.java @@ -17,12 +17,10 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void disableTool() { - } + public void disableTool() { } @Override - public void refresh(CanvasQuestLine gui) { - } + public void refresh(CanvasQuestLine gui) { } @Override public boolean onMouseClick(int mx, int my, int click) { @@ -49,12 +47,10 @@ public boolean onMouseRelease(int mx, int my, int click) { } @Override - public void drawCanvas(int mx, int my, float partialTick) { - } + public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override public List getTooltip(int mx, int my) { @@ -77,8 +73,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java index 9afa3e19c..10ba23eb3 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolRemove.java @@ -23,12 +23,10 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void disableTool() { - } + public void disableTool() { } @Override - public void refresh(CanvasQuestLine gui) { - } + public void refresh(CanvasQuestLine gui) { } @Override public boolean onMouseClick(int mx, int my, int click) { @@ -41,8 +39,12 @@ public boolean onMouseClick(int mx, int my, int click) { if (line != null && btn != null) { if (!PanelToolController.selected.isEmpty()) { - if (!PanelToolController.selected.contains(btn)) { return false; } - for (PanelButtonQuest b : PanelToolController.selected) { line.removeID(b.getStoredValue().getID()); } + if (!PanelToolController.selected.contains(btn)) { + return false; + } + for (PanelButtonQuest b : PanelToolController.selected) { + line.removeID(b.getStoredValue().getID()); + } } else { int qID = btn.getStoredValue().getID(); line.removeID(qID); @@ -70,12 +72,10 @@ public boolean onMouseRelease(int mx, int my, int click) { } @Override - public void drawCanvas(int mx, int my, float partialTick) { - } + public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override public List getTooltip(int mx, int my) { @@ -91,7 +91,9 @@ public boolean onMouseScroll(int mx, int my, int scroll) { public boolean onKeyPressed(char c, int key) { if (!PanelToolController.selected.isEmpty() && key == Keyboard.KEY_RETURN) { IQuestLine line = gui.getQuestLine(); - for (PanelButtonQuest b : PanelToolController.selected) { line.removeID(b.getStoredValue().getID()); } + for (PanelButtonQuest b : PanelToolController.selected) { + line.removeID(b.getStoredValue().getID()); + } // Sync Line NBTTagCompound chPayload = new NBTTagCompound(); @@ -115,8 +117,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java index 1962a5312..ccb6a4111 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolReset.java @@ -21,16 +21,16 @@ public void initTool(CanvasQuestLine gui) { } @Override - public void disableTool() { - } + public void disableTool() { } @Override - public void refresh(CanvasQuestLine gui) { - } + public void refresh(CanvasQuestLine gui) { } @Override public boolean onMouseClick(int mx, int my, int click) { - if (click != 0 || !gui.getTransform().contains(mx, my)) { return false; } + if (click != 0 || !gui.getTransform().contains(mx, my)) { + return false; + } PanelButtonQuest btn = gui.getButtonAt(mx, my); @@ -64,12 +64,10 @@ public boolean onMouseRelease(int mx, int my, int click) { } @Override - public void drawCanvas(int mx, int my, float partialTick) { - } + public void drawCanvas(int mx, int my, float partialTick) { } @Override - public void drawOverlay(int mx, int my, float partialTick) { - } + public void drawOverlay(int mx, int my, float partialTick) { } @Override public List getTooltip(int mx, int my) { @@ -83,7 +81,9 @@ public boolean onMouseScroll(int mx, int my, int scroll) { @Override public boolean onKeyPressed(char c, int key) { - if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { return false; } + if (PanelToolController.selected.isEmpty() || key != Keyboard.KEY_RETURN) { + return false; + } List btnList = PanelToolController.selected; int[] questIDs = new int[btnList.size()]; @@ -107,8 +107,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { diff --git a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java index d9abbabc8..00efc7ec9 100644 --- a/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java +++ b/src/main/java/betterquesting/client/toolbox/tools/ToolboxToolScale.java @@ -233,8 +233,7 @@ public boolean clampScrolling() { } @Override - public void onSelection(NonNullList buttons) { - } + public void onSelection(NonNullList buttons) { } @Override public boolean useSelection() { @@ -250,8 +249,8 @@ private static class GrabEntry { private GrabEntry(PanelButtonQuest btn, Vector4f anchor) { this.btn = btn; this.anchor = anchor; - this.sx = btn.rect.x + btn.rect.w / 2; - this.sy = btn.rect.y + btn.rect.h / 2; + sx = btn.rect.x + btn.rect.w / 2; + sy = btn.rect.y + btn.rect.h / 2; } } } diff --git a/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java b/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java index 3cff42cfb..27cec5cf4 100644 --- a/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java +++ b/src/main/java/betterquesting/client/ui_builder/ComponentPanel.java @@ -65,7 +65,7 @@ public NBTTagCompound getPanelData() { } public void setPanelData(@Nonnull NBTTagCompound tag) { - this.panelData = tag; + panelData = tag; } public IGuiPanel build() { diff --git a/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java b/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java index 0feb1b652..021a21c49 100644 --- a/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java +++ b/src/main/java/betterquesting/client/ui_builder/GuiBuilderMain.java @@ -65,8 +65,8 @@ public GuiBuilderMain(GuiScreen parent) { super(parent); // We're using the entire screen including areas normally reserved for margins to make space for tools - this.useMargins(false); - this.useDefaultBG(true); + useMargins(false); + useDefaultBG(true); } @Override @@ -74,19 +74,19 @@ public void initPanel() { super.initPanel(); // The normal area with margins will now be the inner preview so we recalculate margins for that here - int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (this.width - BQ_Settings.guiWidth) / 2); - int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (this.height - BQ_Settings.guiHeight) / 2); + int marginX = BQ_Settings.guiWidth <= 0 ? 16 : Math.max(16, (width - BQ_Settings.guiWidth) / 2); + int marginY = BQ_Settings.guiHeight <= 0 ? 16 : Math.max(16, (height - BQ_Settings.guiHeight) / 2); GuiTransform pvTransform = new GuiTransform(GuiAlign.FULL_BOX, new GuiPadding(marginX, marginY, marginX, marginY), 0); cvPreview = new CanvasEmpty(pvTransform); - this.addPanel(cvPreview); + addPanel(cvPreview); // === PROPERTY TRAY === cvPropTray = new CanvasTextured(new GuiTransform(new Vector4f(0.5F, 0F, 1F, 1F), new GuiPadding(0, 32, 0, 0), 0), PresetTexture.PANEL_MAIN.getTexture()); - this.addPanel(cvPropTray); + addPanel(cvPropTray); cvPropTray.setEnabled(false); btnTrayToggle = @@ -98,12 +98,14 @@ public void initPanel() { } else if (selectedID >= 0 && !(toolMode == 0 || toolMode == 2)) { ComponentPanel com = COM_DB.getValue(selectedID); // TODO: Add a callback here so the component can read in changes - if (com != null) { openTrayNBT(com.writeToNBT(new NBTTagCompound())); } + if (com != null) { + openTrayNBT(com.writeToNBT(new NBTTagCompound())); + } } else if (toolMode == 3) { openTrayPalette(); } }); - this.addPanel(btnTrayToggle); + addPanel(btnTrayToggle); // === EXIT CORNER === @@ -113,7 +115,7 @@ public void onButtonClick() { mc.displayGuiScreen(parent); } }.setIcon(PresetIcon.ICON_CROSS.getTexture()); - this.addPanel(btnExit); + addPanel(btnExit); // === SAVE - LOAD - REFRESH === @@ -123,7 +125,7 @@ public void onButtonClick() { // Deal with this later } }.setIcon(PresetIcon.ICON_TICK.getTexture()); - this.addPanel(btnSave); + addPanel(btnSave); PanelButton btnLoad = new PanelButton(new GuiRectangle(16, 0, 16, 16, 0), -1, "") { @Override @@ -131,7 +133,7 @@ public void onButtonClick() { // Deal with this later } }.setIcon(PresetIcon.ICON_FOLDER_OPEN.getTexture()); - this.addPanel(btnLoad); + addPanel(btnLoad); PanelButton btnRefresh = new PanelButton(new GuiRectangle(32, 0, 16, 16, 0), -1, "") { @Override @@ -139,7 +141,7 @@ public void onButtonClick() { refreshComponents(); } }.setIcon(PresetIcon.ICON_REFRESH.getTexture()); - this.addPanel(btnRefresh); + addPanel(btnRefresh); // === TOOL ROW === @@ -149,24 +151,24 @@ public void onButtonClick() { @Override public void onButtonClick() { toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); + setActive(false); toolMode = 0; } }.setIcon(PresetIcon.ICON_CURSOR.getTexture()); btnCursor.setActive(toolMode != 0); - this.addPanel(btnCursor); + addPanel(btnCursor); toolBtns.add(btnCursor); PanelButton btnProp = new PanelButton(new GuiTransform(GuiAlign.BOTTOM_LEFT, 16, -16, 16, 16, 0), -1, "") { @Override public void onButtonClick() { toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); + setActive(false); toolMode = 1; } }.setIcon(PresetIcon.ICON_PROPS.getTexture()); btnProp.setActive(toolMode != 1); - this.addPanel(btnProp); + addPanel(btnProp); toolBtns.add(btnProp); // Adds a new panel based on where the user clicked (we can re-parent thing later so we don't need pre-selection functionality) @@ -174,14 +176,14 @@ public void onButtonClick() { @Override public void onButtonClick() { toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); + setActive(false); toolMode = 2; openTrayPalette(); } }.setIcon(PresetIcon.ICON_POSITIVE.getTexture()); btnAdd.setActive(toolMode != 2); - this.addPanel(btnAdd); + addPanel(btnAdd); toolBtns.add(btnAdd); // Changes the canvas parent @@ -189,12 +191,12 @@ public void onButtonClick() { @Override public void onButtonClick() { toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); + setActive(false); toolMode = 3; } }.setIcon(PresetIcon.ICON_SCALE.getTexture()); btnSize.setActive(toolMode != 3); - this.addPanel(btnSize); + addPanel(btnSize); toolBtns.add(btnSize); // Edit the transform bounds @@ -203,12 +205,12 @@ public void onButtonClick() { @Override public void onButtonClick() { toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); + setActive(false); toolMode = 4; } }.setIcon(PresetIcon.ICON_LINK.getTexture()); btnLink.setActive(toolMode != 4); - this.addPanel(btnLink); + addPanel(btnLink); toolBtns.add(btnLink); // Delete the panel and its children @@ -216,12 +218,12 @@ public void onButtonClick() { @Override public void onButtonClick() { toolBtns.forEach((btn) -> btn.setActive(true)); - this.setActive(false); + setActive(false); toolMode = 5; } }.setIcon(PresetIcon.ICON_TRASH.getTexture()); btnDel.setActive(toolMode != 5); - this.addPanel(btnDel); + addPanel(btnDel); toolBtns.add(btnDel); refreshComponents(); @@ -284,7 +286,9 @@ public void drawPanel(int mx, int my, float partialTick) { } } - if (com != null) { com.setTransform(trans); } + if (com != null) { + com.setTransform(trans); + } } else if ((dragType & 16) == 0 && selPn.getTransform() instanceof GuiTransform) { // TODO: Make this work for GuiRectangle (or just deprecate that class entirely... but legacy support uhg) GuiTransform trans = (GuiTransform) selPn.getTransform(); @@ -329,12 +333,16 @@ public void drawPanel(int mx, int my, float partialTick) { } } - if (com != null) { com.setTransform(trans); } + if (com != null) { + com.setTransform(trans); + } } } if (!Mouse.isButtonDown(0)) { - if (dragID >= 0) { refreshComponents(); } + if (dragID >= 0) { + refreshComponents(); + } dragID = -1; dragType = -1; } @@ -344,7 +352,9 @@ public void drawPanel(int mx, int my, float partialTick) { if (toolMode == 2 && cvPreview.getTransform().contains(mx, my)) { IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); - if (topPanel == null) { topPanel = cvPreview; } + if (topPanel == null) { + topPanel = cvPreview; + } IGuiRect drawBounds; @@ -374,10 +384,14 @@ public void drawPanel(int mx, int my, float partialTick) { private final IGuiColor boundsCol = new GuiColorStatic(0xFF0000FF); private void drawTransformBounds(@Nonnull IGuiRect rect, boolean showNumbers) { - if (rect.getParent() != null) { boxLine.drawLine(rect.getParent(), rect.getParent(), 2, parCol, 1F); } + if (rect.getParent() != null) { + boxLine.drawLine(rect.getParent(), rect.getParent(), 2, parCol, 1F); + } boxLine.drawLine(rect, rect, 2, boundsCol, 1F); - if (rect.getParent() == null) { return; } + if (rect.getParent() == null) { + return; + } int midX = rect.getX() + rect.getWidth() / 2; int midY = rect.getY() + rect.getHeight() / 2; @@ -449,14 +463,18 @@ private void drawSimpleLine(int x1, int y1, int x2, int y2, int width, IGuiColor @Override public boolean onMouseClick(int mx, int my, int click) { - if (toolMode == 0 || !cvPreview.getTransform().contains(mx, my)) { return super.onMouseClick(mx, my, click); } + if (toolMode == 0 || !cvPreview.getTransform().contains(mx, my)) { + return super.onMouseClick(mx, my, click); + } if (toolMode == 1) { if (click == 0) { IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); // Has a bit of give in it so tiny panels can still be grabbed selectedID = PANEL_DB.getID(topPanel); - if (selectedID >= 0) { selPn = topPanel; } + if (selectedID >= 0) { + selPn = topPanel; + } } else if (click == 1) { selPn = null; selectedID = -1; @@ -464,7 +482,9 @@ public boolean onMouseClick(int mx, int my, int click) { } else if (toolMode == 2 && click == 0 && paletteSel != null) // Create { IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); - if (topPanel == null) { topPanel = cvPreview; } + if (topPanel == null) { + topPanel = cvPreview; + } GuiTransform drawBounds; @@ -505,7 +525,9 @@ public boolean onMouseClick(int mx, int my, int click) { IGuiPanel topPanel = getPanelUnderMouse(mx, my, 0); // Has a bit of give in it so tiny panels can still be grabbed selectedID = PANEL_DB.getID(topPanel); - if (selectedID >= 0) { selPn = topPanel; } + if (selectedID >= 0) { + selPn = topPanel; + } } else if (click == 0) { int edgePad = getNearbyEdges(selPn.getTransform(), mx, my, 4, true); int edgePar = 0; @@ -566,7 +588,9 @@ private void refreshComponents() { while (!parentQueue.isEmpty()) { int pID = parentQueue.poll(); IGuiPanel pPan = PANEL_DB.getValue(pID); - if (pPan == null) { pPan = cvPreview; } + if (pPan == null) { + pPan = cvPreview; + } if (pPan instanceof IGuiCanvas) // Skip if we can't parent it { @@ -580,12 +604,16 @@ private void refreshComponents() { // Transform parenting (must occur after canvas parenting) ComponentPanel com = COM_DB.getValue(pID); IGuiPanel tPan = com == null ? null : PANEL_DB.getValue(com.tfParentID); - if (tPan != null) { pPan.getTransform().setParent(tPan.getTransform()); } + if (tPan != null) { + pPan.getTransform().setParent(tPan.getTransform()); + } } if (selectedID >= 0) { selPn = PANEL_DB.getValue(selectedID); - if (selPn == null) { selectedID = -1; } + if (selPn == null) { + selectedID = -1; + } } } @@ -609,7 +637,9 @@ private List> getCanvasChildren(int panelID) { List> list = new ArrayList<>(); COM_DB.getEntries().forEach((entry) -> { - if (entry.getValue().cvParentID == panelID) { list.add(entry); } + if (entry.getValue().cvParentID == panelID) { + list.add(entry); + } }); return list; @@ -620,7 +650,9 @@ private List> getTransformChildren(int panelID) { List> list = new ArrayList<>(); COM_DB.getEntries().forEach((entry) -> { - if (entry.getValue().tfParentID == panelID) { list.add(entry); } + if (entry.getValue().tfParentID == panelID) { + list.add(entry); + } }); return list; @@ -721,7 +753,9 @@ private int getNearbyEdges(IGuiRect rect, int mx, int my, int range, boolean bou } private int getSegmentSlice(IGuiRect rect, int mx, int my) { - if (!rect.contains(mx, my)) { return -1; } + if (!rect.contains(mx, my)) { + return -1; + } int dx = mx - rect.getX(); int dy = my - rect.getY(); diff --git a/src/main/java/betterquesting/commands/BQ_CommandAdmin.java b/src/main/java/betterquesting/commands/BQ_CommandAdmin.java index 870b6ab0a..92db27201 100644 --- a/src/main/java/betterquesting/commands/BQ_CommandAdmin.java +++ b/src/main/java/betterquesting/commands/BQ_CommandAdmin.java @@ -72,7 +72,8 @@ public String getUsage(@Nonnull ICommandSender sender) { */ @Nonnull @Override - public List getTabCompletions(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] strings, BlockPos pos) { + public List getTabCompletions(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, + String[] strings, BlockPos pos) { if (strings.length == 1) { List base = new ArrayList<>(); for (QuestCommandBase c : coms) { @@ -102,9 +103,10 @@ public int getRequiredPermissionLevel() { } @Override - public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] args) throws CommandException { + public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] args) + throws CommandException { if (args.length < 1) { - throw new WrongUsageException(this.getUsage(sender)); + throw new WrongUsageException(getUsage(sender)); } for (QuestCommandBase c : coms) { @@ -126,7 +128,7 @@ public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sen } } - throw new WrongUsageException(this.getUsage(sender)); + throw new WrongUsageException(getUsage(sender)); } /** diff --git a/src/main/java/betterquesting/commands/BQ_CommandUser.java b/src/main/java/betterquesting/commands/BQ_CommandUser.java index ad7d0365d..bd0fcb10a 100644 --- a/src/main/java/betterquesting/commands/BQ_CommandUser.java +++ b/src/main/java/betterquesting/commands/BQ_CommandUser.java @@ -74,7 +74,8 @@ public String getUsage(@Nonnull ICommandSender sender) { */ @Nonnull @Override - public List getTabCompletions(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] strings, BlockPos pos) { + public List getTabCompletions(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, + String[] strings, BlockPos pos) { if (strings.length == 1) { List base = new ArrayList<>(); for (QuestCommandBase c : coms) { @@ -99,9 +100,10 @@ public List getTabCompletions(@Nonnull MinecraftServer server, @Nonnull } @Override - public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] args) throws CommandException { + public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, String[] args) + throws CommandException { if (args.length < 1) { - throw new WrongUsageException(this.getUsage(sender)); + throw new WrongUsageException(getUsage(sender)); } for (QuestCommandBase c : coms) { @@ -123,7 +125,7 @@ public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sen } } - throw new WrongUsageException(this.getUsage(sender)); + throw new WrongUsageException(getUsage(sender)); } /** diff --git a/src/main/java/betterquesting/commands/QuestCommandBase.java b/src/main/java/betterquesting/commands/QuestCommandBase.java index fb4098e9c..76a89eada 100644 --- a/src/main/java/betterquesting/commands/QuestCommandBase.java +++ b/src/main/java/betterquesting/commands/QuestCommandBase.java @@ -23,7 +23,7 @@ public String getUsageSuffix() { } public QuestCommandBase() { - this.registerPermission(); + registerPermission(); } public abstract String getPermissionNode(); @@ -33,7 +33,7 @@ public QuestCommandBase() { public abstract String getPermissionDescription(); private void registerPermission() { - PermissionAPI.registerNode(this.getPermissionNode(), this.getPermissionLevel(), this.getPermissionDescription()); + PermissionAPI.registerNode(getPermissionNode(), getPermissionLevel(), getPermissionDescription()); } /** diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java b/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java index fa2204d05..e22a00b89 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandComplete.java @@ -56,22 +56,26 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend UUID uuid; if (args.length >= 3) { - uuid = this.findPlayerID(server, sender, args[2]); + uuid = findPlayerID(server, sender, args[2]); if (uuid == null) { - throw this.getException(command); + throw getException(command); } } else { - uuid = this.findPlayerID(server, sender, sender.getName()); + uuid = findPlayerID(server, sender, sender.getName()); } - if (uuid == null) { return; } + if (uuid == null) { + return; + } String pName = NameCache.INSTANCE.getName(uuid); int id = Integer.parseInt(args[1].trim()); IQuest quest = QuestDatabase.INSTANCE.getValue(id); - if (quest == null) { throw getException(command); } + if (quest == null) { + throw getException(command); + } NetQuestEdit.setQuestStates(new int[] { id }, true, uuid); sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.complete", new TextComponentTranslation(quest.getProperty(NativeProps.NAME)), diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java b/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java index b7fdb35b1..54ccd695e 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandEdit.java @@ -52,7 +52,7 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend flag = Boolean.parseBoolean(args[1]); } } catch (Exception e) { - throw this.getException(command); + throw getException(command); } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java b/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java index 76e77a85c..99d450a92 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandHardcore.java @@ -52,7 +52,7 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend flag = Boolean.parseBoolean(args[1]); } } catch (Exception e) { - throw this.getException(command); + throw getException(command); } } diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandLives.java b/src/main/java/betterquesting/commands/admin/QuestCommandLives.java index ba5b62e83..072570dd0 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandLives.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandLives.java @@ -60,7 +60,7 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend } if (args.length >= 4) { - playerID = this.findPlayerID(server, sender, args[3]); + playerID = findPlayerID(server, sender, args[3]); if (playerID == null) { throw getException(command); @@ -76,7 +76,9 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend LifeDatabase.INSTANCE.setLives(playerID, value); EntityPlayerMP target = server.getPlayerList().getPlayerByUUID(playerID); //noinspection ConstantConditions - if (target != null) { NetLifeSync.sendSync(new EntityPlayerMP[] { target }, new UUID[] { playerID }); } + if (target != null) { + NetLifeSync.sendSync(new EntityPlayerMP[] { target }, new UUID[] { playerID }); + } sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.set_player", pName, value)); } else { for (EntityPlayerMP p : server.getPlayerList().getPlayers()) // TODO: Make this work for offline players @@ -94,7 +96,9 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend LifeDatabase.INSTANCE.setLives(playerID, lives); EntityPlayerMP target = server.getPlayerList().getPlayerByUUID(playerID); //noinspection ConstantConditions - if (target != null) { NetLifeSync.sendSync(new EntityPlayerMP[] { target }, new UUID[] { playerID }); } + if (target != null) { + NetLifeSync.sendSync(new EntityPlayerMP[] { target }, new UUID[] { playerID }); + } if (value >= 0) { sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.lives.add_player", value, pName, lives)); diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java b/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java index 1db4eaba6..6b0f28d12 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandPurge.java @@ -40,13 +40,19 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend int n = -1; for (DBEntry entry : QuestDatabase.INSTANCE.getEntries()) { - while (n < entry.getID() && keyIterator.hasNext()) { n = keyIterator.next(); } - if (n != entry.getID()) { removeQueue.add(entry.getID()); } + while (n < entry.getID() && keyIterator.hasNext()) { + n = keyIterator.next(); + } + if (n != entry.getID()) { + removeQueue.add(entry.getID()); + } } int removed = removeQueue.size(); int[] bulkIDs = new int[removeQueue.size()]; - for (n = 0; n < bulkIDs.length; n++) { bulkIDs[n] = removeQueue.get(n); } + for (n = 0; n < bulkIDs.length; n++) { + bulkIDs[n] = removeQueue.get(n); + } NetQuestEdit.deleteQuests(bulkIDs); sender.sendMessage(new TextComponentTranslation("betterquesting.cmd.purge_hidden", removed)); diff --git a/src/main/java/betterquesting/commands/admin/QuestCommandReset.java b/src/main/java/betterquesting/commands/admin/QuestCommandReset.java index 1480bef38..a471de073 100644 --- a/src/main/java/betterquesting/commands/admin/QuestCommandReset.java +++ b/src/main/java/betterquesting/commands/admin/QuestCommandReset.java @@ -62,10 +62,10 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend UUID uuid = null; if (args.length == 3) { - uuid = this.findPlayerID(server, sender, args[2]); + uuid = findPlayerID(server, sender, args[2]); if (uuid == null) { - throw this.getException(command); + throw getException(command); } } diff --git a/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java b/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java index d7a3bf846..26c5f542d 100644 --- a/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java +++ b/src/main/java/betterquesting/commands/user/QuestCommandRefresh.java @@ -23,7 +23,9 @@ public String getCommand() { @Override public void runCommand(MinecraftServer server, CommandBase command, ICommandSender sender, String[] args) { - if (!(sender instanceof EntityPlayerMP)) { return; } + if (!(sender instanceof EntityPlayerMP)) { + return; + } EntityPlayerMP player = (EntityPlayerMP) sender; if (server.isDedicatedServer() || !server.getServerOwner().equals(player.getGameProfile().getName())) { @@ -32,7 +34,9 @@ public void runCommand(MinecraftServer server, CommandBase command, ICommandSend } else { boolean nameChanged = NameCache.INSTANCE.updateName(player); DBEntry party = PartyManager.INSTANCE.getParty(QuestingAPI.getQuestingUUID(player)); - if (nameChanged && party != null) { NetNameSync.quickSync(null, party.getID()); } + if (nameChanged && party != null) { + NetNameSync.quickSync(null, party.getID()); + } } } diff --git a/src/main/java/betterquesting/core/BetterQuesting.java b/src/main/java/betterquesting/core/BetterQuesting.java index b4a5924f8..8199ea7c6 100644 --- a/src/main/java/betterquesting/core/BetterQuesting.java +++ b/src/main/java/betterquesting/core/BetterQuesting.java @@ -30,7 +30,10 @@ import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.event.*; +import net.minecraftforge.fml.common.event.FMLInitializationEvent; +import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; +import net.minecraftforge.fml.common.event.FMLServerStartingEvent; +import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.registry.EntityRegistry; diff --git a/src/main/java/betterquesting/core/proxies/CommonProxy.java b/src/main/java/betterquesting/core/proxies/CommonProxy.java index 9382729b7..0be79c772 100644 --- a/src/main/java/betterquesting/core/proxies/CommonProxy.java +++ b/src/main/java/betterquesting/core/proxies/CommonProxy.java @@ -22,6 +22,5 @@ public void registerHandlers() { NetworkRegistry.INSTANCE.registerGuiHandler(BetterQuesting.instance, new GuiHandler()); } - public void registerRenderers() { - } + public void registerRenderers() { } } diff --git a/src/main/java/betterquesting/handlers/EventHandler.java b/src/main/java/betterquesting/handlers/EventHandler.java index d6488853d..138b7a230 100644 --- a/src/main/java/betterquesting/handlers/EventHandler.java +++ b/src/main/java/betterquesting/handlers/EventHandler.java @@ -91,7 +91,9 @@ public void onKey(InputEvent.KeyInputEvent event) { @SubscribeEvent public void onCapabilityPlayer(AttachCapabilitiesEvent event) { - if (!(event.getObject() instanceof EntityPlayer)) { return; } + if (!(event.getObject() instanceof EntityPlayer)) { + return; + } event.addCapability(CapabilityProviderQuestCache.LOC_QUEST_CACHE, new CapabilityProviderQuestCache()); } @@ -102,7 +104,9 @@ public void onPlayerClone(Clone event) { QuestCache nCache = event.getEntityPlayer().getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (oCache != null && nCache != null) { nCache.deserializeNBT(oCache.serializeNBT()); } + if (oCache != null && nCache != null) { + nCache.deserializeNBT(oCache.serializeNBT()); + } } @SubscribeEvent @@ -143,7 +147,9 @@ public void onLivingUpdate(TickEvent.PlayerTickEvent event) { qc.markQuestDirty(quest.getID()); com.add(quest.getID()); - if (!quest.getValue().getProperty(NativeProps.SILENT)) { postPresetNotice(quest.getValue(), player, 2); } + if (!quest.getValue().getProperty(NativeProps.SILENT)) { + postPresetNotice(quest.getValue(), player, 2); + } } } @@ -169,7 +175,9 @@ public void onLivingUpdate(TickEvent.PlayerTickEvent event) { refreshCache = true; qc.markQuestDirty(rTime.questID); res.add(rTime.questID); - if (!entry.getProperty(NativeProps.SILENT)) { postPresetNotice(entry, player, 1); } + if (!entry.getProperty(NativeProps.SILENT)) { + postPresetNotice(entry, player, 1); + } } else { break; // Entries are sorted by time so we fail fast and skip checking the others } @@ -203,7 +211,9 @@ public void onLivingUpdate(TickEvent.PlayerTickEvent event) { // TODO: Create a new message inbox system for these things. On screen popups aren't ideal in combat private static void postPresetNotice(IQuest quest, EntityPlayer player, int preset) { - if (!(player instanceof EntityPlayerMP)) { return; } + if (!(player instanceof EntityPlayerMP)) { + return; + } ItemStack icon = quest.getProperty(NativeProps.ICON).getBaseStack(); String mainText = ""; String subText = quest.getProperty(NativeProps.NAME); @@ -275,7 +285,9 @@ public void onPlayerRespawn(PlayerRespawnEvent event) { if (lives <= 0) { MinecraftServer server = mpPlayer.getServer(); - if (server == null) { return; } + if (server == null) { + return; + } mpPlayer.setGameType(GameType.SPECTATOR); if (!server.isDedicatedServer()) { @@ -341,14 +353,18 @@ public void onCommand(CommandEvent event) { @SubscribeEvent public void onServerTick(ServerTickEvent event) { - if (event.phase != Phase.END) { return; } + if (event.phase != Phase.END) { + return; + } MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); if (!server.isDedicatedServer()) { boolean tmp = openToLAN; openToLAN = server instanceof IntegratedServer && ((IntegratedServer) server).getPublic(); - if (openToLAN && !tmp) { opQueue.addAll(server.getPlayerList().getPlayers()); } + if (openToLAN && !tmp) { + opQueue.addAll(server.getPlayerList().getPlayers()); + } } else if (!openToLAN) { openToLAN = true; } @@ -366,6 +382,8 @@ public void onServerTick(ServerTickEvent event) { } } - if (server.getTickCounter() % 60 == 0) { PartyInvitations.INSTANCE.cleanExpired(); } + if (server.getTickCounter() % 60 == 0) { + PartyInvitations.INSTANCE.cleanExpired(); + } } } diff --git a/src/main/java/betterquesting/handlers/SaveLoadHandler.java b/src/main/java/betterquesting/handlers/SaveLoadHandler.java index 656cacb53..44509b717 100644 --- a/src/main/java/betterquesting/handlers/SaveLoadHandler.java +++ b/src/main/java/betterquesting/handlers/SaveLoadHandler.java @@ -35,15 +35,15 @@ public class SaveLoadHandler { private boolean isDirty = false; public boolean hasUpdate() { - return this.hasUpdate; + return hasUpdate; } public void resetUpdate() { - this.hasUpdate = false; + hasUpdate = false; } public void markDirty() { - this.isDirty = true; + isDirty = true; } public void loadDatabases(MinecraftServer server) { @@ -129,7 +129,9 @@ public void loadDatabases(MinecraftServer server) { { String fsVer = JsonHelper.makeFileNameSafe(bVer); - if (fsVer.isEmpty()) { fsVer = "pre-251"; } + if (fsVer.isEmpty()) { + fsVer = "pre-251"; + } BetterQuesting.logger.warn( "BetterQuesting has been updated to from \"" + fsVer + "\" to \"" + cVer + "\"! Creating back ups..."); diff --git a/src/main/java/betterquesting/items/ItemExtraLife.java b/src/main/java/betterquesting/items/ItemExtraLife.java index 929ef6f1d..2a2ef49b3 100644 --- a/src/main/java/betterquesting/items/ItemExtraLife.java +++ b/src/main/java/betterquesting/items/ItemExtraLife.java @@ -23,9 +23,9 @@ public class ItemExtraLife extends Item { public ItemExtraLife() { - this.setTranslationKey("betterquesting.extra_life"); - this.setCreativeTab(BetterQuesting.tabQuesting); - this.setHasSubtypes(true); + setTranslationKey("betterquesting.extra_life"); + setCreativeTab(BetterQuesting.tabQuesting); + setHasSubtypes(true); } /** @@ -80,11 +80,11 @@ public ActionResult onItemRightClick(@Nonnull World world, EntityPlay public String getTranslationKey(ItemStack stack) { switch (stack.getItemDamage() % 3) { case 2: - return this.getTranslationKey() + ".quarter"; + return getTranslationKey() + ".quarter"; case 1: - return this.getTranslationKey() + ".half"; + return getTranslationKey() + ".half"; default: - return this.getTranslationKey() + ".full"; + return getTranslationKey() + ".full"; } } @@ -100,7 +100,7 @@ public boolean hasEffect(ItemStack stack) { @Override @SideOnly(Side.CLIENT) public void getSubItems(@Nonnull CreativeTabs tab, @Nonnull NonNullList list) { - if (this.isInCreativeTab(tab)) { + if (isInCreativeTab(tab)) { list.add(new ItemStack(this, 1, 0)); list.add(new ItemStack(this, 1, 1)); list.add(new ItemStack(this, 1, 2)); diff --git a/src/main/java/betterquesting/items/ItemGuideBook.java b/src/main/java/betterquesting/items/ItemGuideBook.java index 57991c6ca..16dc260d9 100644 --- a/src/main/java/betterquesting/items/ItemGuideBook.java +++ b/src/main/java/betterquesting/items/ItemGuideBook.java @@ -15,8 +15,8 @@ public class ItemGuideBook extends Item { public ItemGuideBook() { - this.setTranslationKey("betterquesting.guide"); - this.setCreativeTab(BetterQuesting.tabQuesting); + setTranslationKey("betterquesting.guide"); + setCreativeTab(BetterQuesting.tabQuesting); } /** diff --git a/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java b/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java index 39c699a4f..9aef9a2ac 100644 --- a/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java +++ b/src/main/java/betterquesting/legacy/v0/LegacyLoader_v0.java @@ -30,8 +30,7 @@ public final class LegacyLoader_v0 implements ILegacyLoader { public static final LegacyLoader_v0 INSTANCE = new LegacyLoader_v0(); - private LegacyLoader_v0() { - } + private LegacyLoader_v0() { } @Override public void readFromJson(JsonElement rawJson) { @@ -78,7 +77,9 @@ public void readQuestDatabase(JsonArray jAry) { @Override public void readProgressFromJson(JsonElement json) { - if (!json.isJsonObject()) { return; } + if (!json.isJsonObject()) { + return; + } QuestDatabase.INSTANCE.readProgressFromNBT( NBTConverter.JSONtoNBT_Object(json.getAsJsonObject(), new NBTTagCompound(), true) .getTagList("questProgress", 10), false); diff --git a/src/main/java/betterquesting/misc/QuestResourcesFile.java b/src/main/java/betterquesting/misc/QuestResourcesFile.java index d7a1b60fe..fca81fe72 100644 --- a/src/main/java/betterquesting/misc/QuestResourcesFile.java +++ b/src/main/java/betterquesting/misc/QuestResourcesFile.java @@ -94,7 +94,7 @@ private Set GetZipDomains(ZipFile zipfile) { String s1 = arraylist.get(1); if (!s1.equals(s1.toLowerCase())) { - this.logNameNotLowercase(s1, zipfile.getName()); + logNameNotLowercase(s1, zipfile.getName()); } else { hashset.add(s1); } @@ -113,7 +113,9 @@ public T getPackMetadata(@Nonnull MetadataSerialize @Nonnull @Override public BufferedImage getPackImage() { - if (bufferedImage != null) { return bufferedImage; } + if (bufferedImage != null) { + return bufferedImage; + } try { bufferedImage = TextureUtil.readBufferedImage( @@ -132,14 +134,18 @@ public String getPackName() { } private List getZipFiles() { - if (zipList != null) { return zipList; } + if (zipList != null) { + return zipList; + } if (!rootFolder.exists() && !rootFolder.mkdirs()) { return Collections.emptyList(); } File[] files = rootFolder.listFiles(); - if (files == null || files.length == 0) { return Collections.emptyList(); } + if (files == null || files.length == 0) { + return Collections.emptyList(); + } zipList = new ArrayList<>(); @@ -165,7 +171,7 @@ private void logNameNotLowercase(String name, String file) { @Override protected void finalize() throws Throwable { - this.close(); + close(); super.finalize(); } diff --git a/src/main/java/betterquesting/misc/QuestResourcesFolder.java b/src/main/java/betterquesting/misc/QuestResourcesFolder.java index 5aa46c8f7..9cfb09f52 100644 --- a/src/main/java/betterquesting/misc/QuestResourcesFolder.java +++ b/src/main/java/betterquesting/misc/QuestResourcesFolder.java @@ -34,7 +34,8 @@ public InputStream getInputStream(@Nonnull ResourceLocation location) throws IOE } // TODO: Figure out if we can fix UTF8 encoding from here - return Files.newInputStream(new File(rootFolder.getPath() + "/" + location.getNamespace(), location.getPath()).toPath()); + return Files.newInputStream( + new File(rootFolder.getPath() + "/" + location.getNamespace(), location.getPath()).toPath()); } @Override @@ -51,7 +52,9 @@ public Set getResourceDomains() { } String[] content = rootFolder.list(); - if (content == null || content.length == 0) { return Collections.emptySet(); } + if (content == null || content.length == 0) { + return Collections.emptySet(); + } HashSet folders = new HashSet<>(); for (String s : content) { @@ -77,7 +80,9 @@ public T getPackMetadata(@Nonnull MetadataSerialize @Nonnull @Override public BufferedImage getPackImage() { - if (bufferedImage != null) { return bufferedImage; } + if (bufferedImage != null) { + return bufferedImage; + } try { bufferedImage = TextureUtil.readBufferedImage( diff --git a/src/main/java/betterquesting/network/PacketQuesting.java b/src/main/java/betterquesting/network/PacketQuesting.java index cbf7e0404..8b4cd4e5a 100644 --- a/src/main/java/betterquesting/network/PacketQuesting.java +++ b/src/main/java/betterquesting/network/PacketQuesting.java @@ -21,8 +21,7 @@ public class PacketQuesting implements IMessage { @SuppressWarnings("unused") public PacketQuesting() // For use only by forge - { - } + { } public PacketQuesting(NBTTagCompound tags) // Use PacketDataTypes to instantiate new packets { diff --git a/src/main/java/betterquesting/network/PacketSetupStation.java b/src/main/java/betterquesting/network/PacketSetupStation.java index ae8924b0b..f27911725 100644 --- a/src/main/java/betterquesting/network/PacketSetupStation.java +++ b/src/main/java/betterquesting/network/PacketSetupStation.java @@ -66,7 +66,8 @@ public IMessage onMessage(PacketSetupStation message, MessageContext ctx) { return; } ContainerSubmitStation containerSS = (ContainerSubmitStation) container; - if (containerSS.tile != oss || containerSS.windowId != sync) { //If Vanilla checks windowId then there is some point in it, right? + //If Vanilla checks windowId then there is some point in it, right? + if (containerSS.tile != oss || containerSS.windowId != sync) { return; } oss.setupTask(player.getUniqueID(), questId, taskId); diff --git a/src/main/java/betterquesting/network/handlers/NetBulkSync.java b/src/main/java/betterquesting/network/handlers/NetBulkSync.java index 2aa3a673e..5e337f060 100644 --- a/src/main/java/betterquesting/network/handlers/NetBulkSync.java +++ b/src/main/java/betterquesting/network/handlers/NetBulkSync.java @@ -66,7 +66,9 @@ public static void sendSync(@Nonnull EntityPlayerMP player) { for (int i = 0; i < invites.size(); i++) { pids[i] = invites.get(i).getKey(); } - if (party != null) { pids[partyCount - 1] = party.getID(); } + if (party != null) { + pids[partyCount - 1] = party.getID(); + } NetPartySync.sendSync(new EntityPlayerMP[] { player }, pids); } if (party != null) { diff --git a/src/main/java/betterquesting/network/handlers/NetCacheSync.java b/src/main/java/betterquesting/network/handlers/NetCacheSync.java index 6a8797057..5920de78d 100644 --- a/src/main/java/betterquesting/network/handlers/NetCacheSync.java +++ b/src/main/java/betterquesting/network/handlers/NetCacheSync.java @@ -27,7 +27,9 @@ public static void registerHandler() { public static void sendSync(@Nonnull EntityPlayerMP player) { QuestCache qc = player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null); - if (qc == null) { return; } + if (qc == null) { + return; + } NBTTagCompound payload = new NBTTagCompound(); payload.setTag("data", qc.serializeNBT()); PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), player); @@ -37,6 +39,8 @@ public static void sendSync(@Nonnull EntityPlayerMP player) { private static void onClient(NBTTagCompound message) { EntityPlayer player = Minecraft.getMinecraft().player; QuestCache qc = player != null ? player.getCapability(CapabilityProviderQuestCache.CAP_QUEST_CACHE, null) : null; - if (qc != null) { qc.deserializeNBT(message.getCompoundTag("data")); } + if (qc != null) { + qc.deserializeNBT(message.getCompoundTag("data")); + } } } diff --git a/src/main/java/betterquesting/network/handlers/NetChapterEdit.java b/src/main/java/betterquesting/network/handlers/NetChapterEdit.java index 61b6ba473..bf857ca2a 100644 --- a/src/main/java/betterquesting/network/handlers/NetChapterEdit.java +++ b/src/main/java/betterquesting/network/handlers/NetChapterEdit.java @@ -94,7 +94,9 @@ private static void editChapters(NBTTagList data) { ids[i] = chapterID; IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); - if (chapter != null) { chapter.readFromNBT(entry.getCompoundTag("config"), false); } + if (chapter != null) { + chapter.readFromNBT(entry.getCompoundTag("config"), false); + } } SaveLoadHandler.INSTANCE.markDirty(); @@ -133,12 +135,18 @@ private static void createChapters(NBTTagList data) // Includes future copy pote for (int i = 0; i < data.tagCount(); i++) { NBTTagCompound entry = data.getCompoundTagAt(i); int chapterID = entry.hasKey("chapterID", 99) ? entry.getInteger("chapterID") : -1; - if (chapterID < 0) { chapterID = QuestLineDatabase.INSTANCE.nextID(); } + if (chapterID < 0) { + chapterID = QuestLineDatabase.INSTANCE.nextID(); + } ids[i] = chapterID; IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); - if (chapter == null) { chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); } - if (entry.hasKey("config", 10)) { chapter.readFromNBT(entry.getCompoundTag("config"), false); } + if (chapter == null) { + chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); + } + if (entry.hasKey("config", 10)) { + chapter.readFromNBT(entry.getCompoundTag("config"), false); + } } SaveLoadHandler.INSTANCE.markDirty(); diff --git a/src/main/java/betterquesting/network/handlers/NetChapterSync.java b/src/main/java/betterquesting/network/handlers/NetChapterSync.java index a2b26658d..987bb4536 100644 --- a/src/main/java/betterquesting/network/handlers/NetChapterSync.java +++ b/src/main/java/betterquesting/network/handlers/NetChapterSync.java @@ -34,7 +34,9 @@ public static void registerHandler() { } public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] chapterIDs) { - if (chapterIDs != null && chapterIDs.length == 0) { return; } + if (chapterIDs != null && chapterIDs.length == 0) { + return; + } BQThreadedIO.INSTANCE.enqueue(() -> { NBTTagList data = new NBTTagList(); @@ -72,7 +74,9 @@ public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] cha @SideOnly(Side.CLIENT) public static void requestSync(@Nullable int[] chapterIDs) { NBTTagCompound payload = new NBTTagCompound(); - if (chapterIDs != null) { payload.setIntArray("requestIDs", chapterIDs); } + if (chapterIDs != null) { + payload.setIntArray("requestIDs", chapterIDs); + } PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); } @@ -85,16 +89,22 @@ private static void onServer(Tuple message) { @SideOnly(Side.CLIENT) private static void onClient(NBTTagCompound message) { NBTTagList data = message.getTagList("data", 10); - if (!message.getBoolean("merge")) { QuestLineDatabase.INSTANCE.reset(); } + if (!message.getBoolean("merge")) { + QuestLineDatabase.INSTANCE.reset(); + } for (int i = 0; i < data.tagCount(); i++) { NBTTagCompound tag = data.getCompoundTagAt(i); - if (!tag.hasKey("chapterID", 99)) { continue; } + if (!tag.hasKey("chapterID", 99)) { + continue; + } int chapterID = tag.getInteger("chapterID"); //int order = tag.getInteger("order"); IQuestLine chapter = QuestLineDatabase.INSTANCE.getValue(chapterID); // TODO: Send to client side database - if (chapter == null) { chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); } + if (chapter == null) { + chapter = QuestLineDatabase.INSTANCE.createNew(chapterID); + } //QuestLineDatabase.INSTANCE.setOrderIndex(chapterID, order); chapter.readFromNBT(tag.getCompoundTag("config"), diff --git a/src/main/java/betterquesting/network/handlers/NetImport.java b/src/main/java/betterquesting/network/handlers/NetImport.java index cc42aa2a0..ccec2325b 100644 --- a/src/main/java/betterquesting/network/handlers/NetImport.java +++ b/src/main/java/betterquesting/network/handlers/NetImport.java @@ -43,7 +43,9 @@ public static void sendImport(@Nonnull IQuestDatabase questDB, @Nonnull IQuestLi private static void onServer(Tuple message) { EntityPlayerMP sender = message.getSecond(); - if (sender.getServer() == null) { return; } + if (sender.getServer() == null) { + return; + } boolean isOP = sender.getServer().getPlayerList().canSendCommands(sender.getGameProfile()); @@ -125,7 +127,9 @@ private static int[] getNextIDs(int num) { int[] nxtIDs = new int[num]; if (listDB.isEmpty() || listDB.get(listDB.size() - 1).getID() == listDB.size() - 1) { - for (int i = 0; i < num; i++) { nxtIDs[i] = listDB.size() + i; } + for (int i = 0; i < num; i++) { + nxtIDs[i] = listDB.size() + i; + } return nxtIDs; } diff --git a/src/main/java/betterquesting/network/handlers/NetNameSync.java b/src/main/java/betterquesting/network/handlers/NetNameSync.java index e2d17a578..a064251d9 100644 --- a/src/main/java/betterquesting/network/handlers/NetNameSync.java +++ b/src/main/java/betterquesting/network/handlers/NetNameSync.java @@ -46,7 +46,9 @@ public static void sendRequest(@Nullable UUID[] uuids, @Nullable String[] names) if (uuids != null) { NBTTagList uList = new NBTTagList(); for (UUID id : uuids) { - if (id == null) { continue; } + if (id == null) { + continue; + } uList.appendTag(new NBTTagString(id.toString())); } payload.setTag("uuids", uList); @@ -54,7 +56,9 @@ public static void sendRequest(@Nullable UUID[] uuids, @Nullable String[] names) if (names != null) { NBTTagList nList = new NBTTagList(); for (String s : names) { - if (StringUtils.isNullOrEmpty(s)) { continue; } + if (StringUtils.isNullOrEmpty(s)) { + continue; + } nList.appendTag(new NBTTagString(s)); } payload.setTag("names", nList); @@ -64,7 +68,9 @@ public static void sendRequest(@Nullable UUID[] uuids, @Nullable String[] names) public static void quickSync(@Nullable EntityPlayerMP player, int partyID) { IParty party = PartyManager.INSTANCE.getValue(partyID); - if (party == null) { return; } + if (party == null) { + return; + } NBTTagCompound payload = new NBTTagCompound(); payload.setTag("data", NameCache.INSTANCE.writeToNBT(new NBTTagList(), party.getMembers())); @@ -78,7 +84,9 @@ public static void quickSync(@Nullable EntityPlayerMP player, int partyID) { for (UUID playerID : party.getMembers()) { EntityPlayerMP p = server.getPlayerList().getPlayerByUUID(playerID); //noinspection ConstantConditions - if (p != null) { playerList.add(p); } + if (p != null) { + playerList.add(p); + } } PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), playerList.toArray(new EntityPlayerMP[0])); @@ -87,11 +95,15 @@ public static void quickSync(@Nullable EntityPlayerMP player, int partyID) { public static void sendNames(@Nullable EntityPlayerMP[] players, @Nullable UUID[] uuids, @Nullable String[] names) { List idList = (uuids == null && names == null) ? null : new ArrayList<>(); - if (uuids != null) { idList.addAll(Arrays.asList(uuids)); } + if (uuids != null) { + idList.addAll(Arrays.asList(uuids)); + } if (names != null) { for (String s : names) { UUID id = NameCache.INSTANCE.getUUID(s); - if (id != null) { idList.add(id); } + if (id != null) { + idList.add(id); + } } } diff --git a/src/main/java/betterquesting/network/handlers/NetNotices.java b/src/main/java/betterquesting/network/handlers/NetNotices.java index 50976b0c4..8802b5045 100644 --- a/src/main/java/betterquesting/network/handlers/NetNotices.java +++ b/src/main/java/betterquesting/network/handlers/NetNotices.java @@ -28,9 +28,15 @@ public static void sendNotice(@Nullable EntityPlayerMP[] players, ItemStack icon String sound) { NBTTagCompound payload = new NBTTagCompound(); payload.setTag("icon", (icon != null ? icon : ItemStack.EMPTY).writeToNBT(new NBTTagCompound())); - if (mainText != null) { payload.setString("mainText", mainText); } - if (subText != null) { payload.setString("subText", subText); } - if (sound != null) { payload.setString("sound", sound); } + if (mainText != null) { + payload.setString("mainText", mainText); + } + if (subText != null) { + payload.setString("subText", subText); + } + if (sound != null) { + payload.setString("sound", sound); + } if (players != null) { PacketSender.INSTANCE.sendToPlayers(new QuestingPacket(ID_NAME, payload), players); diff --git a/src/main/java/betterquesting/network/handlers/NetPartyAction.java b/src/main/java/betterquesting/network/handlers/NetPartyAction.java index 3ffbd49c2..ae832d060 100644 --- a/src/main/java/betterquesting/network/handlers/NetPartyAction.java +++ b/src/main/java/betterquesting/network/handlers/NetPartyAction.java @@ -58,17 +58,23 @@ private static void onServer(Tuple message) { break; } case 1: { - if (permission < 3) { break; } + if (permission < 3) { + break; + } deleteParty(partyID); break; } case 2: { - if (permission < 2) { break; } + if (permission < 2) { + break; + } editParty(partyID, party, message.getFirst().getCompoundTag("data")); break; } case 3: { - if (permission < 2) { break; } + if (permission < 2) { + break; + } inviteUser(partyID, message.getFirst().getString("username"), message.getFirst().getLong("expiry")); break; } @@ -89,7 +95,9 @@ private static void onServer(Tuple message) { private static void createParty(EntityPlayerMP sender, String name) { UUID playerID = QuestingAPI.getQuestingUUID(sender); - if (PartyManager.INSTANCE.getParty(playerID) != null) { return; } + if (PartyManager.INSTANCE.getParty(playerID) != null) { + return; + } int partyID = PartyManager.INSTANCE.nextID(); IParty party = PartyManager.INSTANCE.createNew(partyID); @@ -117,8 +125,12 @@ private static void inviteUser(int partyID, String username, long expiry) { UUID uuid = null; MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); EntityPlayerMP player = server.getPlayerList().getPlayerByUsername(username); - if (player != null) { uuid = QuestingAPI.getQuestingUUID(player); } - if (uuid == null) { uuid = NameCache.INSTANCE.getUUID(username); } + if (player != null) { + uuid = QuestingAPI.getQuestingUUID(player); + } + if (uuid == null) { + uuid = NameCache.INSTANCE.getUUID(username); + } if (uuid != null) { PartyInvitations.INSTANCE.postInvite(uuid, partyID, expiry); if (player != null) { @@ -134,7 +146,9 @@ private static void inviteUser(int partyID, String username, long expiry) { private static void acceptInvite(int partyID, EntityPlayerMP sender) { UUID playerID = QuestingAPI.getQuestingUUID(sender); DBEntry party = PartyManager.INSTANCE.getParty(playerID); - if (party != null) { return; } + if (party != null) { + return; + } if (PartyInvitations.INSTANCE.acceptInvite(playerID, partyID)) { NetPartySync.quickSync(partyID); NetNameSync.quickSync(sender, partyID); @@ -155,8 +169,12 @@ private static void kickUser(int partyID, EntityPlayerMP sender, IParty party, S UUID uuid = null; MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); EntityPlayerMP player = server.getPlayerList().getPlayerByUsername(username); - if (player != null) { uuid = QuestingAPI.getQuestingUUID(player); } - if (uuid == null) { uuid = NameCache.INSTANCE.getUUID(username); } + if (player != null) { + uuid = QuestingAPI.getQuestingUUID(player); + } + if (uuid == null) { + uuid = NameCache.INSTANCE.getUUID(username); + } if (uuid == null) { BetterQuesting.logger.error("Unable to identify " + username + " to remove them from party " + partyID); return; // No idea who this is @@ -166,7 +184,9 @@ private static void kickUser(int partyID, EntityPlayerMP sender, IParty party, S permission) // For future reference, this is checking the target has a permission lower than the sender { // Even if the kick isn't confirmed we still need to tell the clients incase of desync - if (party.getStatus(uuid) != null) { party.kickUser(uuid); } + if (party.getStatus(uuid) != null) { + party.kickUser(uuid); + } if (!party.getMembers().isEmpty()) { NetPartySync.quickSync(partyID); diff --git a/src/main/java/betterquesting/network/handlers/NetPartySync.java b/src/main/java/betterquesting/network/handlers/NetPartySync.java index 951887c14..125749601 100644 --- a/src/main/java/betterquesting/network/handlers/NetPartySync.java +++ b/src/main/java/betterquesting/network/handlers/NetPartySync.java @@ -41,21 +41,29 @@ public static void quickSync(int partyID) { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); IParty party = PartyManager.INSTANCE.getValue(partyID); - if (server == null || party == null) { return; } + if (server == null || party == null) { + return; + } List players = new ArrayList<>(); for (UUID uuid : party.getMembers()) { EntityPlayerMP p = server.getPlayerList().getPlayerByUUID(uuid); //noinspection ConstantConditions - if (p != null) { players.add(p); } + if (p != null) { + players.add(p); + } } sendSync(players.toArray(new EntityPlayerMP[0]), new int[] { partyID }); } public static void sendSync(@Nullable EntityPlayerMP[] players, @Nullable int[] partyIDs) { - if (partyIDs != null && partyIDs.length == 0) { return; } - if (players != null && players.length == 0) { return; } + if (partyIDs != null && partyIDs.length == 0) { + return; + } + if (players != null && players.length == 0) { + return; + } NBTTagList dataList = new NBTTagList(); final List> partySubset = @@ -81,7 +89,9 @@ public static void sendSync(@Nullable EntityPlayerMP[] players, @Nullable int[] @SideOnly(Side.CLIENT) public static void requestSync(@Nullable int[] partyIDs) { NBTTagCompound payload = new NBTTagCompound(); - if (partyIDs != null) { payload.setIntArray("partyIDs", partyIDs); } + if (partyIDs != null) { + payload.setIntArray("partyIDs", partyIDs); + } PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); } @@ -94,15 +104,21 @@ private static void onServer(Tuple message) { @SideOnly(Side.CLIENT) private static void onClient(NBTTagCompound message) { NBTTagList data = message.getTagList("data", 10); - if (!message.getBoolean("merge")) { PartyManager.INSTANCE.reset(); } + if (!message.getBoolean("merge")) { + PartyManager.INSTANCE.reset(); + } for (int i = 0; i < data.tagCount(); i++) { NBTTagCompound tag = data.getCompoundTagAt(i); - if (!tag.hasKey("partyID", 99)) { continue; } + if (!tag.hasKey("partyID", 99)) { + continue; + } int partyID = tag.getInteger("partyID"); IParty party = PartyManager.INSTANCE.getValue(partyID); // TODO: Send to client side database - if (party == null) { party = PartyManager.INSTANCE.createNew(partyID); } + if (party == null) { + party = PartyManager.INSTANCE.createNew(partyID); + } party.readFromNBT(tag.getCompoundTag("config")); } diff --git a/src/main/java/betterquesting/network/handlers/NetQuestAction.java b/src/main/java/betterquesting/network/handlers/NetQuestAction.java index 2dd720f1a..e43d3aa08 100644 --- a/src/main/java/betterquesting/network/handlers/NetQuestAction.java +++ b/src/main/java/betterquesting/network/handlers/NetQuestAction.java @@ -27,7 +27,9 @@ public static void registerHandler() { @SideOnly(Side.CLIENT) public static void requestClaim(@Nonnull int[] questIDs) { - if (questIDs.length == 0) { return; } + if (questIDs.length == 0) { + return; + } NBTTagCompound payload = new NBTTagCompound(); payload.setInteger("action", 0); payload.setIntArray("questIDs", questIDs); @@ -36,7 +38,9 @@ public static void requestClaim(@Nonnull int[] questIDs) { @SideOnly(Side.CLIENT) public static void requestDetect(@Nonnull int[] questIDs) { - if (questIDs.length == 0) { return; } + if (questIDs.length == 0) { + return; + } NBTTagCompound payload = new NBTTagCompound(); payload.setInteger("action", 1); payload.setIntArray("questIDs", questIDs); @@ -66,7 +70,9 @@ public static void claimQuest(int[] questIDs, EntityPlayerMP player) { List> qLists = QuestDatabase.INSTANCE.bulkLookup(questIDs); for (DBEntry entry : qLists) { - if (!entry.getValue().canClaim(player)) { continue; } + if (!entry.getValue().canClaim(player)) { + continue; + } entry.getValue().claimReward(player); } } diff --git a/src/main/java/betterquesting/network/handlers/NetQuestEdit.java b/src/main/java/betterquesting/network/handlers/NetQuestEdit.java index fb9cbcfa8..78b796b1f 100644 --- a/src/main/java/betterquesting/network/handlers/NetQuestEdit.java +++ b/src/main/java/betterquesting/network/handlers/NetQuestEdit.java @@ -105,7 +105,9 @@ public static void editQuests(NBTTagList data) { ids[i] = questID; IQuest quest = QuestDatabase.INSTANCE.getValue(questID); - if (quest != null) { quest.readFromNBT(entry.getCompoundTag("config")); } + if (quest != null) { + quest.readFromNBT(entry.getCompoundTag("config")); + } } SaveLoadHandler.INSTANCE.markDirty(); @@ -163,10 +165,14 @@ public static void setQuestStates(int[] questIDs, boolean state, UUID targetID) SaveLoadHandler.INSTANCE.markDirty(); MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if (server == null) { return; } + if (server == null) { + return; + } EntityPlayerMP player = server.getPlayerList().getPlayerByUUID(targetID); //noinspection ConstantConditions - if (player == null) { return; } + if (player == null) { + return; + } NetQuestSync.sendSync(player, questIDs, false, true); } @@ -176,12 +182,18 @@ public static void createQuests(NBTTagList data) { for (int i = 0; i < data.tagCount(); i++) { NBTTagCompound entry = data.getCompoundTagAt(i); int questID = entry.hasKey("questID", 99) ? entry.getInteger("questID") : -1; - if (questID < 0) { questID = QuestDatabase.INSTANCE.nextID(); } + if (questID < 0) { + questID = QuestDatabase.INSTANCE.nextID(); + } ids[i] = questID; IQuest quest = QuestDatabase.INSTANCE.getValue(questID); - if (quest == null) { quest = QuestDatabase.INSTANCE.createNew(questID); } - if (entry.hasKey("config", 10)) { quest.readFromNBT(entry.getCompoundTag("config")); } + if (quest == null) { + quest = QuestDatabase.INSTANCE.createNew(questID); + } + if (entry.hasKey("config", 10)) { + quest.readFromNBT(entry.getCompoundTag("config")); + } } SaveLoadHandler.INSTANCE.markDirty(); diff --git a/src/main/java/betterquesting/network/handlers/NetQuestSync.java b/src/main/java/betterquesting/network/handlers/NetQuestSync.java index 4c6285c67..97e277188 100644 --- a/src/main/java/betterquesting/network/handlers/NetQuestSync.java +++ b/src/main/java/betterquesting/network/handlers/NetQuestSync.java @@ -40,7 +40,9 @@ public static void registerHandler() { } public static void quickSync(int questID, boolean config, boolean progress) { - if (!config && !progress) { return; } + if (!config && !progress) { + return; + } int[] IDs = questID < 0 ? null : new int[] { questID }; @@ -51,7 +53,9 @@ public static void quickSync(int questID, boolean config, boolean progress) { if (progress) // Send everyone's individual progression { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if (server == null) { return; } + if (server == null) { + return; + } for (EntityPlayerMP player : server.getPlayerList().getPlayers()) { sendSync(player, IDs, false, true); // Progression only this pass @@ -67,7 +71,9 @@ public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] que public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] questIDs, @Nullable int[] resetIDs, boolean config, boolean progress) { - if ((!config && !progress) || (questIDs != null && questIDs.length == 0)) { return; } + if ((!config && !progress) || (questIDs != null && questIDs.length == 0)) { + return; + } // Offload this to another thread as it could take a while to build BQThreadedIO.INSTANCE.enqueue(() -> { @@ -79,9 +85,15 @@ public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] que for (DBEntry entry : questSubset) { NBTTagCompound tag = new NBTTagCompound(); - if (config) { tag.setTag("config", entry.getValue().writeToNBT(new NBTTagCompound())); } - if (progress) { tag.setTag("progress", entry.getValue().writeProgressToNBT(new NBTTagCompound(), pidList)); } - if (resetIDs != null) { tag.setIntArray("resets", resetIDs); } + if (config) { + tag.setTag("config", entry.getValue().writeToNBT(new NBTTagCompound())); + } + if (progress) { + tag.setTag("progress", entry.getValue().writeProgressToNBT(new NBTTagCompound(), pidList)); + } + if (resetIDs != null) { + tag.setIntArray("resets", resetIDs); + } tag.setInteger("questID", entry.getID()); dataList.appendTag(tag); } @@ -102,7 +114,9 @@ public static void sendSync(@Nullable EntityPlayerMP player, @Nullable int[] que @SideOnly(Side.CLIENT) public static void requestSync(@Nullable int[] questIDs, boolean configs, boolean progress) { NBTTagCompound payload = new NBTTagCompound(); - if (questIDs != null) { payload.setIntArray("requestIDs", questIDs); } + if (questIDs != null) { + payload.setIntArray("requestIDs", questIDs); + } payload.setBoolean("getConfig", configs); payload.setBoolean("getProgress", progress); PacketSender.INSTANCE.sendToServer(new QuestingPacket(ID_NAME, payload)); @@ -118,17 +132,23 @@ private static void onServer(Tuple message) { private static void onClient(NBTTagCompound message) { NBTTagList data = message.getTagList("data", 10); boolean merge = message.getBoolean("merge"); - if (!merge) { QuestDatabase.INSTANCE.reset(); } + if (!merge) { + QuestDatabase.INSTANCE.reset(); + } for (int i = 0; i < data.tagCount(); i++) { NBTTagCompound tag = data.getCompoundTagAt(i); - if (!tag.hasKey("questID", 99)) { continue; } + if (!tag.hasKey("questID", 99)) { + continue; + } int questID = tag.getInteger("questID"); IQuest quest = QuestDatabase.INSTANCE.getValue(questID); if (tag.hasKey("config", 10)) { - if (quest == null) { quest = QuestDatabase.INSTANCE.createNew(questID); } + if (quest == null) { + quest = QuestDatabase.INSTANCE.createNew(questID); + } quest.readFromNBT(tag.getCompoundTag("config")); } diff --git a/src/main/java/betterquesting/questing/CompletionInfo.java b/src/main/java/betterquesting/questing/CompletionInfo.java index 23bb3afc6..5ba1481eb 100644 --- a/src/main/java/betterquesting/questing/CompletionInfo.java +++ b/src/main/java/betterquesting/questing/CompletionInfo.java @@ -14,7 +14,7 @@ public long getTimestamp() { } public void setTimestamp(long time) { - this.timestamp = time; + timestamp = time; } public boolean isClaimed() { diff --git a/src/main/java/betterquesting/questing/QuestDatabase.java b/src/main/java/betterquesting/questing/QuestDatabase.java index 370dbc95b..f896ed9a0 100644 --- a/src/main/java/betterquesting/questing/QuestDatabase.java +++ b/src/main/java/betterquesting/questing/QuestDatabase.java @@ -18,7 +18,7 @@ public final class QuestDatabase extends SimpleDatabase implements IQues public synchronized IQuest createNew(int id) { IQuest quest = new QuestInstance(); if (id >= 0) { - this.add(id, quest); + add(id, quest); } return quest; } @@ -36,36 +36,52 @@ public synchronized boolean removeID(int id) { @Override public synchronized boolean removeValue(IQuest value) { - int id = this.getID(value); - if (id < 0) { return false; } - boolean success = this.removeValue(value); - if (success) { for (DBEntry entry : getEntries()) { removeReq(entry.getValue(), id); } } + int id = getID(value); + if (id < 0) { + return false; + } + boolean success = removeValue(value); + if (success) { + for (DBEntry entry : getEntries()) { + removeReq(entry.getValue(), id); + } + } return success; } private void removeReq(IQuest quest, int id) { int[] orig = quest.getRequirements(); - if (orig.length == 0) { return; } + if (orig.length == 0) { + return; + } boolean hasRemoved = false; int[] rem = new int[orig.length - 1]; for (int i = 0; i < orig.length; i++) { if (!hasRemoved && orig[i] == id) { hasRemoved = true; continue; - } else if (!hasRemoved && i >= rem.length) { break; } + } else if (!hasRemoved && i >= rem.length) { + break; + } rem[!hasRemoved ? i : (i - 1)] = orig[i]; } - if (hasRemoved) { quest.setRequirements(rem); } + if (hasRemoved) { + quest.setRequirements(rem); + } } @Override public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { - for (DBEntry entry : this.getEntries()) { - if (subset != null && !subset.contains(entry.getID())) { continue; } + for (DBEntry entry : getEntries()) { + if (subset != null && !subset.contains(entry.getID())) { + continue; + } NBTTagCompound jq = entry.getValue().writeToNBT(new NBTTagCompound()); - if (subset != null && jq.isEmpty()) { continue; } + if (subset != null && jq.isEmpty()) { + continue; + } jq.setInteger("questID", entry.getID()); json.appendTag(jq); } @@ -75,23 +91,29 @@ public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List users) { - for (DBEntry entry : this.getEntries()) { + for (DBEntry entry : getEntries()) { NBTTagCompound jq = entry.getValue().writeProgressToNBT(new NBTTagCompound(), users); jq.setInteger("questID", entry.getID()); json.appendTag(jq); @@ -106,10 +128,14 @@ public synchronized void readProgressFromNBT(NBTTagList json, boolean merge) { NBTTagCompound qTag = json.getCompoundTagAt(i); int qID = qTag.hasKey("questID", 99) ? qTag.getInteger("questID") : -1; - if (qID < 0) { continue; } + if (qID < 0) { + continue; + } IQuest quest = getValue(qID); - if (quest != null) { quest.readProgressFromNBT(qTag, merge); } + if (quest != null) { + quest.readProgressFromNBT(qTag, merge); + } } } } diff --git a/src/main/java/betterquesting/questing/QuestInstance.java b/src/main/java/betterquesting/questing/QuestInstance.java index e0d008add..7bcd0a1d8 100644 --- a/src/main/java/betterquesting/questing/QuestInstance.java +++ b/src/main/java/betterquesting/questing/QuestInstance.java @@ -42,7 +42,7 @@ public class QuestInstance implements IQuest { private final PropertyContainer qInfo = new PropertyContainer(); public QuestInstance() { - this.setupProps(); + setupProps(); } private void setupProps() { @@ -70,7 +70,7 @@ private void setupProps() { } private void setupValue(IPropertyType prop) { - this.setupValue(prop, prop.getDefault()); + setupValue(prop, prop.getDefault()); } private void setupValue(IPropertyType prop, T def) { @@ -206,7 +206,7 @@ public void claimReward(EntityPlayer player) { if (entry == null) { entry = new CompletionInfo(System.currentTimeMillis(), true); - this.completeUsers.put(pID, entry); + completeUsers.put(pID, entry); } else { entry.setClaimed(true); entry.setTimestamp(System.currentTimeMillis()); @@ -223,14 +223,16 @@ public boolean canSubmit(@Nonnull EntityPlayer player) { UUID playerID = QuestingAPI.getQuestingUUID(player); synchronized (completeUsers) { - CompletionInfo entry = this.getCompletionInfo(playerID); + CompletionInfo entry = getCompletionInfo(playerID); if (entry == null) { return true; } if (!entry.isClaimed() && getProperty(NativeProps.REPEAT_TIME) >= 0) // Complete but repeatable { - if (tasks.size() <= 0) { return true; } + if (tasks.size() <= 0) { + return true; + } int done = 0; @@ -272,7 +274,7 @@ public void setComplete(UUID uuid, long timestamp) { } synchronized (completeUsers) { - CompletionInfo entry = this.getCompletionInfo(uuid); + CompletionInfo entry = getCompletionInfo(uuid); if (entry == null) { entry = new CompletionInfo(timestamp, false); @@ -298,13 +300,13 @@ public boolean isComplete(UUID uuid) { @Override public EnumQuestState getState(UUID uuid) { - if (this.isComplete(uuid)) { - if (this.hasClaimed(uuid)) { + if (isComplete(uuid)) { + if (hasClaimed(uuid)) { return EnumQuestState.COMPLETED; } else { return EnumQuestState.UNCLAIMED; } - } else if (this.isUnlocked(uuid)) { + } else if (isUnlocked(uuid)) { return EnumQuestState.UNLOCKED; } @@ -377,11 +379,11 @@ public IDatabaseNBT getRewards() { @Nonnull @Override public int[] getRequirements() { - return this.preRequisites; + return preRequisites; } public void setRequirements(@Nonnull int[] req) { - this.preRequisites = req; + preRequisites = req; } @Override @@ -396,9 +398,9 @@ public NBTTagCompound writeToNBT(NBTTagCompound jObj) { @Override public void readFromNBT(NBTTagCompound jObj) { - this.qInfo.readFromNBT(jObj.getCompoundTag("properties")); - this.tasks.readFromNBT(jObj.getTagList("tasks", 10), false); - this.rewards.readFromNBT(jObj.getTagList("rewards", 10), false); + qInfo.readFromNBT(jObj.getCompoundTag("properties")); + tasks.readFromNBT(jObj.getTagList("tasks", 10), false); + rewards.readFromNBT(jObj.getTagList("rewards", 10), false); if (jObj.getTagId("preRequisites") == 11) // Native NBT { @@ -414,7 +416,7 @@ public void readFromNBT(NBTTagCompound jObj) { setRequirements(req); } - this.setupProps(); + setupProps(); } @Override diff --git a/src/main/java/betterquesting/questing/QuestLine.java b/src/main/java/betterquesting/questing/QuestLine.java index 83121fd15..9a682647a 100644 --- a/src/main/java/betterquesting/questing/QuestLine.java +++ b/src/main/java/betterquesting/questing/QuestLine.java @@ -24,16 +24,16 @@ public QuestLine() { } private void setupProps() { - this.setupValue(NativeProps.NAME, "New Quest Line"); - this.setupValue(NativeProps.DESC, "No Description"); - this.setupValue(NativeProps.ICON, new BigItemStack(Items.BOOK)); - this.setupValue(NativeProps.VISIBILITY, EnumQuestVisibility.NORMAL); - this.setupValue(NativeProps.BG_IMAGE); - this.setupValue(NativeProps.BG_SIZE); + setupValue(NativeProps.NAME, "New Quest Line"); + setupValue(NativeProps.DESC, "No Description"); + setupValue(NativeProps.ICON, new BigItemStack(Items.BOOK)); + setupValue(NativeProps.VISIBILITY, EnumQuestVisibility.NORMAL); + setupValue(NativeProps.BG_IMAGE); + setupValue(NativeProps.BG_SIZE); } private void setupValue(IPropertyType prop) { - this.setupValue(prop, prop.getDefault()); + setupValue(prop, prop.getDefault()); } private void setupValue(IPropertyType prop, T def) { @@ -43,7 +43,7 @@ private void setupValue(IPropertyType prop, T def) { @Override public IQuestLineEntry createNew(int id) { IQuestLineEntry qle = new QuestLineEntry(0, 0, 24, 24); - this.add(id, qle); + add(id, qle); return qle; } @@ -94,7 +94,9 @@ public NBTTagCompound writeToNBT(NBTTagCompound json, @Nullable List su NBTTagList jArr = new NBTTagList(); for (DBEntry entry : getEntries()) { - if (subset != null && !subset.contains(entry.getID())) { continue; } + if (subset != null && !subset.contains(entry.getID())) { + continue; + } NBTTagCompound qle = entry.getValue().writeToNBT(new NBTTagCompound()); qle.setInteger("id", entry.getID()); jArr.appendTag(qle); @@ -108,19 +110,23 @@ public NBTTagCompound writeToNBT(NBTTagCompound json, @Nullable List su public void readFromNBT(NBTTagCompound json, boolean merge) { info.readFromNBT(json.getCompoundTag("properties")); - if (!merge) { reset(); } + if (!merge) { + reset(); + } NBTTagList qList = json.getTagList("quests", 10); for (int i = 0; i < qList.tagCount(); i++) { NBTTagCompound qTag = qList.getCompoundTagAt(i); int id = qTag.hasKey("id", 99) ? qTag.getInteger("id") : -1; - if (id < 0) { continue; } + if (id < 0) { + continue; + } add(id, new QuestLineEntry(qTag)); } - this.setupProps(); + setupProps(); } @Override diff --git a/src/main/java/betterquesting/questing/QuestLineDatabase.java b/src/main/java/betterquesting/questing/QuestLineDatabase.java index c9a3e1cd5..04ce023c4 100644 --- a/src/main/java/betterquesting/questing/QuestLineDatabase.java +++ b/src/main/java/betterquesting/questing/QuestLineDatabase.java @@ -24,8 +24,12 @@ public final class QuestLineDatabase extends SimpleDatabase implemen @Override public synchronized int getOrderIndex(int lineID) { int order = lineOrder.indexOf(lineID); - if (order >= 0) { return order; } - if (getValue(lineID) == null) { return -1; } + if (order >= 0) { + return order; + } + if (getValue(lineID) == null) { + return -1; + } lineOrder.add(lineID); return lineOrder.size() - 1; @@ -39,7 +43,7 @@ public synchronized void setOrderIndex(int lineID, int index) { @Override public synchronized List> getSortedEntries() { - List> list = new ArrayList<>(this.getEntries()); + List> list = new ArrayList<>(getEntries()); list.sort(SORTER); return list; } @@ -47,7 +51,9 @@ public synchronized List> getSortedEntries() { @Override public synchronized IQuestLine createNew(int id) { IQuestLine ql = new QuestLine(); - if (id >= 0) { this.add(id, ql); } + if (id >= 0) { + add(id, ql); + } return ql; } @@ -61,7 +67,9 @@ public synchronized void removeQuest(int questID) { @Override public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { for (DBEntry entry : getEntries()) { - if (subset != null && !subset.contains(entry.getID())) { continue; } + if (subset != null && !subset.contains(entry.getID())) { + continue; + } NBTTagCompound jObj = entry.getValue().writeToNBT(new NBTTagCompound(), null); jObj.setInteger("lineID", entry.getID()); jObj.setInteger("order", getOrderIndex(entry.getID())); @@ -73,7 +81,9 @@ public synchronized NBTTagList writeToNBT(NBTTagList json, @Nullable List unassigned = new ArrayList<>(); HashMap orderMap = new HashMap<>(); @@ -85,7 +95,9 @@ public synchronized void readFromNBT(NBTTagList json, boolean merge) { int order = jql.hasKey("order", 99) ? jql.getInteger("order") : -1; IQuestLine line = getValue(id); - if (line == null) { line = new QuestLine(); } + if (line == null) { + line = new QuestLine(); + } line.readFromNBT(jql, false); if (id >= 0) { @@ -94,17 +106,23 @@ public synchronized void readFromNBT(NBTTagList json, boolean merge) { unassigned.add(line); } - if (order >= 0) { orderMap.put(order, id); } + if (order >= 0) { + orderMap.put(order, id); + } } // Legacy support ONLY - for (IQuestLine q : unassigned) { add(nextID(), q); } + for (IQuestLine q : unassigned) { + add(nextID(), q); + } List orderKeys = new ArrayList<>(orderMap.keySet()); Collections.sort(orderKeys); lineOrder.clear(); - for (int o : orderKeys) { lineOrder.add(orderMap.get(o)); } + for (int o : orderKeys) { + lineOrder.add(orderMap.get(o)); + } } @Override diff --git a/src/main/java/betterquesting/questing/QuestLineEntry.java b/src/main/java/betterquesting/questing/QuestLineEntry.java index e685ed8ee..f43ad171a 100644 --- a/src/main/java/betterquesting/questing/QuestLineEntry.java +++ b/src/main/java/betterquesting/questing/QuestLineEntry.java @@ -10,7 +10,7 @@ public class QuestLineEntry implements IQuestLineEntry { private int posY = 0; public QuestLineEntry(NBTTagCompound json) { - this.readFromNBT(json); + readFromNBT(json); } public QuestLineEntry(int x, int y) { @@ -19,17 +19,17 @@ public QuestLineEntry(int x, int y) { @Deprecated public QuestLineEntry(int x, int y, int size) { - this.sizeX = size; - this.sizeY = size; - this.posX = x; - this.posY = y; + sizeX = size; + sizeY = size; + posX = x; + posY = y; } public QuestLineEntry(int x, int y, int sizeX, int sizeY) { this.sizeX = sizeX; this.sizeY = sizeY; - this.posX = x; - this.posY = y; + posX = x; + posY = y; } @Override @@ -40,12 +40,12 @@ public int getSize() { @Override public int getSizeX() { - return this.sizeX; + return sizeX; } @Override public int getSizeY() { - return this.sizeY; + return sizeY; } @Override @@ -67,8 +67,8 @@ public void setPosition(int posX, int posY) { @Override @Deprecated public void setSize(int size) { - this.sizeX = size; - this.sizeY = size; + sizeX = size; + sizeY = size; } @Override diff --git a/src/main/java/betterquesting/questing/party/PartyInstance.java b/src/main/java/betterquesting/questing/party/PartyInstance.java index d86f9309d..9dabc2f8a 100644 --- a/src/main/java/betterquesting/questing/party/PartyInstance.java +++ b/src/main/java/betterquesting/questing/party/PartyInstance.java @@ -21,7 +21,7 @@ public class PartyInstance implements IParty { private final PropertyContainer pInfo = new PropertyContainer(); public PartyInstance() { - this.setupProps(); + setupProps(); } private void setupProps() { @@ -29,7 +29,7 @@ private void setupProps() { } private void setupValue(IPropertyType prop) { - this.setupValue(prop, prop.getDefault()); + setupValue(prop, prop.getDefault()); } private void setupValue(IPropertyType prop, T def) { @@ -47,19 +47,25 @@ public IPropertyContainer getProperties() { @Override public void kickUser(@Nonnull UUID uuid) { - if (!members.containsKey(uuid)) { return; } + if (!members.containsKey(uuid)) { + return; + } EnumPartyStatus old = members.get(uuid); members.remove(uuid); - if (old == EnumPartyStatus.OWNER && !members.isEmpty()) { hostMigrate(); } + if (old == EnumPartyStatus.OWNER && !members.isEmpty()) { + hostMigrate(); + } refreshCache(); } @Override public void setStatus(@Nonnull UUID uuid, @Nonnull EnumPartyStatus priv) { EnumPartyStatus old = members.get(uuid); - if (old == priv) { return; } + if (old == priv) { + return; + } members.put(uuid, priv); @@ -75,7 +81,9 @@ public void setStatus(@Nonnull UUID uuid, @Nonnull EnumPartyStatus priv) { // Find new owner for (UUID mem : getMembers()) { - if (mem == uuid) { continue; } + if (mem == uuid) { + continue; + } if (members.get(mem) == EnumPartyStatus.ADMIN) { migrate = mem; @@ -104,7 +112,9 @@ public EnumPartyStatus getStatus(@Nonnull UUID uuid) { @Override public List getMembers() { - if (memCache == null) { refreshCache(); } + if (memCache == null) { + refreshCache(); + } return memCache; } @@ -133,7 +143,7 @@ private void hostMigrate() { members.put(migrate, EnumPartyStatus.OWNER); } else { BetterQuesting.logger.error( - "Failed to find suitable host to migrate party " + this.pInfo.getProperty(NativeProps.NAME)); + "Failed to find suitable host to migrate party " + pInfo.getProperty(NativeProps.NAME)); } } @@ -168,7 +178,9 @@ public void readFromNBT(NBTTagCompound jObj) { for (int i = 0; i < memList.tagCount(); i++) { try { NBTTagCompound jMem = memList.getCompoundTagAt(i); - if (!jMem.hasKey("uuid", 8) || !jMem.hasKey("status")) { continue; } + if (!jMem.hasKey("uuid", 8) || !jMem.hasKey("status")) { + continue; + } UUID uuid = UUID.fromString(jMem.getString("uuid")); EnumPartyStatus priv = EnumPartyStatus.valueOf(jMem.getString("status")); members.put(uuid, priv); @@ -176,7 +188,7 @@ public void readFromNBT(NBTTagCompound jObj) { } refreshCache(); - this.setupProps(); + setupProps(); } @Override diff --git a/src/main/java/betterquesting/questing/party/PartyInvitations.java b/src/main/java/betterquesting/questing/party/PartyInvitations.java index 4e1cddc08..4b2c9cd28 100644 --- a/src/main/java/betterquesting/questing/party/PartyInvitations.java +++ b/src/main/java/betterquesting/questing/party/PartyInvitations.java @@ -39,30 +39,44 @@ public synchronized void postInvite(@Nonnull UUID uuid, int id, long expiryTime) public synchronized boolean acceptInvite(@Nonnull UUID uuid, int id) { HashMap userInvites = invites.get(uuid); - if (userInvites == null || userInvites.isEmpty()) { return false; } + if (userInvites == null || userInvites.isEmpty()) { + return false; + } long timestamp = userInvites.get(id); IParty party = PartyManager.INSTANCE.getValue(id); boolean valid = timestamp > System.currentTimeMillis(); - if (valid && party != null) { party.setStatus(uuid, EnumPartyStatus.MEMBER); } + if (valid && party != null) { + party.setStatus(uuid, EnumPartyStatus.MEMBER); + } userInvites.remove(id); // We still remove it regardless of validity - if (userInvites.isEmpty()) { invites.remove(uuid); } + if (userInvites.isEmpty()) { + invites.remove(uuid); + } return valid; } public synchronized void revokeInvites(@Nonnull UUID uuid, int... ids) { HashMap userInvites = invites.get(uuid); - if (userInvites == null || userInvites.isEmpty()) { return; } - for (int i : ids) { userInvites.remove(i); } - if (userInvites.isEmpty()) { invites.remove(uuid); } + if (userInvites == null || userInvites.isEmpty()) { + return; + } + for (int i : ids) { + userInvites.remove(i); + } + if (userInvites.isEmpty()) { + invites.remove(uuid); + } } public synchronized List> getPartyInvites(@Nonnull UUID uuid) { HashMap userInvites = invites.get(uuid); - if (userInvites == null || userInvites.isEmpty()) { return Collections.emptyList(); } + if (userInvites == null || userInvites.isEmpty()) { + return Collections.emptyList(); + } List> list = new ArrayList<>(userInvites.entrySet()); list.sort(Entry.comparingByValue()); // Sort by expiry time @@ -93,10 +107,14 @@ public synchronized void cleanExpired() { //noinspection ConstantConditions if (player != null && revoked.size() >= 0) { int[] revAry = new int[revoked.size()]; - for (int i = 0; i < revoked.size(); i++) { revAry[i] = revoked.get(i); } + for (int i = 0; i < revoked.size(); i++) { + revAry[i] = revoked.get(i); + } NetInviteSync.sendRevoked(player, revAry); // Normally I avoid including networking calls into the database... } - if (userInvites.getValue().isEmpty()) { iterA.remove(); } + if (userInvites.getValue().isEmpty()) { + iterA.remove(); + } } } @@ -114,7 +132,9 @@ public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable userTag.setString("uuid", uuid.toString()); Map userMap = invites.get(uuid); - if (userMap == null) { userMap = Collections.emptyMap(); } + if (userMap == null) { + userMap = Collections.emptyMap(); + } NBTTagList invList = new NBTTagList(); for (Entry invEntry : userMap.entrySet()) { @@ -148,7 +168,9 @@ public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable @Override public synchronized void readFromNBT(NBTTagList nbt, boolean merge) { - if (!merge) { invites.clear(); } + if (!merge) { + invites.clear(); + } for (int i = 0; i < nbt.tagCount(); i++) { NBTTagCompound userEntry = nbt.getCompoundTagAt(i); UUID uuid; @@ -164,7 +186,9 @@ public synchronized void readFromNBT(NBTTagList nbt, boolean merge) { NBTTagCompound invEntry = invList.getCompoundTagAt(n); int partyID = invEntry.hasKey("partyID", 99) ? invEntry.getInteger("partyID") : -1; long timestamp = invEntry.hasKey("expiry", 99) ? invEntry.getLong("expiry") : -1; - if (partyID < 0) { continue; } + if (partyID < 0) { + continue; + } map.put(partyID, timestamp); } } diff --git a/src/main/java/betterquesting/questing/party/PartyManager.java b/src/main/java/betterquesting/questing/party/PartyManager.java index a3434d5fd..45de8be3e 100644 --- a/src/main/java/betterquesting/questing/party/PartyManager.java +++ b/src/main/java/betterquesting/questing/party/PartyManager.java @@ -24,7 +24,9 @@ public class PartyManager extends SimpleDatabase implements IPartyDataba @Override public synchronized IParty createNew(int id) { IParty party = new PartyInstance(); - if (id >= 0) { this.add(id, party); } + if (id >= 0) { + add(id, party); + } return party; } @@ -44,7 +46,9 @@ public synchronized DBEntry getParty(@Nonnull UUID uuid) { } else if (cachedParty != null) // Active party. Check validity... { EnumPartyStatus status = cachedParty.getStatus(uuid); - if (status != null) { return new DBEntry<>(cachedID, cachedParty); } + if (status != null) { + return new DBEntry<>(cachedID, cachedParty); + } partyCache.remove(uuid); // User isn't a party member anymore } @@ -64,7 +68,9 @@ public synchronized DBEntry getParty(@Nonnull UUID uuid) { @Override public synchronized NBTTagList writeToNBT(NBTTagList json, List subset) { for (DBEntry entry : getEntries()) { - if (subset != null && !subset.contains(entry.getID())) { continue; } + if (subset != null && !subset.contains(entry.getID())) { + continue; + } NBTTagCompound jp = entry.getValue().writeToNBT(new NBTTagCompound()); jp.setInteger("partyID", entry.getID()); json.appendTag(jp); @@ -75,13 +81,17 @@ public synchronized NBTTagList writeToNBT(NBTTagList json, List subset) @Override public synchronized void readFromNBT(NBTTagList json, boolean merge) { - if (!merge) { reset(); } + if (!merge) { + reset(); + } for (int i = 0; i < json.tagCount(); i++) { NBTTagCompound jp = json.getCompoundTagAt(i); int partyID = jp.hasKey("partyID", 99) ? jp.getInteger("partyID") : -1; - if (partyID < 0) { continue; } + if (partyID < 0) { + continue; + } IParty party = new PartyInstance(); party.readFromNBT(jp); diff --git a/src/main/java/betterquesting/questing/rewards/RewardStorage.java b/src/main/java/betterquesting/questing/rewards/RewardStorage.java index f392d175f..24eeb0259 100644 --- a/src/main/java/betterquesting/questing/rewards/RewardStorage.java +++ b/src/main/java/betterquesting/questing/rewards/RewardStorage.java @@ -18,7 +18,9 @@ public class RewardStorage extends SimpleDatabase implements IDatabaseN @Override public NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { for (DBEntry rew : getEntries()) { - if (subset != null && !subset.contains(rew.getID())) { continue; } + if (subset != null && !subset.contains(rew.getID())) { + continue; + } ResourceLocation rewardID = rew.getValue().getFactoryID(); NBTTagCompound rJson = rew.getValue().writeToNBT(new NBTTagCompound()); rJson.setString("rewardID", rewardID.toString()); @@ -31,7 +33,9 @@ public NBTTagList writeToNBT(NBTTagList json, @Nullable List subset) { @Override public void readFromNBT(NBTTagList json, boolean merge) { - if (!merge) { reset(); } + if (!merge) { + reset(); + } List unassigned = new ArrayList<>(); for (int i = 0; i < json.tagCount(); i++) { @@ -84,6 +88,5 @@ public NBTTagList writeProgressToNBT(NBTTagList nbt, @Nullable List user) } @Override - public void readProgressFromNBT(NBTTagList nbt, boolean merge) { - } + public void readProgressFromNBT(NBTTagList nbt, boolean merge) { } } diff --git a/src/main/java/betterquesting/questing/tasks/TaskStorage.java b/src/main/java/betterquesting/questing/tasks/TaskStorage.java index f89febac9..1d0af32b6 100644 --- a/src/main/java/betterquesting/questing/tasks/TaskStorage.java +++ b/src/main/java/betterquesting/questing/tasks/TaskStorage.java @@ -70,7 +70,9 @@ public void readFromNBT(NBTTagList json, boolean merge) { } } - for (ITask t : unassigned) { add(nextID(), t); } + for (ITask t : unassigned) { + add(nextID(), t); + } } @Override diff --git a/src/main/java/betterquesting/storage/LifeDatabase.java b/src/main/java/betterquesting/storage/LifeDatabase.java index c5f19209e..cacd27697 100644 --- a/src/main/java/betterquesting/storage/LifeDatabase.java +++ b/src/main/java/betterquesting/storage/LifeDatabase.java @@ -32,7 +32,9 @@ public synchronized void setLives(@Nonnull UUID uuid, int value) { public synchronized NBTTagCompound writeToNBT(NBTTagCompound nbt, @Nullable List users) { NBTTagList jul = new NBTTagList(); for (Entry entry : playerLives.entrySet()) { - if (users != null && !users.contains(entry.getKey())) { continue; } + if (users != null && !users.contains(entry.getKey())) { + continue; + } NBTTagCompound j = new NBTTagCompound(); j.setString("uuid", entry.getKey().toString()); j.setInteger("lives", entry.getValue()); @@ -45,7 +47,9 @@ public synchronized NBTTagCompound writeToNBT(NBTTagCompound nbt, @Nullable List @Override public synchronized void readFromNBT(NBTTagCompound nbt, boolean merge) { - if (!merge) { playerLives.clear(); } + if (!merge) { + playerLives.clear(); + } NBTTagList tagList = nbt.getTagList("playerLives", 10); for (int i = 0; i < tagList.tagCount(); i++) { NBTTagCompound j = tagList.getCompoundTagAt(i); diff --git a/src/main/java/betterquesting/storage/NameCache.java b/src/main/java/betterquesting/storage/NameCache.java index 3a795dbfe..85d39dcfc 100644 --- a/src/main/java/betterquesting/storage/NameCache.java +++ b/src/main/java/betterquesting/storage/NameCache.java @@ -66,7 +66,9 @@ public synchronized int size() { @Override public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable List users) { for (Entry entry : cache.entrySet()) { - if (users != null && !users.contains(entry.getKey())) { continue; } + if (users != null && !users.contains(entry.getKey())) { + continue; + } NBTTagCompound jn = new NBTTagCompound(); jn.setString("uuid", entry.getKey().toString()); jn.setString("name", entry.getValue().getString("name")); @@ -79,7 +81,9 @@ public synchronized NBTTagList writeToNBT(NBTTagList nbt, @Nullable List u @Override public synchronized void readFromNBT(NBTTagList nbt, boolean merge) { - if (!merge) { cache.clear(); } + if (!merge) { + cache.clear(); + } for (int i = 0; i < nbt.tagCount(); i++) { NBTTagCompound jn = nbt.getCompoundTagAt(i); @@ -106,7 +110,9 @@ public synchronized void reset() { @Override public synchronized List getAllNames() { - if (nameCache != null) { return nameCache; } + if (nameCache != null) { + return nameCache; + } nameCache = new ArrayList<>(); diff --git a/src/main/java/betterquesting/storage/PropertyContainer.java b/src/main/java/betterquesting/storage/PropertyContainer.java index 3e0a4cab2..68df6583d 100644 --- a/src/main/java/betterquesting/storage/PropertyContainer.java +++ b/src/main/java/betterquesting/storage/PropertyContainer.java @@ -14,43 +14,59 @@ public class PropertyContainer implements IPropertyContainer, INBTSaveLoad T getProperty(IPropertyType prop) { - if (prop == null) { return null; } + if (prop == null) { + return null; + } return getProperty(prop, prop.getDefault()); } @Override public synchronized T getProperty(IPropertyType prop, T def) { - if (prop == null) { return def; } + if (prop == null) { + return def; + } NBTTagCompound jProp = getDomain(prop.getKey()); - if (!jProp.hasKey(prop.getKey().getPath())) { return def; } + if (!jProp.hasKey(prop.getKey().getPath())) { + return def; + } return prop.readValue(jProp.getTag(prop.getKey().getPath())); } @Override public synchronized boolean hasProperty(IPropertyType prop) { - if (prop == null) { return false; } + if (prop == null) { + return false; + } return getDomain(prop.getKey()).hasKey(prop.getKey().getPath()); } @Override public synchronized void removeProperty(IPropertyType prop) { - if (prop == null) { return; } + if (prop == null) { + return; + } NBTTagCompound jProp = getDomain(prop.getKey()); - if (!jProp.hasKey(prop.getKey().getPath())) { return; } + if (!jProp.hasKey(prop.getKey().getPath())) { + return; + } jProp.removeTag(prop.getKey().getPath()); - if (jProp.isEmpty()) { nbtInfo.removeTag(prop.getKey().getNamespace()); } + if (jProp.isEmpty()) { + nbtInfo.removeTag(prop.getKey().getNamespace()); + } } @Override public synchronized void setProperty(IPropertyType prop, T value) { - if (prop == null || value == null) { return; } + if (prop == null || value == null) { + return; + } NBTTagCompound dom = getDomain(prop.getKey()); dom.setTag(prop.getKey().getPath(), prop.writeValue(value)); nbtInfo.setTag(prop.getKey().getNamespace(), dom); @@ -59,7 +75,9 @@ public synchronized void setProperty(IPropertyType prop, T value) { @Override public synchronized void removeAllProps() { List keys = new ArrayList<>(nbtInfo.getKeySet()); - for (String key : keys) { nbtInfo.removeTag(key); } + for (String key : keys) { + nbtInfo.removeTag(key); + } } @Override @@ -70,15 +88,10 @@ public synchronized NBTTagCompound writeToNBT(NBTTagCompound nbt) { @Override public synchronized void readFromNBT(NBTTagCompound nbt) { - for (String key : nbtInfo.getKeySet()) { nbtInfo.removeTag(key); } + for (String key : new ArrayList<>(nbtInfo.getKeySet())) { + nbtInfo.removeTag(key); + } nbtInfo.merge(nbt); - - // TODO: FIX CASING - /*List keys = new ArrayList<>(nbtInfo.getKeySet()); - for(nbt) - { - - }*/ } private NBTTagCompound getDomain(ResourceLocation res) { diff --git a/src/main/java/betterquesting/storage/QuestSettings.java b/src/main/java/betterquesting/storage/QuestSettings.java index 75cade719..e59bec988 100644 --- a/src/main/java/betterquesting/storage/QuestSettings.java +++ b/src/main/java/betterquesting/storage/QuestSettings.java @@ -11,49 +11,51 @@ public class QuestSettings extends PropertyContainer implements IQuestSettings { public static final QuestSettings INSTANCE = new QuestSettings(); public QuestSettings() { - this.setupProps(); + setupProps(); } @Override public boolean canUserEdit(EntityPlayer player) { - if (player == null) { return false; } - return this.getProperty(NativeProps.EDIT_MODE) && NameCache.INSTANCE.isOP(QuestingAPI.getQuestingUUID(player)); + if (player == null) { + return false; + } + return getProperty(NativeProps.EDIT_MODE) && NameCache.INSTANCE.isOP(QuestingAPI.getQuestingUUID(player)); } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); - this.setupProps(); + setupProps(); } @Override public void reset() { - this.readFromNBT(new NBTTagCompound()); + readFromNBT(new NBTTagCompound()); } private void setupProps() { - this.setupValue(NativeProps.PACK_NAME); - this.setupValue(NativeProps.PACK_VER); - - this.setupValue(NativeProps.PARTY_ENABLE); - this.setupValue(NativeProps.EDIT_MODE); - this.setupValue(NativeProps.HARDCORE); - this.setupValue(NativeProps.LIVES_DEF); - this.setupValue(NativeProps.LIVES_MAX); - - this.setupValue(NativeProps.HOME_IMAGE); - this.setupValue(NativeProps.HOME_ANC_X); - this.setupValue(NativeProps.HOME_ANC_Y); - this.setupValue(NativeProps.HOME_OFF_X); - this.setupValue(NativeProps.HOME_OFF_Y); + setupValue(NativeProps.PACK_NAME); + setupValue(NativeProps.PACK_VER); + + setupValue(NativeProps.PARTY_ENABLE); + setupValue(NativeProps.EDIT_MODE); + setupValue(NativeProps.HARDCORE); + setupValue(NativeProps.LIVES_DEF); + setupValue(NativeProps.LIVES_MAX); + + setupValue(NativeProps.HOME_IMAGE); + setupValue(NativeProps.HOME_ANC_X); + setupValue(NativeProps.HOME_ANC_Y); + setupValue(NativeProps.HOME_OFF_X); + setupValue(NativeProps.HOME_OFF_Y); } private void setupValue(IPropertyType prop) { - this.setupValue(prop, prop.getDefault()); + setupValue(prop, prop.getDefault()); } private void setupValue(IPropertyType prop, T def) { - this.setProperty(prop, this.getProperty(prop, def)); + setProperty(prop, getProperty(prop, def)); } } From 88b1f2eec2206b2f0ec356e933aa4df4e892a0a1 Mon Sep 17 00:00:00 2001 From: Olexy Date: Mon, 16 Oct 2023 16:55:28 +0300 Subject: [PATCH 10/10] Fixed buggy mods crashing PanelItemSlot when wildcard is used. --- gradle.properties | 2 +- .../gui/panels/content/PanelItemSlot.java | 56 +++++++++++-------- 2 files changed, 34 insertions(+), 24 deletions(-) diff --git a/gradle.properties b/gradle.properties index 5df5afe05..02362b5b1 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,3 +1,3 @@ -version=3.6.5 +version=3.6.6 minecraftVersion=1.12.2 forgeVersion=14.23.5.2860 \ No newline at end of file diff --git a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java index e8a93683b..91906bbc6 100644 --- a/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java +++ b/src/main/java/betterquesting/api2/client/gui/panels/content/PanelItemSlot.java @@ -15,11 +15,15 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; -import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import static net.minecraft.client.util.ITooltipFlag.TooltipFlags.ADVANCED; +import static net.minecraft.client.util.ITooltipFlag.TooltipFlags.NORMAL; +import static net.minecraftforge.oredict.OreDictionary.WILDCARD_VALUE; + public class PanelItemSlot extends PanelButtonStorage { private final boolean showCount; private final boolean oreDict; @@ -39,11 +43,12 @@ public PanelItemSlot(IGuiRect rect, int id, BigItemStack value, boolean showCoun this.showCount = showCount; this.oreDict = oreDict; - setTextures(PresetTexture.ITEM_FRAME.getTexture(), PresetTexture.ITEM_FRAME.getTexture(), + setTextures(PresetTexture.ITEM_FRAME.getTexture(), + PresetTexture.ITEM_FRAME.getTexture(), new LayeredTexture(PresetTexture.ITEM_FRAME.getTexture(), - new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), - new GuiPadding(1, 1, 1, 1)))); - setStoredValue(value); // Need to run this again because of the instatiation order of showCount + new ColorTexture(PresetColor.ITEM_HIGHLIGHT.getColor(), new GuiPadding(1, 1, 1, 1))) + ); + setStoredValue(value); // Need to run this again because of the instantiation order of showCount } @Override @@ -52,17 +57,25 @@ public PanelItemSlot setStoredValue(BigItemStack value) { if (value != null) { Minecraft mc = Minecraft.getMinecraft(); - setIcon( - oreDict || value.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE ? new OreDictTexture(1F, - value, - showCount, - true) - : new ItemTexture(value, - showCount, - true), 1); - setTooltip(value.getBaseStack().getTooltip(mc.player, - mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED - : TooltipFlags.NORMAL)); + ItemStack base = value.getBaseStack(); + setIcon(oreDict || base.getItemDamage() == WILDCARD_VALUE ? new OreDictTexture(1F, value, showCount, true) + : new ItemTexture(value, showCount, true), 1); + TooltipFlags mode = mc.gameSettings.advancedItemTooltips ? ADVANCED : NORMAL; + List tooltip = null; + try { + tooltip = base.getTooltip(mc.player, mode); + } catch (Exception ignored) { } + if (tooltip == null) { + try { + base = base.copy(); + base.setItemDamage(0); + tooltip = base.getTooltip(mc.player, mode); + } catch (Exception ignored) { } + } + if (tooltip == null) { + tooltip = Collections.singletonList(base.getItem().getRegistryName().toString()); + } + setTooltip(tooltip); } else { setIcon(null); setTooltip(null); @@ -83,8 +96,7 @@ public List getTooltip(int mx, int my) { } Minecraft mc = Minecraft.getMinecraft(); - return ttStack.getBaseStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? TooltipFlags.ADVANCED - : TooltipFlags.NORMAL); + return ttStack.getBaseStack().getTooltip(mc.player, mc.gameSettings.advancedItemTooltips ? ADVANCED : NORMAL); } return null; @@ -99,12 +111,10 @@ private void updateOreStacks() { oreVariants.clear(); BigItemStack stack = getStoredValue(); - if (stack == null) { - return; - } + if (stack == null) { return; } if (!stack.hasOreDict()) { - if (stack.getBaseStack().getItemDamage() == OreDictionary.WILDCARD_VALUE) { + if (stack.getBaseStack().getItemDamage() == WILDCARD_VALUE) { NonNullList subItems = NonNullList.create(); stack.getBaseStack().getItem().getSubItems(CreativeTabs.SEARCH, subItems); subItems.forEach((is) -> { @@ -119,7 +129,7 @@ private void updateOreStacks() { } for (ItemStack iStack : stack.getOreIngredient().getMatchingStacks()) { - if (iStack.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + if (iStack.getItemDamage() == WILDCARD_VALUE) { NonNullList subItems = NonNullList.create(); iStack.getItem().getSubItems(CreativeTabs.SEARCH, subItems);