From ead6762eb1c005914b05f9d3c29f334989c67513 Mon Sep 17 00:00:00 2001 From: nea Date: Tue, 16 May 2023 01:23:43 +0200 Subject: Replace references to NEU with Firmament --- .editorconfig | 2 +- build.gradle.kts | 6 +- .../java/moe/nea/firmament/init/MixinPlugin.java | 46 ++++ .../firmament/mixins/MixinClientPacketHandler.java | 23 ++ .../mixins/MixinDownloadingTerrainScreen.java | 16 ++ .../nea/firmament/mixins/MixinMessageHandler.java | 34 +++ .../moe/nea/firmament/mixins/MixinMinecraft.java | 26 +++ .../nea/firmament/mixins/MixinWorldRenderer.java | 26 +++ .../mixins/accessor/AccessorHandledScreen.java | 14 ++ .../mixins/devenv/DisableCommonPacketWarnings.java | 37 ++++ .../mixins/devenv/DisableInvalidFishingHook.java | 15 ++ .../firmament/mixins/devenv/MixinScoreboard.java | 15 ++ .../moe/nea/notenoughupdates/init/MixinPlugin.java | 47 ---- .../mixins/MixinClientPacketHandler.java | 23 -- .../mixins/MixinDownloadingTerrainScreen.java | 16 -- .../mixins/MixinMessageHandler.java | 34 --- .../notenoughupdates/mixins/MixinMinecraft.java | 26 --- .../mixins/MixinWorldRenderer.java | 26 --- .../mixins/accessor/AccessorHandledScreen.java | 14 -- .../mixins/devenv/DisableCommonPacketWarnings.java | 37 ---- .../mixins/devenv/DisableInvalidFishingHook.java | 15 -- .../mixins/devenv/MixinScoreboard.java | 16 -- src/main/kotlin/moe/nea/firmament/Firmament.kt | 92 ++++++++ src/main/kotlin/moe/nea/firmament/commands/dsl.kt | 81 +++++++ src/main/kotlin/moe/nea/firmament/commands/rome.kt | 66 ++++++ .../nea/firmament/dbus/FirmamentDbusInterface.kt | 11 + .../moe/nea/firmament/dbus/FirmamentDbusObject.kt | 21 ++ .../kotlin/moe/nea/firmament/events/NEUEvent.kt | 36 +++ .../kotlin/moe/nea/firmament/events/NEUEventBus.kt | 37 ++++ .../moe/nea/firmament/events/ParticleSpawnEvent.kt | 13 ++ .../moe/nea/firmament/events/ScreenOpenEvent.kt | 7 + .../events/ServerChatLineReceivedEvent.kt | 13 ++ .../firmament/events/SkyblockServerUpdateEvent.kt | 13 ++ .../moe/nea/firmament/events/WorldReadyEvent.kt | 5 + .../nea/firmament/events/WorldRenderLastEvent.kt | 22 ++ .../moe/nea/firmament/features/FeatureManager.kt | 53 +++++ .../moe/nea/firmament/features/NEUFeature.kt | 18 ++ .../firmament/features/fishing/FishingWarning.kt | 117 ++++++++++ .../moe/nea/firmament/features/world/FairySouls.kt | 120 ++++++++++ src/main/kotlin/moe/nea/firmament/gui/ConfigGui.kt | 94 ++++++++ .../moe/nea/firmament/gui/WGridPanelWithPadding.kt | 33 +++ src/main/kotlin/moe/nea/firmament/gui/repogui.kt | 36 +++ .../moe/nea/firmament/hud/RepoDownloadProgress.kt | 63 ++++++ .../moe/nea/firmament/recipes/SBCraftingRecipe.kt | 53 +++++ .../moe/nea/firmament/recipes/SBForgeRecipe.kt | 53 +++++ .../kotlin/moe/nea/firmament/recipes/SBRecipe.kt | 24 ++ .../moe/nea/firmament/rei/FirmamentReiPlugin.kt | 73 +++++++ .../moe/nea/firmament/rei/NEUItemEntryRenderer.kt | 31 +++ .../nea/firmament/rei/NEUItemEntrySerializer.kt | 25 +++ .../moe/nea/firmament/rei/SBItemEntryDefinition.kt | 85 +++++++ .../rei/SkyblockCraftingRecipeDynamicGenerator.kt | 52 +++++ .../rei/SkyblockItemIdFocusedStackProvider.kt | 25 +++ .../kotlin/moe/nea/firmament/repo/ItemCache.kt | 123 +++++++++++ .../moe/nea/firmament/repo/RepoDownloadManager.kt | 118 ++++++++++ .../kotlin/moe/nea/firmament/repo/RepoManager.kt | 102 +++++++++ src/main/kotlin/moe/nea/firmament/util/ItemUtil.kt | 24 ++ .../moe/nea/firmament/util/LegacyTagParser.kt | 243 +++++++++++++++++++++ src/main/kotlin/moe/nea/firmament/util/Locraw.kt | 8 + src/main/kotlin/moe/nea/firmament/util/MC.kt | 13 ++ .../moe/nea/firmament/util/MinecraftDispatcher.kt | 22 ++ src/main/kotlin/moe/nea/firmament/util/SBData.kt | 62 ++++++ .../kotlin/moe/nea/firmament/util/ScreenUtil.kt | 36 +++ .../kotlin/moe/nea/firmament/util/SequenceUtil.kt | 9 + .../kotlin/moe/nea/firmament/util/SkyblockId.kt | 48 ++++ src/main/kotlin/moe/nea/firmament/util/TimeMark.kt | 15 ++ src/main/kotlin/moe/nea/firmament/util/Timer.kt | 23 ++ .../moe/nea/firmament/util/config/ManagedConfig.kt | 204 +++++++++++++++++ .../moe/nea/firmament/util/data/DataHolder.kt | 60 +++++ .../moe/nea/firmament/util/data/IDataHolder.kt | 75 +++++++ .../util/data/ProfileSpecificDataHolder.kt | 82 +++++++ .../kotlin/moe/nea/firmament/util/render/block.kt | 105 +++++++++ src/main/kotlin/moe/nea/firmament/util/textutil.kt | 70 ++++++ .../moe/nea/notenoughupdates/NotEnoughUpdates.kt | 92 -------- .../moe/nea/notenoughupdates/commands/dsl.kt | 81 ------- .../moe/nea/notenoughupdates/commands/rome.kt | 66 ------ .../nea/notenoughupdates/dbus/NEUDbusInterface.kt | 11 - .../moe/nea/notenoughupdates/dbus/NEUDbusObject.kt | 21 -- .../moe/nea/notenoughupdates/events/NEUEvent.kt | 36 --- .../moe/nea/notenoughupdates/events/NEUEventBus.kt | 37 ---- .../notenoughupdates/events/ParticleSpawnEvent.kt | 13 -- .../nea/notenoughupdates/events/ScreenOpenEvent.kt | 7 - .../events/ServerChatLineReceivedEvent.kt | 13 -- .../events/SkyblockServerUpdateEvent.kt | 13 -- .../nea/notenoughupdates/events/WorldReadyEvent.kt | 5 - .../events/WorldRenderLastEvent.kt | 22 -- .../notenoughupdates/features/FeatureManager.kt | 53 ----- .../nea/notenoughupdates/features/NEUFeature.kt | 18 -- .../features/fishing/FishingWarning.kt | 117 ---------- .../notenoughupdates/features/world/FairySouls.kt | 120 ---------- .../moe/nea/notenoughupdates/gui/ConfigGui.kt | 94 -------- .../notenoughupdates/gui/WGridPanelWithPadding.kt | 33 --- .../kotlin/moe/nea/notenoughupdates/gui/repogui.kt | 36 --- .../notenoughupdates/hud/RepoDownloadProgress.kt | 63 ------ .../notenoughupdates/recipes/SBCraftingRecipe.kt | 53 ----- .../nea/notenoughupdates/recipes/SBForgeRecipe.kt | 53 ----- .../moe/nea/notenoughupdates/recipes/SBRecipe.kt | 24 -- .../notenoughupdates/rei/NEUItemEntryRenderer.kt | 31 --- .../notenoughupdates/rei/NEUItemEntrySerializer.kt | 25 --- .../moe/nea/notenoughupdates/rei/NEUReiPlugin.kt | 73 ------- .../notenoughupdates/rei/SBItemEntryDefinition.kt | 85 ------- .../rei/SkyblockCraftingRecipeDynamicGenerator.kt | 52 ----- .../rei/SkyblockItemIdFocusedStackProvider.kt | 25 --- .../moe/nea/notenoughupdates/repo/ItemCache.kt | 123 ----------- .../notenoughupdates/repo/RepoDownloadManager.kt | 118 ---------- .../moe/nea/notenoughupdates/repo/RepoManager.kt | 102 --------- .../moe/nea/notenoughupdates/util/ItemUtil.kt | 24 -- .../nea/notenoughupdates/util/LegacyTagParser.kt | 243 --------------------- .../kotlin/moe/nea/notenoughupdates/util/Locraw.kt | 8 - .../kotlin/moe/nea/notenoughupdates/util/MC.kt | 13 -- .../notenoughupdates/util/MinecraftDispatcher.kt | 22 -- .../kotlin/moe/nea/notenoughupdates/util/SBData.kt | 64 ------ .../moe/nea/notenoughupdates/util/ScreenUtil.kt | 36 --- .../moe/nea/notenoughupdates/util/SequenceUtil.kt | 9 - .../moe/nea/notenoughupdates/util/SkyblockId.kt | 48 ---- .../moe/nea/notenoughupdates/util/TimeMark.kt | 15 -- .../kotlin/moe/nea/notenoughupdates/util/Timer.kt | 23 -- .../notenoughupdates/util/config/ManagedConfig.kt | 206 ----------------- .../nea/notenoughupdates/util/data/DataHolder.kt | 60 ----- .../nea/notenoughupdates/util/data/IDataHolder.kt | 75 ------- .../util/data/ProfileSpecificDataHolder.kt | 82 ------- .../moe/nea/notenoughupdates/util/render/block.kt | 105 --------- .../moe/nea/notenoughupdates/util/textutil.kt | 70 ------ src/main/resources/assets/firmament/icon.png | Bin 0 -> 20279 bytes .../resources/assets/firmament/lang/en_us.json | 26 +++ .../resources/assets/notenoughupdates/icon.png | Bin 20279 -> 0 bytes .../assets/notenoughupdates/lang/en_us.json | 26 --- src/main/resources/fabric.mod.json | 18 +- src/main/resources/firmament.accesswidener | 1 + src/main/resources/firmament.mixins.json | 22 ++ src/main/resources/notenoughupdates.accesswidener | 1 - src/main/resources/notenoughupdates.mixins.json | 22 -- 131 files changed, 3128 insertions(+), 3134 deletions(-) create mode 100644 src/main/java/moe/nea/firmament/init/MixinPlugin.java create mode 100644 src/main/java/moe/nea/firmament/mixins/MixinClientPacketHandler.java create mode 100644 src/main/java/moe/nea/firmament/mixins/MixinDownloadingTerrainScreen.java create mode 100644 src/main/java/moe/nea/firmament/mixins/MixinMessageHandler.java create mode 100644 src/main/java/moe/nea/firmament/mixins/MixinMinecraft.java create mode 100644 src/main/java/moe/nea/firmament/mixins/MixinWorldRenderer.java create mode 100644 src/main/java/moe/nea/firmament/mixins/accessor/AccessorHandledScreen.java create mode 100644 src/main/java/moe/nea/firmament/mixins/devenv/DisableCommonPacketWarnings.java create mode 100644 src/main/java/moe/nea/firmament/mixins/devenv/DisableInvalidFishingHook.java create mode 100644 src/main/java/moe/nea/firmament/mixins/devenv/MixinScoreboard.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/init/MixinPlugin.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/MixinClientPacketHandler.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/MixinDownloadingTerrainScreen.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/MixinMessageHandler.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/MixinMinecraft.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/MixinWorldRenderer.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/accessor/AccessorHandledScreen.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableCommonPacketWarnings.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableInvalidFishingHook.java delete mode 100644 src/main/java/moe/nea/notenoughupdates/mixins/devenv/MixinScoreboard.java create mode 100644 src/main/kotlin/moe/nea/firmament/Firmament.kt create mode 100644 src/main/kotlin/moe/nea/firmament/commands/dsl.kt create mode 100644 src/main/kotlin/moe/nea/firmament/commands/rome.kt create mode 100644 src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusInterface.kt create mode 100644 src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusObject.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/NEUEvent.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/NEUEventBus.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/ParticleSpawnEvent.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/ScreenOpenEvent.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/ServerChatLineReceivedEvent.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/SkyblockServerUpdateEvent.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/WorldReadyEvent.kt create mode 100644 src/main/kotlin/moe/nea/firmament/events/WorldRenderLastEvent.kt create mode 100644 src/main/kotlin/moe/nea/firmament/features/FeatureManager.kt create mode 100644 src/main/kotlin/moe/nea/firmament/features/NEUFeature.kt create mode 100644 src/main/kotlin/moe/nea/firmament/features/fishing/FishingWarning.kt create mode 100644 src/main/kotlin/moe/nea/firmament/features/world/FairySouls.kt create mode 100644 src/main/kotlin/moe/nea/firmament/gui/ConfigGui.kt create mode 100644 src/main/kotlin/moe/nea/firmament/gui/WGridPanelWithPadding.kt create mode 100644 src/main/kotlin/moe/nea/firmament/gui/repogui.kt create mode 100644 src/main/kotlin/moe/nea/firmament/hud/RepoDownloadProgress.kt create mode 100644 src/main/kotlin/moe/nea/firmament/recipes/SBCraftingRecipe.kt create mode 100644 src/main/kotlin/moe/nea/firmament/recipes/SBForgeRecipe.kt create mode 100644 src/main/kotlin/moe/nea/firmament/recipes/SBRecipe.kt create mode 100644 src/main/kotlin/moe/nea/firmament/rei/FirmamentReiPlugin.kt create mode 100644 src/main/kotlin/moe/nea/firmament/rei/NEUItemEntryRenderer.kt create mode 100644 src/main/kotlin/moe/nea/firmament/rei/NEUItemEntrySerializer.kt create mode 100644 src/main/kotlin/moe/nea/firmament/rei/SBItemEntryDefinition.kt create mode 100644 src/main/kotlin/moe/nea/firmament/rei/SkyblockCraftingRecipeDynamicGenerator.kt create mode 100644 src/main/kotlin/moe/nea/firmament/rei/SkyblockItemIdFocusedStackProvider.kt create mode 100644 src/main/kotlin/moe/nea/firmament/repo/ItemCache.kt create mode 100644 src/main/kotlin/moe/nea/firmament/repo/RepoDownloadManager.kt create mode 100644 src/main/kotlin/moe/nea/firmament/repo/RepoManager.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/ItemUtil.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/LegacyTagParser.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/Locraw.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/MC.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/MinecraftDispatcher.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/SBData.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/ScreenUtil.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/SequenceUtil.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/SkyblockId.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/TimeMark.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/Timer.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/config/ManagedConfig.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/data/DataHolder.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/data/IDataHolder.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/data/ProfileSpecificDataHolder.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/render/block.kt create mode 100644 src/main/kotlin/moe/nea/firmament/util/textutil.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/NotEnoughUpdates.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/commands/dsl.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/commands/rome.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusInterface.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusObject.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/NEUEvent.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/NEUEventBus.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/ParticleSpawnEvent.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/ScreenOpenEvent.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/ServerChatLineReceivedEvent.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/SkyblockServerUpdateEvent.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/WorldReadyEvent.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/events/WorldRenderLastEvent.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/features/FeatureManager.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/features/NEUFeature.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/features/fishing/FishingWarning.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/features/world/FairySouls.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/gui/ConfigGui.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/gui/WGridPanelWithPadding.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/gui/repogui.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/hud/RepoDownloadProgress.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/recipes/SBCraftingRecipe.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/recipes/SBForgeRecipe.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/recipes/SBRecipe.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntryRenderer.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntrySerializer.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/rei/NEUReiPlugin.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/rei/SBItemEntryDefinition.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockCraftingRecipeDynamicGenerator.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockItemIdFocusedStackProvider.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/repo/ItemCache.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/repo/RepoDownloadManager.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/repo/RepoManager.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/ItemUtil.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/LegacyTagParser.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/Locraw.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/MC.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/MinecraftDispatcher.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/SBData.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/ScreenUtil.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/SequenceUtil.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/SkyblockId.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/TimeMark.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/Timer.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/config/ManagedConfig.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/data/IDataHolder.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/data/ProfileSpecificDataHolder.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/render/block.kt delete mode 100644 src/main/kotlin/moe/nea/notenoughupdates/util/textutil.kt create mode 100644 src/main/resources/assets/firmament/icon.png create mode 100644 src/main/resources/assets/firmament/lang/en_us.json delete mode 100644 src/main/resources/assets/notenoughupdates/icon.png delete mode 100644 src/main/resources/assets/notenoughupdates/lang/en_us.json create mode 100644 src/main/resources/firmament.accesswidener create mode 100644 src/main/resources/firmament.mixins.json delete mode 100644 src/main/resources/notenoughupdates.accesswidener delete mode 100644 src/main/resources/notenoughupdates.mixins.json diff --git a/.editorconfig b/.editorconfig index c0c6bb2..b7eca3c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -12,4 +12,4 @@ max_line_length = 120 [*.kt] ij_kotlin_name_count_to_use_star_import = 99999 ij_kotlin_name_count_to_use_star_import_for_members = 99999 -ij_kotlin_imports_layout = *, |, kotlinx.**, kotlin.**, net.minecraft.**, moe.nea.notenoughupdates.**, |, $* +ij_kotlin_imports_layout = *, |, kotlinx.**, kotlin.**, net.minecraft.**, moe.nea.firmament.**, |, $* diff --git a/build.gradle.kts b/build.gradle.kts index 3c2cc3c..65f8dbd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -13,13 +13,13 @@ plugins { loom { clientOnlyMinecraftJar() - accessWidenerPath.set(project.file("src/main/resources/notenoughupdates.accesswidener")) + accessWidenerPath.set(project.file("src/main/resources/firmament.accesswidener")) runs { removeIf { it.name != "client" } named("client") { property("devauth.enabled", "true") property("fabric.log.level", "info") - property("notenoughupdates.debug", "true") + property("firmament.debug", "true") /* vmArg("-XX:+AllowEnhancedClassRedefinition") vmArg("-XX:HotswapAgent=fatjar") @@ -145,6 +145,6 @@ tasks.processResources { tasks.license { scanConfiguration(project.configurations.compileClasspath.get()) - outputFile.set(file("$buildDir/LICENSES-NEU.json")) + outputFile.set(file("$buildDir/LICENSES-FIRMAMENT.json")) licenseFormatter.set(moe.nea.licenseextractificator.JsonLicenseFormatter()) } diff --git a/src/main/java/moe/nea/firmament/init/MixinPlugin.java b/src/main/java/moe/nea/firmament/init/MixinPlugin.java new file mode 100644 index 0000000..ddb17f4 --- /dev/null +++ b/src/main/java/moe/nea/firmament/init/MixinPlugin.java @@ -0,0 +1,46 @@ +package moe.nea.firmament.init; + +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Set; + +public class MixinPlugin implements IMixinConfigPlugin { + @Override + public void onLoad(String mixinPackage) { + + } + + @Override + public String getRefMapperConfig() { + return null; + } + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + return Boolean.getBoolean("firmament.debug") || + !mixinClassName.startsWith("moe.nea.firmament.mixins.devenv"); + } + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) { + + } + + @Override + public List getMixins() { + return null; + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + + } + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/MixinClientPacketHandler.java b/src/main/java/moe/nea/firmament/mixins/MixinClientPacketHandler.java new file mode 100644 index 0000000..01ef98e --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/MixinClientPacketHandler.java @@ -0,0 +1,23 @@ +package moe.nea.firmament.mixins; + +import moe.nea.firmament.events.ParticleSpawnEvent; +import net.minecraft.client.network.ClientPlayNetworkHandler; +import net.minecraft.network.packet.s2c.play.ParticleS2CPacket; +import net.minecraft.util.math.Vec3d; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ClientPlayNetworkHandler.class) +public class MixinClientPacketHandler { + @Inject(method = "onParticle", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/NetworkThreadUtils;forceMainThread(Lnet/minecraft/network/packet/Packet;Lnet/minecraft/network/listener/PacketListener;Lnet/minecraft/util/thread/ThreadExecutor;)V", shift = At.Shift.AFTER)) + public void onParticleSpawn(ParticleS2CPacket packet, CallbackInfo ci) { + ParticleSpawnEvent.Companion.publish(new ParticleSpawnEvent( + packet.getParameters(), + new Vec3d(packet.getX(), packet.getY(), packet.getZ()), + new Vec3d(packet.getOffsetX(), packet.getOffsetY(), packet.getOffsetZ()), + packet.isLongDistance() + )); + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/MixinDownloadingTerrainScreen.java b/src/main/java/moe/nea/firmament/mixins/MixinDownloadingTerrainScreen.java new file mode 100644 index 0000000..a1c4ff3 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/MixinDownloadingTerrainScreen.java @@ -0,0 +1,16 @@ +package moe.nea.firmament.mixins; + +import moe.nea.firmament.events.WorldReadyEvent; +import net.minecraft.client.gui.screen.DownloadingTerrainScreen; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(DownloadingTerrainScreen.class) +public class MixinDownloadingTerrainScreen { + @Inject(method = "close", at = @At("HEAD")) + public void onClose(CallbackInfo ci) { + WorldReadyEvent.Companion.publish(new WorldReadyEvent()); + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/MixinMessageHandler.java b/src/main/java/moe/nea/firmament/mixins/MixinMessageHandler.java new file mode 100644 index 0000000..34dd5a1 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/MixinMessageHandler.java @@ -0,0 +1,34 @@ +package moe.nea.firmament.mixins; + +import com.mojang.authlib.GameProfile; +import moe.nea.firmament.events.ServerChatLineReceivedEvent; +import net.minecraft.client.network.message.MessageHandler; +import net.minecraft.network.message.MessageType; +import net.minecraft.network.message.SignedMessage; +import net.minecraft.text.Text; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(MessageHandler.class) +public class MixinMessageHandler { + @Inject(method = "onChatMessage", cancellable = true, at = @At("HEAD")) + public void onOnChatMessage(SignedMessage message, GameProfile sender, MessageType.Parameters params, CallbackInfo ci) { + var decoratedText = params.applyChatDecoration(message.unsignedContent() != null ? message.unsignedContent() : message.getContent()); + var event = new ServerChatLineReceivedEvent(decoratedText); + if (ServerChatLineReceivedEvent.Companion.publish(event).getCancelled()) { + ci.cancel(); + } + } + + @Inject(method = "onGameMessage", at = @At("HEAD"), cancellable = true) + public void onOnGameMessage(Text message, boolean overlay, CallbackInfo ci) { + if (!overlay) { + var event = new ServerChatLineReceivedEvent(message); + if (ServerChatLineReceivedEvent.Companion.publish(event).getCancelled()) { + ci.cancel(); + } + } + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/MixinMinecraft.java b/src/main/java/moe/nea/firmament/mixins/MixinMinecraft.java new file mode 100644 index 0000000..f2313d7 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/MixinMinecraft.java @@ -0,0 +1,26 @@ +package moe.nea.firmament.mixins; + +import moe.nea.firmament.events.ScreenOpenEvent; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.Screen; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(MinecraftClient.class) +public abstract class MixinMinecraft { + @Shadow + @Nullable + public Screen currentScreen; + + @Inject(method = "setScreen", at = @At("HEAD"), cancellable = true) + public void onScreenChange(Screen screen, CallbackInfo ci) { + var event = new ScreenOpenEvent(currentScreen, screen); + if (ScreenOpenEvent.Companion.publish(event).getCancelled()) { + ci.cancel(); + } + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/MixinWorldRenderer.java b/src/main/java/moe/nea/firmament/mixins/MixinWorldRenderer.java new file mode 100644 index 0000000..e149168 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/MixinWorldRenderer.java @@ -0,0 +1,26 @@ +package moe.nea.firmament.mixins; + +import moe.nea.firmament.events.WorldRenderLastEvent; +import net.minecraft.client.render.Camera; +import net.minecraft.client.render.GameRenderer; +import net.minecraft.client.render.LightmapTextureManager; +import net.minecraft.client.render.WorldRenderer; +import net.minecraft.client.util.math.MatrixStack; +import org.joml.Matrix4f; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(WorldRenderer.class) +public class MixinWorldRenderer { + @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;renderChunkDebugInfo(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/client/render/Camera;)V", shift = At.Shift.AFTER)) + public void onWorldRenderLast(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f positionMatrix, CallbackInfo ci) { + var event = new WorldRenderLastEvent( + matrices, tickDelta, renderBlockOutline, + camera, gameRenderer, lightmapTextureManager, + positionMatrix + ); + WorldRenderLastEvent.Companion.publish(event); + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/accessor/AccessorHandledScreen.java b/src/main/java/moe/nea/firmament/mixins/accessor/AccessorHandledScreen.java new file mode 100644 index 0000000..1a575c6 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/accessor/AccessorHandledScreen.java @@ -0,0 +1,14 @@ +package moe.nea.firmament.mixins.accessor; + +import net.minecraft.client.gui.screen.ingame.HandledScreen; +import net.minecraft.screen.slot.Slot; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(HandledScreen.class) +public interface AccessorHandledScreen { + @Accessor("focusedSlot") + @Nullable + Slot getFocusedSlot_NEU(); +} diff --git a/src/main/java/moe/nea/firmament/mixins/devenv/DisableCommonPacketWarnings.java b/src/main/java/moe/nea/firmament/mixins/devenv/DisableCommonPacketWarnings.java new file mode 100644 index 0000000..16ca7c1 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/devenv/DisableCommonPacketWarnings.java @@ -0,0 +1,37 @@ +package moe.nea.firmament.mixins.devenv; + +import net.minecraft.client.network.ClientPlayNetworkHandler; +import net.minecraft.util.Identifier; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +import java.util.Objects; + +@Mixin(ClientPlayNetworkHandler.class) +public class DisableCommonPacketWarnings { + + @Redirect(method = "onCustomPayload", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V")) + public void onCustomPacket(Logger instance, String s, Object o) { + if (!Objects.equals(o, Identifier.of("badlion", "mods"))) { + instance.warn(s, o); + } + } + + @Redirect(method = "onEntityPassengersSet", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;)V")) + public void onUnknownPassenger(Logger instance, String s) { + // Ignore passenger data for unknown entities, since HyPixel just sends a lot of those. + } + + @Redirect(method = "onTeam", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;[Ljava/lang/Object;)V")) + public void onOnTeam(Logger instance, String s, Object[] objects) { + // Ignore data for unknown teams, since HyPixel just sends a lot of invalid team data. + } + + @Redirect(method = "onPlayerList", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V")) + public void onOnPlayerList(Logger instance, String s, Object o) { + // Ignore invalid player info, since HyPixel just sends a lot of invalid player info + } + +} diff --git a/src/main/java/moe/nea/firmament/mixins/devenv/DisableInvalidFishingHook.java b/src/main/java/moe/nea/firmament/mixins/devenv/DisableInvalidFishingHook.java new file mode 100644 index 0000000..b1a4049 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/devenv/DisableInvalidFishingHook.java @@ -0,0 +1,15 @@ +package moe.nea.firmament.mixins.devenv; + +import net.minecraft.entity.projectile.FishingBobberEntity; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(FishingBobberEntity.class) +public class DisableInvalidFishingHook { + @Redirect(method = "onSpawnPacket", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;error(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V")) + public void onOnSpawnPacket(Logger instance, String s, Object o, Object o1) { + // Don't warn for broken fishing hooks, since HyPixel sends a bunch of those + } +} diff --git a/src/main/java/moe/nea/firmament/mixins/devenv/MixinScoreboard.java b/src/main/java/moe/nea/firmament/mixins/devenv/MixinScoreboard.java new file mode 100644 index 0000000..acb0033 --- /dev/null +++ b/src/main/java/moe/nea/firmament/mixins/devenv/MixinScoreboard.java @@ -0,0 +1,15 @@ +package moe.nea.firmament.mixins.devenv; + +import net.minecraft.scoreboard.Scoreboard; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(Scoreboard.class) +public class MixinScoreboard { + @Redirect(method = "addTeam", at=@At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V")) + public void onExistingteam(Logger instance, String s, Object o) { + // Ignore creations of existing teams + } +} diff --git a/src/main/java/moe/nea/notenoughupdates/init/MixinPlugin.java b/src/main/java/moe/nea/notenoughupdates/init/MixinPlugin.java deleted file mode 100644 index b2e7e4c..0000000 --- a/src/main/java/moe/nea/notenoughupdates/init/MixinPlugin.java +++ /dev/null @@ -1,47 +0,0 @@ -package moe.nea.notenoughupdates.init; - -import moe.nea.notenoughupdates.NotEnoughUpdates; -import org.objectweb.asm.tree.ClassNode; -import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; -import org.spongepowered.asm.mixin.extensibility.IMixinInfo; - -import java.util.List; -import java.util.Set; - -public class MixinPlugin implements IMixinConfigPlugin { - @Override - public void onLoad(String mixinPackage) { - - } - - @Override - public String getRefMapperConfig() { - return null; - } - - @Override - public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { - return Boolean.getBoolean("notenoughupdates.debug") || - !mixinClassName.startsWith("moe.nea.notenoughupdates.mixins.devenv"); - } - - @Override - public void acceptTargets(Set myTargets, Set otherTargets) { - - } - - @Override - public List getMixins() { - return null; - } - - @Override - public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - - } - - @Override - public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - - } -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/MixinClientPacketHandler.java b/src/main/java/moe/nea/notenoughupdates/mixins/MixinClientPacketHandler.java deleted file mode 100644 index dc57113..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/MixinClientPacketHandler.java +++ /dev/null @@ -1,23 +0,0 @@ -package moe.nea.notenoughupdates.mixins; - -import moe.nea.notenoughupdates.events.ParticleSpawnEvent; -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.network.packet.s2c.play.ParticleS2CPacket; -import net.minecraft.util.math.Vec3d; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(ClientPlayNetworkHandler.class) -public class MixinClientPacketHandler { - @Inject(method = "onParticle", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/NetworkThreadUtils;forceMainThread(Lnet/minecraft/network/packet/Packet;Lnet/minecraft/network/listener/PacketListener;Lnet/minecraft/util/thread/ThreadExecutor;)V", shift = At.Shift.AFTER)) - public void onParticleSpawn(ParticleS2CPacket packet, CallbackInfo ci) { - ParticleSpawnEvent.Companion.publish(new ParticleSpawnEvent( - packet.getParameters(), - new Vec3d(packet.getX(), packet.getY(), packet.getZ()), - new Vec3d(packet.getOffsetX(), packet.getOffsetY(), packet.getOffsetZ()), - packet.isLongDistance() - )); - } -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/MixinDownloadingTerrainScreen.java b/src/main/java/moe/nea/notenoughupdates/mixins/MixinDownloadingTerrainScreen.java deleted file mode 100644 index 3ed8a73..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/MixinDownloadingTerrainScreen.java +++ /dev/null @@ -1,16 +0,0 @@ -package moe.nea.notenoughupdates.mixins; - -import moe.nea.notenoughupdates.events.WorldReadyEvent; -import net.minecraft.client.gui.screen.DownloadingTerrainScreen; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(DownloadingTerrainScreen.class) -public class MixinDownloadingTerrainScreen { - @Inject(method = "close", at = @At("HEAD")) - public void onClose(CallbackInfo ci) { - WorldReadyEvent.Companion.publish(new WorldReadyEvent()); - } -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/MixinMessageHandler.java b/src/main/java/moe/nea/notenoughupdates/mixins/MixinMessageHandler.java deleted file mode 100644 index 5d3e70f..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/MixinMessageHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -package moe.nea.notenoughupdates.mixins; - -import com.mojang.authlib.GameProfile; -import moe.nea.notenoughupdates.events.ServerChatLineReceivedEvent; -import net.minecraft.client.network.message.MessageHandler; -import net.minecraft.network.message.MessageType; -import net.minecraft.network.message.SignedMessage; -import net.minecraft.text.Text; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(MessageHandler.class) -public class MixinMessageHandler { - @Inject(method = "onChatMessage", cancellable = true, at = @At("HEAD")) - public void onOnChatMessage(SignedMessage message, GameProfile sender, MessageType.Parameters params, CallbackInfo ci) { - var decoratedText = params.applyChatDecoration(message.unsignedContent() != null ? message.unsignedContent() : message.getContent()); - var event = new ServerChatLineReceivedEvent(decoratedText); - if (ServerChatLineReceivedEvent.Companion.publish(event).getCancelled()) { - ci.cancel(); - } - } - - @Inject(method = "onGameMessage", at = @At("HEAD"), cancellable = true) - public void onOnGameMessage(Text message, boolean overlay, CallbackInfo ci) { - if (!overlay) { - var event = new ServerChatLineReceivedEvent(message); - if (ServerChatLineReceivedEvent.Companion.publish(event).getCancelled()) { - ci.cancel(); - } - } - } -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/MixinMinecraft.java b/src/main/java/moe/nea/notenoughupdates/mixins/MixinMinecraft.java deleted file mode 100644 index 17f49e1..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/MixinMinecraft.java +++ /dev/null @@ -1,26 +0,0 @@ -package moe.nea.notenoughupdates.mixins; - -import moe.nea.notenoughupdates.events.ScreenOpenEvent; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.Screen; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(MinecraftClient.class) -public abstract class MixinMinecraft { - @Shadow - @Nullable - public Screen currentScreen; - - @Inject(method = "setScreen", at = @At("HEAD"), cancellable = true) - public void onScreenChange(Screen screen, CallbackInfo ci) { - var event = new ScreenOpenEvent(currentScreen, screen); - if (ScreenOpenEvent.Companion.publish(event).getCancelled()) { - ci.cancel(); - } - } -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/MixinWorldRenderer.java b/src/main/java/moe/nea/notenoughupdates/mixins/MixinWorldRenderer.java deleted file mode 100644 index c3d70fe..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/MixinWorldRenderer.java +++ /dev/null @@ -1,26 +0,0 @@ -package moe.nea.notenoughupdates.mixins; - -import moe.nea.notenoughupdates.events.WorldRenderLastEvent; -import net.minecraft.client.render.Camera; -import net.minecraft.client.render.GameRenderer; -import net.minecraft.client.render.LightmapTextureManager; -import net.minecraft.client.render.WorldRenderer; -import net.minecraft.client.util.math.MatrixStack; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(WorldRenderer.class) -public class MixinWorldRenderer { - @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;renderChunkDebugInfo(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/client/render/Camera;)V", shift = At.Shift.AFTER)) - public void onWorldRenderLast(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f positionMatrix, CallbackInfo ci) { - var event = new WorldRenderLastEvent( - matrices, tickDelta, renderBlockOutline, - camera, gameRenderer, lightmapTextureManager, - positionMatrix - ); - WorldRenderLastEvent.Companion.publish(event); - } -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/accessor/AccessorHandledScreen.java b/src/main/java/moe/nea/notenoughupdates/mixins/accessor/AccessorHandledScreen.java deleted file mode 100644 index cea44cf..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/accessor/AccessorHandledScreen.java +++ /dev/null @@ -1,14 +0,0 @@ -package moe.nea.notenoughupdates.mixins.accessor; - -import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.screen.slot.Slot; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(HandledScreen.class) -public interface AccessorHandledScreen { - @Accessor("focusedSlot") - @Nullable - Slot getFocusedSlot_NEU(); -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableCommonPacketWarnings.java b/src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableCommonPacketWarnings.java deleted file mode 100644 index 8302170..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableCommonPacketWarnings.java +++ /dev/null @@ -1,37 +0,0 @@ -package moe.nea.notenoughupdates.mixins.devenv; - -import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.util.Identifier; -import org.slf4j.Logger; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.Objects; - -@Mixin(ClientPlayNetworkHandler.class) -public class DisableCommonPacketWarnings { - - @Redirect(method = "onCustomPayload", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V")) - public void onCustomPacket(Logger instance, String s, Object o) { - if (!Objects.equals(o, Identifier.of("badlion", "mods"))) { - instance.warn(s, o); - } - } - - @Redirect(method = "onEntityPassengersSet", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;)V")) - public void onUnknownPassenger(Logger instance, String s) { - // Ignore passenger data for unknown entities, since HyPixel just sends a lot of those. - } - - @Redirect(method = "onTeam", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;[Ljava/lang/Object;)V")) - public void onOnTeam(Logger instance, String s, Object[] objects) { - // Ignore data for unknown teams, since HyPixel just sends a lot of invalid team data. - } - - @Redirect(method = "onPlayerList", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V")) - public void onOnPlayerList(Logger instance, String s, Object o) { - // Ignore invalid player info, since HyPixel just sends a lot of invalid player info - } - -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableInvalidFishingHook.java b/src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableInvalidFishingHook.java deleted file mode 100644 index 0c434bd..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/devenv/DisableInvalidFishingHook.java +++ /dev/null @@ -1,15 +0,0 @@ -package moe.nea.notenoughupdates.mixins.devenv; - -import net.minecraft.entity.projectile.FishingBobberEntity; -import org.slf4j.Logger; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(FishingBobberEntity.class) -public class DisableInvalidFishingHook { - @Redirect(method = "onSpawnPacket", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;error(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V")) - public void onOnSpawnPacket(Logger instance, String s, Object o, Object o1) { - // Don't warn for broken fishing hooks, since HyPixel sends a bunch of those - } -} diff --git a/src/main/java/moe/nea/notenoughupdates/mixins/devenv/MixinScoreboard.java b/src/main/java/moe/nea/notenoughupdates/mixins/devenv/MixinScoreboard.java deleted file mode 100644 index 306b900..0000000 --- a/src/main/java/moe/nea/notenoughupdates/mixins/devenv/MixinScoreboard.java +++ /dev/null @@ -1,16 +0,0 @@ -package moe.nea.notenoughupdates.mixins.devenv; - -import net.minecraft.scoreboard.Scoreboard; -import org.slf4j.Logger; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(Scoreboard.class) -public class MixinScoreboard { - @Redirect(method = "addTeam", at=@At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;)V")) - public void onExistingteam(Logger instance, String s, Object o) { - // Ignore creations of existing teams - } -} diff --git a/src/main/kotlin/moe/nea/firmament/Firmament.kt b/src/main/kotlin/moe/nea/firmament/Firmament.kt new file mode 100644 index 0000000..ec6cd3e --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/Firmament.kt @@ -0,0 +1,92 @@ +package moe.nea.firmament + +import com.mojang.brigadier.CommandDispatcher +import io.ktor.client.* +import io.ktor.client.plugins.* +import io.ktor.client.plugins.contentnegotiation.* +import io.ktor.serialization.kotlinx.json.* +import java.nio.file.Files +import java.nio.file.Path +import net.fabricmc.api.ClientModInitializer +import net.fabricmc.api.ModInitializer +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents +import net.fabricmc.loader.api.FabricLoader +import net.fabricmc.loader.api.Version +import net.fabricmc.loader.api.metadata.ModMetadata +import org.apache.logging.log4j.LogManager +import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder +import kotlinx.coroutines.* +import kotlinx.serialization.json.Json +import kotlin.coroutines.EmptyCoroutineContext +import net.minecraft.command.CommandRegistryAccess +import moe.nea.firmament.commands.registerFirmamentCommand +import moe.nea.firmament.dbus.FirmamentDbusObject +import moe.nea.firmament.features.FeatureManager +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.SBData +import moe.nea.firmament.util.data.IDataHolder + +object Firmament : ModInitializer, ClientModInitializer { + const val MOD_ID = "firmament" + + val DEBUG = System.getProperty("firmament.debug") == "true" + val DATA_DIR: Path = Path.of(".firmament").also { Files.createDirectories(it) } + val CONFIG_DIR: Path = Path.of("config/firmament").also { Files.createDirectories(it) } + val logger = LogManager.getLogger("Firmament") + val metadata: ModMetadata by lazy { FabricLoader.getInstance().getModContainer(MOD_ID).orElseThrow().metadata } + val version: Version by lazy { metadata.version } + + val json = Json { + prettyPrint = DEBUG + ignoreUnknownKeys = true + encodeDefaults = true + } + + val httpClient by lazy { + HttpClient { + install(ContentNegotiation) { + json(json) + } + install(UserAgent) { + agent = "Firmament/$version" + } + } + } + + val globalJob = Job() + val dbusConnection = DBusConnectionBuilder.forSessionBus() + .build() + val coroutineScope = + CoroutineScope(EmptyCoroutineContext + CoroutineName("Firmament")) + SupervisorJob(globalJob) + + private fun registerCommands( + dispatcher: CommandDispatcher, + @Suppress("UNUSED_PARAMETER") + ctx: CommandRegistryAccess + ) { + registerFirmamentCommand(dispatcher) + } + + override fun onInitialize() { + + dbusConnection.requestBusName("moe.nea.firmament") + dbusConnection.exportObject(FirmamentDbusObject) + IDataHolder.registerEvents() + RepoManager.initialize() + SBData.init() + FeatureManager.autoload() + + ClientCommandRegistrationCallback.EVENT.register(this::registerCommands) + ClientLifecycleEvents.CLIENT_STOPPING.register(ClientLifecycleEvents.ClientStopping { + runBlocking { + logger.info("Shutting down NEU coroutines") + globalJob.cancel() + } + }) + } + + override fun onInitializeClient() { + } +} diff --git a/src/main/kotlin/moe/nea/firmament/commands/dsl.kt b/src/main/kotlin/moe/nea/firmament/commands/dsl.kt new file mode 100644 index 0000000..5ead624 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/commands/dsl.kt @@ -0,0 +1,81 @@ +package moe.nea.firmament.commands + +import com.mojang.brigadier.arguments.ArgumentType +import com.mojang.brigadier.builder.ArgumentBuilder +import com.mojang.brigadier.builder.LiteralArgumentBuilder +import com.mojang.brigadier.builder.RequiredArgumentBuilder +import com.mojang.brigadier.context.CommandContext +import java.lang.reflect.ParameterizedType +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource +import moe.nea.firmament.util.iterate + + +typealias DefaultSource = FabricClientCommandSource + + +inline val > T.context get() = this +operator fun > C.get(arg: TypeSafeArg): T { + return arg.get(this) +} + +fun literal( + name: String, + block: LiteralArgumentBuilder.() -> Unit +): LiteralArgumentBuilder = + LiteralArgumentBuilder.literal(name).also(block) + +data class TypeSafeArg(val name: String, val argument: ArgumentType) { + val argClass by lazy { + argument.javaClass + .iterate>> { + it.superclass + } + .map { + it.genericSuperclass + } + .filterIsInstance() + .find { it.rawType == ArgumentType::class.java }!! + .let { it.actualTypeArguments[0] as Class<*> } + } + + @JvmName("getWithThis") + fun CommandContext.get(): T = + get(this) + + + fun get(ctx: CommandContext): T { + return ctx.getArgument(name, argClass) as T + } +} + + +fun argument( + name: String, + argument: ArgumentType, + block: RequiredArgumentBuilder.(TypeSafeArg) -> Unit +): RequiredArgumentBuilder = + RequiredArgumentBuilder.argument(name, argument).also { block(it, TypeSafeArg(name, argument)) } + +fun , AT : Any> T.thenArgument( + name: String, + argument: ArgumentType, + block: RequiredArgumentBuilder.(TypeSafeArg) -> Unit +): T = then(argument(name, argument, block)) + + +fun > T.thenLiteral( + name: String, + block: LiteralArgumentBuilder.() -> Unit +): T = + then(literal(name, block)) + +fun > T.then(node: ArgumentBuilder, block: T.() -> Unit): T = + then(node).also(block) + +fun > T.thenExecute(block: CommandContext.() -> Unit): T = + executes { + block(it) + 1 + } + + diff --git a/src/main/kotlin/moe/nea/firmament/commands/rome.kt b/src/main/kotlin/moe/nea/firmament/commands/rome.kt new file mode 100644 index 0000000..bdbaa3f --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/commands/rome.kt @@ -0,0 +1,66 @@ +package moe.nea.firmament.commands + +import com.mojang.brigadier.CommandDispatcher +import io.github.cottonmc.cotton.gui.client.CottonClientScreen +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource +import net.minecraft.text.Text +import moe.nea.firmament.features.world.FairySouls +import moe.nea.firmament.gui.repoGui +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.SBData +import moe.nea.firmament.util.ScreenUtil.setScreenLater + + +fun firmamentCommand() = literal("firmament") { + thenLiteral("repo") { + thenLiteral("reload") { + thenLiteral("fetch") { + thenExecute { + source.sendFeedback(Text.translatable("firmament.repo.reload.network")) // TODO better reporting + RepoManager.launchAsyncUpdate() + } + } + thenExecute { + source.sendFeedback(Text.translatable("firmament.repo.reload.disk")) + RepoManager.reload() + } + } + thenExecute { + setScreenLater(CottonClientScreen(repoGui())) + } + } + thenLiteral("dev") { + thenLiteral("config") { + thenExecute { + FairySouls.TConfig.showConfigEditor() + } + } + thenLiteral("sbdata") { + thenExecute { + source.sendFeedback(Text.translatable("firmament.sbinfo.profile", SBData.profileCuteName)) + val locrawInfo = SBData.locraw + if (locrawInfo == null) { + source.sendFeedback(Text.translatable("firmament.sbinfo.nolocraw")) + } else { + source.sendFeedback(Text.translatable("firmament.sbinfo.server", locrawInfo.server)) + source.sendFeedback(Text.translatable("firmament.sbinfo.gametype", locrawInfo.gametype)) + source.sendFeedback(Text.translatable("firmament.sbinfo.mode", locrawInfo.mode)) + source.sendFeedback(Text.translatable("firmament.sbinfo.map", locrawInfo.map)) + } + + } + } + } +} + + +fun registerFirmamentCommand(dispatcher: CommandDispatcher) { + val firmament = dispatcher.register(firmamentCommand()) + dispatcher.register(literal("firm") { + redirect(firmament) + }) +} + + + + diff --git a/src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusInterface.kt b/src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusInterface.kt new file mode 100644 index 0000000..24b7dc8 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusInterface.kt @@ -0,0 +1,11 @@ +package moe.nea.firmament.dbus + +import org.freedesktop.dbus.annotations.DBusInterfaceName +import org.freedesktop.dbus.interfaces.DBusInterface + +@DBusInterfaceName("moe.nea.Firmament") +interface FirmamentDbusInterface : DBusInterface { + fun sayHello(): String + fun getCurrentRepoCommit(): String + fun requestRepoReDownload() +} diff --git a/src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusObject.kt b/src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusObject.kt new file mode 100644 index 0000000..48d4cf7 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/dbus/FirmamentDbusObject.kt @@ -0,0 +1,21 @@ +package moe.nea.firmament.dbus + +import moe.nea.firmament.repo.RepoManager + +object FirmamentDbusObject : FirmamentDbusInterface { + override fun sayHello(): String { + return "Hello from Firmanet" + } + + override fun getCurrentRepoCommit(): String { + return RepoManager.currentDownloadedSha ?: "none" + } + + override fun requestRepoReDownload() { + RepoManager.launchAsyncUpdate() + } + + override fun getObjectPath(): String { + return "/moe/nea/Firmament" + } +} diff --git a/src/main/kotlin/moe/nea/firmament/events/NEUEvent.kt b/src/main/kotlin/moe/nea/firmament/events/NEUEvent.kt new file mode 100644 index 0000000..722ea64 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/NEUEvent.kt @@ -0,0 +1,36 @@ +package moe.nea.firmament.events + +/** + * An event that can be fired by a [NEUEventBus]. + * + * Typically, that event bus is implemented as a companion object + * + * ``` + * class SomeEvent : NEUEvent() { + * companion object : NEUEventBus() + * } + * ``` + */ +abstract class NEUEvent { + /** + * A [NEUEvent] that can be [cancelled] + */ + abstract class Cancellable : NEUEvent() { + /** + * Cancels this is event. + * + * @see cancelled + */ + fun cancel() { + cancelled = true + } + + /** + * Whether this event is cancelled. + * + * Cancelled events will bypass handlers unless otherwise specified and will prevent the action that this + * event was originally fired for. + */ + var cancelled: Boolean = false + } +} diff --git a/src/main/kotlin/moe/nea/firmament/events/NEUEventBus.kt b/src/main/kotlin/moe/nea/firmament/events/NEUEventBus.kt new file mode 100644 index 0000000..b3b9152 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/NEUEventBus.kt @@ -0,0 +1,37 @@ +package moe.nea.firmament.events + +import java.util.concurrent.CopyOnWriteArrayList +import moe.nea.firmament.Firmament + +/** + * A pubsub event bus. + * + * [subscribe] to events [publish]ed on this event bus. + * Subscriptions may not necessarily be delivered in the order or registering. + */ +open class NEUEventBus { + data class Handler(val invocation: (T) -> Unit, val receivesCancelled: Boolean) + + private val toHandle: MutableList> = CopyOnWriteArrayList() + fun subscribe(handle: (T) -> Unit) { + subscribe(handle, false) + } + + fun subscribe(handle: (T) -> Unit, receivesCancelled: Boolean) { + toHandle.add(Handler(handle, receivesCancelled)) + } + + fun publish(event: T): T { + for (function in toHandle) { + if (function.receivesCancelled || event !is NEUEvent.Cancellable || !event.cancelled) { + try { + function.invocation(event) + } catch (e: Exception) { + Firmament.logger.error("Caught exception during processing event $event", e) + } + } + } + return event + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/events/ParticleSpawnEvent.kt b/src/main/kotlin/moe/nea/firmament/events/ParticleSpawnEvent.kt new file mode 100644 index 0000000..bbf7289 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/ParticleSpawnEvent.kt @@ -0,0 +1,13 @@ +package moe.nea.firmament.events + +import net.minecraft.particle.ParticleEffect +import net.minecraft.util.math.Vec3d + +data class ParticleSpawnEvent( + val particleEffect: ParticleEffect, + val position: Vec3d, + val offset: Vec3d, + val longDistance: Boolean, +) : NEUEvent() { + companion object : NEUEventBus() +} diff --git a/src/main/kotlin/moe/nea/firmament/events/ScreenOpenEvent.kt b/src/main/kotlin/moe/nea/firmament/events/ScreenOpenEvent.kt new file mode 100644 index 0000000..ee162ab --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/ScreenOpenEvent.kt @@ -0,0 +1,7 @@ +package moe.nea.firmament.events + +import net.minecraft.client.gui.screen.Screen + +data class ScreenOpenEvent(val old: Screen?, val new: Screen?) : NEUEvent.Cancellable() { + companion object : NEUEventBus() +} diff --git a/src/main/kotlin/moe/nea/firmament/events/ServerChatLineReceivedEvent.kt b/src/main/kotlin/moe/nea/firmament/events/ServerChatLineReceivedEvent.kt new file mode 100644 index 0000000..7e8531c --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/ServerChatLineReceivedEvent.kt @@ -0,0 +1,13 @@ +package moe.nea.firmament.events + +import net.minecraft.text.Text +import moe.nea.firmament.util.unformattedString + +/** + * This event gets published whenever the client receives a chat message from the server. + */ +data class ServerChatLineReceivedEvent(val text: Text) : NEUEvent.Cancellable() { + companion object : NEUEventBus() + + val unformattedString = text.unformattedString +} diff --git a/src/main/kotlin/moe/nea/firmament/events/SkyblockServerUpdateEvent.kt b/src/main/kotlin/moe/nea/firmament/events/SkyblockServerUpdateEvent.kt new file mode 100644 index 0000000..ae3227f --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/SkyblockServerUpdateEvent.kt @@ -0,0 +1,13 @@ +package moe.nea.firmament.events + +import moe.nea.firmament.util.Locraw + +/** + * This event gets published whenever `/locraw` is queried and HyPixel returns a location different to the old one. + * + * **N.B.:** This event may get fired multiple times while on the server (for example, first to null, then to the + * correct location). + */ +data class SkyblockServerUpdateEvent(val oldLocraw: Locraw?, val newLocraw: Locraw?) : NEUEvent() { + companion object : NEUEventBus() +} diff --git a/src/main/kotlin/moe/nea/firmament/events/WorldReadyEvent.kt b/src/main/kotlin/moe/nea/firmament/events/WorldReadyEvent.kt new file mode 100644 index 0000000..5b01258 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/WorldReadyEvent.kt @@ -0,0 +1,5 @@ +package moe.nea.firmament.events + +class WorldReadyEvent : NEUEvent() { + companion object : NEUEventBus() +} diff --git a/src/main/kotlin/moe/nea/firmament/events/WorldRenderLastEvent.kt b/src/main/kotlin/moe/nea/firmament/events/WorldRenderLastEvent.kt new file mode 100644 index 0000000..c23d923 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/events/WorldRenderLastEvent.kt @@ -0,0 +1,22 @@ +package moe.nea.firmament.events + +import org.joml.Matrix4f +import net.minecraft.client.render.Camera +import net.minecraft.client.render.GameRenderer +import net.minecraft.client.render.LightmapTextureManager +import net.minecraft.client.util.math.MatrixStack + +/** + * This event is called after all world rendering is done, but before any GUI rendering (including hand) has been done. + */ +data class WorldRenderLastEvent( + val matrices: MatrixStack, + val tickDelta: Float, + val renderBlockOutline: Boolean, + val camera: Camera, + val gameRenderer: GameRenderer, + val lightmapTextureManager: LightmapTextureManager, + val positionMatrix: Matrix4f, +) : NEUEvent() { + companion object : NEUEventBus() +} diff --git a/src/main/kotlin/moe/nea/firmament/features/FeatureManager.kt b/src/main/kotlin/moe/nea/firmament/features/FeatureManager.kt new file mode 100644 index 0000000..68205f4 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/features/FeatureManager.kt @@ -0,0 +1,53 @@ +package moe.nea.firmament.features + +import kotlinx.serialization.Serializable +import kotlinx.serialization.serializer +import moe.nea.firmament.Firmament +import moe.nea.firmament.features.fishing.FishingWarning +import moe.nea.firmament.features.world.FairySouls +import moe.nea.firmament.util.data.DataHolder + +object FeatureManager : DataHolder(serializer(), "features", ::Config) { + @Serializable + data class Config( + val enabledFeatures: MutableMap = mutableMapOf() + ) + + private val features = mutableMapOf() + + private var hasAutoloaded = false + + init { + autoload() + } + + fun autoload() { + synchronized(this) { + if (hasAutoloaded) return + loadFeature(FairySouls) + loadFeature(FishingWarning) + hasAutoloaded = true + } + } + + fun loadFeature(feature: NEUFeature) { + synchronized(features) { + if (feature.identifier in features) { + Firmament.logger.error("Double registering feature ${feature.identifier}. Ignoring second instance $feature") + return + } + features[feature.identifier] = feature + feature.onLoad() + } + } + + fun isEnabled(identifier: String): Boolean? = + data.enabledFeatures[identifier] + + + fun setEnabled(identifier: String, value: Boolean) { + data.enabledFeatures[identifier] = value + markDirty() + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/features/NEUFeature.kt b/src/main/kotlin/moe/nea/firmament/features/NEUFeature.kt new file mode 100644 index 0000000..f231003 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/features/NEUFeature.kt @@ -0,0 +1,18 @@ +package moe.nea.firmament.features + +import moe.nea.firmament.util.config.ManagedConfig + +interface NEUFeature { + val name: String + val identifier: String + val defaultEnabled: Boolean + get() = true + var isEnabled: Boolean + get() = FeatureManager.isEnabled(identifier) ?: defaultEnabled + set(value) { + FeatureManager.setEnabled(identifier, value) + } + val config: ManagedConfig? get() = null + fun onLoad() + +} diff --git a/src/main/kotlin/moe/nea/firmament/features/fishing/FishingWarning.kt b/src/main/kotlin/moe/nea/firmament/features/fishing/FishingWarning.kt new file mode 100644 index 0000000..cdeb24c --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/features/fishing/FishingWarning.kt @@ -0,0 +1,117 @@ +package moe.nea.firmament.features.fishing + +import kotlin.math.abs +import kotlin.math.absoluteValue +import kotlin.math.acos +import kotlin.math.asin +import kotlin.math.atan2 +import kotlin.math.sqrt +import kotlin.time.Duration.Companion.seconds +import net.minecraft.entity.projectile.FishingBobberEntity +import net.minecraft.particle.ParticleTypes +import net.minecraft.util.math.Vec3d +import moe.nea.firmament.events.ParticleSpawnEvent +import moe.nea.firmament.events.WorldReadyEvent +import moe.nea.firmament.events.WorldRenderLastEvent +import moe.nea.firmament.features.NEUFeature +import moe.nea.firmament.util.MC +import moe.nea.firmament.util.TimeMark +import moe.nea.firmament.util.config.ManagedConfig +import moe.nea.firmament.util.render.RenderBlockContext.Companion.renderBlocks + +object FishingWarning : NEUFeature { + override val name: String + get() = "Fishing Warning" + override val identifier: String + get() = "fishing-warning" + + object TConfig : ManagedConfig("fishing-warning") { + // Display a warning when you are about to hook a fish + val displayWarning by toggle("display-warning") { false } + val highlightWakeChain by toggle("highlight-wake-chain") { false } + } + + override val config: ManagedConfig get() = TConfig + + + data class WakeChain( + val delta: Vec3d, + val momentum: Vec3d, + val lastContinued: TimeMark, + ) + + + val chains = mutableListOf() + + private fun areAnglesClose(a: Double, b: Double, tolerance: Double): Boolean { + var dist = (a - b).absoluteValue + if (180 < dist) dist = 360 - dist; + return dist <= tolerance + } + + private fun calculateAngleFromOffsets(xOffset: Double, zOffset: Double): Double { + // See also: Vanilla 1.8.9 Fishing particle code. + var angleX = Math.toDegrees(acos(xOffset / 0.04)) + var angleZ = Math.toDegrees(asin(zOffset / 0.04)) + if (xOffset < 0) { + // Old: angleZ = 180 - angleZ; + angleZ = 180 - angleZ + } + if (zOffset < 0) { + angleX = 360 - angleX + } + angleX %= 360.0 + angleZ %= 360.0 + if (angleX < 0) angleX += 360.0 + if (angleZ < 0) angleZ += 360.0 + var dist = angleX - angleZ + if (dist < -180) dist += 360.0 + if (dist > 180) dist -= 360.0 + return angleZ + dist / 2 + } + + private fun toDegrees(d: Double) = d * 180 / Math.PI + + fun isHookPossible(hook: FishingBobberEntity, particlePos: Vec3d, angle1: Double, angle2: Double): Boolean { + val dx = particlePos.x - hook.pos.x + val dz = particlePos.z - hook.pos.z + val dist = sqrt(dx * dx + dz * dz) + + if (dist < 0.2) return true + val tolerance = toDegrees(atan2(0.03125, dist)) * 1.5 + var angleToHook = toDegrees(atan2(dx, dz)) % 360 + if (angleToHook < 0) angleToHook += 360 + return areAnglesClose(angle1, angleToHook, tolerance) || areAnglesClose(angle2, angleToHook, tolerance) + } + + val recentParticles = mutableListOf>() + + private fun onParticleSpawn(event: ParticleSpawnEvent) { + if (event.particleEffect.type != ParticleTypes.FISHING) return + if (!(abs(event.offset.y - 0.01f) < 0.001f)) return + val hook = MC.player?.fishHook ?: return + val actualOffset = event.offset + val candidate1 = calculateAngleFromOffsets(actualOffset.x, -actualOffset.z) + val candidate2 = calculateAngleFromOffsets(-actualOffset.x, actualOffset.z) + + if (isHookPossible(hook, event.position, candidate1, candidate2)) { + recentParticles.add(Pair(event.position, TimeMark.now())) + } + } + + override fun onLoad() { + ParticleSpawnEvent.subscribe(::onParticleSpawn) + WorldReadyEvent.subscribe { + recentParticles.clear() + } + WorldRenderLastEvent.subscribe { + recentParticles.removeIf { it.second.passedTime() > 5.seconds } + renderBlocks(it.matrices, it.camera) { + color(0f, 0f, 1f, 1f) + recentParticles.forEach { + tinyBlock(it.first, 0.1F) + } + } + } + } +} diff --git a/src/main/kotlin/moe/nea/firmament/features/world/FairySouls.kt b/src/main/kotlin/moe/nea/firmament/features/world/FairySouls.kt new file mode 100644 index 0000000..f752963 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/features/world/FairySouls.kt @@ -0,0 +1,120 @@ +package moe.nea.firmament.features.world + +import io.github.moulberry.repo.data.Coordinate +import kotlinx.serialization.Serializable +import kotlinx.serialization.serializer +import moe.nea.firmament.events.ServerChatLineReceivedEvent +import moe.nea.firmament.events.SkyblockServerUpdateEvent +import moe.nea.firmament.events.WorldRenderLastEvent +import moe.nea.firmament.features.NEUFeature +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.MC +import moe.nea.firmament.util.SBData +import moe.nea.firmament.util.blockPos +import moe.nea.firmament.util.config.ManagedConfig +import moe.nea.firmament.util.data.ProfileSpecificDataHolder +import moe.nea.firmament.util.render.RenderBlockContext.Companion.renderBlocks +import moe.nea.firmament.util.unformattedString + + +object FairySouls : NEUFeature { + + + @Serializable + data class Data( + val foundSouls: MutableMap> = mutableMapOf() + ) + + override val config: ManagedConfig + get() = TConfig + + object DConfig : ProfileSpecificDataHolder(serializer(), "found-fairysouls", ::Data) + + + object TConfig : ManagedConfig("fairy-souls") { + + val displaySouls by toggle("show") { false } + val resetSouls by button("reset") { + DConfig.data?.foundSouls?.clear() != null + updateMissingSouls() + } + } + + + override val name: String get() = "Fairy Souls" + override val identifier: String get() = "fairy-souls" + + val playerReach = 5 + val playerReachSquared = playerReach * playerReach + + var currentLocationName: String? = null + var currentLocationSouls: List = emptyList() + var currentMissingSouls: List = emptyList() + + fun updateMissingSouls() { + currentMissingSouls = emptyList() + val c = DConfig.data ?: return + val fi = c.foundSouls[currentLocationName] ?: setOf() + val cms = currentLocationSouls.toMutableList() + fi.asSequence().sortedDescending().filter { it in cms.indices }.forEach { cms.removeAt(it) } + currentMissingSouls = cms + } + + fun updateWorldSouls() { + currentLocationSouls = emptyList() + val loc = currentLocationName ?: return + currentLocationSouls = RepoManager.neuRepo.constants.fairySouls.soulLocations[loc] ?: return + } + + fun findNearestClickableSoul(): Coordinate? { + val player = MC.player ?: return null + val pos = player.pos + val location = SBData.skyblockLocation ?: return null + val soulLocations: List = + RepoManager.neuRepo.constants.fairySouls.soulLocations[location] ?: return null + return soulLocations + .map { it to it.blockPos.getSquaredDistance(pos) } + .filter { it.second < playerReachSquared } + .minByOrNull { it.second } + ?.first + } + + private fun markNearestSoul() { + val nearestSoul = findNearestClickableSoul() ?: return + val c = DConfig.data ?: return + val loc = currentLocationName ?: return + val idx = currentLocationSouls.indexOf(nearestSoul) + c.foundSouls.computeIfAbsent(loc) { mutableSetOf() }.add(idx) + DConfig.markDirty() + updateMissingSouls() + } + + + override fun onLoad() { + SkyblockServerUpdateEvent.subscribe { + currentLocationName = it.newLocraw?.skyblockLocation + updateWorldSouls() + updateMissingSouls() + } + ServerChatLineReceivedEvent.subscribe { + when (it.text.unformattedString) { + "You have already found that Fairy Soul!" -> { + markNearestSoul() + } + + "SOUL! You found a Fairy Soul!" -> { + markNearestSoul() + } + } + } + WorldRenderLastEvent.subscribe { + if (!TConfig.displaySouls) return@subscribe + renderBlocks(it.matrices, it.camera) { + color(1F, 1F, 0F, 0.8F) + currentMissingSouls.forEach { + block(it.blockPos) + } + } + } + } +} diff --git a/src/main/kotlin/moe/nea/firmament/gui/ConfigGui.kt b/src/main/kotlin/moe/nea/firmament/gui/ConfigGui.kt new file mode 100644 index 0000000..6acf68a --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/gui/ConfigGui.kt @@ -0,0 +1,94 @@ +package moe.nea.firmament.gui + +import io.github.cottonmc.cotton.gui.client.LightweightGuiDescription +import io.github.cottonmc.cotton.gui.widget.WButton +import io.github.cottonmc.cotton.gui.widget.WLabel +import io.github.cottonmc.cotton.gui.widget.WTextField +import io.github.cottonmc.cotton.gui.widget.WToggleButton +import io.github.cottonmc.cotton.gui.widget.data.HorizontalAlignment +import io.github.cottonmc.cotton.gui.widget.data.Insets +import io.github.cottonmc.cotton.gui.widget.data.VerticalAlignment +import moe.nea.firmament.Firmament +import moe.nea.firmament.util.data.DataHolder +import net.minecraft.text.Text +import kotlin.reflect.KMutableProperty1 + +class ConfigGui(val holder: DataHolder, val build: ConfigGui.() -> Unit) : LightweightGuiDescription() { + private val root = WGridPanelWithPadding(verticalPadding = 4) + private val reloadables = mutableListOf<(() -> Unit)>() + + init { + setRootPanel(root) + root.insets = Insets.ROOT_PANEL + build() + reload() + } + + fun title(text: Text) { + if (col != 0) { + Firmament.logger.warn("Set title not at the top of the ConfigGui") + } + val label = WLabel(text) + label.verticalAlignment = VerticalAlignment.TOP + label.horizontalAlignment = HorizontalAlignment.CENTER + root.add(label, 0, col, 11, 1) + col++ + } + + private fun label(text: Text) { + val label = WLabel(text) + label.verticalAlignment = VerticalAlignment.CENTER + root.add(label, 0, col, 5, 1) + } + + fun toggle(text: Text, prop: KMutableProperty1) { + val toggle = WToggleButton(text) + reloadables.add { toggle.toggle = prop.get(holder.data) } + toggle.setOnToggle { + prop.set(holder.data, true) + holder.markDirty() + } + root.add(toggle, 5, col, 6, 1) + label(text) + col++ + } + + fun button(text: Text, buttonText: Text, runnable: () -> Unit) { + val button = WButton(buttonText) + button.setOnClick { + runnable.invoke() + } + root.add(button, 5, col, 6, 1) + label(text) + col++ + } + + fun textfield( + text: Text, + background: Text, + prop: KMutableProperty1, + maxLength: Int = 255 + ) { + val textfield = WTextField(background) + textfield.isEditable = true + reloadables.add { + textfield.text = prop.get(holder.data) + } + textfield.maxLength = maxLength + textfield.setChangedListener { + prop.set(holder.data, it) + holder.markDirty() + } + root.add(textfield, 5, col, 6, 11) + label(text) + col++ + } + + fun reload() { + reloadables.forEach { it.invoke() } + } + + private var col = 0 + + +} diff --git a/src/main/kotlin/moe/nea/firmament/gui/WGridPanelWithPadding.kt b/src/main/kotlin/moe/nea/firmament/gui/WGridPanelWithPadding.kt new file mode 100644 index 0000000..255b80d --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/gui/WGridPanelWithPadding.kt @@ -0,0 +1,33 @@ +package moe.nea.firmament.gui + +import io.github.cottonmc.cotton.gui.widget.WPanelWithInsets +import io.github.cottonmc.cotton.gui.widget.WWidget +import io.github.cottonmc.cotton.gui.widget.data.Insets + +class WGridPanelWithPadding( + val grid: Int = 18, + val verticalPadding: Int = 0, + val horizontalPadding: Int = 0, +) : WPanelWithInsets() { + + private inline val vertOffset get() = grid + verticalPadding + private inline val horiOffset get() = grid + horizontalPadding + + fun add(w: WWidget, x: Int, y: Int, width: Int = 1, height: Int = 1) { + children.add(w) + w.parent = this + w.setLocation(x * horiOffset + insets.left, y * vertOffset + insets.top) + if (w.canResize()) + w.setSize( + grid + (horiOffset * (width - 1)), + grid + (vertOffset * (height - 1)), + ) + expandToFit(w, insets) + } + + override fun setInsets(insets: Insets): WGridPanelWithPadding { + super.setInsets(insets) + return this + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/gui/repogui.kt b/src/main/kotlin/moe/nea/firmament/gui/repogui.kt new file mode 100644 index 0000000..da681e4 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/gui/repogui.kt @@ -0,0 +1,36 @@ +package moe.nea.firmament.gui + +import net.minecraft.text.Text +import moe.nea.firmament.repo.RepoManager + +fun repoGui(): ConfigGui { + return ConfigGui(RepoManager) { + title(Text.translatable("firmament.gui.repo.title")) + toggle(Text.translatable("firmament.gui.repo.autoupdate"), RepoManager.Config::autoUpdate) + textfield( + Text.translatable("firmament.gui.repo.username"), + Text.translatable("firmament.gui.repo.hint.username"), + RepoManager.Config::user, + maxLength = 255 + ) + textfield( + Text.translatable("firmament.gui.repo.reponame"), + Text.translatable("firmament.gui.repo.hint.reponame"), + RepoManager.Config::repo + ) + textfield( + Text.translatable("firmament.gui.repo.branch"), + Text.translatable("firmament.gui.repo.hint.branch"), + RepoManager.Config::branch + ) + button( + Text.translatable("firmament.gui.repo.reset.label"), + Text.translatable("firmament.gui.repo.reset"), + ) { + RepoManager.data.user = "NotEnoughUpdates" + RepoManager.data.repo = "NotEnoughUpdates-REPO" + RepoManager.data.branch = "dangerous" + reload() + } + } +} diff --git a/src/main/kotlin/moe/nea/firmament/hud/RepoDownloadProgress.kt b/src/main/kotlin/moe/nea/firmament/hud/RepoDownloadProgress.kt new file mode 100644 index 0000000..315230b --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/hud/RepoDownloadProgress.kt @@ -0,0 +1,63 @@ +package moe.nea.firmament.hud + +import io.github.cottonmc.cotton.gui.client.ScreenDrawing +import io.github.cottonmc.cotton.gui.widget.WWidget +import io.github.cottonmc.cotton.gui.widget.data.HorizontalAlignment +import io.github.cottonmc.cotton.gui.widget.data.Insets +import net.minecraft.client.util.math.MatrixStack +import kotlin.math.roundToInt +import kotlin.math.sin + + +val Insets.vertical get() = bottom + top +val Insets.horizontal get() = left + right + +class ProgressBar( + var label: String, + var total: Int?, // If total is null, then make it a bouncy rectangle + var progress: Int = 0, +) : WWidget() { + + var insets: Insets = Insets(7) + override fun canResize(): Boolean = true + + + fun reportProgress(label: String, progress: Int, total: Int?) { + synchronized(this) { + this.label = label + this.progress = progress + this.total = total + } + + } + + override fun paint(matrices: MatrixStack, x: Int, y: Int, mouseX: Int, mouseY: Int) { + ScreenDrawing.coloredRect(matrices, x, y, width, height, 0xFF808080.toInt()) + val (l, prog) = synchronized(this) { + label to (progress to total) + } + val (p, t) = prog + + if (t == null) { + ScreenDrawing.coloredRect( + matrices, + (x + (1 + sin(System.currentTimeMillis().toDouble() / 1000)) * width * 3 / 4 / 2).roundToInt(), + y, + width / 4, + height, + 0xFF00FF00.toInt() + ) + } else { + ScreenDrawing.coloredRect(matrices, x, y, width * p / t, height, 0xFF00FF00.toInt()) + } + ScreenDrawing.drawString( + matrices, + if (t != null) "$l ($p/$t)" else l, + HorizontalAlignment.CENTER, + x + insets.left, + y + insets.top, + width - insets.horizontal, + height - insets.vertical, + ) + } +} diff --git a/src/main/kotlin/moe/nea/firmament/recipes/SBCraftingRecipe.kt b/src/main/kotlin/moe/nea/firmament/recipes/SBCraftingRecipe.kt new file mode 100644 index 0000000..0cf63fc --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/recipes/SBCraftingRecipe.kt @@ -0,0 +1,53 @@ +package moe.nea.firmament.recipes + +import io.github.moulberry.repo.data.NEUCraftingRecipe +import io.github.moulberry.repo.data.NEUIngredient +import me.shedaniel.math.Point +import me.shedaniel.math.Rectangle +import me.shedaniel.rei.api.client.gui.Renderer +import me.shedaniel.rei.api.client.gui.widgets.Widget +import me.shedaniel.rei.api.client.gui.widgets.Widgets +import me.shedaniel.rei.api.client.registry.display.DisplayCategory +import me.shedaniel.rei.api.common.category.CategoryIdentifier +import me.shedaniel.rei.api.common.util.EntryStacks +import net.minecraft.block.Blocks +import net.minecraft.text.Text +import moe.nea.firmament.Firmament +import moe.nea.firmament.rei.SBItemEntryDefinition + +class SBCraftingRecipe(override val neuRecipe: NEUCraftingRecipe) : SBRecipe() { + override fun getCategoryIdentifier(): CategoryIdentifier<*> = Category.catIdentifier + + object Category : DisplayCategory { + val catIdentifier = CategoryIdentifier.of(Firmament.MOD_ID, "crafing_recipe") + override fun getCategoryIdentifier(): CategoryIdentifier = catIdentifier + + override fun getTitle(): Text = Text.literal("SkyBlock Crafting") + + override fun getIcon(): Renderer = EntryStacks.of(Blocks.CRAFTING_TABLE) + override fun setupDisplay(display: SBCraftingRecipe, bounds: Rectangle): List { + val point = Point(bounds.centerX - 58, bounds.centerY - 27) + return buildList { + add(Widgets.createRecipeBase(bounds)) + add(Widgets.createArrow(Point(point.x + 60, point.y + 18))) + add(Widgets.createResultSlotBackground(Point(point.x + 95, point.y + 19))) + for (i in 0 until 3) { + for (j in 0 until 3) { + val slot = Widgets.createSlot(Point(point.x + 1 + i * 18, point.y + 1 + j * 18)).markInput() + add(slot) + val item = display.neuRecipe.inputs[i + j * 3] + if (item == NEUIngredient.SENTINEL_EMPTY) continue + slot.entry(SBItemEntryDefinition.getEntry(item)) // TODO: make use of stackable item entries + } + } + add( + Widgets.createSlot(Point(point.x + 95, point.y + 19)) + .entry(SBItemEntryDefinition.getEntry(display.neuRecipe.output)) + .disableBackground().markOutput() + ) + } + } + + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/recipes/SBForgeRecipe.kt b/src/main/kotlin/moe/nea/firmament/recipes/SBForgeRecipe.kt new file mode 100644 index 0000000..b00005f --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/recipes/SBForgeRecipe.kt @@ -0,0 +1,53 @@ +package moe.nea.firmament.recipes + +import io.github.moulberry.repo.data.NEUForgeRecipe +import me.shedaniel.math.Point +import me.shedaniel.math.Rectangle +import me.shedaniel.rei.api.client.gui.Renderer +import me.shedaniel.rei.api.client.gui.widgets.Widget +import me.shedaniel.rei.api.client.gui.widgets.Widgets +import me.shedaniel.rei.api.client.registry.display.DisplayCategory +import me.shedaniel.rei.api.common.category.CategoryIdentifier +import me.shedaniel.rei.api.common.util.EntryStacks +import net.minecraft.block.Blocks +import net.minecraft.text.Text +import moe.nea.firmament.Firmament +import moe.nea.firmament.rei.SBItemEntryDefinition + +class SBForgeRecipe(override val neuRecipe: NEUForgeRecipe) : SBRecipe() { + override fun getCategoryIdentifier(): CategoryIdentifier<*> = Category.categoryIdentifier + + object Category : DisplayCategory { + override fun getCategoryIdentifier(): CategoryIdentifier = + CategoryIdentifier.of(Firmament.MOD_ID, "forge_recipe") + + override fun getTitle(): Text = Text.literal("Forge Recipes") + override fun getDisplayHeight(): Int { + return super.getDisplayHeight() + } + + override fun getIcon(): Renderer = EntryStacks.of(Blocks.ANVIL) + override fun setupDisplay(display: SBForgeRecipe, bounds: Rectangle): List { + return buildList { + // TODO: proper gui for this (possibly inspired by the old circular gui) + add(Widgets.createRecipeBase(bounds)) + val resultSlot = Point(bounds.centerX, bounds.centerY + 5) + add(Widgets.createResultSlotBackground(resultSlot)) + val ingredientsCenter = Point(bounds.centerX, bounds.centerY - 20) + val count = display.neuRecipe.inputs.size + display.neuRecipe.inputs.forEachIndexed { idx, ingredient -> + add( + Widgets.createSlot( + Point(ingredientsCenter.x + 12 - count * 24 / 2 + idx * 24, ingredientsCenter.y) + ).markInput().entry(SBItemEntryDefinition.getEntry(ingredient)) + ) + } + add( + Widgets.createSlot(resultSlot).markOutput().disableBackground() + .entry(SBItemEntryDefinition.getEntry(display.neuRecipe.outputStack)) + ) + } + } + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/recipes/SBRecipe.kt b/src/main/kotlin/moe/nea/firmament/recipes/SBRecipe.kt new file mode 100644 index 0000000..ed982bd --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/recipes/SBRecipe.kt @@ -0,0 +1,24 @@ +package moe.nea.firmament.recipes + +import io.github.moulberry.repo.data.NEURecipe +import me.shedaniel.rei.api.common.display.Display +import me.shedaniel.rei.api.common.entry.EntryIngredient +import moe.nea.firmament.rei.SBItemEntryDefinition +import moe.nea.firmament.util.SkyblockId + +abstract class SBRecipe() : Display { + abstract val neuRecipe: NEURecipe + override fun getInputEntries(): List { + return neuRecipe.allInputs.map { + val entryStack = SBItemEntryDefinition.getEntry(SkyblockId(it.itemId)) + EntryIngredient.of(entryStack) + } + } + + override fun getOutputEntries(): List { + return neuRecipe.allOutputs.map { + val entryStack = SBItemEntryDefinition.getEntry(SkyblockId(it.itemId)) + EntryIngredient.of(entryStack) + } + } +} diff --git a/src/main/kotlin/moe/nea/firmament/rei/FirmamentReiPlugin.kt b/src/main/kotlin/moe/nea/firmament/rei/FirmamentReiPlugin.kt new file mode 100644 index 0000000..992b104 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/rei/FirmamentReiPlugin.kt @@ -0,0 +1,73 @@ +package moe.nea.firmament.rei + +import io.github.moulberry.repo.data.NEUItem +import me.shedaniel.rei.api.client.plugins.REIClientPlugin +import me.shedaniel.rei.api.client.registry.category.CategoryRegistry +import me.shedaniel.rei.api.client.registry.display.DisplayRegistry +import me.shedaniel.rei.api.client.registry.entry.CollapsibleEntryRegistry +import me.shedaniel.rei.api.client.registry.entry.EntryRegistry +import me.shedaniel.rei.api.client.registry.screen.ScreenRegistry +import me.shedaniel.rei.api.common.entry.EntryStack +import me.shedaniel.rei.api.common.entry.type.EntryTypeRegistry +import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes +import net.minecraft.item.ItemStack +import net.minecraft.text.Text +import net.minecraft.util.Identifier +import moe.nea.firmament.recipes.SBCraftingRecipe +import moe.nea.firmament.recipes.SBForgeRecipe +import moe.nea.firmament.repo.ItemCache.asItemStack +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.SkyblockId + + +class FirmamentReiPlugin : REIClientPlugin { + + companion object { + fun EntryStack.asItemEntry(): EntryStack { + return EntryStack.of(VanillaEntryTypes.ITEM, value.asItemStack()) + } + + val SKYBLOCK_ITEM_TYPE_ID = Identifier("firmament", "skyblockitems") + } + + override fun registerEntryTypes(registry: EntryTypeRegistry) { + registry.register(SKYBLOCK_ITEM_TYPE_ID, SBItemEntryDefinition) + } + + override fun registerCategories(registry: CategoryRegistry) { + registry.add(SBCraftingRecipe.Category) + registry.add(SBForgeRecipe.Category) + } + + override fun registerDisplays(registry: DisplayRegistry) { + registry.registerDisplayGenerator( + SBCraftingRecipe.Category.catIdentifier, + SkyblockCraftingRecipeDynamicGenerator + ) + registry.registerDisplayGenerator( + SBForgeRecipe.Category.categoryIdentifier, + SkyblockForgeRecipeDynamicGenerator + ) + } + + override fun registerCollapsibleEntries(registry: CollapsibleEntryRegistry) { + RepoManager.neuRepo.constants.parents.parents + .forEach { (parent, children) -> + registry.group( + SkyblockId(parent).identifier, + Text.literal(RepoManager.getNEUItem(SkyblockId(parent))?.displayName ?: parent), + (children + parent).map { SBItemEntryDefinition.getEntry(RepoManager.getNEUItem(SkyblockId(it))) }) + } + } + + override fun registerScreens(registry: ScreenRegistry) { + registry.registerFocusedStack(SkyblockItemIdFocusedStackProvider) + } + + override fun registerEntries(registry: EntryRegistry) { + RepoManager.neuRepo.items?.items?.values?.forEach { + if (!it.isVanilla) + registry.addEntry(EntryStack.of(SBItemEntryDefinition, it)) + } + } +} diff --git a/src/main/kotlin/moe/nea/firmament/rei/NEUItemEntryRenderer.kt b/src/main/kotlin/moe/nea/firmament/rei/NEUItemEntryRenderer.kt new file mode 100644 index 0000000..8253c96 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/rei/NEUItemEntryRenderer.kt @@ -0,0 +1,31 @@ +package moe.nea.firmament.rei + +import io.github.moulberry.repo.data.NEUItem +import me.shedaniel.math.Rectangle +import me.shedaniel.rei.api.client.entry.renderer.EntryRenderer +import me.shedaniel.rei.api.client.gui.widgets.Tooltip +import me.shedaniel.rei.api.client.gui.widgets.TooltipContext +import me.shedaniel.rei.api.common.entry.EntryStack +import net.minecraft.client.util.math.MatrixStack +import moe.nea.firmament.rei.FirmamentReiPlugin.Companion.asItemEntry + +object NEUItemEntryRenderer : EntryRenderer { + override fun render( + entry: EntryStack, + matrices: MatrixStack, + bounds: Rectangle, + mouseX: Int, + mouseY: Int, + delta: Float + ) { + matrices.push() + matrices.translate(0F, 0F, 100F) + entry.asItemEntry().render(matrices, bounds, mouseX, mouseY, delta) + matrices.pop() + } + + override fun getTooltip(entry: EntryStack, tooltipContext: TooltipContext): Tooltip? { + return entry.asItemEntry().getTooltip(tooltipContext, false) + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/rei/NEUItemEntrySerializer.kt b/src/main/kotlin/moe/nea/firmament/rei/NEUItemEntrySerializer.kt new file mode 100644 index 0000000..15731cb --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/rei/NEUItemEntrySerializer.kt @@ -0,0 +1,25 @@ +package moe.nea.firmament.rei + +import io.github.moulberry.repo.data.NEUItem +import me.shedaniel.rei.api.common.entry.EntrySerializer +import me.shedaniel.rei.api.common.entry.EntryStack +import net.minecraft.nbt.NbtCompound +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.SkyblockId + +object NEUItemEntrySerializer : EntrySerializer { + const val SKYBLOCK_ID_ENTRY = "SKYBLOCK_ID" + + override fun supportSaving(): Boolean = true + override fun supportReading(): Boolean = true + + override fun read(tag: NbtCompound): NEUItem? { + return RepoManager.getNEUItem(SkyblockId(tag.getString(SKYBLOCK_ID_ENTRY))) + } + + override fun save(entry: EntryStack, value: NEUItem?): NbtCompound { + return NbtCompound().apply { + putString(SKYBLOCK_ID_ENTRY, value?.skyblockItemId ?: "null") + } + } +} diff --git a/src/main/kotlin/moe/nea/firmament/rei/SBItemEntryDefinition.kt b/src/main/kotlin/moe/nea/firmament/rei/SBItemEntryDefinition.kt new file mode 100644 index 0000000..f8dbce7 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/rei/SBItemEntryDefinition.kt @@ -0,0 +1,85 @@ +package moe.nea.firmament.rei + +import io.github.moulberry.repo.data.NEUIngredient +import io.github.moulberry.repo.data.NEUItem +import java.util.stream.Stream +import me.shedaniel.rei.api.client.entry.renderer.EntryRenderer +import me.shedaniel.rei.api.common.entry.EntrySerializer +import me.shedaniel.rei.api.common.entry.EntryStack +import me.shedaniel.rei.api.common.entry.comparison.ComparisonContext +import me.shedaniel.rei.api.common.entry.type.EntryDefinition +import me.shedaniel.rei.api.common.entry.type.EntryType +import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes +import net.minecraft.item.ItemStack +import net.minecraft.registry.tag.TagKey +import net.minecraft.text.Text +import net.minecraft.util.Identifier +import moe.nea.firmament.rei.FirmamentReiPlugin.Companion.asItemEntry +import moe.nea.firmament.repo.ItemCache.asItemStack +import moe.nea.firmament.repo.ItemCache.getIdentifier +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.SkyblockId + +// TODO: allow stackable entries +object SBItemEntryDefinition : EntryDefinition { + override fun equals(o1: NEUItem?, o2: NEUItem?, context: ComparisonContext?): Boolean { + return o1 === o2 + } + + override fun cheatsAs(entry: EntryStack?, value: NEUItem?): ItemStack { + return value.asItemStack() + } + + override fun getValueType(): Class = NEUItem::class.java + override fun getType(): EntryType = EntryType.deferred(FirmamentReiPlugin.SKYBLOCK_ITEM_TYPE_ID) + + override fun getRenderer(): EntryRenderer = NEUItemEntryRenderer + + override fun getSerializer(): EntrySerializer { + return NEUItemEntrySerializer + } + + override fun getTagsFor(entry: EntryStack?, value: NEUItem?): Stream>? { + return Stream.empty() + } + + override fun asFormattedText(entry: EntryStack, value: NEUItem): Text { + return VanillaEntryTypes.ITEM.definition.asFormattedText(entry.asItemEntry(), value.asItemStack()) + } + + override fun hash(entry: EntryStack, value: NEUItem?, context: ComparisonContext): Long { + // Repo items are immutable, and get replaced entirely when loaded from disk + return System.identityHashCode(value) * 31L + } + + override fun wildcard(entry: EntryStack?, value: NEUItem?): NEUItem? { + return value + } + + override fun normalize(entry: EntryStack?, value: NEUItem?): NEUItem? { + return value + } + + override fun copy(entry: EntryStack?, value: NEUItem?): NEUItem? { + return value + } + + override fun isEmpty(entry: EntryStack?, value: NEUItem?): Boolean { + return false + } + + override fun getIdentifier(entry: EntryStack?, value: NEUItem?): Identifier { + return value?.getIdentifier() ?: Identifier.of("skyblockitem", "null")!! + } + + fun getEntry(neuItem: NEUItem?): EntryStack = + EntryStack.of(this, neuItem) + + fun getEntry(skyblockId: SkyblockId?): EntryStack = + EntryStack.of(this, skyblockId?.let { RepoManager.getNEUItem(it) }) + + fun getEntry(ingredient: NEUIngredient?): EntryStack = + getEntry(ingredient?.itemId?.let { SkyblockId(it) }) + + +} diff --git a/src/main/kotlin/moe/nea/firmament/rei/SkyblockCraftingRecipeDynamicGenerator.kt b/src/main/kotlin/moe/nea/firmament/rei/SkyblockCraftingRecipeDynamicGenerator.kt new file mode 100644 index 0000000..c806ea0 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/rei/SkyblockCraftingRecipeDynamicGenerator.kt @@ -0,0 +1,52 @@ +package moe.nea.firmament.rei + +import io.github.moulberry.repo.data.NEUCraftingRecipe +import io.github.moulberry.repo.data.NEUForgeRecipe +import io.github.moulberry.repo.data.NEUItem +import io.github.moulberry.repo.data.NEURecipe +import java.util.* +import me.shedaniel.rei.api.client.registry.display.DynamicDisplayGenerator +import me.shedaniel.rei.api.client.view.ViewSearchBuilder +import me.shedaniel.rei.api.common.display.Display +import me.shedaniel.rei.api.common.entry.EntryStack +import moe.nea.firmament.recipes.SBCraftingRecipe +import moe.nea.firmament.recipes.SBForgeRecipe +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.skyblockId + + +val SkyblockCraftingRecipeDynamicGenerator = neuDisplayGenerator { + SBCraftingRecipe(it) +} + +val SkyblockForgeRecipeDynamicGenerator = neuDisplayGenerator { + SBForgeRecipe(it) +} + +inline fun neuDisplayGenerator(noinline mapper: (T) -> D) = + object : DynamicDisplayGenerator { + override fun getRecipeFor(entry: EntryStack<*>): Optional> { + if (entry.type != SBItemEntryDefinition.type) return Optional.empty() + val item = entry.castValue() + val recipes = RepoManager.getRecipesFor(item.skyblockId) + val craftingRecipes = recipes.filterIsInstance() + return Optional.of(craftingRecipes.map(mapper)) + } + + override fun generate(builder: ViewSearchBuilder): Optional> { + if (SBCraftingRecipe.Category.catIdentifier !in builder.categories) return Optional.empty() + return Optional.of( + RepoManager.getAllRecipes().filterIsInstance().map(mapper) + .toList() + ) + } + + override fun getUsageFor(entry: EntryStack<*>): Optional> { + if (entry.type != SBItemEntryDefinition.type) return Optional.empty() + val item = entry.castValue() + val recipes = RepoManager.getUsagesFor(item.skyblockId) + val craftingRecipes = recipes.filterIsInstance() + return Optional.of(craftingRecipes.map(mapper)) + + } + } diff --git a/src/main/kotlin/moe/nea/firmament/rei/SkyblockItemIdFocusedStackProvider.kt b/src/main/kotlin/moe/nea/firmament/rei/SkyblockItemIdFocusedStackProvider.kt new file mode 100644 index 0000000..c874fc3 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/rei/SkyblockItemIdFocusedStackProvider.kt @@ -0,0 +1,25 @@ +package moe.nea.firmament.rei + +import dev.architectury.event.CompoundEventResult +import me.shedaniel.math.Point +import me.shedaniel.rei.api.client.registry.screen.FocusedStackProvider +import me.shedaniel.rei.api.common.entry.EntryStack +import moe.nea.firmament.mixins.accessor.AccessorHandledScreen +import moe.nea.firmament.repo.RepoManager +import moe.nea.firmament.util.skyBlockId +import net.minecraft.client.gui.screen.Screen +import net.minecraft.client.gui.screen.ingame.HandledScreen + +object SkyblockItemIdFocusedStackProvider : FocusedStackProvider { + override fun provide(screen: Screen?, mouse: Point?): CompoundEventResult> { + if (screen !is HandledScreen<*>) return CompoundEventResult.pass() + screen as AccessorHandledScreen + val focusedSlot = screen.focusedSlot_NEU ?: return CompoundEventResult.pass() + val item = focusedSlot.stack ?: return CompoundEventResult.pass() + val skyblockId = item.skyBlockId ?: return CompoundEventResult.pass() + val neuItem = RepoManager.getNEUItem(skyblockId) ?: return CompoundEventResult.interrupt(false, null) + return CompoundEventResult.interruptTrue(EntryStack.of(SBItemEntryDefinition, neuItem)) + } + + override fun getPriority(): Double = 1_000_000.0 +} diff --git a/src/main/kotlin/moe/nea/firmament/repo/ItemCache.kt b/src/main/kotlin/moe/nea/firmament/repo/ItemCache.kt new file mode 100644 index 0000000..bd624b6 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/repo/ItemCache.kt @@ -0,0 +1,123 @@ +package moe.nea.firmament.repo + +import com.mojang.serialization.Dynamic +import io.github.cottonmc.cotton.gui.client.CottonHud +import io.github.moulberry.repo.IReloadable +import io.github.moulberry.repo.NEURepository +import io.github.moulberry.repo.data.NEUItem +import java.io.PrintWriter +import java.nio.file.Path +import java.util.concurrent.ConcurrentHashMap +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlin.io.path.absolutePathString +import kotlin.io.path.writer +import net.minecraft.SharedConstants +import net.minecraft.client.resource.language.I18n +import net.minecraft.datafixer.Schemas +import net.minecraft.datafixer.TypeReferences +import net.minecraft.item.ItemStack +import net.minecraft.item.Items +import net.minecraft.nbt.NbtCompound +import net.minecraft.nbt.NbtOps +import net.minecraft.text.Text +import moe.nea.firmament.Firmament +import moe.nea.firmament.util.LegacyTagParser +import moe.nea.firmament.util.appendLore +import moe.nea.firmament.util.skyblockId + +object ItemCache : IReloadable { + val dfuLog = Path.of("logs/dfulog.txt") + private val cache: MutableMap = ConcurrentHashMap() + private val df = Schemas.getFixer() + private val dfuHandle = PrintWriter(dfuLog.writer()) + var isFlawless = true + private set + + private fun NEUItem.get10809CompoundTag(): NbtCompound = NbtCompound().apply { + put("tag", LegacyTagParser.parse(nbttag)) + putString("id", minecraftItemId) + putByte("Count", 1) + putShort("Damage", damage.toShort()) + } + + private fun NbtCompound.transformFrom10809ToModern(): NbtCompound? = + try { + df.update( + TypeReferences.ITEM_STACK, + Dynamic(NbtOps.INSTANCE, this), + -1, + SharedConstants.getGameVersion().saveVersion.id + ).value as NbtCompound + } catch (e: Exception) { + if (isFlawless) + Firmament.logger.error("Failed to run data fixer an item. Check ${dfuLog.absolutePathString()} for more information") + isFlawless = false + e.printStackTrace(dfuHandle) + null + } + + fun brokenItemStack(neuItem: NEUItem?): ItemStack { + return ItemStack(Items.PAINTING).apply { + setCustomName(Text.literal(neuItem?.displayName ?: "null")) + appendLore(listOf(Text.translatable("firmament.repo.brokenitem", neuItem?.skyblockItemId))) + } + } + + private fun NEUItem.asItemStackNow(): ItemStack { + try { + val oldItemTag = get10809CompoundTag() + val modernItemTag = oldItemTag.transformFrom10809ToModern() + ?: return brokenItemStack(this) + val itemInstance = ItemStack.fromNbt(modernItemTag) + if (itemInstance.nbt?.contains("Enchantments") == true) { + itemInstance.enchantments.add(NbtCompound()) + } + return itemInstance + } catch (e: Exception) { + e.printStackTrace() + return brokenItemStack(this) + } + } + + fun NEUItem?.asItemStack(): ItemStack { + if (this == null) return brokenItemStack(null) + var s = cache[this.skyblockItemId] + if (s == null) { + s = asItemStackNow() + cache[this.skyblockItemId] = s + } + return s + } + + fun NEUItem.getIdentifier() = skyblockId.identifier + + + var job: Job? = null + + override fun reload(repository: NEURepository) { + val j = job + if (j != null && j.isActive) { + j.cancel() + } + cache.clear() + isFlawless = true + + job = Firmament.coroutineScope.launch { + val items = repository.items?.items + if (items == null) { + CottonHud.remove(RepoManager.progressBar) + return@launch + } + val recacheItems = I18n.translate("firmament.repo.cache") + RepoManager.progressBar.reportProgress(recacheItems, 0, items.size) + CottonHud.add(RepoManager.progressBar) + var i = 0 + items.values.forEach { + it.asItemStack() // Rebuild cache + RepoManager.progressBar.reportProgress(recacheItems, i++, items.size) + } + CottonHud.remove(RepoManager.progressBar) + } + } +} diff --git a/src/main/kotlin/moe/nea/firmament/repo/RepoDownloadManager.kt b/src/main/kotlin/moe/nea/firmament/repo/RepoDownloadManager.kt new file mode 100644 index 0000000..09b246a --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/repo/RepoDownloadManager.kt @@ -0,0 +1,118 @@ +package moe.nea.firmament.repo + +import io.ktor.client.call.* +import io.ktor.client.request.* +import io.ktor.client.statement.* +import io.ktor.utils.io.jvm.nio.* +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.Dispatchers.IO +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import moe.nea.firmament.Firmament +import moe.nea.firmament.Firmament.logger +import moe.nea.firmament.util.iterate +import java.io.IOException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption +import java.util.zip.ZipInputStream +import kotlin.io.path.* + + +object RepoDownloadManager { + + val repoSavedLocation = Firmament.DATA_DIR.resolve("repo-extracted") + val repoMetadataLocation = Firmament.DATA_DIR.resolve("loaded-repo-sha.txt") + + private fun loadSavedVersionHash(): String? = + if (repoSavedLocation.exists()) { + if (repoMetadataLocation.exists()) { + try { + repoMetadataLocation.readText().trim() + } catch (e: IOException) { + null + } + } else { + null + } + } else null + + private fun saveVersionHash(versionHash: String) { + latestSavedVersionHash = versionHash + repoMetadataLocation.writeText(versionHash) + } + + var latestSavedVersionHash: String? = loadSavedVersionHash() + private set + + @Serializable + private class GithubCommitsResponse(val sha: String) + + private suspend fun requestLatestGithubSha(): String? { + val response = + Firmament.httpClient.get("https://api.github.com/repos/${RepoManager.data.user}/${RepoManager.data.repo}/commits/${RepoManager.data.branch}") + if (response.status.value != 200) { + return null + } + return response.body().sha + } + + private suspend fun downloadGithubArchive(url: String): Path = withContext(IO) { + val response = Firmament.httpClient.get(url) + val targetFile = Files.createTempFile("firmament-repo", ".zip") + val outputChannel = Files.newByteChannel(targetFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE) + response.bodyAsChannel().copyTo(outputChannel) + targetFile + } + + /** + * Downloads the latest repository from github, setting [latestSavedVersionHash]. + * @return true, if an update was performed, false, otherwise (no update needed, or wasn't able to complete update) + */ + suspend fun downloadUpdate(force: Boolean): Boolean = withContext(CoroutineName("Repo Update Check")) { + val latestSha = requestLatestGithubSha() + if (latestSha == null) { + logger.warn("Could not request github API to retrieve latest REPO sha.") + return@withContext false + } + val currentSha = loadSavedVersionHash() + if (latestSha != currentSha || force) { + val requestUrl = "https://github.com/${RepoManager.data.user}/${RepoManager.data.repo}/archive/$latestSha.zip" + logger.info("Planning to upgrade repository from $currentSha to $latestSha from $requestUrl") + val zipFile = downloadGithubArchive(requestUrl) + logger.info("Download repository zip file to $zipFile. Deleting old repository") + withContext(IO) { repoSavedLocation.toFile().deleteRecursively() } + logger.info("Extracting new repository") + withContext(IO) { extractNewRepository(zipFile) } + logger.info("Repository loaded on disk.") + saveVersionHash(latestSha) + return@withContext true + } else { + logger.debug("Repository on latest sha $currentSha. Not performing update") + return@withContext false + } + } + + private fun extractNewRepository(zipFile: Path) { + repoSavedLocation.createDirectories() + ZipInputStream(zipFile.inputStream()).use { cis -> + while (true) { + val entry = cis.nextEntry ?: break + if (entry.isDirectory) continue + val extractedLocation = + repoSavedLocation.resolve( + entry.name.substringAfter('/', missingDelimiterValue = "") + ) + if (repoSavedLocation !in extractedLocation.iterate { it.parent }) { + logger.error("Not Enough Updates detected an invalid zip file. This is a potential security risk, please report this in the Moulberry discord.") + throw RuntimeException("Not Enough Updates detected an invalid zip file. This is a potential security risk, please report this in the Moulberry discord.") + } + extractedLocation.parent.createDirectories() + cis.copyTo(extractedLocation.outputStream()) + cis.closeEntry() + } + } + } + + +} diff --git a/src/main/kotlin/moe/nea/firmament/repo/RepoManager.kt b/src/main/kotlin/moe/nea/firmament/repo/RepoManager.kt new file mode 100644 index 0000000..ac880b5 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/repo/RepoManager.kt @@ -0,0 +1,102 @@ +package moe.nea.firmament.repo + +import io.github.cottonmc.cotton.gui.client.CottonHud +import io.github.moulberry.repo.NEURecipeCache +import io.github.moulberry.repo.NEURepository +import io.github.moulberry.repo.NEURepositoryException +import io.github.moulberry.repo.data.NEURecipe +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents +import kotlinx.coroutines.launch +import kotlinx.serialization.Serializable +import kotlinx.serialization.serializer +import net.minecraft.client.MinecraftClient +import net.minecraft.network.packet.s2c.play.SynchronizeRecipesS2CPacket +import net.minecraft.text.Text +import moe.nea.firmament.Firmament +import moe.nea.firmament.Firmament.logger +import moe.nea.firmament.hud.ProgressBar +import moe.nea.firmament.util.SkyblockId +import moe.nea.firmament.util.data.DataHolder + +object RepoManager : DataHolder(serializer(), "repo", ::Config) { + @Serializable + data class Config( + var user: String = "NotEnoughUpdates", + var repo: String = "NotEnoughUpdates-REPO", + var autoUpdate: Boolean = true, + var branch: String = "dangerous", + ) + + val currentDownloadedSha by RepoDownloadManager::latestSavedVersionHash + + var recentlyFailedToUpdateItemList = false + + val progressBar = ProgressBar("", null, 0).also { + it.setSize(180, 22) + } + + val neuRepo: NEURepository = NEURepository.of(RepoDownloadManager.repoSavedLocation).apply { + registerReloadListener(ItemCache) + registerReloadListener { + if (!trySendClientboundUpdateRecipesPacket()) { + logger.warn("Failed to issue a ClientboundUpdateRecipesPacket (to reload REI). This may lead to an outdated item list.") + recentlyFailedToUpdateItemList = true + } + } + } + + private val recipeCache = NEURecipeCache.forRepo(neuRepo) + + fun getAllRecipes() = neuRepo.items.items.values.asSequence().flatMap { it.recipes } + + fun getRecipesFor(skyblockId: SkyblockId): Set = recipeCache.recipes[skyblockId.neuItem] ?: setOf() + fun getUsagesFor(skyblockId: SkyblockId): Set = recipeCache.usages[skyblockId.neuItem] ?: setOf() + + private fun trySendClientboundUpdateRecipesPacket(): Boolean { + return MinecraftClient.getInstance().world != null && MinecraftClient.getInstance().networkHandler?.onSynchronizeRecipes( + SynchronizeRecipesS2CPacket(mutableListOf()) + ) != null + } + + init { + ClientTickEvents.START_WORLD_TICK.register(ClientTickEvents.StartWorldTick { + if (recentlyFailedToUpdateItemList && trySendClientboundUpdateRecipesPacket()) + recentlyFailedToUpdateItemList = false + }) + } + + fun getNEUItem(skyblockId: SkyblockId) = neuRepo.items.getItemBySkyblockId(skyblockId.neuItem) + + fun launchAsyncUpdate(force: Boolean = false) { + Firmament.coroutineScope.launch { + progressBar.reportProgress("Downloading", 0, null) + CottonHud.add(progressBar) + RepoDownloadManager.downloadUpdate(force) + progressBar.reportProgress("Download complete", 1, 1) + reload() + } + } + + fun reload() { + try { + progressBar.reportProgress("Reloading from Disk", 0, null) + CottonHud.add(progressBar) + neuRepo.reload() + } catch (exc: NEURepositoryException) { + MinecraftClient.getInstance().player?.sendMessage( + Text.literal("Failed to reload repository. This will result in some mod features not working.") + ) + CottonHud.remove(progressBar) + exc.printStackTrace() + } + } + + fun initialize() { + if (data.autoUpdate) { + launchAsyncUpdate() + } else { + reload() + } + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/ItemUtil.kt b/src/main/kotlin/moe/nea/firmament/util/ItemUtil.kt new file mode 100644 index 0000000..4419245 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/ItemUtil.kt @@ -0,0 +1,24 @@ +package moe.nea.firmament.util + +import net.minecraft.item.ItemStack +import net.minecraft.nbt.NbtCompound +import net.minecraft.nbt.NbtList +import net.minecraft.nbt.NbtString +import net.minecraft.text.Text + + +fun ItemStack.appendLore(args: List) { + val compoundTag = getOrCreateSubNbt("display") + val loreList = compoundTag.getOrCreateList("Lore", NbtString.STRING_TYPE) + for (arg in args) { + loreList.add(NbtString.of(Text.Serializer.toJson(arg))) + } +} + +fun NbtCompound.getOrCreateList(label: String, tag: Byte): NbtList = getList(label, tag.toInt()).also { + put(label, it) +} + +fun NbtCompound.getOrCreateCompoundTag(label: String): NbtCompound = getCompound(label).also { + put(label, it) +} diff --git a/src/main/kotlin/moe/nea/firmament/util/LegacyTagParser.kt b/src/main/kotlin/moe/nea/firmament/util/LegacyTagParser.kt new file mode 100644 index 0000000..2d54b97 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/LegacyTagParser.kt @@ -0,0 +1,243 @@ +package moe.nea.firmament.util + +import java.util.* +import net.minecraft.nbt.AbstractNbtNumber +import net.minecraft.nbt.NbtByte +import net.minecraft.nbt.NbtCompound +import net.minecraft.nbt.NbtDouble +import net.minecraft.nbt.NbtElement +import net.minecraft.nbt.NbtFloat +import net.minecraft.nbt.NbtInt +import net.minecraft.nbt.NbtList +import net.minecraft.nbt.NbtLong +import net.minecraft.nbt.NbtShort +import net.minecraft.nbt.NbtString + +class LegacyTagParser private constructor(string: String) { + data class TagParsingException(val baseString: String, val offset: Int, val mes0: String) : + Exception("$mes0 at $offset in `$baseString`.") + + class StringRacer(val backing: String) { + var idx = 0 + val stack = Stack() + + fun pushState() { + stack.push(idx) + } + + fun popState() { + idx = stack.pop() + } + + fun discardState() { + stack.pop() + } + + fun peek(count: Int): String { + return backing.substring(minOf(idx, backing.length), minOf(idx + count, backing.length)) + } + + fun finished(): Boolean { + return peek(1).isEmpty() + } + + fun peekReq(count: Int): String? { + val p = peek(count) + if (p.length != count) + return null + return p + } + + fun consumeCountReq(count: Int): String? { + val p = peekReq(count) + if (p != null) + idx += count + return p + } + + fun tryConsume(string: String): Boolean { + val p = peek(string.length) + if (p != string) + return false + idx += p.length + return true + } + + fun consumeWhile(shouldConsumeThisString: (String) -> Boolean): String { + var lastString: String = "" + while (true) { + val nextString = lastString + peek(1) + if (!shouldConsumeThisString(nextString)) { + return lastString + } + idx++ + lastString = nextString + } + } + + fun expect(search: String, errorMessage: String) { + if (!tryConsume(search)) + error(errorMessage) + } + + fun error(errorMessage: String): Nothing { + throw TagParsingException(backing, idx, errorMessage) + } + + } + + val racer = StringRacer(string) + val baseTag = parseTag() + + companion object { + val digitRange = "0123456789-" + fun parse(string: String): NbtCompound { + return LegacyTagParser(string).baseTag + } + } + + fun skipWhitespace() { + racer.consumeWhile { Character.isWhitespace(it.last()) } // Only check last since other chars are always checked before. + } + + fun parseTag(): NbtCompound { + skipWhitespace() + racer.expect("{", "Expected '{’ at start of tag") + skipWhitespace() + val tag = NbtCompound() + while (!racer.tryConsume("}")) { + skipWhitespace() + val lhs = parseIdentifier() + skipWhitespace() + racer.expect(":", "Expected ':' after identifier in tag") + skipWhitespace() + val rhs = parseAny() + tag.put(lhs, rhs) + racer.tryConsume(",") + skipWhitespace() + } + return tag + } + + private fun parseAny(): NbtElement { + skipWhitespace() + val nextChar = racer.peekReq(1) ?: racer.error("Expected new object, found EOF") + return when { + nextChar == "{" -> parseTag() + nextChar == "[" -> parseList() + nextChar == "\"" -> parseStringTag() + nextChar.first() in (digitRange) -> parseNumericTag() + else -> racer.error("Unexpected token found. Expected start of new element") + } + } + + fun parseList(): NbtList { + skipWhitespace() + racer.expect("[", "Expected '[' at start of tag") + skipWhitespace() + val list = NbtList() + while (!racer.tryConsume("]")) { + skipWhitespace() + racer.pushState() + val lhs = racer.consumeWhile { it.all { it in digitRange } } + skipWhitespace() + if (!racer.tryConsume(":") || lhs.isEmpty()) { // No prefixed 0: + racer.popState() + list.add(parseAny()) // Reparse our number (or not a number) as actual tag + } else { + racer.discardState() + skipWhitespace() + list.add(parseAny()) // Ignore prefix indexes. They should not be generated out of order by any vanilla implementation (which is what NEU should export). Instead append where it appears in order. + } + skipWhitespace() + racer.tryConsume(",") + } + return list + } + + fun parseQuotedString(): String { + skipWhitespace() + racer.expect("\"", "Expected '\"' at string start") + val sb = StringBuilder() + while (true) { + when (val peek = racer.consumeCountReq(1)) { + "\"" -> break + "\\" -> { + val escaped = racer.consumeCountReq(1) ?: racer.error("Unfinished backslash escape") + if (escaped != "\"" && escaped != "\\") { + // Surprisingly i couldn't find unicode escapes to be generated by the original minecraft 1.8.9 implementation + racer.idx-- + racer.error("Invalid backslash escape '$escaped'") + } + sb.append(escaped) + } + + null -> racer.error("Unfinished string") + else -> { + sb.append(peek) + } + } + } + return sb.toString() + } + + fun parseStringTag(): NbtString { + return NbtString.of(parseQuotedString()) + } + + object Patterns { + val DOUBLE = "([-+]?[0-9]*\\.?[0-9]+)[d|D]".toRegex() + val FLOAT = "([-+]?[0-9]*\\.?[0-9]+)[f|F]".toRegex() + val BYTE = "([-+]?[0-9]+)[b|B]".toRegex() + val LONG = "([-+]?[0-9]+)[l|L]".toRegex() + val SHORT = "([-+]?[0-9]+)[s|S]".toRegex() + val INTEGER = "([-+]?[0-9]+)".toRegex() + val DOUBLE_UNTYPED = "([-+]?[0-9]*\\.?[0-9]+)".toRegex() + val ROUGH_PATTERN = "[-+]?[0-9]*\\.?[0-9]*[dDbBfFlLsS]?".toRegex() + } + + fun parseNumericTag(): AbstractNbtNumber { + skipWhitespace() + val textForm = racer.consumeWhile { Patterns.ROUGH_PATTERN.matchEntire(it) != null } + if (textForm.isEmpty()) { + racer.error("Expected numeric tag (starting with either -, +, . or a digit") + } + val doubleMatch = Patterns.DOUBLE.matchEntire(textForm) ?: Patterns.DOUBLE_UNTYPED.matchEntire(textForm) + if (doubleMatch != null) { + return NbtDouble.of(doubleMatch.groups[1]!!.value.toDouble()) + } + val floatMatch = Patterns.FLOAT.matchEntire(textForm) + if (floatMatch != null) { + return NbtFloat.of(floatMatch.groups[1]!!.value.toFloat()) + } + val byteMatch = Patterns.BYTE.matchEntire(textForm) + if (byteMatch != null) { + return NbtByte.of(byteMatch.groups[1]!!.value.toByte()) + } + val longMatch = Patterns.LONG.matchEntire(textForm) + if (longMatch != null) { + return NbtLong.of(longMatch.groups[1]!!.value.toLong()) + } + val shortMatch = Patterns.SHORT.matchEntire(textForm) + if (shortMatch != null) { + return NbtShort.of(shortMatch.groups[1]!!.value.toShort()) + } + val integerMatch = Patterns.INTEGER.matchEntire(textForm) + if (integerMatch != null) { + return NbtInt.of(integerMatch.groups[1]!!.value.toInt()) + } + throw IllegalStateException("Could not properly parse numeric tag '$textForm', despite passing rough verification. This is a bug in the LegacyTagParser") + } + + private fun parseIdentifier(): String { + skipWhitespace() + if (racer.peek(1) == "\"") { + return parseQuotedString() + } + return racer.consumeWhile { + val x = it.last() + x != ':' && !Character.isWhitespace(x) + } + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/Locraw.kt b/src/main/kotlin/moe/nea/firmament/util/Locraw.kt new file mode 100644 index 0000000..afbacef --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/Locraw.kt @@ -0,0 +1,8 @@ +package moe.nea.firmament.util + +import kotlinx.serialization.Serializable + +@Serializable +data class Locraw(val server: String, val gametype: String? = null, val mode: String? = null, val map: String? = null) { + val skyblockLocation = if (gametype == "SKYBLOCK") mode else null +} diff --git a/src/main/kotlin/moe/nea/firmament/util/MC.kt b/src/main/kotlin/moe/nea/firmament/util/MC.kt new file mode 100644 index 0000000..ab35f0e --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/MC.kt @@ -0,0 +1,13 @@ +package moe.nea.firmament.util + +import io.github.moulberry.repo.data.Coordinate +import net.minecraft.client.MinecraftClient +import net.minecraft.util.math.BlockPos + +object MC { + inline val player get() = MinecraftClient.getInstance().player + inline val world get() = MinecraftClient.getInstance().world +} + +val Coordinate.blockPos: BlockPos + get() = BlockPos(x, y, z) diff --git a/src/main/kotlin/moe/nea/firmament/util/MinecraftDispatcher.kt b/src/main/kotlin/moe/nea/firmament/util/MinecraftDispatcher.kt new file mode 100644 index 0000000..1e7fba2 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/MinecraftDispatcher.kt @@ -0,0 +1,22 @@ +package moe.nea.firmament.util + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Runnable +import kotlin.coroutines.CoroutineContext +import net.minecraft.client.MinecraftClient + +object MinecraftDispatcher : CoroutineDispatcher() { + @ExperimentalCoroutinesApi + override fun limitedParallelism(parallelism: Int): CoroutineDispatcher { + throw UnsupportedOperationException("limitedParallelism is not supported for MinecraftDispatcher") + } + + override fun isDispatchNeeded(context: CoroutineContext): Boolean = + !MinecraftClient.getInstance().isOnThread + + + override fun dispatch(context: CoroutineContext, block: Runnable) { + MinecraftClient.getInstance().execute(block) + } +} diff --git a/src/main/kotlin/moe/nea/firmament/util/SBData.kt b/src/main/kotlin/moe/nea/firmament/util/SBData.kt new file mode 100644 index 0000000..6e866f8 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/SBData.kt @@ -0,0 +1,62 @@ +package moe.nea.firmament.util + +import kotlinx.serialization.SerializationException +import kotlinx.serialization.decodeFromString +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import moe.nea.firmament.Firmament +import moe.nea.firmament.events.ServerChatLineReceivedEvent +import moe.nea.firmament.events.SkyblockServerUpdateEvent +import moe.nea.firmament.events.WorldReadyEvent + +object SBData { + val profileRegex = "(?:Your profile was changed to: |You are playing on profile: )(.+)".toRegex() + var profileCuteName: String? = null + + private var lastLocrawSent = Timer() + private val locrawRoundtripTime: Duration = 5.seconds + var locraw: Locraw? = null + val skyblockLocation get() = locraw?.skyblockLocation + + + fun init() { + ServerChatLineReceivedEvent.subscribe { event -> + val profileMatch = profileRegex.matchEntire(event.unformattedString) + if (profileMatch != null) { + profileCuteName = profileMatch.groupValues[1] + } + if (event.unformattedString.startsWith("{")) { + if (tryReceiveLocraw(event.unformattedString) && lastLocrawSent.timePassed() < locrawRoundtripTime) { + lastLocrawSent.markFarPast() + event.cancel() + } + } + } + + WorldReadyEvent.subscribe { + sendLocraw() + locraw = null + } + } + + private fun tryReceiveLocraw(unformattedString: String): Boolean = try { + val lastLocraw = locraw + locraw = Firmament.json.decodeFromString(unformattedString) + SkyblockServerUpdateEvent.publish(SkyblockServerUpdateEvent(lastLocraw, locraw)) + true + } catch (e: SerializationException) { + e.printStackTrace() + false + } catch (e: IllegalArgumentException) { + e.printStackTrace() + false + } + + fun sendLocraw() { + lastLocrawSent.markNow() + val nh = MC.player?.networkHandler ?: return + nh.sendChatCommand("locraw") + } + + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/ScreenUtil.kt b/src/main/kotlin/moe/nea/firmament/util/ScreenUtil.kt new file mode 100644 index 0000000..74b750b --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/ScreenUtil.kt @@ -0,0 +1,36 @@ +package moe.nea.firmament.util + +import moe.nea.firmament.Firmament +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents +import net.minecraft.client.MinecraftClient +import net.minecraft.client.gui.screen.Screen + +object ScreenUtil { + init { + ClientTickEvents.START_CLIENT_TICK.register(::onTick) + } + + private fun onTick(minecraft: MinecraftClient) { + if (nextOpenedGui != null) { + val p = minecraft.player + if (p?.currentScreenHandler != null) { + p.closeHandledScreen() + } + minecraft.setScreen(nextOpenedGui) + nextOpenedGui = null + } + } + + private var nextOpenedGui: Screen? = null + + fun setScreenLater(nextScreen: Screen) { + val nog = nextOpenedGui + if (nog != null) { + Firmament.logger.warn("Setting screen ${nextScreen::class.qualifiedName} to be opened later, but ${nog::class.qualifiedName} is already queued.") + return + } + nextOpenedGui = nextScreen + } + + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/SequenceUtil.kt b/src/main/kotlin/moe/nea/firmament/util/SequenceUtil.kt new file mode 100644 index 0000000..b30744d --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/SequenceUtil.kt @@ -0,0 +1,9 @@ +package moe.nea.firmament.util + +fun T.iterate(iterator: (T) -> T?): Sequence = sequence { + var x: T? = this@iterate + while (x != null) { + yield(x) + x = iterator(x) + } +} diff --git a/src/main/kotlin/moe/nea/firmament/util/SkyblockId.kt b/src/main/kotlin/moe/nea/firmament/util/SkyblockId.kt new file mode 100644 index 0000000..70d511c --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/SkyblockId.kt @@ -0,0 +1,48 @@ +package moe.nea.firmament.util + +import io.github.moulberry.repo.data.NEUItem +import io.github.moulberry.repo.data.Rarity +import kotlinx.serialization.Serializable +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.json.Json +import net.minecraft.item.ItemStack +import net.minecraft.nbt.NbtCompound +import net.minecraft.util.Identifier + +@JvmInline +value class SkyblockId(val neuItem: String) { + val identifier get() = Identifier("skyblockitem", neuItem.lowercase().replace(";", "__")) +} + +val NEUItem.skyblockId get() = SkyblockId(skyblockItemId) + +@Serializable +data class HypixelPetInfo( + val type: String, + val tier: Rarity, +) { + val skyblockId get() = SkyblockId("${type.uppercase()};${tier.ordinal}") +} + +private val jsonparser = Json { ignoreUnknownKeys = true } + +val ItemStack.extraAttributes: NbtCompound + get() = getOrCreateSubNbt("ExtraAttributes") + +val ItemStack.skyBlockId: SkyblockId? + get() { + when (val id = extraAttributes.getString("id")) { + "PET" -> { + val jsonString = extraAttributes.getString("petInfo") + if (jsonString.isNullOrBlank()) return null + val petInfo = + runCatching { jsonparser.decodeFromString(jsonString) } + .getOrElse { return null } + return petInfo.skyblockId + } + // TODO: RUNE, ENCHANTED_BOOK, PARTY_HAT_CRAB{,_ANIMATED}, ABICASE + else -> { + return SkyblockId(id) + } + } + } diff --git a/src/main/kotlin/moe/nea/firmament/util/TimeMark.kt b/src/main/kotlin/moe/nea/firmament/util/TimeMark.kt new file mode 100644 index 0000000..4068bda --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/TimeMark.kt @@ -0,0 +1,15 @@ +package moe.nea.firmament.util + +import kotlin.time.Duration +import kotlin.time.ExperimentalTime +import kotlin.time.TimeSource + +@OptIn(ExperimentalTime::class) +class TimeMark private constructor(private val timeMark: TimeSource.Monotonic.ValueTimeMark?) { + fun passedTime() = timeMark?.elapsedNow() ?: Duration.INFINITE + + companion object { + fun now() = TimeMark(TimeSource.Monotonic.markNow()) + fun farPast() = TimeMark(null) + } +} diff --git a/src/main/kotlin/moe/nea/firmament/util/Timer.kt b/src/main/kotlin/moe/nea/firmament/util/Timer.kt new file mode 100644 index 0000000..bfdc9d1 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/Timer.kt @@ -0,0 +1,23 @@ +package moe.nea.firmament.util + +import kotlin.time.Duration +import kotlin.time.ExperimentalTime +import kotlin.time.TimeSource + +@OptIn(ExperimentalTime::class) +class Timer { + private var mark: TimeSource.Monotonic.ValueTimeMark? = null + + fun timePassed(): Duration { + return mark?.elapsedNow() ?: Duration.INFINITE + } + + fun markNow() { + mark = TimeSource.Monotonic.markNow() + } + + fun markFarPast() { + mark = null + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/config/ManagedConfig.kt b/src/main/kotlin/moe/nea/firmament/util/config/ManagedConfig.kt new file mode 100644 index 0000000..bc06064 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/config/ManagedConfig.kt @@ -0,0 +1,204 @@ +package moe.nea.firmament.util.config + +import io.github.cottonmc.cotton.gui.client.CottonClientScreen +import io.github.cottonmc.cotton.gui.client.LightweightGuiDescription +import io.github.cottonmc.cotton.gui.widget.WButton +import io.github.cottonmc.cotton.gui.widget.WLabel +import io.github.cottonmc.cotton.gui.widget.WToggleButton +import io.github.cottonmc.cotton.gui.widget.WWidget +import io.github.cottonmc.cotton.gui.widget.data.Insets +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.jsonPrimitive +import kotlin.io.path.createDirectories +import kotlin.io.path.readText +import kotlin.io.path.writeText +import kotlin.properties.ReadOnlyProperty +import kotlin.reflect.KProperty +import net.minecraft.text.Text +import moe.nea.firmament.Firmament +import moe.nea.firmament.gui.WGridPanelWithPadding +import moe.nea.firmament.util.ScreenUtil.setScreenLater + +abstract class ManagedConfig(val name: String) { + + class GuiAppender(val width: Int) { + private var row = 0 + internal val panel = WGridPanelWithPadding(verticalPadding = 4, horizontalPadding = 4) + internal val reloadables = mutableListOf<(() -> Unit)>() + fun set(x: Int, y: Int, w: Int, h: Int, widget: WWidget) { + panel.add(widget, x, y, w, h) + } + + + fun onReload(reloadable: () -> Unit) { + reloadables.add(reloadable) + } + + fun skipRows(r: Int) { + row += r + } + + fun appendSplitRow(left: WWidget, right: WWidget) { + val lw = width / 2 + set(0, row, lw, 1, left) + set(lw, row, width - lw, 1, right) + skipRows(1) + } + + fun appendFullRow(widget: WWidget) { + set(0, row, width, 1, widget) + skipRows(1) + } + } + + interface OptionHandler { + fun toJson(element: T): JsonElement? + fun fromJson(element: JsonElement): T + fun emitGuiElements(opt: Option, guiAppender: GuiAppender) + } + + inner class Option internal constructor( + val propertyName: String, + val default: () -> T, + val handler: OptionHandler + ) : ReadOnlyProperty { + + private lateinit var _value: T + private var loaded = false + var value: T + get() { + if (!loaded) + load() + return _value + } + set(value) { + loaded = true + _value = value + } + + override fun getValue(thisRef: Any?, property: KProperty<*>): T { + return value + } + + private fun load() { + if (data.containsKey(propertyName)) { + try { + value = handler.fromJson(data[propertyName]!!) + } catch (e: Exception) { + Firmament.logger.error( + "Exception during loading of config file $name. This will reset this config.", + e + ) + } + } + value = default() + } + + internal fun toJson(): JsonElement? { + return handler.toJson(value) + } + + fun appendToGui(guiapp: GuiAppender) { + handler.emitGuiElements(this, guiapp) + } + } + + val file = Firmament.CONFIG_DIR.resolve("$name.json") + val data: JsonObject by lazy { + try { + Firmament.json.decodeFromString( + file.readText() + ) + } catch (e: Exception) { + Firmament.logger.info("Could not read config $name. Loading empty config.") + JsonObject(mutableMapOf()) + } + } + + fun save() { + val data = JsonObject(allOptions.mapNotNull { (key, value) -> + value.toJson()?.let { + key to it + } + }.toMap()) + file.parent.createDirectories() + file.writeText(Firmament.json.encodeToString(data)) + } + + + val allOptions = mutableMapOf>() + val sortedOptions = mutableListOf>() + + protected fun option(propertyName: String, default: () -> T, handler: OptionHandler): Option { + if (propertyName in allOptions) error("Cannot register the same name twice") + return Option(propertyName, default, handler).also { + allOptions[propertyName] = it + sortedOptions.add(it) + } + } + + class BooleanHandler(val config: ManagedConfig) : OptionHandler { + override fun toJson(element: Boolean): JsonElement? { + return JsonPrimitive(element) + } + + override fun fromJson(element: JsonElement): Boolean { + return element.jsonPrimitive.boolean + } + + override fun emitGuiElements(opt: Option, guiAppender: GuiAppender) { + guiAppender.appendFullRow( + WToggleButton(Text.translatable("firmament.config.${config.name}.${opt.propertyName}")).apply { + guiAppender.onReload { toggle = opt.value } + setOnToggle { + opt.value = it + config.save() + } + } + ) + } + } + + class ClickHandler(val config: ManagedConfig, val runnable: () -> Unit) : OptionHandler { + override fun toJson(element: Unit): JsonElement? { + return null + } + + override fun fromJson(element: JsonElement) {} + + override fun emitGuiElements(opt: Option, guiAppender: GuiAppender) { + guiAppender.appendSplitRow( + WLabel(Text.translatable("firmament.config.${config.name}.${opt.propertyName}")), + WButton(Text.translatable("firmament.config.${config.name}.${opt.propertyName}")).apply { + setOnClick { + runnable() + } + }, + ) + } + } + + protected fun toggle(propertyName: String, default: () -> Boolean): Option { + return option(propertyName, default, BooleanHandler(this)) + } + + fun showConfigEditor() { + val lwgd = LightweightGuiDescription() + val guiapp = GuiAppender(20) + guiapp.panel.insets = Insets.ROOT_PANEL + sortedOptions.forEach { it.appendToGui(guiapp) } + guiapp.reloadables.forEach { it() } + lwgd.setRootPanel(guiapp.panel) + setScreenLater(CottonClientScreen(lwgd)) + } + + protected fun button(propertyName: String, runnable: () -> Unit): Option { + return option(propertyName, { }, ClickHandler(this, runnable)) + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/data/DataHolder.kt b/src/main/kotlin/moe/nea/firmament/util/data/DataHolder.kt new file mode 100644 index 0000000..4d66a96 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/data/DataHolder.kt @@ -0,0 +1,60 @@ +package moe.nea.firmament.util.data + +import java.nio.file.Path +import kotlinx.serialization.KSerializer +import kotlin.io.path.exists +import kotlin.io.path.readText +import kotlin.io.path.writeText +import moe.nea.firmament.Firmament + +abstract class DataHolder( + val serializer: KSerializer, + val name: String, + val default: () -> T +) : IDataHolder { + + + final override var data: T + private set + + init { + data = readValueOrDefault() + IDataHolder.putDataHolder(this::class, this) + } + + private val file: Path get() = Firmament.CONFIG_DIR.resolve("$name.json") + + protected fun readValueOrDefault(): T { + if (file.exists()) + try { + return Firmament.json.decodeFromString( + serializer, + file.readText() + ) + } catch (e: Exception) {/* Expecting IOException and SerializationException, but Kotlin doesn't allow multi catches*/ + IDataHolder.badLoads.add(name) + Firmament.logger.error( + "Exception during loading of config file $name. This will reset this config.", + e + ) + } + return default() + } + + private fun writeValue(t: T) { + file.writeText(Firmament.json.encodeToString(serializer, t)) + } + + override fun save() { + writeValue(data) + } + + override fun load() { + data = readValueOrDefault() + } + + override fun markDirty() { + IDataHolder.markDirty(this::class) + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/data/IDataHolder.kt b/src/main/kotlin/moe/nea/firmament/util/data/IDataHolder.kt new file mode 100644 index 0000000..4fa8c38 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/data/IDataHolder.kt @@ -0,0 +1,75 @@ +package moe.nea.firmament.util.data + +import java.util.concurrent.CopyOnWriteArrayList +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents +import kotlin.reflect.KClass +import net.minecraft.client.MinecraftClient +import net.minecraft.server.command.CommandOutput +import net.minecraft.text.Text +import moe.nea.firmament.Firmament +import moe.nea.firmament.events.ScreenOpenEvent + +interface IDataHolder { + companion object { + internal var badLoads: MutableList = CopyOnWriteArrayList() + private val allConfigs: MutableMap>, IDataHolder<*>> = mutableMapOf() + private val dirty: MutableSet>> = mutableSetOf() + + internal fun , K> putDataHolder(kClass: KClass, inst: IDataHolder) { + allConfigs[kClass] = inst + } + + fun , K> markDirty(kClass: KClass) { + if (kClass !in allConfigs) { + Firmament.logger.error("Tried to markDirty '${kClass.qualifiedName}', which isn't registered as 'IConfigHolder'") + return + } + dirty.add(kClass) + } + + private fun performSaves() { + val toSave = dirty.toList().also { + dirty.clear() + } + for (it in toSave) { + val obj = allConfigs[it] + if (obj == null) { + Firmament.logger.error("Tried to save '${it}', which isn't registered as 'ConfigHolder'") + continue + } + obj.save() + } + } + + private fun warnForResetConfigs(player: CommandOutput) { + if (badLoads.isNotEmpty()) { + player.sendMessage( + Text.literal( + "The following configs have been reset: ${badLoads.joinToString(", ")}. " + + "This can be intentional, but probably isn't." + ) + ) + badLoads.clear() + } + } + + fun registerEvents() { + ScreenOpenEvent.subscribe { event -> + performSaves() + val p = MinecraftClient.getInstance().player + if (p != null) { + warnForResetConfigs(p) + } + } + ClientLifecycleEvents.CLIENT_STOPPING.register(ClientLifecycleEvents.ClientStopping { + performSaves() + }) + } + + } + + val data: T + fun save() + fun markDirty() + fun load() +} diff --git a/src/main/kotlin/moe/nea/firmament/util/data/ProfileSpecificDataHolder.kt b/src/main/kotlin/moe/nea/firmament/util/data/ProfileSpecificDataHolder.kt new file mode 100644 index 0000000..c3e1d38 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/data/ProfileSpecificDataHolder.kt @@ -0,0 +1,82 @@ +package moe.nea.firmament.util.data + +import java.nio.file.Path +import kotlinx.serialization.KSerializer +import kotlin.io.path.createDirectories +import kotlin.io.path.deleteExisting +import kotlin.io.path.exists +import kotlin.io.path.extension +import kotlin.io.path.listDirectoryEntries +import kotlin.io.path.nameWithoutExtension +import kotlin.io.path.readText +import kotlin.io.path.writeText +import moe.nea.firmament.Firmament +import moe.nea.firmament.util.SBData + +abstract class ProfileSpecificDataHolder( + private val dataSerializer: KSerializer, + val configName: String, + private val configDefault: () -> S +) : IDataHolder { + + var allConfigs: MutableMap + + override val data: S? + get() = SBData.profileCuteName?.let { + allConfigs.computeIfAbsent(it) { configDefault() } + } + + init { + allConfigs = readValues() + readValues() + IDataHolder.putDataHolder(this::class, this) + } + + private val configDirectory: Path get() = Firmament.CONFIG_DIR.resolve("profiles").resolve(configName) + + private fun readValues(): MutableMap { + if (!configDirectory.exists()) { + configDirectory.createDirectories() + } + val profileFiles = configDirectory.listDirectoryEntries() + return profileFiles + .filter { it.extension == "json" } + .mapNotNull { + try { + it.nameWithoutExtension to Firmament.json.decodeFromString(dataSerializer, it.readText()) + } catch (e: Exception) { /* Expecting IOException and SerializationException, but Kotlin doesn't allow multi catches*/ + IDataHolder.badLoads.add(configName) + Firmament.logger.error( + "Exception during loading of profile specific config file $it ($configName). This will reset that profiles config.", + e + ) + null + } + }.toMap().toMutableMap() + } + + override fun save() { + if (!configDirectory.exists()) { + configDirectory.createDirectories() + } + val c = allConfigs + configDirectory.listDirectoryEntries().forEach { + if (it.nameWithoutExtension !in c) { + it.deleteExisting() + } + } + c.forEach { (name, value) -> + val f = configDirectory.resolve("$name.json") + f.writeText(Firmament.json.encodeToString(dataSerializer, value)) + } + } + + override fun markDirty() { + IDataHolder.markDirty(this::class) + } + + override fun load() { + allConfigs = readValues() + } + +} diff --git a/src/main/kotlin/moe/nea/firmament/util/render/block.kt b/src/main/kotlin/moe/nea/firmament/util/render/block.kt new file mode 100644 index 0000000..1fd1393 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/render/block.kt @@ -0,0 +1,105 @@ +package moe.nea.firmament.util.render + +import com.mojang.blaze3d.systems.RenderSystem +import org.joml.Matrix4f +import net.minecraft.client.gl.VertexBuffer +import net.minecraft.client.render.BufferBuilder +import net.minecraft.client.render.Camera +import net.minecraft.client.render.GameRenderer +import net.minecraft.client.render.Tessellator +import net.minecraft.client.render.VertexFormat +import net.minecraft.client.render.VertexFormats +import net.minecraft.client.util.math.MatrixStack +import net.minecraft.util.math.BlockPos +import net.minecraft.util.math.Vec3d + +class RenderBlockContext private constructor(private val tesselator: Tessellator, private val matrixStack: MatrixStack) { + private val buffer = tesselator.buffer + fun color(red: Float, green: Float, blue: Float, alpha: Float) { + RenderSystem.setShaderColor(red, green, blue, alpha) + } + + fun block(blockPos: BlockPos) { + matrixStack.push() + matrixStack.translate(blockPos.x.toFloat(), blockPos.y.toFloat(), blockPos.z.toFloat()) + buildCube(matrixStack.peek().positionMatrix, buffer) + tesselator.draw() + matrixStack.pop() + } + + fun tinyBlock(vec3d: Vec3d, size: Float) { + matrixStack.push() + matrixStack.translate(vec3d.x, vec3d.y, vec3d.z) + matrixStack.scale(size, size, size) + matrixStack.translate(-.5, -.5, -.5) + buildCube(matrixStack.peek().positionMatrix, buffer) + tesselator.draw() + matrixStack.pop() + } + + companion object { + private fun buildCube(matrix: Matrix4f, buf: BufferBuilder) { + buf.begin(VertexFormat.DrawMode.TRIANGLES, VertexFormats.POSITION_COLOR) + buf.fixedColor(255, 255, 255, 255) + buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 0.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() + buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() + buf.unfixColor() + } + + fun renderBlocks(matrices: MatrixStack, camera: Camera, block: RenderBlockContext. () -> Unit) { + RenderSystem.disableDepthTest() + RenderSystem.enableBlend() + RenderSystem.defaultBlendFunc() + RenderSystem.setShader(GameRenderer::getPositionColorProgram) + + matrices.push() + matrices.translate(-camera.pos.x, -camera.pos.y, -camera.pos.z) + + val ctx = RenderBlockContext(Tessellator.getInstance(), matrices) + block(ctx) + + matrices.pop() + + RenderSystem.setShaderColor(1F,1F,1F,1F) + VertexBuffer.unbind() + RenderSystem.enableDepthTest() + RenderSystem.disableBlend() + } + } +} + + diff --git a/src/main/kotlin/moe/nea/firmament/util/textutil.kt b/src/main/kotlin/moe/nea/firmament/util/textutil.kt new file mode 100644 index 0000000..b12d6c4 --- /dev/null +++ b/src/main/kotlin/moe/nea/firmament/util/textutil.kt @@ -0,0 +1,70 @@ +package moe.nea.firmament.util + +import net.minecraft.text.LiteralTextContent +import net.minecraft.text.Text +import net.minecraft.text.TextContent +import moe.nea.firmament.Firmament + + +class TextMatcher(text: Text) { + data class State( + var iterator: MutableList, + var currentText: Text?, + var offset: Int, + var textContent: String, + ) + + var state = State( + mutableListOf(text), + null, + 0, + "" + ) + + fun pollChunk(): Boolean { + val firstOrNull = state.iterator.removeFirstOrNull() ?: return false + state.offset = 0 + state.currentText = firstOrNull + state.textContent = when (val content = firstOrNull.content) { + is LiteralTextContent -> content.string + TextContent.EMPTY -> "" + else -> { + Firmament.logger.warn("TextContent of type ${content.javaClass} not understood.") + return false + } + } + state.iterator.addAll(0, firstOrNull.siblings) + return true + } + + fun pollChunks(): Boolean { + while (state.offset !in state.textContent.indices) { + if (!pollChunk()) { + return false + } + } + return true + } + + fun pollChar(): Char? { + if (!pollChunks()) return null + return state.textContent[state.offset++] + } + + + fun expectString(string: String): Boolean { + var found = "" + while (found.length < string.length) { + if (!pollChunks()) return false + val takeable = state.textContent.drop(state.offset).take(string.length - found.length) + state.offset += takeable.length + found += takeable + } + return found == string + } +} + + +val Text.unformattedString + get() = string.replace("§.".toRegex(), "") + diff --git a/src/main/kotlin/moe/nea/notenoughupdates/NotEnoughUpdates.kt b/src/main/kotlin/moe/nea/notenoughupdates/NotEnoughUpdates.kt deleted file mode 100644 index 7563a7a..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/NotEnoughUpdates.kt +++ /dev/null @@ -1,92 +0,0 @@ -package moe.nea.notenoughupdates - -import com.mojang.brigadier.CommandDispatcher -import io.ktor.client.* -import io.ktor.client.plugins.* -import io.ktor.client.plugins.contentnegotiation.* -import io.ktor.serialization.kotlinx.json.* -import java.nio.file.Files -import java.nio.file.Path -import net.fabricmc.api.ClientModInitializer -import net.fabricmc.api.ModInitializer -import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback -import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource -import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents -import net.fabricmc.loader.api.FabricLoader -import net.fabricmc.loader.api.Version -import net.fabricmc.loader.api.metadata.ModMetadata -import org.apache.logging.log4j.LogManager -import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder -import kotlinx.coroutines.* -import kotlinx.serialization.json.Json -import kotlin.coroutines.EmptyCoroutineContext -import net.minecraft.command.CommandRegistryAccess -import moe.nea.notenoughupdates.commands.registerNeuCommand -import moe.nea.notenoughupdates.dbus.NEUDbusObject -import moe.nea.notenoughupdates.features.FeatureManager -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.SBData -import moe.nea.notenoughupdates.util.data.IDataHolder - -object NotEnoughUpdates : ModInitializer, ClientModInitializer { - const val MOD_ID = "notenoughupdates" - - val DEBUG = System.getProperty("notenoughupdates.debug") == "true" - val DATA_DIR: Path = Path.of(".notenoughupdates").also { Files.createDirectories(it) } - val CONFIG_DIR: Path = Path.of("config/notenoughupdates").also { Files.createDirectories(it) } - val logger = LogManager.getLogger("NotEnoughUpdates") - val metadata: ModMetadata by lazy { FabricLoader.getInstance().getModContainer(MOD_ID).orElseThrow().metadata } - val version: Version by lazy { metadata.version } - - val json = Json { - prettyPrint = DEBUG - ignoreUnknownKeys = true - encodeDefaults = true - } - - val httpClient by lazy { - HttpClient { - install(ContentNegotiation) { - json(json) - } - install(UserAgent) { - agent = "NotEnoughUpdates1.19/$version" - } - } - } - - val globalJob = Job() - val dbusConnection = DBusConnectionBuilder.forSessionBus() - .build() - val coroutineScope = - CoroutineScope(EmptyCoroutineContext + CoroutineName("NotEnoughUpdates")) + SupervisorJob(globalJob) - - private fun registerCommands( - dispatcher: CommandDispatcher, - @Suppress("UNUSED_PARAMETER") - ctx: CommandRegistryAccess - ) { - registerNeuCommand(dispatcher) - } - - override fun onInitialize() { - - dbusConnection.requestBusName("moe.nea.notenoughupdates") - dbusConnection.exportObject(NEUDbusObject) - IDataHolder.registerEvents() - RepoManager.initialize() - SBData.init() - FeatureManager.autoload() - - ClientCommandRegistrationCallback.EVENT.register(this::registerCommands) - ClientLifecycleEvents.CLIENT_STOPPING.register(ClientLifecycleEvents.ClientStopping { - runBlocking { - logger.info("Shutting down NEU coroutines") - globalJob.cancel() - } - }) - } - - override fun onInitializeClient() { - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/commands/dsl.kt b/src/main/kotlin/moe/nea/notenoughupdates/commands/dsl.kt deleted file mode 100644 index 6190d88..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/commands/dsl.kt +++ /dev/null @@ -1,81 +0,0 @@ -package moe.nea.notenoughupdates.commands - -import com.mojang.brigadier.arguments.ArgumentType -import com.mojang.brigadier.builder.ArgumentBuilder -import com.mojang.brigadier.builder.LiteralArgumentBuilder -import com.mojang.brigadier.builder.RequiredArgumentBuilder -import com.mojang.brigadier.context.CommandContext -import java.lang.reflect.ParameterizedType -import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource -import moe.nea.notenoughupdates.util.iterate - - -typealias DefaultSource = FabricClientCommandSource - - -inline val > T.context get() = this -operator fun > C.get(arg: TypeSafeArg): T { - return arg.get(this) -} - -fun literal( - name: String, - block: LiteralArgumentBuilder.() -> Unit -): LiteralArgumentBuilder = - LiteralArgumentBuilder.literal(name).also(block) - -data class TypeSafeArg(val name: String, val argument: ArgumentType) { - val argClass by lazy { - argument.javaClass - .iterate>> { - it.superclass - } - .map { - it.genericSuperclass - } - .filterIsInstance() - .find { it.rawType == ArgumentType::class.java }!! - .let { it.actualTypeArguments[0] as Class<*> } - } - - @JvmName("getWithThis") - fun CommandContext.get(): T = - get(this) - - - fun get(ctx: CommandContext): T { - return ctx.getArgument(name, argClass) as T - } -} - - -fun argument( - name: String, - argument: ArgumentType, - block: RequiredArgumentBuilder.(TypeSafeArg) -> Unit -): RequiredArgumentBuilder = - RequiredArgumentBuilder.argument(name, argument).also { block(it, TypeSafeArg(name, argument)) } - -fun , AT : Any> T.thenArgument( - name: String, - argument: ArgumentType, - block: RequiredArgumentBuilder.(TypeSafeArg) -> Unit -): T = then(argument(name, argument, block)) - - -fun > T.thenLiteral( - name: String, - block: LiteralArgumentBuilder.() -> Unit -): T = - then(literal(name, block)) - -fun > T.then(node: ArgumentBuilder, block: T.() -> Unit): T = - then(node).also(block) - -fun > T.thenExecute(block: CommandContext.() -> Unit): T = - executes { - block(it) - 1 - } - - diff --git a/src/main/kotlin/moe/nea/notenoughupdates/commands/rome.kt b/src/main/kotlin/moe/nea/notenoughupdates/commands/rome.kt deleted file mode 100644 index a60073a..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/commands/rome.kt +++ /dev/null @@ -1,66 +0,0 @@ -package moe.nea.notenoughupdates.commands - -import com.mojang.brigadier.CommandDispatcher -import io.github.cottonmc.cotton.gui.client.CottonClientScreen -import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource -import net.minecraft.text.Text -import moe.nea.notenoughupdates.features.world.FairySouls -import moe.nea.notenoughupdates.gui.repoGui -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.SBData -import moe.nea.notenoughupdates.util.ScreenUtil.setScreenLater - - -fun neuCommand() = literal("neu") { - thenLiteral("repo") { - thenLiteral("reload") { - thenLiteral("fetch") { - thenExecute { - source.sendFeedback(Text.translatable("notenoughupdates.repo.reload.network")) // TODO better reporting - RepoManager.launchAsyncUpdate() - } - } - thenExecute { - source.sendFeedback(Text.translatable("notenoughupdates.repo.reload.disk")) - RepoManager.reload() - } - } - thenExecute { - setScreenLater(CottonClientScreen(repoGui())) - } - } - thenLiteral("dev") { - thenLiteral("config") { - thenExecute { - FairySouls.TConfig.showConfigEditor() - } - } - thenLiteral("sbdata") { - thenExecute { - source.sendFeedback(Text.translatable("notenoughupdates.sbinfo.profile", SBData.profileCuteName)) - val locrawInfo = SBData.locraw - if (locrawInfo == null) { - source.sendFeedback(Text.translatable("notenoughupdates.sbinfo.nolocraw")) - } else { - source.sendFeedback(Text.translatable("notenoughupdates.sbinfo.server", locrawInfo.server)) - source.sendFeedback(Text.translatable("notenoughupdates.sbinfo.gametype", locrawInfo.gametype)) - source.sendFeedback(Text.translatable("notenoughupdates.sbinfo.mode", locrawInfo.mode)) - source.sendFeedback(Text.translatable("notenoughupdates.sbinfo.map", locrawInfo.map)) - } - - } - } - } -} - - -fun registerNeuCommand(dispatcher: CommandDispatcher) { - val neu = dispatcher.register(neuCommand()) - dispatcher.register(literal("alsoneu") { - redirect(neu) - }) -} - - - - diff --git a/src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusInterface.kt b/src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusInterface.kt deleted file mode 100644 index 28ff370..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusInterface.kt +++ /dev/null @@ -1,11 +0,0 @@ -package moe.nea.notenoughupdates.dbus - -import org.freedesktop.dbus.annotations.DBusInterfaceName -import org.freedesktop.dbus.interfaces.DBusInterface - -@DBusInterfaceName("moe.nea.NotEnoughUpdates") -interface NEUDbusInterface : DBusInterface { - fun sayHello(): String - fun getCurrentRepoCommit(): String - fun requestRepoReDownload() -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusObject.kt b/src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusObject.kt deleted file mode 100644 index 4e3d362..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/dbus/NEUDbusObject.kt +++ /dev/null @@ -1,21 +0,0 @@ -package moe.nea.notenoughupdates.dbus - -import moe.nea.notenoughupdates.repo.RepoManager - -object NEUDbusObject : NEUDbusInterface { - override fun sayHello(): String { - return "Hello from NEU" - } - - override fun getCurrentRepoCommit(): String { - return RepoManager.currentDownloadedSha ?: "none" - } - - override fun requestRepoReDownload() { - RepoManager.launchAsyncUpdate() - } - - override fun getObjectPath(): String { - return "/moe/nea/NotEnoughUpdates" - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/NEUEvent.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/NEUEvent.kt deleted file mode 100644 index 81dc6fc..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/NEUEvent.kt +++ /dev/null @@ -1,36 +0,0 @@ -package moe.nea.notenoughupdates.events - -/** - * An event that can be fired by a [NEUEventBus]. - * - * Typically, that event bus is implemented as a companion object - * - * ``` - * class SomeEvent : NEUEvent() { - * companion object : NEUEventBus() - * } - * ``` - */ -abstract class NEUEvent { - /** - * A [NEUEvent] that can be [cancelled] - */ - abstract class Cancellable : NEUEvent() { - /** - * Cancels this is event. - * - * @see cancelled - */ - fun cancel() { - cancelled = true - } - - /** - * Whether this event is cancelled. - * - * Cancelled events will bypass handlers unless otherwise specified and will prevent the action that this - * event was originally fired for. - */ - var cancelled: Boolean = false - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/NEUEventBus.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/NEUEventBus.kt deleted file mode 100644 index 7eb0ecd..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/NEUEventBus.kt +++ /dev/null @@ -1,37 +0,0 @@ -package moe.nea.notenoughupdates.events - -import java.util.concurrent.CopyOnWriteArrayList -import moe.nea.notenoughupdates.NotEnoughUpdates - -/** - * A pubsub event bus. - * - * [subscribe] to events [publish]ed on this event bus. - * Subscriptions may not necessarily be delivered in the order or registering. - */ -open class NEUEventBus { - data class Handler(val invocation: (T) -> Unit, val receivesCancelled: Boolean) - - private val toHandle: MutableList> = CopyOnWriteArrayList() - fun subscribe(handle: (T) -> Unit) { - subscribe(handle, false) - } - - fun subscribe(handle: (T) -> Unit, receivesCancelled: Boolean) { - toHandle.add(Handler(handle, receivesCancelled)) - } - - fun publish(event: T): T { - for (function in toHandle) { - if (function.receivesCancelled || event !is NEUEvent.Cancellable || !event.cancelled) { - try { - function.invocation(event) - } catch (e: Exception) { - NotEnoughUpdates.logger.error("Caught exception during processing event $event", e) - } - } - } - return event - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/ParticleSpawnEvent.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/ParticleSpawnEvent.kt deleted file mode 100644 index 23c67a0..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/ParticleSpawnEvent.kt +++ /dev/null @@ -1,13 +0,0 @@ -package moe.nea.notenoughupdates.events - -import net.minecraft.particle.ParticleEffect -import net.minecraft.util.math.Vec3d - -data class ParticleSpawnEvent( - val particleEffect: ParticleEffect, - val position: Vec3d, - val offset: Vec3d, - val longDistance: Boolean, -) : NEUEvent() { - companion object : NEUEventBus() -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/ScreenOpenEvent.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/ScreenOpenEvent.kt deleted file mode 100644 index 793f066..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/ScreenOpenEvent.kt +++ /dev/null @@ -1,7 +0,0 @@ -package moe.nea.notenoughupdates.events - -import net.minecraft.client.gui.screen.Screen - -data class ScreenOpenEvent(val old: Screen?, val new: Screen?) : NEUEvent.Cancellable() { - companion object : NEUEventBus() -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/ServerChatLineReceivedEvent.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/ServerChatLineReceivedEvent.kt deleted file mode 100644 index 681ec6c..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/ServerChatLineReceivedEvent.kt +++ /dev/null @@ -1,13 +0,0 @@ -package moe.nea.notenoughupdates.events - -import net.minecraft.text.Text -import moe.nea.notenoughupdates.util.unformattedString - -/** - * This event gets published whenever the client receives a chat message from the server. - */ -data class ServerChatLineReceivedEvent(val text: Text) : NEUEvent.Cancellable() { - companion object : NEUEventBus() - - val unformattedString = text.unformattedString -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/SkyblockServerUpdateEvent.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/SkyblockServerUpdateEvent.kt deleted file mode 100644 index 541b4c6..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/SkyblockServerUpdateEvent.kt +++ /dev/null @@ -1,13 +0,0 @@ -package moe.nea.notenoughupdates.events - -import moe.nea.notenoughupdates.util.Locraw - -/** - * This event gets published whenever `/locraw` is queried and HyPixel returns a location different to the old one. - * - * **N.B.:** This event may get fired multiple times while on the server (for example, first to null, then to the - * correct location). - */ -data class SkyblockServerUpdateEvent(val oldLocraw: Locraw?, val newLocraw: Locraw?) : NEUEvent() { - companion object : NEUEventBus() -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/WorldReadyEvent.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/WorldReadyEvent.kt deleted file mode 100644 index 5f305f1..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/WorldReadyEvent.kt +++ /dev/null @@ -1,5 +0,0 @@ -package moe.nea.notenoughupdates.events - -class WorldReadyEvent : NEUEvent() { - companion object : NEUEventBus() -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/events/WorldRenderLastEvent.kt b/src/main/kotlin/moe/nea/notenoughupdates/events/WorldRenderLastEvent.kt deleted file mode 100644 index 60b7e06..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/events/WorldRenderLastEvent.kt +++ /dev/null @@ -1,22 +0,0 @@ -package moe.nea.notenoughupdates.events - -import org.joml.Matrix4f -import net.minecraft.client.render.Camera -import net.minecraft.client.render.GameRenderer -import net.minecraft.client.render.LightmapTextureManager -import net.minecraft.client.util.math.MatrixStack - -/** - * This event is called after all world rendering is done, but before any GUI rendering (including hand) has been done. - */ -data class WorldRenderLastEvent( - val matrices: MatrixStack, - val tickDelta: Float, - val renderBlockOutline: Boolean, - val camera: Camera, - val gameRenderer: GameRenderer, - val lightmapTextureManager: LightmapTextureManager, - val positionMatrix: Matrix4f, -) : NEUEvent() { - companion object : NEUEventBus() -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/features/FeatureManager.kt b/src/main/kotlin/moe/nea/notenoughupdates/features/FeatureManager.kt deleted file mode 100644 index 2512992..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/features/FeatureManager.kt +++ /dev/null @@ -1,53 +0,0 @@ -package moe.nea.notenoughupdates.features - -import kotlinx.serialization.Serializable -import kotlinx.serialization.serializer -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.features.fishing.FishingWarning -import moe.nea.notenoughupdates.features.world.FairySouls -import moe.nea.notenoughupdates.util.data.DataHolder - -object FeatureManager : DataHolder(serializer(), "features", ::Config) { - @Serializable - data class Config( - val enabledFeatures: MutableMap = mutableMapOf() - ) - - private val features = mutableMapOf() - - private var hasAutoloaded = false - - init { - autoload() - } - - fun autoload() { - synchronized(this) { - if (hasAutoloaded) return - loadFeature(FairySouls) - loadFeature(FishingWarning) - hasAutoloaded = true - } - } - - fun loadFeature(feature: NEUFeature) { - synchronized(features) { - if (feature.identifier in features) { - NotEnoughUpdates.logger.error("Double registering feature ${feature.identifier}. Ignoring second instance $feature") - return - } - features[feature.identifier] = feature - feature.onLoad() - } - } - - fun isEnabled(identifier: String): Boolean? = - data.enabledFeatures[identifier] - - - fun setEnabled(identifier: String, value: Boolean) { - data.enabledFeatures[identifier] = value - markDirty() - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/features/NEUFeature.kt b/src/main/kotlin/moe/nea/notenoughupdates/features/NEUFeature.kt deleted file mode 100644 index 39cfb35..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/features/NEUFeature.kt +++ /dev/null @@ -1,18 +0,0 @@ -package moe.nea.notenoughupdates.features - -import moe.nea.notenoughupdates.util.config.ManagedConfig - -interface NEUFeature { - val name: String - val identifier: String - val defaultEnabled: Boolean - get() = true - var isEnabled: Boolean - get() = FeatureManager.isEnabled(identifier) ?: defaultEnabled - set(value) { - FeatureManager.setEnabled(identifier, value) - } - val config: ManagedConfig? get() = null - fun onLoad() - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/features/fishing/FishingWarning.kt b/src/main/kotlin/moe/nea/notenoughupdates/features/fishing/FishingWarning.kt deleted file mode 100644 index c44201c..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/features/fishing/FishingWarning.kt +++ /dev/null @@ -1,117 +0,0 @@ -package moe.nea.notenoughupdates.features.fishing - -import kotlin.math.abs -import kotlin.math.absoluteValue -import kotlin.math.acos -import kotlin.math.asin -import kotlin.math.atan2 -import kotlin.math.sqrt -import kotlin.time.Duration.Companion.seconds -import net.minecraft.entity.projectile.FishingBobberEntity -import net.minecraft.particle.ParticleTypes -import net.minecraft.util.math.Vec3d -import moe.nea.notenoughupdates.events.ParticleSpawnEvent -import moe.nea.notenoughupdates.events.WorldReadyEvent -import moe.nea.notenoughupdates.events.WorldRenderLastEvent -import moe.nea.notenoughupdates.features.NEUFeature -import moe.nea.notenoughupdates.util.MC -import moe.nea.notenoughupdates.util.TimeMark -import moe.nea.notenoughupdates.util.config.ManagedConfig -import moe.nea.notenoughupdates.util.render.RenderBlockContext.Companion.renderBlocks - -object FishingWarning : NEUFeature { - override val name: String - get() = "Fishing Warning" - override val identifier: String - get() = "fishing-warning" - - object TConfig : ManagedConfig("fishing-warning") { - // Display a warning when you are about to hook a fish - val displayWarning by toggle("display-warning") { false } - val highlightWakeChain by toggle("highlight-wake-chain") { false } - } - - override val config: ManagedConfig get() = TConfig - - - data class WakeChain( - val delta: Vec3d, - val momentum: Vec3d, - val lastContinued: TimeMark, - ) - - - val chains = mutableListOf() - - private fun areAnglesClose(a: Double, b: Double, tolerance: Double): Boolean { - var dist = (a - b).absoluteValue - if (180 < dist) dist = 360 - dist; - return dist <= tolerance - } - - private fun calculateAngleFromOffsets(xOffset: Double, zOffset: Double): Double { - // See also: Vanilla 1.8.9 Fishing particle code. - var angleX = Math.toDegrees(acos(xOffset / 0.04)) - var angleZ = Math.toDegrees(asin(zOffset / 0.04)) - if (xOffset < 0) { - // Old: angleZ = 180 - angleZ; - angleZ = 180 - angleZ - } - if (zOffset < 0) { - angleX = 360 - angleX - } - angleX %= 360.0 - angleZ %= 360.0 - if (angleX < 0) angleX += 360.0 - if (angleZ < 0) angleZ += 360.0 - var dist = angleX - angleZ - if (dist < -180) dist += 360.0 - if (dist > 180) dist -= 360.0 - return angleZ + dist / 2 - } - - private fun toDegrees(d: Double) = d * 180 / Math.PI - - fun isHookPossible(hook: FishingBobberEntity, particlePos: Vec3d, angle1: Double, angle2: Double): Boolean { - val dx = particlePos.x - hook.pos.x - val dz = particlePos.z - hook.pos.z - val dist = sqrt(dx * dx + dz * dz) - - if (dist < 0.2) return true - val tolerance = toDegrees(atan2(0.03125, dist)) * 1.5 - var angleToHook = toDegrees(atan2(dx, dz)) % 360 - if (angleToHook < 0) angleToHook += 360 - return areAnglesClose(angle1, angleToHook, tolerance) || areAnglesClose(angle2, angleToHook, tolerance) - } - - val recentParticles = mutableListOf>() - - private fun onParticleSpawn(event: ParticleSpawnEvent) { - if (event.particleEffect.type != ParticleTypes.FISHING) return - if (!(abs(event.offset.y - 0.01f) < 0.001f)) return - val hook = MC.player?.fishHook ?: return - val actualOffset = event.offset - val candidate1 = calculateAngleFromOffsets(actualOffset.x, -actualOffset.z) - val candidate2 = calculateAngleFromOffsets(-actualOffset.x, actualOffset.z) - - if (isHookPossible(hook, event.position, candidate1, candidate2)) { - recentParticles.add(Pair(event.position, TimeMark.now())) - } - } - - override fun onLoad() { - ParticleSpawnEvent.subscribe(::onParticleSpawn) - WorldReadyEvent.subscribe { - recentParticles.clear() - } - WorldRenderLastEvent.subscribe { - recentParticles.removeIf { it.second.passedTime() > 5.seconds } - renderBlocks(it.matrices, it.camera) { - color(0f, 0f, 1f, 1f) - recentParticles.forEach { - tinyBlock(it.first, 0.1F) - } - } - } - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/features/world/FairySouls.kt b/src/main/kotlin/moe/nea/notenoughupdates/features/world/FairySouls.kt deleted file mode 100644 index ae045c0..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/features/world/FairySouls.kt +++ /dev/null @@ -1,120 +0,0 @@ -package moe.nea.notenoughupdates.features.world - -import io.github.moulberry.repo.data.Coordinate -import kotlinx.serialization.Serializable -import kotlinx.serialization.serializer -import moe.nea.notenoughupdates.events.ServerChatLineReceivedEvent -import moe.nea.notenoughupdates.events.SkyblockServerUpdateEvent -import moe.nea.notenoughupdates.events.WorldRenderLastEvent -import moe.nea.notenoughupdates.features.NEUFeature -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.MC -import moe.nea.notenoughupdates.util.SBData -import moe.nea.notenoughupdates.util.blockPos -import moe.nea.notenoughupdates.util.config.ManagedConfig -import moe.nea.notenoughupdates.util.data.ProfileSpecificDataHolder -import moe.nea.notenoughupdates.util.render.RenderBlockContext.Companion.renderBlocks -import moe.nea.notenoughupdates.util.unformattedString - - -object FairySouls : NEUFeature { - - - @Serializable - data class Data( - val foundSouls: MutableMap> = mutableMapOf() - ) - - override val config: ManagedConfig - get() = TConfig - - object DConfig : ProfileSpecificDataHolder(serializer(), "found-fairysouls", ::Data) - - - object TConfig : ManagedConfig("fairy-souls") { - - val displaySouls by toggle("show") { false } - val resetSouls by button("reset") { - DConfig.data?.foundSouls?.clear() != null - updateMissingSouls() - } - } - - - override val name: String get() = "Fairy Souls" - override val identifier: String get() = "fairy-souls" - - val playerReach = 5 - val playerReachSquared = playerReach * playerReach - - var currentLocationName: String? = null - var currentLocationSouls: List = emptyList() - var currentMissingSouls: List = emptyList() - - fun updateMissingSouls() { - currentMissingSouls = emptyList() - val c = DConfig.data ?: return - val fi = c.foundSouls[currentLocationName] ?: setOf() - val cms = currentLocationSouls.toMutableList() - fi.asSequence().sortedDescending().filter { it in cms.indices }.forEach { cms.removeAt(it) } - currentMissingSouls = cms - } - - fun updateWorldSouls() { - currentLocationSouls = emptyList() - val loc = currentLocationName ?: return - currentLocationSouls = RepoManager.neuRepo.constants.fairySouls.soulLocations[loc] ?: return - } - - fun findNearestClickableSoul(): Coordinate? { - val player = MC.player ?: return null - val pos = player.pos - val location = SBData.skyblockLocation ?: return null - val soulLocations: List = - RepoManager.neuRepo.constants.fairySouls.soulLocations[location] ?: return null - return soulLocations - .map { it to it.blockPos.getSquaredDistance(pos) } - .filter { it.second < playerReachSquared } - .minByOrNull { it.second } - ?.first - } - - private fun markNearestSoul() { - val nearestSoul = findNearestClickableSoul() ?: return - val c = DConfig.data ?: return - val loc = currentLocationName ?: return - val idx = currentLocationSouls.indexOf(nearestSoul) - c.foundSouls.computeIfAbsent(loc) { mutableSetOf() }.add(idx) - DConfig.markDirty() - updateMissingSouls() - } - - - override fun onLoad() { - SkyblockServerUpdateEvent.subscribe { - currentLocationName = it.newLocraw?.skyblockLocation - updateWorldSouls() - updateMissingSouls() - } - ServerChatLineReceivedEvent.subscribe { - when (it.text.unformattedString) { - "You have already found that Fairy Soul!" -> { - markNearestSoul() - } - - "SOUL! You found a Fairy Soul!" -> { - markNearestSoul() - } - } - } - WorldRenderLastEvent.subscribe { - if (!TConfig.displaySouls) return@subscribe - renderBlocks(it.matrices, it.camera) { - color(1F, 1F, 0F, 0.8F) - currentMissingSouls.forEach { - block(it.blockPos) - } - } - } - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/gui/ConfigGui.kt b/src/main/kotlin/moe/nea/notenoughupdates/gui/ConfigGui.kt deleted file mode 100644 index 06d0ad0..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/gui/ConfigGui.kt +++ /dev/null @@ -1,94 +0,0 @@ -package moe.nea.notenoughupdates.gui - -import io.github.cottonmc.cotton.gui.client.LightweightGuiDescription -import io.github.cottonmc.cotton.gui.widget.WButton -import io.github.cottonmc.cotton.gui.widget.WLabel -import io.github.cottonmc.cotton.gui.widget.WTextField -import io.github.cottonmc.cotton.gui.widget.WToggleButton -import io.github.cottonmc.cotton.gui.widget.data.HorizontalAlignment -import io.github.cottonmc.cotton.gui.widget.data.Insets -import io.github.cottonmc.cotton.gui.widget.data.VerticalAlignment -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.util.data.DataHolder -import net.minecraft.text.Text -import kotlin.reflect.KMutableProperty1 - -class ConfigGui(val holder: DataHolder, val build: ConfigGui.() -> Unit) : LightweightGuiDescription() { - private val root = WGridPanelWithPadding(verticalPadding = 4) - private val reloadables = mutableListOf<(() -> Unit)>() - - init { - setRootPanel(root) - root.insets = Insets.ROOT_PANEL - build() - reload() - } - - fun title(text: Text) { - if (col != 0) { - NotEnoughUpdates.logger.warn("Set title not at the top of the ConfigGui") - } - val label = WLabel(text) - label.verticalAlignment = VerticalAlignment.TOP - label.horizontalAlignment = HorizontalAlignment.CENTER - root.add(label, 0, col, 11, 1) - col++ - } - - private fun label(text: Text) { - val label = WLabel(text) - label.verticalAlignment = VerticalAlignment.CENTER - root.add(label, 0, col, 5, 1) - } - - fun toggle(text: Text, prop: KMutableProperty1) { - val toggle = WToggleButton(text) - reloadables.add { toggle.toggle = prop.get(holder.data) } - toggle.setOnToggle { - prop.set(holder.data, true) - holder.markDirty() - } - root.add(toggle, 5, col, 6, 1) - label(text) - col++ - } - - fun button(text: Text, buttonText: Text, runnable: () -> Unit) { - val button = WButton(buttonText) - button.setOnClick { - runnable.invoke() - } - root.add(button, 5, col, 6, 1) - label(text) - col++ - } - - fun textfield( - text: Text, - background: Text, - prop: KMutableProperty1, - maxLength: Int = 255 - ) { - val textfield = WTextField(background) - textfield.isEditable = true - reloadables.add { - textfield.text = prop.get(holder.data) - } - textfield.maxLength = maxLength - textfield.setChangedListener { - prop.set(holder.data, it) - holder.markDirty() - } - root.add(textfield, 5, col, 6, 11) - label(text) - col++ - } - - fun reload() { - reloadables.forEach { it.invoke() } - } - - private var col = 0 - - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/gui/WGridPanelWithPadding.kt b/src/main/kotlin/moe/nea/notenoughupdates/gui/WGridPanelWithPadding.kt deleted file mode 100644 index 287483e..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/gui/WGridPanelWithPadding.kt +++ /dev/null @@ -1,33 +0,0 @@ -package moe.nea.notenoughupdates.gui - -import io.github.cottonmc.cotton.gui.widget.WPanelWithInsets -import io.github.cottonmc.cotton.gui.widget.WWidget -import io.github.cottonmc.cotton.gui.widget.data.Insets - -class WGridPanelWithPadding( - val grid: Int = 18, - val verticalPadding: Int = 0, - val horizontalPadding: Int = 0, -) : WPanelWithInsets() { - - private inline val vertOffset get() = grid + verticalPadding - private inline val horiOffset get() = grid + horizontalPadding - - fun add(w: WWidget, x: Int, y: Int, width: Int = 1, height: Int = 1) { - children.add(w) - w.parent = this - w.setLocation(x * horiOffset + insets.left, y * vertOffset + insets.top) - if (w.canResize()) - w.setSize( - grid + (horiOffset * (width - 1)), - grid + (vertOffset * (height - 1)), - ) - expandToFit(w, insets) - } - - override fun setInsets(insets: Insets): WGridPanelWithPadding { - super.setInsets(insets) - return this - } - -} \ No newline at end of file diff --git a/src/main/kotlin/moe/nea/notenoughupdates/gui/repogui.kt b/src/main/kotlin/moe/nea/notenoughupdates/gui/repogui.kt deleted file mode 100644 index b2fba91..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/gui/repogui.kt +++ /dev/null @@ -1,36 +0,0 @@ -package moe.nea.notenoughupdates.gui - -import net.minecraft.text.Text -import moe.nea.notenoughupdates.repo.RepoManager - -fun repoGui(): ConfigGui { - return ConfigGui(RepoManager) { - title(Text.translatable("notenoughupdates.gui.repo.title")) - toggle(Text.translatable("notenoughupdates.gui.repo.autoupdate"), RepoManager.Config::autoUpdate) - textfield( - Text.translatable("notenoughupdates.gui.repo.username"), - Text.translatable("notenoughupdates.gui.repo.hint.username"), - RepoManager.Config::user, - maxLength = 255 - ) - textfield( - Text.translatable("notenoughupdates.gui.repo.reponame"), - Text.translatable("notenoughupdates.gui.repo.hint.reponame"), - RepoManager.Config::repo - ) - textfield( - Text.translatable("notenoughupdates.gui.repo.branch"), - Text.translatable("notenoughupdates.gui.repo.hint.branch"), - RepoManager.Config::branch - ) - button( - Text.translatable("notenoughupdates.gui.repo.reset.label"), - Text.translatable("notenoughupdates.gui.repo.reset"), - ) { - RepoManager.data.user = "NotEnoughUpdates" - RepoManager.data.repo = "NotEnoughUpdates-REPO" - RepoManager.data.branch = "dangerous" - reload() - } - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/hud/RepoDownloadProgress.kt b/src/main/kotlin/moe/nea/notenoughupdates/hud/RepoDownloadProgress.kt deleted file mode 100644 index 5ef6c5b..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/hud/RepoDownloadProgress.kt +++ /dev/null @@ -1,63 +0,0 @@ -package moe.nea.notenoughupdates.hud - -import io.github.cottonmc.cotton.gui.client.ScreenDrawing -import io.github.cottonmc.cotton.gui.widget.WWidget -import io.github.cottonmc.cotton.gui.widget.data.HorizontalAlignment -import io.github.cottonmc.cotton.gui.widget.data.Insets -import net.minecraft.client.util.math.MatrixStack -import kotlin.math.roundToInt -import kotlin.math.sin - - -val Insets.vertical get() = bottom + top -val Insets.horizontal get() = left + right - -class ProgressBar( - var label: String, - var total: Int?, // If total is null, then make it a bouncy rectangle - var progress: Int = 0, -) : WWidget() { - - var insets: Insets = Insets(7) - override fun canResize(): Boolean = true - - - fun reportProgress(label: String, progress: Int, total: Int?) { - synchronized(this) { - this.label = label - this.progress = progress - this.total = total - } - - } - - override fun paint(matrices: MatrixStack, x: Int, y: Int, mouseX: Int, mouseY: Int) { - ScreenDrawing.coloredRect(matrices, x, y, width, height, 0xFF808080.toInt()) - val (l, prog) = synchronized(this) { - label to (progress to total) - } - val (p, t) = prog - - if (t == null) { - ScreenDrawing.coloredRect( - matrices, - (x + (1 + sin(System.currentTimeMillis().toDouble() / 1000)) * width * 3 / 4 / 2).roundToInt(), - y, - width / 4, - height, - 0xFF00FF00.toInt() - ) - } else { - ScreenDrawing.coloredRect(matrices, x, y, width * p / t, height, 0xFF00FF00.toInt()) - } - ScreenDrawing.drawString( - matrices, - if (t != null) "$l ($p/$t)" else l, - HorizontalAlignment.CENTER, - x + insets.left, - y + insets.top, - width - insets.horizontal, - height - insets.vertical, - ) - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBCraftingRecipe.kt b/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBCraftingRecipe.kt deleted file mode 100644 index 9d7e9cc..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBCraftingRecipe.kt +++ /dev/null @@ -1,53 +0,0 @@ -package moe.nea.notenoughupdates.recipes - -import io.github.moulberry.repo.data.NEUCraftingRecipe -import io.github.moulberry.repo.data.NEUIngredient -import me.shedaniel.math.Point -import me.shedaniel.math.Rectangle -import me.shedaniel.rei.api.client.gui.Renderer -import me.shedaniel.rei.api.client.gui.widgets.Widget -import me.shedaniel.rei.api.client.gui.widgets.Widgets -import me.shedaniel.rei.api.client.registry.display.DisplayCategory -import me.shedaniel.rei.api.common.category.CategoryIdentifier -import me.shedaniel.rei.api.common.util.EntryStacks -import net.minecraft.block.Blocks -import net.minecraft.text.Text -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.rei.SBItemEntryDefinition - -class SBCraftingRecipe(override val neuRecipe: NEUCraftingRecipe) : SBRecipe() { - override fun getCategoryIdentifier(): CategoryIdentifier<*> = Category.catIdentifier - - object Category : DisplayCategory { - val catIdentifier = CategoryIdentifier.of(NotEnoughUpdates.MOD_ID, "crafing_recipe") - override fun getCategoryIdentifier(): CategoryIdentifier = catIdentifier - - override fun getTitle(): Text = Text.literal("SkyBlock Crafting") - - override fun getIcon(): Renderer = EntryStacks.of(Blocks.CRAFTING_TABLE) - override fun setupDisplay(display: SBCraftingRecipe, bounds: Rectangle): List { - val point = Point(bounds.centerX - 58, bounds.centerY - 27) - return buildList { - add(Widgets.createRecipeBase(bounds)) - add(Widgets.createArrow(Point(point.x + 60, point.y + 18))) - add(Widgets.createResultSlotBackground(Point(point.x + 95, point.y + 19))) - for (i in 0 until 3) { - for (j in 0 until 3) { - val slot = Widgets.createSlot(Point(point.x + 1 + i * 18, point.y + 1 + j * 18)).markInput() - add(slot) - val item = display.neuRecipe.inputs[i + j * 3] - if (item == NEUIngredient.SENTINEL_EMPTY) continue - slot.entry(SBItemEntryDefinition.getEntry(item)) // TODO: make use of stackable item entries - } - } - add( - Widgets.createSlot(Point(point.x + 95, point.y + 19)) - .entry(SBItemEntryDefinition.getEntry(display.neuRecipe.output)) - .disableBackground().markOutput() - ) - } - } - - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBForgeRecipe.kt b/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBForgeRecipe.kt deleted file mode 100644 index a9301ac..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBForgeRecipe.kt +++ /dev/null @@ -1,53 +0,0 @@ -package moe.nea.notenoughupdates.recipes - -import io.github.moulberry.repo.data.NEUForgeRecipe -import me.shedaniel.math.Point -import me.shedaniel.math.Rectangle -import me.shedaniel.rei.api.client.gui.Renderer -import me.shedaniel.rei.api.client.gui.widgets.Widget -import me.shedaniel.rei.api.client.gui.widgets.Widgets -import me.shedaniel.rei.api.client.registry.display.DisplayCategory -import me.shedaniel.rei.api.common.category.CategoryIdentifier -import me.shedaniel.rei.api.common.util.EntryStacks -import net.minecraft.block.Blocks -import net.minecraft.text.Text -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.rei.SBItemEntryDefinition - -class SBForgeRecipe(override val neuRecipe: NEUForgeRecipe) : SBRecipe() { - override fun getCategoryIdentifier(): CategoryIdentifier<*> = Category.categoryIdentifier - - object Category : DisplayCategory { - override fun getCategoryIdentifier(): CategoryIdentifier = - CategoryIdentifier.of(NotEnoughUpdates.MOD_ID, "forge_recipe") - - override fun getTitle(): Text = Text.literal("Forge Recipes") - override fun getDisplayHeight(): Int { - return super.getDisplayHeight() - } - - override fun getIcon(): Renderer = EntryStacks.of(Blocks.ANVIL) - override fun setupDisplay(display: SBForgeRecipe, bounds: Rectangle): List { - return buildList { - // TODO: proper gui for this (possibly inspired by the old circular gui) - add(Widgets.createRecipeBase(bounds)) - val resultSlot = Point(bounds.centerX, bounds.centerY + 5) - add(Widgets.createResultSlotBackground(resultSlot)) - val ingredientsCenter = Point(bounds.centerX, bounds.centerY - 20) - val count = display.neuRecipe.inputs.size - display.neuRecipe.inputs.forEachIndexed { idx, ingredient -> - add( - Widgets.createSlot( - Point(ingredientsCenter.x + 12 - count * 24 / 2 + idx * 24, ingredientsCenter.y) - ).markInput().entry(SBItemEntryDefinition.getEntry(ingredient)) - ) - } - add( - Widgets.createSlot(resultSlot).markOutput().disableBackground() - .entry(SBItemEntryDefinition.getEntry(display.neuRecipe.outputStack)) - ) - } - } - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBRecipe.kt b/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBRecipe.kt deleted file mode 100644 index 2e39d7e..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/recipes/SBRecipe.kt +++ /dev/null @@ -1,24 +0,0 @@ -package moe.nea.notenoughupdates.recipes - -import io.github.moulberry.repo.data.NEURecipe -import me.shedaniel.rei.api.common.display.Display -import me.shedaniel.rei.api.common.entry.EntryIngredient -import moe.nea.notenoughupdates.rei.SBItemEntryDefinition -import moe.nea.notenoughupdates.util.SkyblockId - -abstract class SBRecipe() : Display { - abstract val neuRecipe: NEURecipe - override fun getInputEntries(): List { - return neuRecipe.allInputs.map { - val entryStack = SBItemEntryDefinition.getEntry(SkyblockId(it.itemId)) - EntryIngredient.of(entryStack) - } - } - - override fun getOutputEntries(): List { - return neuRecipe.allOutputs.map { - val entryStack = SBItemEntryDefinition.getEntry(SkyblockId(it.itemId)) - EntryIngredient.of(entryStack) - } - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntryRenderer.kt b/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntryRenderer.kt deleted file mode 100644 index 111aaf7..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntryRenderer.kt +++ /dev/null @@ -1,31 +0,0 @@ -package moe.nea.notenoughupdates.rei - -import io.github.moulberry.repo.data.NEUItem -import me.shedaniel.math.Rectangle -import me.shedaniel.rei.api.client.entry.renderer.EntryRenderer -import me.shedaniel.rei.api.client.gui.widgets.Tooltip -import me.shedaniel.rei.api.client.gui.widgets.TooltipContext -import me.shedaniel.rei.api.common.entry.EntryStack -import net.minecraft.client.util.math.MatrixStack -import moe.nea.notenoughupdates.rei.NEUReiPlugin.Companion.asItemEntry - -object NEUItemEntryRenderer : EntryRenderer { - override fun render( - entry: EntryStack, - matrices: MatrixStack, - bounds: Rectangle, - mouseX: Int, - mouseY: Int, - delta: Float - ) { - matrices.push() - matrices.translate(0F, 0F, 100F) - entry.asItemEntry().render(matrices, bounds, mouseX, mouseY, delta) - matrices.pop() - } - - override fun getTooltip(entry: EntryStack, tooltipContext: TooltipContext): Tooltip? { - return entry.asItemEntry().getTooltip(tooltipContext, false) - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntrySerializer.kt b/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntrySerializer.kt deleted file mode 100644 index b6c81a7..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUItemEntrySerializer.kt +++ /dev/null @@ -1,25 +0,0 @@ -package moe.nea.notenoughupdates.rei - -import io.github.moulberry.repo.data.NEUItem -import me.shedaniel.rei.api.common.entry.EntrySerializer -import me.shedaniel.rei.api.common.entry.EntryStack -import net.minecraft.nbt.NbtCompound -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.SkyblockId - -object NEUItemEntrySerializer : EntrySerializer { - const val SKYBLOCK_ID_ENTRY = "SKYBLOCK_ID" - - override fun supportSaving(): Boolean = true - override fun supportReading(): Boolean = true - - override fun read(tag: NbtCompound): NEUItem? { - return RepoManager.getNEUItem(SkyblockId(tag.getString(SKYBLOCK_ID_ENTRY))) - } - - override fun save(entry: EntryStack, value: NEUItem?): NbtCompound { - return NbtCompound().apply { - putString(SKYBLOCK_ID_ENTRY, value?.skyblockItemId ?: "null") - } - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUReiPlugin.kt b/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUReiPlugin.kt deleted file mode 100644 index 34d98fa..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/rei/NEUReiPlugin.kt +++ /dev/null @@ -1,73 +0,0 @@ -package moe.nea.notenoughupdates.rei - -import io.github.moulberry.repo.data.NEUItem -import me.shedaniel.rei.api.client.plugins.REIClientPlugin -import me.shedaniel.rei.api.client.registry.category.CategoryRegistry -import me.shedaniel.rei.api.client.registry.display.DisplayRegistry -import me.shedaniel.rei.api.client.registry.entry.CollapsibleEntryRegistry -import me.shedaniel.rei.api.client.registry.entry.EntryRegistry -import me.shedaniel.rei.api.client.registry.screen.ScreenRegistry -import me.shedaniel.rei.api.common.entry.EntryStack -import me.shedaniel.rei.api.common.entry.type.EntryTypeRegistry -import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes -import net.minecraft.item.ItemStack -import net.minecraft.text.Text -import net.minecraft.util.Identifier -import moe.nea.notenoughupdates.recipes.SBCraftingRecipe -import moe.nea.notenoughupdates.recipes.SBForgeRecipe -import moe.nea.notenoughupdates.repo.ItemCache.asItemStack -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.SkyblockId - - -class NEUReiPlugin : REIClientPlugin { - - companion object { - fun EntryStack.asItemEntry(): EntryStack { - return EntryStack.of(VanillaEntryTypes.ITEM, value.asItemStack()) - } - - val SKYBLOCK_ITEM_TYPE_ID = Identifier("notenoughupdates", "skyblockitems") - } - - override fun registerEntryTypes(registry: EntryTypeRegistry) { - registry.register(SKYBLOCK_ITEM_TYPE_ID, SBItemEntryDefinition) - } - - override fun registerCategories(registry: CategoryRegistry) { - registry.add(SBCraftingRecipe.Category) - registry.add(SBForgeRecipe.Category) - } - - override fun registerDisplays(registry: DisplayRegistry) { - registry.registerDisplayGenerator( - SBCraftingRecipe.Category.catIdentifier, - SkyblockCraftingRecipeDynamicGenerator - ) - registry.registerDisplayGenerator( - SBForgeRecipe.Category.categoryIdentifier, - SkyblockForgeRecipeDynamicGenerator - ) - } - - override fun registerCollapsibleEntries(registry: CollapsibleEntryRegistry) { - RepoManager.neuRepo.constants.parents.parents - .forEach { (parent, children) -> - registry.group( - SkyblockId(parent).identifier, - Text.literal(RepoManager.getNEUItem(SkyblockId(parent))?.displayName ?: parent), - (children + parent).map { SBItemEntryDefinition.getEntry(RepoManager.getNEUItem(SkyblockId(it))) }) - } - } - - override fun registerScreens(registry: ScreenRegistry) { - registry.registerFocusedStack(SkyblockItemIdFocusedStackProvider) - } - - override fun registerEntries(registry: EntryRegistry) { - RepoManager.neuRepo.items?.items?.values?.forEach { - if (!it.isVanilla) - registry.addEntry(EntryStack.of(SBItemEntryDefinition, it)) - } - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/rei/SBItemEntryDefinition.kt b/src/main/kotlin/moe/nea/notenoughupdates/rei/SBItemEntryDefinition.kt deleted file mode 100644 index 0b43407..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/rei/SBItemEntryDefinition.kt +++ /dev/null @@ -1,85 +0,0 @@ -package moe.nea.notenoughupdates.rei - -import io.github.moulberry.repo.data.NEUIngredient -import io.github.moulberry.repo.data.NEUItem -import java.util.stream.Stream -import me.shedaniel.rei.api.client.entry.renderer.EntryRenderer -import me.shedaniel.rei.api.common.entry.EntrySerializer -import me.shedaniel.rei.api.common.entry.EntryStack -import me.shedaniel.rei.api.common.entry.comparison.ComparisonContext -import me.shedaniel.rei.api.common.entry.type.EntryDefinition -import me.shedaniel.rei.api.common.entry.type.EntryType -import me.shedaniel.rei.api.common.entry.type.VanillaEntryTypes -import net.minecraft.item.ItemStack -import net.minecraft.registry.tag.TagKey -import net.minecraft.text.Text -import net.minecraft.util.Identifier -import moe.nea.notenoughupdates.rei.NEUReiPlugin.Companion.asItemEntry -import moe.nea.notenoughupdates.repo.ItemCache.asItemStack -import moe.nea.notenoughupdates.repo.ItemCache.getIdentifier -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.SkyblockId - -// TODO: allow stackable entries -object SBItemEntryDefinition : EntryDefinition { - override fun equals(o1: NEUItem?, o2: NEUItem?, context: ComparisonContext?): Boolean { - return o1 === o2 - } - - override fun cheatsAs(entry: EntryStack?, value: NEUItem?): ItemStack { - return value.asItemStack() - } - - override fun getValueType(): Class = NEUItem::class.java - override fun getType(): EntryType = EntryType.deferred(NEUReiPlugin.SKYBLOCK_ITEM_TYPE_ID) - - override fun getRenderer(): EntryRenderer = NEUItemEntryRenderer - - override fun getSerializer(): EntrySerializer { - return NEUItemEntrySerializer - } - - override fun getTagsFor(entry: EntryStack?, value: NEUItem?): Stream>? { - return Stream.empty() - } - - override fun asFormattedText(entry: EntryStack, value: NEUItem): Text { - return VanillaEntryTypes.ITEM.definition.asFormattedText(entry.asItemEntry(), value.asItemStack()) - } - - override fun hash(entry: EntryStack, value: NEUItem?, context: ComparisonContext): Long { - // Repo items are immutable, and get replaced entirely when loaded from disk - return System.identityHashCode(value) * 31L - } - - override fun wildcard(entry: EntryStack?, value: NEUItem?): NEUItem? { - return value - } - - override fun normalize(entry: EntryStack?, value: NEUItem?): NEUItem? { - return value - } - - override fun copy(entry: EntryStack?, value: NEUItem?): NEUItem? { - return value - } - - override fun isEmpty(entry: EntryStack?, value: NEUItem?): Boolean { - return false - } - - override fun getIdentifier(entry: EntryStack?, value: NEUItem?): Identifier { - return value?.getIdentifier() ?: Identifier.of("skyblockitem", "null")!! - } - - fun getEntry(neuItem: NEUItem?): EntryStack = - EntryStack.of(this, neuItem) - - fun getEntry(skyblockId: SkyblockId?): EntryStack = - EntryStack.of(this, skyblockId?.let { RepoManager.getNEUItem(it) }) - - fun getEntry(ingredient: NEUIngredient?): EntryStack = - getEntry(ingredient?.itemId?.let { SkyblockId(it) }) - - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockCraftingRecipeDynamicGenerator.kt b/src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockCraftingRecipeDynamicGenerator.kt deleted file mode 100644 index cc31427..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockCraftingRecipeDynamicGenerator.kt +++ /dev/null @@ -1,52 +0,0 @@ -package moe.nea.notenoughupdates.rei - -import io.github.moulberry.repo.data.NEUCraftingRecipe -import io.github.moulberry.repo.data.NEUForgeRecipe -import io.github.moulberry.repo.data.NEUItem -import io.github.moulberry.repo.data.NEURecipe -import java.util.* -import me.shedaniel.rei.api.client.registry.display.DynamicDisplayGenerator -import me.shedaniel.rei.api.client.view.ViewSearchBuilder -import me.shedaniel.rei.api.common.display.Display -import me.shedaniel.rei.api.common.entry.EntryStack -import moe.nea.notenoughupdates.recipes.SBCraftingRecipe -import moe.nea.notenoughupdates.recipes.SBForgeRecipe -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.skyblockId - - -val SkyblockCraftingRecipeDynamicGenerator = neuDisplayGenerator { - SBCraftingRecipe(it) -} - -val SkyblockForgeRecipeDynamicGenerator = neuDisplayGenerator { - SBForgeRecipe(it) -} - -inline fun neuDisplayGenerator(noinline mapper: (T) -> D) = - object : DynamicDisplayGenerator { - override fun getRecipeFor(entry: EntryStack<*>): Optional> { - if (entry.type != SBItemEntryDefinition.type) return Optional.empty() - val item = entry.castValue() - val recipes = RepoManager.getRecipesFor(item.skyblockId) - val craftingRecipes = recipes.filterIsInstance() - return Optional.of(craftingRecipes.map(mapper)) - } - - override fun generate(builder: ViewSearchBuilder): Optional> { - if (SBCraftingRecipe.Category.catIdentifier !in builder.categories) return Optional.empty() - return Optional.of( - RepoManager.getAllRecipes().filterIsInstance().map(mapper) - .toList() - ) - } - - override fun getUsageFor(entry: EntryStack<*>): Optional> { - if (entry.type != SBItemEntryDefinition.type) return Optional.empty() - val item = entry.castValue() - val recipes = RepoManager.getUsagesFor(item.skyblockId) - val craftingRecipes = recipes.filterIsInstance() - return Optional.of(craftingRecipes.map(mapper)) - - } - } diff --git a/src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockItemIdFocusedStackProvider.kt b/src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockItemIdFocusedStackProvider.kt deleted file mode 100644 index 8592126..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/rei/SkyblockItemIdFocusedStackProvider.kt +++ /dev/null @@ -1,25 +0,0 @@ -package moe.nea.notenoughupdates.rei - -import dev.architectury.event.CompoundEventResult -import me.shedaniel.math.Point -import me.shedaniel.rei.api.client.registry.screen.FocusedStackProvider -import me.shedaniel.rei.api.common.entry.EntryStack -import moe.nea.notenoughupdates.mixins.accessor.AccessorHandledScreen -import moe.nea.notenoughupdates.repo.RepoManager -import moe.nea.notenoughupdates.util.skyBlockId -import net.minecraft.client.gui.screen.Screen -import net.minecraft.client.gui.screen.ingame.HandledScreen - -object SkyblockItemIdFocusedStackProvider : FocusedStackProvider { - override fun provide(screen: Screen?, mouse: Point?): CompoundEventResult> { - if (screen !is HandledScreen<*>) return CompoundEventResult.pass() - screen as AccessorHandledScreen - val focusedSlot = screen.focusedSlot_NEU ?: return CompoundEventResult.pass() - val item = focusedSlot.stack ?: return CompoundEventResult.pass() - val skyblockId = item.skyBlockId ?: return CompoundEventResult.pass() - val neuItem = RepoManager.getNEUItem(skyblockId) ?: return CompoundEventResult.interrupt(false, null) - return CompoundEventResult.interruptTrue(EntryStack.of(SBItemEntryDefinition, neuItem)) - } - - override fun getPriority(): Double = 1_000_000.0 -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/repo/ItemCache.kt b/src/main/kotlin/moe/nea/notenoughupdates/repo/ItemCache.kt deleted file mode 100644 index ae2b7d2..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/repo/ItemCache.kt +++ /dev/null @@ -1,123 +0,0 @@ -package moe.nea.notenoughupdates.repo - -import com.mojang.serialization.Dynamic -import io.github.cottonmc.cotton.gui.client.CottonHud -import io.github.moulberry.repo.IReloadable -import io.github.moulberry.repo.NEURepository -import io.github.moulberry.repo.data.NEUItem -import java.io.PrintWriter -import java.nio.file.Path -import java.util.concurrent.ConcurrentHashMap -import kotlinx.coroutines.Job -import kotlinx.coroutines.launch -import kotlin.io.path.absolutePathString -import kotlin.io.path.writer -import net.minecraft.SharedConstants -import net.minecraft.client.resource.language.I18n -import net.minecraft.datafixer.Schemas -import net.minecraft.datafixer.TypeReferences -import net.minecraft.item.ItemStack -import net.minecraft.item.Items -import net.minecraft.nbt.NbtCompound -import net.minecraft.nbt.NbtOps -import net.minecraft.text.Text -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.util.LegacyTagParser -import moe.nea.notenoughupdates.util.appendLore -import moe.nea.notenoughupdates.util.skyblockId - -object ItemCache : IReloadable { - val dfuLog = Path.of("logs/dfulog.txt") - private val cache: MutableMap = ConcurrentHashMap() - private val df = Schemas.getFixer() - private val dfuHandle = PrintWriter(dfuLog.writer()) - var isFlawless = true - private set - - private fun NEUItem.get10809CompoundTag(): NbtCompound = NbtCompound().apply { - put("tag", LegacyTagParser.parse(nbttag)) - putString("id", minecraftItemId) - putByte("Count", 1) - putShort("Damage", damage.toShort()) - } - - private fun NbtCompound.transformFrom10809ToModern(): NbtCompound? = - try { - df.update( - TypeReferences.ITEM_STACK, - Dynamic(NbtOps.INSTANCE, this), - -1, - SharedConstants.getGameVersion().saveVersion.id - ).value as NbtCompound - } catch (e: Exception) { - if (isFlawless) - NotEnoughUpdates.logger.error("Failed to run data fixer an item. Check ${dfuLog.absolutePathString()} for more information") - isFlawless = false - e.printStackTrace(dfuHandle) - null - } - - fun brokenItemStack(neuItem: NEUItem?): ItemStack { - return ItemStack(Items.PAINTING).apply { - setCustomName(Text.literal(neuItem?.displayName ?: "null")) - appendLore(listOf(Text.translatable("notenoughupdates.repo.brokenitem", neuItem?.skyblockItemId))) - } - } - - private fun NEUItem.asItemStackNow(): ItemStack { - try { - val oldItemTag = get10809CompoundTag() - val modernItemTag = oldItemTag.transformFrom10809ToModern() - ?: return brokenItemStack(this) - val itemInstance = ItemStack.fromNbt(modernItemTag) - if (itemInstance.nbt?.contains("Enchantments") == true) { - itemInstance.enchantments.add(NbtCompound()) - } - return itemInstance - } catch (e: Exception) { - e.printStackTrace() - return brokenItemStack(this) - } - } - - fun NEUItem?.asItemStack(): ItemStack { - if (this == null) return brokenItemStack(null) - var s = cache[this.skyblockItemId] - if (s == null) { - s = asItemStackNow() - cache[this.skyblockItemId] = s - } - return s - } - - fun NEUItem.getIdentifier() = skyblockId.identifier - - - var job: Job? = null - - override fun reload(repository: NEURepository) { - val j = job - if (j != null && j.isActive) { - j.cancel() - } - cache.clear() - isFlawless = true - - job = NotEnoughUpdates.coroutineScope.launch { - val items = repository.items?.items - if (items == null) { - CottonHud.remove(RepoManager.progressBar) - return@launch - } - val recacheItems = I18n.translate("notenoughupdates.repo.cache") - RepoManager.progressBar.reportProgress(recacheItems, 0, items.size) - CottonHud.add(RepoManager.progressBar) - var i = 0 - items.values.forEach { - it.asItemStack() // Rebuild cache - RepoManager.progressBar.reportProgress(recacheItems, i++, items.size) - } - CottonHud.remove(RepoManager.progressBar) - } - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/repo/RepoDownloadManager.kt b/src/main/kotlin/moe/nea/notenoughupdates/repo/RepoDownloadManager.kt deleted file mode 100644 index 34b49e7..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/repo/RepoDownloadManager.kt +++ /dev/null @@ -1,118 +0,0 @@ -package moe.nea.notenoughupdates.repo - -import io.ktor.client.call.* -import io.ktor.client.request.* -import io.ktor.client.statement.* -import io.ktor.utils.io.jvm.nio.* -import kotlinx.coroutines.CoroutineName -import kotlinx.coroutines.Dispatchers.IO -import kotlinx.coroutines.withContext -import kotlinx.serialization.Serializable -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.NotEnoughUpdates.logger -import moe.nea.notenoughupdates.util.iterate -import java.io.IOException -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardOpenOption -import java.util.zip.ZipInputStream -import kotlin.io.path.* - - -object RepoDownloadManager { - - val repoSavedLocation = NotEnoughUpdates.DATA_DIR.resolve("repo-extracted") - val repoMetadataLocation = NotEnoughUpdates.DATA_DIR.resolve("loaded-repo-sha.txt") - - private fun loadSavedVersionHash(): String? = - if (repoSavedLocation.exists()) { - if (repoMetadataLocation.exists()) { - try { - repoMetadataLocation.readText().trim() - } catch (e: IOException) { - null - } - } else { - null - } - } else null - - private fun saveVersionHash(versionHash: String) { - latestSavedVersionHash = versionHash - repoMetadataLocation.writeText(versionHash) - } - - var latestSavedVersionHash: String? = loadSavedVersionHash() - private set - - @Serializable - private class GithubCommitsResponse(val sha: String) - - private suspend fun requestLatestGithubSha(): String? { - val response = - NotEnoughUpdates.httpClient.get("https://api.github.com/repos/${RepoManager.data.user}/${RepoManager.data.repo}/commits/${RepoManager.data.branch}") - if (response.status.value != 200) { - return null - } - return response.body().sha - } - - private suspend fun downloadGithubArchive(url: String): Path = withContext(IO) { - val response = NotEnoughUpdates.httpClient.get(url) - val targetFile = Files.createTempFile("notenoughupdates-repo", ".zip") - val outputChannel = Files.newByteChannel(targetFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE) - response.bodyAsChannel().copyTo(outputChannel) - targetFile - } - - /** - * Downloads the latest repository from github, setting [latestSavedVersionHash]. - * @return true, if an update was performed, false, otherwise (no update needed, or wasn't able to complete update) - */ - suspend fun downloadUpdate(force: Boolean): Boolean = withContext(CoroutineName("Repo Update Check")) { - val latestSha = requestLatestGithubSha() - if (latestSha == null) { - logger.warn("Could not request github API to retrieve latest REPO sha.") - return@withContext false - } - val currentSha = loadSavedVersionHash() - if (latestSha != currentSha || force) { - val requestUrl = "https://github.com/${RepoManager.data.user}/${RepoManager.data.repo}/archive/$latestSha.zip" - logger.info("Planning to upgrade repository from $currentSha to $latestSha from $requestUrl") - val zipFile = downloadGithubArchive(requestUrl) - logger.info("Download repository zip file to $zipFile. Deleting old repository") - withContext(IO) { repoSavedLocation.toFile().deleteRecursively() } - logger.info("Extracting new repository") - withContext(IO) { extractNewRepository(zipFile) } - logger.info("Repository loaded on disk.") - saveVersionHash(latestSha) - return@withContext true - } else { - logger.debug("Repository on latest sha $currentSha. Not performing update") - return@withContext false - } - } - - private fun extractNewRepository(zipFile: Path) { - repoSavedLocation.createDirectories() - ZipInputStream(zipFile.inputStream()).use { cis -> - while (true) { - val entry = cis.nextEntry ?: break - if (entry.isDirectory) continue - val extractedLocation = - repoSavedLocation.resolve( - entry.name.substringAfter('/', missingDelimiterValue = "") - ) - if (repoSavedLocation !in extractedLocation.iterate { it.parent }) { - logger.error("Not Enough Updates detected an invalid zip file. This is a potential security risk, please report this in the Moulberry discord.") - throw RuntimeException("Not Enough Updates detected an invalid zip file. This is a potential security risk, please report this in the Moulberry discord.") - } - extractedLocation.parent.createDirectories() - cis.copyTo(extractedLocation.outputStream()) - cis.closeEntry() - } - } - } - - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/repo/RepoManager.kt b/src/main/kotlin/moe/nea/notenoughupdates/repo/RepoManager.kt deleted file mode 100644 index acaaacd..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/repo/RepoManager.kt +++ /dev/null @@ -1,102 +0,0 @@ -package moe.nea.notenoughupdates.repo - -import io.github.cottonmc.cotton.gui.client.CottonHud -import io.github.moulberry.repo.NEURecipeCache -import io.github.moulberry.repo.NEURepository -import io.github.moulberry.repo.NEURepositoryException -import io.github.moulberry.repo.data.NEURecipe -import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents -import kotlinx.coroutines.launch -import kotlinx.serialization.Serializable -import kotlinx.serialization.serializer -import net.minecraft.client.MinecraftClient -import net.minecraft.network.packet.s2c.play.SynchronizeRecipesS2CPacket -import net.minecraft.text.Text -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.NotEnoughUpdates.logger -import moe.nea.notenoughupdates.hud.ProgressBar -import moe.nea.notenoughupdates.util.SkyblockId -import moe.nea.notenoughupdates.util.data.DataHolder - -object RepoManager : DataHolder(serializer(), "repo", ::Config) { - @Serializable - data class Config( - var user: String = "NotEnoughUpdates", - var repo: String = "NotEnoughUpdates-REPO", - var autoUpdate: Boolean = true, - var branch: String = "dangerous", - ) - - val currentDownloadedSha by RepoDownloadManager::latestSavedVersionHash - - var recentlyFailedToUpdateItemList = false - - val progressBar = ProgressBar("", null, 0).also { - it.setSize(180, 22) - } - - val neuRepo: NEURepository = NEURepository.of(RepoDownloadManager.repoSavedLocation).apply { - registerReloadListener(ItemCache) - registerReloadListener { - if (!trySendClientboundUpdateRecipesPacket()) { - logger.warn("Failed to issue a ClientboundUpdateRecipesPacket (to reload REI). This may lead to an outdated item list.") - recentlyFailedToUpdateItemList = true - } - } - } - - private val recipeCache = NEURecipeCache.forRepo(neuRepo) - - fun getAllRecipes() = neuRepo.items.items.values.asSequence().flatMap { it.recipes } - - fun getRecipesFor(skyblockId: SkyblockId): Set = recipeCache.recipes[skyblockId.neuItem] ?: setOf() - fun getUsagesFor(skyblockId: SkyblockId): Set = recipeCache.usages[skyblockId.neuItem] ?: setOf() - - private fun trySendClientboundUpdateRecipesPacket(): Boolean { - return MinecraftClient.getInstance().world != null && MinecraftClient.getInstance().networkHandler?.onSynchronizeRecipes( - SynchronizeRecipesS2CPacket(mutableListOf()) - ) != null - } - - init { - ClientTickEvents.START_WORLD_TICK.register(ClientTickEvents.StartWorldTick { - if (recentlyFailedToUpdateItemList && trySendClientboundUpdateRecipesPacket()) - recentlyFailedToUpdateItemList = false - }) - } - - fun getNEUItem(skyblockId: SkyblockId) = neuRepo.items.getItemBySkyblockId(skyblockId.neuItem) - - fun launchAsyncUpdate(force: Boolean = false) { - NotEnoughUpdates.coroutineScope.launch { - progressBar.reportProgress("Downloading", 0, null) - CottonHud.add(progressBar) - RepoDownloadManager.downloadUpdate(force) - progressBar.reportProgress("Download complete", 1, 1) - reload() - } - } - - fun reload() { - try { - progressBar.reportProgress("Reloading from Disk", 0, null) - CottonHud.add(progressBar) - neuRepo.reload() - } catch (exc: NEURepositoryException) { - MinecraftClient.getInstance().player?.sendMessage( - Text.literal("Failed to reload repository. This will result in some mod features not working.") - ) - CottonHud.remove(progressBar) - exc.printStackTrace() - } - } - - fun initialize() { - if (data.autoUpdate) { - launchAsyncUpdate() - } else { - reload() - } - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/ItemUtil.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/ItemUtil.kt deleted file mode 100644 index 2fbff87..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/ItemUtil.kt +++ /dev/null @@ -1,24 +0,0 @@ -package moe.nea.notenoughupdates.util - -import net.minecraft.item.ItemStack -import net.minecraft.nbt.NbtCompound -import net.minecraft.nbt.NbtList -import net.minecraft.nbt.NbtString -import net.minecraft.text.Text - - -fun ItemStack.appendLore(args: List) { - val compoundTag = getOrCreateSubNbt("display") - val loreList = compoundTag.getOrCreateList("Lore", NbtString.STRING_TYPE) - for (arg in args) { - loreList.add(NbtString.of(Text.Serializer.toJson(arg))) - } -} - -fun NbtCompound.getOrCreateList(label: String, tag: Byte): NbtList = getList(label, tag.toInt()).also { - put(label, it) -} - -fun NbtCompound.getOrCreateCompoundTag(label: String): NbtCompound = getCompound(label).also { - put(label, it) -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/LegacyTagParser.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/LegacyTagParser.kt deleted file mode 100644 index 9f3379b..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/LegacyTagParser.kt +++ /dev/null @@ -1,243 +0,0 @@ -package moe.nea.notenoughupdates.util - -import java.util.* -import net.minecraft.nbt.AbstractNbtNumber -import net.minecraft.nbt.NbtByte -import net.minecraft.nbt.NbtCompound -import net.minecraft.nbt.NbtDouble -import net.minecraft.nbt.NbtElement -import net.minecraft.nbt.NbtFloat -import net.minecraft.nbt.NbtInt -import net.minecraft.nbt.NbtList -import net.minecraft.nbt.NbtLong -import net.minecraft.nbt.NbtShort -import net.minecraft.nbt.NbtString - -class LegacyTagParser private constructor(string: String) { - data class TagParsingException(val baseString: String, val offset: Int, val mes0: String) : - Exception("$mes0 at $offset in `$baseString`.") - - class StringRacer(val backing: String) { - var idx = 0 - val stack = Stack() - - fun pushState() { - stack.push(idx) - } - - fun popState() { - idx = stack.pop() - } - - fun discardState() { - stack.pop() - } - - fun peek(count: Int): String { - return backing.substring(minOf(idx, backing.length), minOf(idx + count, backing.length)) - } - - fun finished(): Boolean { - return peek(1).isEmpty() - } - - fun peekReq(count: Int): String? { - val p = peek(count) - if (p.length != count) - return null - return p - } - - fun consumeCountReq(count: Int): String? { - val p = peekReq(count) - if (p != null) - idx += count - return p - } - - fun tryConsume(string: String): Boolean { - val p = peek(string.length) - if (p != string) - return false - idx += p.length - return true - } - - fun consumeWhile(shouldConsumeThisString: (String) -> Boolean): String { - var lastString: String = "" - while (true) { - val nextString = lastString + peek(1) - if (!shouldConsumeThisString(nextString)) { - return lastString - } - idx++ - lastString = nextString - } - } - - fun expect(search: String, errorMessage: String) { - if (!tryConsume(search)) - error(errorMessage) - } - - fun error(errorMessage: String): Nothing { - throw TagParsingException(backing, idx, errorMessage) - } - - } - - val racer = StringRacer(string) - val baseTag = parseTag() - - companion object { - val digitRange = "0123456789-" - fun parse(string: String): NbtCompound { - return LegacyTagParser(string).baseTag - } - } - - fun skipWhitespace() { - racer.consumeWhile { Character.isWhitespace(it.last()) } // Only check last since other chars are always checked before. - } - - fun parseTag(): NbtCompound { - skipWhitespace() - racer.expect("{", "Expected '{’ at start of tag") - skipWhitespace() - val tag = NbtCompound() - while (!racer.tryConsume("}")) { - skipWhitespace() - val lhs = parseIdentifier() - skipWhitespace() - racer.expect(":", "Expected ':' after identifier in tag") - skipWhitespace() - val rhs = parseAny() - tag.put(lhs, rhs) - racer.tryConsume(",") - skipWhitespace() - } - return tag - } - - private fun parseAny(): NbtElement { - skipWhitespace() - val nextChar = racer.peekReq(1) ?: racer.error("Expected new object, found EOF") - return when { - nextChar == "{" -> parseTag() - nextChar == "[" -> parseList() - nextChar == "\"" -> parseStringTag() - nextChar.first() in (digitRange) -> parseNumericTag() - else -> racer.error("Unexpected token found. Expected start of new element") - } - } - - fun parseList(): NbtList { - skipWhitespace() - racer.expect("[", "Expected '[' at start of tag") - skipWhitespace() - val list = NbtList() - while (!racer.tryConsume("]")) { - skipWhitespace() - racer.pushState() - val lhs = racer.consumeWhile { it.all { it in digitRange } } - skipWhitespace() - if (!racer.tryConsume(":") || lhs.isEmpty()) { // No prefixed 0: - racer.popState() - list.add(parseAny()) // Reparse our number (or not a number) as actual tag - } else { - racer.discardState() - skipWhitespace() - list.add(parseAny()) // Ignore prefix indexes. They should not be generated out of order by any vanilla implementation (which is what NEU should export). Instead append where it appears in order. - } - skipWhitespace() - racer.tryConsume(",") - } - return list - } - - fun parseQuotedString(): String { - skipWhitespace() - racer.expect("\"", "Expected '\"' at string start") - val sb = StringBuilder() - while (true) { - when (val peek = racer.consumeCountReq(1)) { - "\"" -> break - "\\" -> { - val escaped = racer.consumeCountReq(1) ?: racer.error("Unfinished backslash escape") - if (escaped != "\"" && escaped != "\\") { - // Surprisingly i couldn't find unicode escapes to be generated by the original minecraft 1.8.9 implementation - racer.idx-- - racer.error("Invalid backslash escape '$escaped'") - } - sb.append(escaped) - } - - null -> racer.error("Unfinished string") - else -> { - sb.append(peek) - } - } - } - return sb.toString() - } - - fun parseStringTag(): NbtString { - return NbtString.of(parseQuotedString()) - } - - object Patterns { - val DOUBLE = "([-+]?[0-9]*\\.?[0-9]+)[d|D]".toRegex() - val FLOAT = "([-+]?[0-9]*\\.?[0-9]+)[f|F]".toRegex() - val BYTE = "([-+]?[0-9]+)[b|B]".toRegex() - val LONG = "([-+]?[0-9]+)[l|L]".toRegex() - val SHORT = "([-+]?[0-9]+)[s|S]".toRegex() - val INTEGER = "([-+]?[0-9]+)".toRegex() - val DOUBLE_UNTYPED = "([-+]?[0-9]*\\.?[0-9]+)".toRegex() - val ROUGH_PATTERN = "[-+]?[0-9]*\\.?[0-9]*[dDbBfFlLsS]?".toRegex() - } - - fun parseNumericTag(): AbstractNbtNumber { - skipWhitespace() - val textForm = racer.consumeWhile { Patterns.ROUGH_PATTERN.matchEntire(it) != null } - if (textForm.isEmpty()) { - racer.error("Expected numeric tag (starting with either -, +, . or a digit") - } - val doubleMatch = Patterns.DOUBLE.matchEntire(textForm) ?: Patterns.DOUBLE_UNTYPED.matchEntire(textForm) - if (doubleMatch != null) { - return NbtDouble.of(doubleMatch.groups[1]!!.value.toDouble()) - } - val floatMatch = Patterns.FLOAT.matchEntire(textForm) - if (floatMatch != null) { - return NbtFloat.of(floatMatch.groups[1]!!.value.toFloat()) - } - val byteMatch = Patterns.BYTE.matchEntire(textForm) - if (byteMatch != null) { - return NbtByte.of(byteMatch.groups[1]!!.value.toByte()) - } - val longMatch = Patterns.LONG.matchEntire(textForm) - if (longMatch != null) { - return NbtLong.of(longMatch.groups[1]!!.value.toLong()) - } - val shortMatch = Patterns.SHORT.matchEntire(textForm) - if (shortMatch != null) { - return NbtShort.of(shortMatch.groups[1]!!.value.toShort()) - } - val integerMatch = Patterns.INTEGER.matchEntire(textForm) - if (integerMatch != null) { - return NbtInt.of(integerMatch.groups[1]!!.value.toInt()) - } - throw IllegalStateException("Could not properly parse numeric tag '$textForm', despite passing rough verification. This is a bug in the LegacyTagParser") - } - - private fun parseIdentifier(): String { - skipWhitespace() - if (racer.peek(1) == "\"") { - return parseQuotedString() - } - return racer.consumeWhile { - val x = it.last() - x != ':' && !Character.isWhitespace(x) - } - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/Locraw.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/Locraw.kt deleted file mode 100644 index 400842f..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/Locraw.kt +++ /dev/null @@ -1,8 +0,0 @@ -package moe.nea.notenoughupdates.util - -import kotlinx.serialization.Serializable - -@Serializable -data class Locraw(val server: String, val gametype: String? = null, val mode: String? = null, val map: String? = null) { - val skyblockLocation = if (gametype == "SKYBLOCK") mode else null -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/MC.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/MC.kt deleted file mode 100644 index 956a330..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/MC.kt +++ /dev/null @@ -1,13 +0,0 @@ -package moe.nea.notenoughupdates.util - -import io.github.moulberry.repo.data.Coordinate -import net.minecraft.client.MinecraftClient -import net.minecraft.util.math.BlockPos - -object MC { - inline val player get() = MinecraftClient.getInstance().player - inline val world get() = MinecraftClient.getInstance().world -} - -val Coordinate.blockPos: BlockPos - get() = BlockPos(x, y, z) diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/MinecraftDispatcher.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/MinecraftDispatcher.kt deleted file mode 100644 index 366b81a..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/MinecraftDispatcher.kt +++ /dev/null @@ -1,22 +0,0 @@ -package moe.nea.notenoughupdates.util - -import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.Runnable -import kotlin.coroutines.CoroutineContext -import net.minecraft.client.MinecraftClient - -object MinecraftDispatcher : CoroutineDispatcher() { - @ExperimentalCoroutinesApi - override fun limitedParallelism(parallelism: Int): CoroutineDispatcher { - throw UnsupportedOperationException("limitedParallelism is not supported for MinecraftDispatcher") - } - - override fun isDispatchNeeded(context: CoroutineContext): Boolean = - !MinecraftClient.getInstance().isOnThread - - - override fun dispatch(context: CoroutineContext, block: Runnable) { - MinecraftClient.getInstance().execute(block) - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/SBData.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/SBData.kt deleted file mode 100644 index 393cdbb..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/SBData.kt +++ /dev/null @@ -1,64 +0,0 @@ -package moe.nea.notenoughupdates.util - -import kotlinx.serialization.SerializationException -import kotlinx.serialization.decodeFromString -import kotlin.time.Duration -import kotlin.time.Duration.Companion.seconds -import kotlin.time.ExperimentalTime -import kotlin.time.TimeSource -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.events.ServerChatLineReceivedEvent -import moe.nea.notenoughupdates.events.SkyblockServerUpdateEvent -import moe.nea.notenoughupdates.events.WorldReadyEvent - -object SBData { - val profileRegex = "(?:Your profile was changed to: |You are playing on profile: )(.+)".toRegex() - var profileCuteName: String? = null - - private var lastLocrawSent = Timer() - private val locrawRoundtripTime: Duration = 5.seconds - var locraw: Locraw? = null - val skyblockLocation get() = locraw?.skyblockLocation - - - fun init() { - ServerChatLineReceivedEvent.subscribe { event -> - val profileMatch = profileRegex.matchEntire(event.unformattedString) - if (profileMatch != null) { - profileCuteName = profileMatch.groupValues[1] - } - if (event.unformattedString.startsWith("{")) { - if (tryReceiveLocraw(event.unformattedString) && lastLocrawSent.timePassed() < locrawRoundtripTime) { - lastLocrawSent.markFarPast() - event.cancel() - } - } - } - - WorldReadyEvent.subscribe { - sendLocraw() - locraw = null - } - } - - private fun tryReceiveLocraw(unformattedString: String): Boolean = try { - val lastLocraw = locraw - locraw = NotEnoughUpdates.json.decodeFromString(unformattedString) - SkyblockServerUpdateEvent.publish(SkyblockServerUpdateEvent(lastLocraw, locraw)) - true - } catch (e: SerializationException) { - e.printStackTrace() - false - } catch (e: IllegalArgumentException) { - e.printStackTrace() - false - } - - fun sendLocraw() { - lastLocrawSent.markNow() - val nh = MC.player?.networkHandler ?: return - nh.sendChatCommand("locraw") - } - - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/ScreenUtil.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/ScreenUtil.kt deleted file mode 100644 index 6c86c41..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/ScreenUtil.kt +++ /dev/null @@ -1,36 +0,0 @@ -package moe.nea.notenoughupdates.util - -import moe.nea.notenoughupdates.NotEnoughUpdates -import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents -import net.minecraft.client.MinecraftClient -import net.minecraft.client.gui.screen.Screen - -object ScreenUtil { - init { - ClientTickEvents.START_CLIENT_TICK.register(::onTick) - } - - private fun onTick(minecraft: MinecraftClient) { - if (nextOpenedGui != null) { - val p = minecraft.player - if (p?.currentScreenHandler != null) { - p.closeHandledScreen() - } - minecraft.setScreen(nextOpenedGui) - nextOpenedGui = null - } - } - - private var nextOpenedGui: Screen? = null - - fun setScreenLater(nextScreen: Screen) { - val nog = nextOpenedGui - if (nog != null) { - NotEnoughUpdates.logger.warn("Setting screen ${nextScreen::class.qualifiedName} to be opened later, but ${nog::class.qualifiedName} is already queued.") - return - } - nextOpenedGui = nextScreen - } - - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/SequenceUtil.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/SequenceUtil.kt deleted file mode 100644 index 3e338bd..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/SequenceUtil.kt +++ /dev/null @@ -1,9 +0,0 @@ -package moe.nea.notenoughupdates.util - -fun T.iterate(iterator: (T) -> T?): Sequence = sequence { - var x: T? = this@iterate - while (x != null) { - yield(x) - x = iterator(x) - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/SkyblockId.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/SkyblockId.kt deleted file mode 100644 index 7c6c391..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/SkyblockId.kt +++ /dev/null @@ -1,48 +0,0 @@ -package moe.nea.notenoughupdates.util - -import io.github.moulberry.repo.data.NEUItem -import io.github.moulberry.repo.data.Rarity -import kotlinx.serialization.Serializable -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json -import net.minecraft.item.ItemStack -import net.minecraft.nbt.NbtCompound -import net.minecraft.util.Identifier - -@JvmInline -value class SkyblockId(val neuItem: String) { - val identifier get() = Identifier("skyblockitem", neuItem.lowercase().replace(";", "__")) -} - -val NEUItem.skyblockId get() = SkyblockId(skyblockItemId) - -@Serializable -data class HypixelPetInfo( - val type: String, - val tier: Rarity, -) { - val skyblockId get() = SkyblockId("${type.uppercase()};${tier.ordinal}") -} - -private val jsonparser = Json { ignoreUnknownKeys = true } - -val ItemStack.extraAttributes: NbtCompound - get() = getOrCreateSubNbt("ExtraAttributes") - -val ItemStack.skyBlockId: SkyblockId? - get() { - when (val id = extraAttributes.getString("id")) { - "PET" -> { - val jsonString = extraAttributes.getString("petInfo") - if (jsonString.isNullOrBlank()) return null - val petInfo = - runCatching { jsonparser.decodeFromString(jsonString) } - .getOrElse { return null } - return petInfo.skyblockId - } - // TODO: RUNE, ENCHANTED_BOOK, PARTY_HAT_CRAB{,_ANIMATED}, ABICASE - else -> { - return SkyblockId(id) - } - } - } diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/TimeMark.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/TimeMark.kt deleted file mode 100644 index 5196606..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/TimeMark.kt +++ /dev/null @@ -1,15 +0,0 @@ -package moe.nea.notenoughupdates.util - -import kotlin.time.Duration -import kotlin.time.ExperimentalTime -import kotlin.time.TimeSource - -@OptIn(ExperimentalTime::class) -class TimeMark private constructor(private val timeMark: TimeSource.Monotonic.ValueTimeMark?) { - fun passedTime() = timeMark?.elapsedNow() ?: Duration.INFINITE - - companion object { - fun now() = TimeMark(TimeSource.Monotonic.markNow()) - fun farPast() = TimeMark(null) - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/Timer.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/Timer.kt deleted file mode 100644 index 14f76f7..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/Timer.kt +++ /dev/null @@ -1,23 +0,0 @@ -package moe.nea.notenoughupdates.util - -import kotlin.time.Duration -import kotlin.time.ExperimentalTime -import kotlin.time.TimeSource - -@OptIn(ExperimentalTime::class) -class Timer { - private var mark: TimeSource.Monotonic.ValueTimeMark? = null - - fun timePassed(): Duration { - return mark?.elapsedNow() ?: Duration.INFINITE - } - - fun markNow() { - mark = TimeSource.Monotonic.markNow() - } - - fun markFarPast() { - mark = null - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/config/ManagedConfig.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/config/ManagedConfig.kt deleted file mode 100644 index a149bf2..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/config/ManagedConfig.kt +++ /dev/null @@ -1,206 +0,0 @@ -package moe.nea.notenoughupdates.util.config - -import io.github.cottonmc.cotton.gui.client.CottonClientScreen -import io.github.cottonmc.cotton.gui.client.LibGui -import io.github.cottonmc.cotton.gui.client.LightweightGuiDescription -import io.github.cottonmc.cotton.gui.widget.WButton -import io.github.cottonmc.cotton.gui.widget.WLabel -import io.github.cottonmc.cotton.gui.widget.WToggleButton -import io.github.cottonmc.cotton.gui.widget.WWidget -import io.github.cottonmc.cotton.gui.widget.data.Insets -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.boolean -import kotlinx.serialization.json.jsonPrimitive -import kotlin.io.path.createDirectories -import kotlin.io.path.readText -import kotlin.io.path.writeText -import kotlin.properties.ReadOnlyProperty -import kotlin.reflect.KProperty -import net.minecraft.client.MinecraftClient -import net.minecraft.text.Text -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.gui.WGridPanelWithPadding -import moe.nea.notenoughupdates.util.ScreenUtil.setScreenLater - -abstract class ManagedConfig(val name: String) { - - class GuiAppender(val width: Int) { - private var row = 0 - internal val panel = WGridPanelWithPadding(verticalPadding = 4, horizontalPadding = 4) - internal val reloadables = mutableListOf<(() -> Unit)>() - fun set(x: Int, y: Int, w: Int, h: Int, widget: WWidget) { - panel.add(widget, x, y, w, h) - } - - - fun onReload(reloadable: () -> Unit) { - reloadables.add(reloadable) - } - - fun skipRows(r: Int) { - row += r - } - - fun appendSplitRow(left: WWidget, right: WWidget) { - val lw = width / 2 - set(0, row, lw, 1, left) - set(lw, row, width - lw, 1, right) - skipRows(1) - } - - fun appendFullRow(widget: WWidget) { - set(0, row, width, 1, widget) - skipRows(1) - } - } - - interface OptionHandler { - fun toJson(element: T): JsonElement? - fun fromJson(element: JsonElement): T - fun emitGuiElements(opt: Option, guiAppender: GuiAppender) - } - - inner class Option internal constructor( - val propertyName: String, - val default: () -> T, - val handler: OptionHandler - ) : ReadOnlyProperty { - - private lateinit var _value: T - private var loaded = false - var value: T - get() { - if (!loaded) - load() - return _value - } - set(value) { - loaded = true - _value = value - } - - override fun getValue(thisRef: Any?, property: KProperty<*>): T { - return value - } - - private fun load() { - if (data.containsKey(propertyName)) { - try { - value = handler.fromJson(data[propertyName]!!) - } catch (e: Exception) { - NotEnoughUpdates.logger.error( - "Exception during loading of config file $name. This will reset this config.", - e - ) - } - } - value = default() - } - - internal fun toJson(): JsonElement? { - return handler.toJson(value) - } - - fun appendToGui(guiapp: GuiAppender) { - handler.emitGuiElements(this, guiapp) - } - } - - val file = NotEnoughUpdates.CONFIG_DIR.resolve("$name.json") - val data: JsonObject by lazy { - try { - NotEnoughUpdates.json.decodeFromString( - file.readText() - ) - } catch (e: Exception) { - NotEnoughUpdates.logger.info("Could not read config $name. Loading empty config.") - JsonObject(mutableMapOf()) - } - } - - fun save() { - val data = JsonObject(allOptions.mapNotNull { (key, value) -> - value.toJson()?.let { - key to it - } - }.toMap()) - file.parent.createDirectories() - file.writeText(NotEnoughUpdates.json.encodeToString(data)) - } - - - val allOptions = mutableMapOf>() - val sortedOptions = mutableListOf>() - - protected fun option(propertyName: String, default: () -> T, handler: OptionHandler): Option { - if (propertyName in allOptions) error("Cannot register the same name twice") - return Option(propertyName, default, handler).also { - allOptions[propertyName] = it - sortedOptions.add(it) - } - } - - class BooleanHandler(val config: ManagedConfig) : OptionHandler { - override fun toJson(element: Boolean): JsonElement? { - return JsonPrimitive(element) - } - - override fun fromJson(element: JsonElement): Boolean { - return element.jsonPrimitive.boolean - } - - override fun emitGuiElements(opt: Option, guiAppender: GuiAppender) { - guiAppender.appendFullRow( - WToggleButton(Text.translatable("neu.config.${config.name}.${opt.propertyName}")).apply { - guiAppender.onReload { toggle = opt.value } - setOnToggle { - opt.value = it - config.save() - } - } - ) - } - } - - class ClickHandler(val config: ManagedConfig, val runnable: () -> Unit) : OptionHandler { - override fun toJson(element: Unit): JsonElement? { - return null - } - - override fun fromJson(element: JsonElement) {} - - override fun emitGuiElements(opt: Option, guiAppender: GuiAppender) { - guiAppender.appendSplitRow( - WLabel(Text.translatable("neu.config.${config.name}.${opt.propertyName}")), - WButton(Text.translatable("neu.config.${config.name}.${opt.propertyName}")).apply { - setOnClick { - runnable() - } - }, - ) - } - } - - protected fun toggle(propertyName: String, default: () -> Boolean): Option { - return option(propertyName, default, BooleanHandler(this)) - } - - fun showConfigEditor() { - val lwgd = LightweightGuiDescription() - val guiapp = GuiAppender(20) - guiapp.panel.insets = Insets.ROOT_PANEL - sortedOptions.forEach { it.appendToGui(guiapp) } - guiapp.reloadables.forEach { it() } - lwgd.setRootPanel(guiapp.panel) - setScreenLater(CottonClientScreen(lwgd)) - } - - protected fun button(propertyName: String, runnable: () -> Unit): Option { - return option(propertyName, { }, ClickHandler(this, runnable)) - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt deleted file mode 100644 index 6c9d8e8..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/data/DataHolder.kt +++ /dev/null @@ -1,60 +0,0 @@ -package moe.nea.notenoughupdates.util.data - -import java.nio.file.Path -import kotlinx.serialization.KSerializer -import kotlin.io.path.exists -import kotlin.io.path.readText -import kotlin.io.path.writeText -import moe.nea.notenoughupdates.NotEnoughUpdates - -abstract class DataHolder( - val serializer: KSerializer, - val name: String, - val default: () -> T -) : IDataHolder { - - - final override var data: T - private set - - init { - data = readValueOrDefault() - IDataHolder.putDataHolder(this::class, this) - } - - private val file: Path get() = NotEnoughUpdates.CONFIG_DIR.resolve("$name.json") - - protected fun readValueOrDefault(): T { - if (file.exists()) - try { - return NotEnoughUpdates.json.decodeFromString( - serializer, - file.readText() - ) - } catch (e: Exception) {/* Expecting IOException and SerializationException, but Kotlin doesn't allow multi catches*/ - IDataHolder.badLoads.add(name) - NotEnoughUpdates.logger.error( - "Exception during loading of config file $name. This will reset this config.", - e - ) - } - return default() - } - - private fun writeValue(t: T) { - file.writeText(NotEnoughUpdates.json.encodeToString(serializer, t)) - } - - override fun save() { - writeValue(data) - } - - override fun load() { - data = readValueOrDefault() - } - - override fun markDirty() { - IDataHolder.markDirty(this::class) - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/data/IDataHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/data/IDataHolder.kt deleted file mode 100644 index ccbf676..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/data/IDataHolder.kt +++ /dev/null @@ -1,75 +0,0 @@ -package moe.nea.notenoughupdates.util.data - -import java.util.concurrent.CopyOnWriteArrayList -import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents -import kotlin.reflect.KClass -import net.minecraft.client.MinecraftClient -import net.minecraft.server.command.CommandOutput -import net.minecraft.text.Text -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.events.ScreenOpenEvent - -interface IDataHolder { - companion object { - internal var badLoads: MutableList = CopyOnWriteArrayList() - private val allConfigs: MutableMap>, IDataHolder<*>> = mutableMapOf() - private val dirty: MutableSet>> = mutableSetOf() - - internal fun , K> putDataHolder(kClass: KClass, inst: IDataHolder) { - allConfigs[kClass] = inst - } - - fun , K> markDirty(kClass: KClass) { - if (kClass !in allConfigs) { - NotEnoughUpdates.logger.error("Tried to markDirty '${kClass.qualifiedName}', which isn't registered as 'IConfigHolder'") - return - } - dirty.add(kClass) - } - - private fun performSaves() { - val toSave = dirty.toList().also { - dirty.clear() - } - for (it in toSave) { - val obj = allConfigs[it] - if (obj == null) { - NotEnoughUpdates.logger.error("Tried to save '${it}', which isn't registered as 'ConfigHolder'") - continue - } - obj.save() - } - } - - private fun warnForResetConfigs(player: CommandOutput) { - if (badLoads.isNotEmpty()) { - player.sendMessage( - Text.literal( - "The following configs have been reset: ${badLoads.joinToString(", ")}. " + - "This can be intentional, but probably isn't." - ) - ) - badLoads.clear() - } - } - - fun registerEvents() { - ScreenOpenEvent.subscribe { event -> - performSaves() - val p = MinecraftClient.getInstance().player - if (p != null) { - warnForResetConfigs(p) - } - } - ClientLifecycleEvents.CLIENT_STOPPING.register(ClientLifecycleEvents.ClientStopping { - performSaves() - }) - } - - } - - val data: T - fun save() - fun markDirty() - fun load() -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/data/ProfileSpecificDataHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/data/ProfileSpecificDataHolder.kt deleted file mode 100644 index a2f78b1..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/data/ProfileSpecificDataHolder.kt +++ /dev/null @@ -1,82 +0,0 @@ -package moe.nea.notenoughupdates.util.data - -import java.nio.file.Path -import kotlinx.serialization.KSerializer -import kotlin.io.path.createDirectories -import kotlin.io.path.deleteExisting -import kotlin.io.path.exists -import kotlin.io.path.extension -import kotlin.io.path.listDirectoryEntries -import kotlin.io.path.nameWithoutExtension -import kotlin.io.path.readText -import kotlin.io.path.writeText -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.util.SBData - -abstract class ProfileSpecificDataHolder( - private val dataSerializer: KSerializer, - val configName: String, - private val configDefault: () -> S -) : IDataHolder { - - var allConfigs: MutableMap - - override val data: S? - get() = SBData.profileCuteName?.let { - allConfigs.computeIfAbsent(it) { configDefault() } - } - - init { - allConfigs = readValues() - readValues() - IDataHolder.putDataHolder(this::class, this) - } - - private val configDirectory: Path get() = NotEnoughUpdates.CONFIG_DIR.resolve("profiles").resolve(configName) - - private fun readValues(): MutableMap { - if (!configDirectory.exists()) { - configDirectory.createDirectories() - } - val profileFiles = configDirectory.listDirectoryEntries() - return profileFiles - .filter { it.extension == "json" } - .mapNotNull { - try { - it.nameWithoutExtension to NotEnoughUpdates.json.decodeFromString(dataSerializer, it.readText()) - } catch (e: Exception) { /* Expecting IOException and SerializationException, but Kotlin doesn't allow multi catches*/ - IDataHolder.badLoads.add(configName) - NotEnoughUpdates.logger.error( - "Exception during loading of profile specific config file $it ($configName). This will reset that profiles config.", - e - ) - null - } - }.toMap().toMutableMap() - } - - override fun save() { - if (!configDirectory.exists()) { - configDirectory.createDirectories() - } - val c = allConfigs - configDirectory.listDirectoryEntries().forEach { - if (it.nameWithoutExtension !in c) { - it.deleteExisting() - } - } - c.forEach { (name, value) -> - val f = configDirectory.resolve("$name.json") - f.writeText(NotEnoughUpdates.json.encodeToString(dataSerializer, value)) - } - } - - override fun markDirty() { - IDataHolder.markDirty(this::class) - } - - override fun load() { - allConfigs = readValues() - } - -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/render/block.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/render/block.kt deleted file mode 100644 index 0d6c63b..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/render/block.kt +++ /dev/null @@ -1,105 +0,0 @@ -package moe.nea.notenoughupdates.util.render - -import com.mojang.blaze3d.systems.RenderSystem -import org.joml.Matrix4f -import net.minecraft.client.gl.VertexBuffer -import net.minecraft.client.render.BufferBuilder -import net.minecraft.client.render.Camera -import net.minecraft.client.render.GameRenderer -import net.minecraft.client.render.Tessellator -import net.minecraft.client.render.VertexFormat -import net.minecraft.client.render.VertexFormats -import net.minecraft.client.util.math.MatrixStack -import net.minecraft.util.math.BlockPos -import net.minecraft.util.math.Vec3d - -class RenderBlockContext private constructor(private val tesselator: Tessellator, private val matrixStack: MatrixStack) { - private val buffer = tesselator.buffer - fun color(red: Float, green: Float, blue: Float, alpha: Float) { - RenderSystem.setShaderColor(red, green, blue, alpha) - } - - fun block(blockPos: BlockPos) { - matrixStack.push() - matrixStack.translate(blockPos.x.toFloat(), blockPos.y.toFloat(), blockPos.z.toFloat()) - buildCube(matrixStack.peek().positionMatrix, buffer) - tesselator.draw() - matrixStack.pop() - } - - fun tinyBlock(vec3d: Vec3d, size: Float) { - matrixStack.push() - matrixStack.translate(vec3d.x, vec3d.y, vec3d.z) - matrixStack.scale(size, size, size) - matrixStack.translate(-.5, -.5, -.5) - buildCube(matrixStack.peek().positionMatrix, buffer) - tesselator.draw() - matrixStack.pop() - } - - companion object { - private fun buildCube(matrix: Matrix4f, buf: BufferBuilder) { - buf.begin(VertexFormat.DrawMode.TRIANGLES, VertexFormats.POSITION_COLOR) - buf.fixedColor(255, 255, 255, 255) - buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 0.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 0.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 0.0F, 1.0F, 1.0F).next() - buf.vertex(matrix, 1.0F, 0.0F, 1.0F).next() - buf.unfixColor() - } - - fun renderBlocks(matrices: MatrixStack, camera: Camera, block: RenderBlockContext. () -> Unit) { - RenderSystem.disableDepthTest() - RenderSystem.enableBlend() - RenderSystem.defaultBlendFunc() - RenderSystem.setShader(GameRenderer::getPositionColorProgram) - - matrices.push() - matrices.translate(-camera.pos.x, -camera.pos.y, -camera.pos.z) - - val ctx = RenderBlockContext(Tessellator.getInstance(), matrices) - block(ctx) - - matrices.pop() - - RenderSystem.setShaderColor(1F,1F,1F,1F) - VertexBuffer.unbind() - RenderSystem.enableDepthTest() - RenderSystem.disableBlend() - } - } -} - - diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/textutil.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/textutil.kt deleted file mode 100644 index ac640be..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/textutil.kt +++ /dev/null @@ -1,70 +0,0 @@ -package moe.nea.notenoughupdates.util - -import net.minecraft.text.LiteralTextContent -import net.minecraft.text.Text -import net.minecraft.text.TextContent -import moe.nea.notenoughupdates.NotEnoughUpdates - - -class TextMatcher(text: Text) { - data class State( - var iterator: MutableList, - var currentText: Text?, - var offset: Int, - var textContent: String, - ) - - var state = State( - mutableListOf(text), - null, - 0, - "" - ) - - fun pollChunk(): Boolean { - val firstOrNull = state.iterator.removeFirstOrNull() ?: return false - state.offset = 0 - state.currentText = firstOrNull - state.textContent = when (val content = firstOrNull.content) { - is LiteralTextContent -> content.string - TextContent.EMPTY -> "" - else -> { - NotEnoughUpdates.logger.warn("TextContent of type ${content.javaClass} not understood.") - return false - } - } - state.iterator.addAll(0, firstOrNull.siblings) - return true - } - - fun pollChunks(): Boolean { - while (state.offset !in state.textContent.indices) { - if (!pollChunk()) { - return false - } - } - return true - } - - fun pollChar(): Char? { - if (!pollChunks()) return null - return state.textContent[state.offset++] - } - - - fun expectString(string: String): Boolean { - var found = "" - while (found.length < string.length) { - if (!pollChunks()) return false - val takeable = state.textContent.drop(state.offset).take(string.length - found.length) - state.offset += takeable.length - found += takeable - } - return found == string - } -} - - -val Text.unformattedString - get() = string.replace("§.".toRegex(), "") - diff --git a/src/main/resources/assets/firmament/icon.png b/src/main/resources/assets/firmament/icon.png new file mode 100644 index 0000000..467f962 Binary files /dev/null and b/src/main/resources/assets/firmament/icon.png differ diff --git a/src/main/resources/assets/firmament/lang/en_us.json b/src/main/resources/assets/firmament/lang/en_us.json new file mode 100644 index 0000000..bb0a0d0 --- /dev/null +++ b/src/main/resources/assets/firmament/lang/en_us.json @@ -0,0 +1,26 @@ +{ + "firmament.repo.reload.network": "Trying to redownload the repository", + "firmament.repo.reload.disk": "Reloading repository from disk. This may lag a bit.", + "firmament.repo.cache": "Recaching items", + "firmament.repo.brokenitem": "Failed to render item: %s", + "firmament.gui.repo.title": "firmament Repo Settings", + "firmament.gui.repo.autoupdate": "Auto Update", + "firmament.gui.repo.username": "Repo Username", + "firmament.gui.repo.hint.username": "NotEnoughUpdates", + "firmament.gui.repo.reponame": "Repo Name", + "firmament.gui.repo.hint.reponame": "NotEnoughUpdates-REPO", + "firmament.gui.repo.branch": "Repo Branch", + "firmament.gui.repo.hint.branch": "dangerous", + "firmament.gui.repo.reset": "Reset", + "firmament.gui.repo.reset.label": "Reset to Defaults", + "firmament.sbinfo.nolocraw": "No locraw data available", + "firmament.sbinfo.profile": "Current profile cutename: %s", + "firmament.sbinfo.server": "Locraw Server: %s", + "firmament.sbinfo.gametype": "Locraw Gametype: %s", + "firmament.sbinfo.mode": "Locraw Mode: %s", + "firmament.sbinfo.map": "Locraw Map: %s", + "firmament.config.fairy-souls.show": "Show Fairy Soul Waypoints", + "firmament.config.fairy-souls.reset": "Reset Collected Fairy Souls", + "firmament.config.fishing-warning.display-warning": "Display a warning when you are about to hook a fish", + "firmament.config.fishing-warning.highlight-wake-chain": "Highlight fishing particles" +} diff --git a/src/main/resources/assets/notenoughupdates/icon.png b/src/main/resources/assets/notenoughupdates/icon.png deleted file mode 100644 index 467f962..0000000 Binary files a/src/main/resources/assets/notenoughupdates/icon.png and /dev/null differ diff --git a/src/main/resources/assets/notenoughupdates/lang/en_us.json b/src/main/resources/assets/notenoughupdates/lang/en_us.json deleted file mode 100644 index e688eb7..0000000 --- a/src/main/resources/assets/notenoughupdates/lang/en_us.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "notenoughupdates.repo.reload.network": "Trying to redownload the repository", - "notenoughupdates.repo.reload.disk": "Reloading repository from disk. This may lag a bit.", - "notenoughupdates.repo.cache": "Recaching items", - "notenoughupdates.repo.brokenitem": "Failed to render item: %s", - "notenoughupdates.gui.repo.title": "NotEnoughUpdates Repo Settings", - "notenoughupdates.gui.repo.autoupdate": "Auto Update", - "notenoughupdates.gui.repo.username": "Repo Username", - "notenoughupdates.gui.repo.hint.username": "NotEnoughUpdates", - "notenoughupdates.gui.repo.reponame": "Repo Name", - "notenoughupdates.gui.repo.hint.reponame": "NotEnoughUpdates-REPO", - "notenoughupdates.gui.repo.branch": "Repo Branch", - "notenoughupdates.gui.repo.hint.branch": "dangerous", - "notenoughupdates.gui.repo.reset": "Reset", - "notenoughupdates.gui.repo.reset.label": "Reset to Defaults", - "notenoughupdates.sbinfo.nolocraw": "No locraw data available", - "notenoughupdates.sbinfo.profile": "Current profile cutename: %s", - "notenoughupdates.sbinfo.server": "Locraw Server: %s", - "notenoughupdates.sbinfo.gametype": "Locraw Gametype: %s", - "notenoughupdates.sbinfo.mode": "Locraw Mode: %s", - "notenoughupdates.sbinfo.map": "Locraw Map: %s", - "neu.config.fairy-souls.show": "Show Fairy Soul Waypoints", - "neu.config.fairy-souls.reset": "Reset Collected Fairy Souls", - "neu.config.fishing-warning.display-warning": "Display a warning when you are about to hook a fish", - "neu.config.fishing-warning.highlight-wake-chain": "Highlight fishing particles" -} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 64d7bb2..20b77a9 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -1,9 +1,9 @@ { "schemaVersion": 1, - "id": "notenoughupdates", + "id": "firmament", "version": "${version}", - "name": "Not Enough Updates", - "description": "Not Enough Updates - A mod for Hypixel Skyblock", + "name": "Firmament", + "description": "Firmament powered by NEU", "authors": [ { "name": "Linnea Gräf", @@ -14,30 +14,30 @@ ], "contact": { "discord": "https://discord.gg/moulberry", - "sources": "https://git.nea.moe/nea/NotEnoughUpdates1.19/" + "sources": "https://git.nea.moe/nea/firmament/" }, "license": "ARR", - "icon": "assets/notenoughupdates/icon.png", + "icon": "assets/firmament/icon.png", "environment": "client", "entrypoints": { "main": [ { "adapter": "kotlin", - "value": "moe.nea.notenoughupdates.NotEnoughUpdates" + "value": "moe.nea.firmament.NotEnoughUpdates" } ], "client": [ { "adapter": "kotlin", - "value": "moe.nea.notenoughupdates.NotEnoughUpdates" + "value": "moe.nea.firmament.NotEnoughUpdates" } ], "rei_client": [ - "moe.nea.notenoughupdates.rei.NEUReiPlugin" + "moe.nea.firmament.rei.FirmamentReiPlugin" ] }, "mixins": [ - "notenoughupdates.mixins.json" + "firmament.mixins.json" ], "depends": { "fabric": "*", diff --git a/src/main/resources/firmament.accesswidener b/src/main/resources/firmament.accesswidener new file mode 100644 index 0000000..236e6b1 --- /dev/null +++ b/src/main/resources/firmament.accesswidener @@ -0,0 +1 @@ +accessWidener v2 named diff --git a/src/main/resources/firmament.mixins.json b/src/main/resources/firmament.mixins.json new file mode 100644 index 0000000..ac040cb --- /dev/null +++ b/src/main/resources/firmament.mixins.json @@ -0,0 +1,22 @@ +{ + "required": true, + "plugin": "moe.nea.firmament.init.MixinPlugin", + "package": "moe.nea.firmament.mixins", + "compatibilityLevel": "JAVA_16", + "client": [ + "MixinDownloadingTerrainScreen", + "MixinMessageHandler", + "MixinMinecraft", + "MixinWorldRenderer", + "accessor.AccessorHandledScreen", + "devenv.DisableCommonPacketWarnings" + ], + "mixins": [ + "MixinClientPacketHandler", + "devenv.DisableInvalidFishingHook", + "devenv.MixinScoreboard" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/src/main/resources/notenoughupdates.accesswidener b/src/main/resources/notenoughupdates.accesswidener deleted file mode 100644 index 236e6b1..0000000 --- a/src/main/resources/notenoughupdates.accesswidener +++ /dev/null @@ -1 +0,0 @@ -accessWidener v2 named diff --git a/src/main/resources/notenoughupdates.mixins.json b/src/main/resources/notenoughupdates.mixins.json deleted file mode 100644 index 2b3a4e2..0000000 --- a/src/main/resources/notenoughupdates.mixins.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "required": true, - "plugin": "moe.nea.notenoughupdates.init.MixinPlugin", - "package": "moe.nea.notenoughupdates.mixins", - "compatibilityLevel": "JAVA_16", - "client": [ - "MixinDownloadingTerrainScreen", - "MixinMessageHandler", - "MixinMinecraft", - "MixinWorldRenderer", - "accessor.AccessorHandledScreen", - "devenv.DisableCommonPacketWarnings" - ], - "mixins": [ - "MixinClientPacketHandler", - "devenv.DisableInvalidFishingHook", - "devenv.MixinScoreboard" - ], - "injectors": { - "defaultRequire": 1 - } -} -- cgit