From 4b2fae70bb59f6f6da3488e4d8dde79824fa829d Mon Sep 17 00:00:00 2001 From: Hileb <107909747+Ecdcaeb@users.noreply.github.com> Date: Thu, 29 Aug 2024 12:48:40 +0800 Subject: [PATCH] Revert "update base structure" This reverts commit 3bd28c46298b55ff899782f5f5290d027f0ad059. --- gradle.properties | 18 +-- .../Redirectionor.java | 46 ------ .../RedirectionorConfig.java | 68 --------- .../RedirectionorContainer.java | 31 ---- .../RedirectionorFastUtil.java | 61 -------- .../RedirectionorTransformer.java | 52 ------- .../java/com/example/examplemod/Config.java | 63 ++++++++ .../com/example/examplemod/ExampleMod.java | 136 ++++++++++++++++++ .../templates/META-INF/neoforge.mods.toml | 4 +- 9 files changed, 210 insertions(+), 269 deletions(-) delete mode 100644 src/main/java/com/Hileb/teampotato.redirectionor/Redirectionor.java delete mode 100644 src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorConfig.java delete mode 100644 src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorContainer.java delete mode 100644 src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorFastUtil.java delete mode 100644 src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorTransformer.java create mode 100644 src/main/java/com/example/examplemod/Config.java create mode 100644 src/main/java/com/example/examplemod/ExampleMod.java diff --git a/gradle.properties b/gradle.properties index d082188..148a9e6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,26 +20,26 @@ minecraft_version_range=[1.21.1, 1.22) # The Neo version must agree with the Minecraft version to get a valid artifact neo_version=21.1.28 # The Neo version range can use any version of Neo as bounds -neo_version_range=[0,) +neo_version_range=[21.1.0,) # The loader version range can only use the major version of FML as bounds -loader_version_range=[0,) +loader_version_range=[4,) ## Mod Properties # The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63} # Must match the String constant located in the main mod class annotated with @Mod. -mod_id=redirectionor +mod_id=examplemod # The human-readable display name for the mod. -mod_name=Redirectionor +mod_name=Example Mod # The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default. -mod_license=LGPL-3.0 +mod_license=All Rights Reserved # The mod version. See https://semver.org/ -mod_version=1.4 for neoforge +mod_version=1.0.0 # The group ID for the mod. It is only important when publishing as an artifact to a Maven repository. # This should match the base package used for the mod sources. # See https://maven.apache.org/guides/mini/guide-naming-conventions.html -mod_group_id=com.Hileb.teampotato.redirectionor +mod_group_id=com.example.examplemod # The authors of the mod. This is a simple text string that is used for display purposes in the mod list. -mod_authors=teampotato, Hileb +mod_authors=YourNameHere, OtherNameHere # The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list. -mod_description=Redirectionor is the implementation of this concept, specifically for the Direction enum class stuff, to reduce the required memory of the game. +mod_description=Example mod description.\nNewline characters can be used and will be replaced properly. diff --git a/src/main/java/com/Hileb/teampotato.redirectionor/Redirectionor.java b/src/main/java/com/Hileb/teampotato.redirectionor/Redirectionor.java deleted file mode 100644 index 19c3c7d..0000000 --- a/src/main/java/com/Hileb/teampotato.redirectionor/Redirectionor.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.Hileb.teampotato.redirectionor; - -import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; - -import javax.annotation.Nullable; -import java.util.Map; - -@IFMLLoadingPlugin.Name(Redirectionor.MODID) -public class Redirectionor implements IFMLLoadingPlugin { - public Redirectionor(){ - try{ - RedirectionorConfig.initConfig(); - }catch (Exception e){ - throw new RuntimeException("unable to set up config for redirectionor",e); - } - } - - public static final String MODID = "redirectionor"; - - public static final String TRANSFORMERCLASS = "com.Hileb.teampotato.redirectionor.RedirectionorTransformer"; - - - @Override - public String[] getASMTransformerClass() { - return new String[]{TRANSFORMERCLASS}; - } - - @Override - public String getModContainerClass() { - return "com.Hileb.teampotato.redirectionor.RedirectionorContainer"; - } - - @Nullable - @Override - public String getSetupClass() { - return null; - } - - @Override - public void injectData(Map data) {} - - @Override - public String getAccessTransformerClass() { - return null; - } -} \ No newline at end of file diff --git a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorConfig.java b/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorConfig.java deleted file mode 100644 index 1cc0985..0000000 --- a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorConfig.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.Hileb.teampotato.redirectionor; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import net.minecraft.launchwrapper.Launch; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.util.HashSet; -import java.util.Locale; - -/** - * @Project Redirectionor - * @Author Hileb - * @Date 2023/9/9 18:14 - **/ -public class RedirectionorConfig { - public static void initConfig(){ - File gameRunRoot = Launch.minecraftHome; - File config=new File(gameRunRoot,"config"); - if (!config.exists()){ - config.mkdir(); - } - File file=new File(config,"redirectionor_cfg.json"); - if (!file.exists()){ - try { - file.createNewFile(); - PrintWriter pw = new PrintWriter(file,"UTF-8"); - pw.println("{\"printTransformedClasses\":true,\"type\":\"block\", \"contains\":[]}"); - pw.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - try { - JsonParser jsonParser = new JsonParser(); - JsonObject jsonObject = (JsonObject)jsonParser.parse(new String(Files.readAllBytes(file.toPath()))); - if (jsonObject.has("printTransformedClasses")){ - RedirectionorTransformer.isDeBug = jsonObject.get("printTransformedClasses").getAsBoolean(); - } - Config.type = jsonObject.get("type").getAsString(); - JsonArray contains = jsonObject.get("contains").getAsJsonArray(); - for(JsonElement element : contains){ - Config.contains.add(element.getAsString()); - } - } catch (IOException e) { - throw new RuntimeException("Could not read the config", e); - } catch (ClassCastException e){ - throw new RuntimeException("The config is not json", e); - } catch (JsonSyntaxException e){ - throw new RuntimeException("The Json is bad", e); - } - } - public static class Config{ - public static String type = "block"; - public static HashSet contains = new HashSet<>(); - public static boolean isBlocking(){ - if ("block".equals(type.toLowerCase(Locale.ENGLISH)))return true; - else if ("allow".equals(type.toLowerCase(Locale.ENGLISH)))return false; - else throw new IllegalArgumentException("unknown type for config/redirectionor_cfg.json :"+type+" it should be \"block\" or \"allow\""); - } - } -} diff --git a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorContainer.java b/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorContainer.java deleted file mode 100644 index 8a74eb8..0000000 --- a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorContainer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.Hileb.teampotato.redirectionor; - -import com.google.common.eventbus.EventBus; -import net.minecraftforge.fml.common.DummyModContainer; -import net.minecraftforge.fml.common.LoadController; -import net.minecraftforge.fml.common.ModMetadata; - -/** - * @Project Redirectionor - * @Author Hileb - * @Date 2023/8/28 10:05 - **/ -public class RedirectionorContainer extends DummyModContainer { - public RedirectionorContainer(){ - super(new ModMetadata()); - ModMetadata metadata=this.getMetadata(); - metadata.modId=Redirectionor.MODID; - metadata.name="Redirectionor"; - metadata.description="Redirectionor is the implementation of this concept, specifically for the Direction enum class stuff, to reduce the required memory of the game."; - metadata.version="1.4 for 1.12.2-1.8.8"; - metadata.url="https://www.curseforge.com/minecraft/mc-mods/redirectionor"; - metadata.logoFile="/icon_redirectionor.png"; - metadata.authorList.add("MCTeamPotato"); - metadata.authorList.add("Kasualix"); - metadata.authorList.add("Hileb"); - } - @Override - public boolean registerBus(EventBus bus, LoadController controller) { - return true; - } -} diff --git a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorFastUtil.java b/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorFastUtil.java deleted file mode 100644 index 23c9b01..0000000 --- a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorFastUtil.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.Hileb.teampotato.redirectionor; - -import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.Opcodes; - -import java.lang.reflect.Modifier; - -/** - * @Project Redirectionor - * @Author Hileb - * @Date 2023/8/29 22:00 - **/ -public class RedirectionorFastUtil { - public static boolean isEnum(byte[] clazz){ - int constantsCount = readUnsignedShort(clazz,8); - int passcount = 10; - for(int i = 1; i < constantsCount; i++){ - int size=0; - switch (clazz[passcount]){ - case 9: - case 10: - case 11: - case 3: - case 4: - case 12: - case 18: - size = 5; - break; - case 5: - case 6: - size = 9; - break; - case 1: - int UTFSize=readUnsignedShort(clazz,passcount + 1); - size = 3 + UTFSize; - break; - case 15: - size = 4; - break; - default: - size = 3; - break; - } - passcount += size; - } - passcount = readUnsignedShort(clazz, passcount); - return (passcount & 16384) !=0; - } - public static int readUnsignedShort(byte[] b, int index) { - return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF); - } - public static boolean isAvailable(String name){ - for(String modid : RedirectionorConfig.Config.contains){ - if (name.contains(modid)){ - return !RedirectionorConfig.Config.isBlocking(); - } - } - return RedirectionorConfig.Config.isBlocking(); - } -} diff --git a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorTransformer.java b/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorTransformer.java deleted file mode 100644 index c8cef42..0000000 --- a/src/main/java/com/Hileb/teampotato.redirectionor/RedirectionorTransformer.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.Hileb.teampotato.redirectionor; - -import net.minecraft.launchwrapper.IClassTransformer; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.InsnList; -import org.objectweb.asm.tree.MethodNode; - -import java.util.ListIterator; - -/** - * @Project Redirectionor - * @Author Hileb - * @Date 2023/8/24 12:31 - **/ -public class RedirectionorTransformer implements IClassTransformer { - public static boolean isDeBug = true; - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) { - try{ - if (!RedirectionorFastUtil.isEnum(basicClass) || !RedirectionorFastUtil.isAvailable(transformedName)){ - return basicClass; - } - ClassReader classReader = new ClassReader(basicClass); - ClassNode cn = new ClassNode(); - classReader.accept(cn,0); - for(MethodNode mn:cn.methods){ - if ("values".equals(mn.name) && mn.desc.startsWith("()")){ - InsnList il=mn.instructions; - ListIterator iterator = mn.instructions.iterator(); - AbstractInsnNode node; - while (iterator.hasNext()){ - node = iterator.next(); - int code = node.getOpcode(); - if (code != Opcodes.GETSTATIC && code != Opcodes.ARETURN){ - iterator.remove(); - } - } - if (isDeBug)System.out.println("Redirect "+transformedName); - } - } - ClassWriter classWriter=new ClassWriter(classReader, 0); - cn.accept(classWriter); - return classWriter.toByteArray(); - }catch (Exception ignore){ - return basicClass; - } - } -} diff --git a/src/main/java/com/example/examplemod/Config.java b/src/main/java/com/example/examplemod/Config.java new file mode 100644 index 0000000..d70d1eb --- /dev/null +++ b/src/main/java/com/example/examplemod/Config.java @@ -0,0 +1,63 @@ +package com.example.examplemod; + +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.event.config.ModConfigEvent; +import net.neoforged.neoforge.common.ModConfigSpec; + +// An example config class. This is not required, but it's a good idea to have one to keep your config organized. +// Demonstrates how to use Neo's config APIs +@EventBusSubscriber(modid = ExampleMod.MODID, bus = EventBusSubscriber.Bus.MOD) +public class Config +{ + private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder(); + + private static final ModConfigSpec.BooleanValue LOG_DIRT_BLOCK = BUILDER + .comment("Whether to log the dirt block on common setup") + .define("logDirtBlock", true); + + private static final ModConfigSpec.IntValue MAGIC_NUMBER = BUILDER + .comment("A magic number") + .defineInRange("magicNumber", 42, 0, Integer.MAX_VALUE); + + public static final ModConfigSpec.ConfigValue MAGIC_NUMBER_INTRODUCTION = BUILDER + .comment("What you want the introduction message to be for the magic number") + .define("magicNumberIntroduction", "The magic number is... "); + + // a list of strings that are treated as resource locations for items + private static final ModConfigSpec.ConfigValue> ITEM_STRINGS = BUILDER + .comment("A list of items to log on common setup.") + .defineListAllowEmpty("items", List.of("minecraft:iron_ingot"), Config::validateItemName); + + static final ModConfigSpec SPEC = BUILDER.build(); + + public static boolean logDirtBlock; + public static int magicNumber; + public static String magicNumberIntroduction; + public static Set items; + + private static boolean validateItemName(final Object obj) + { + return obj instanceof String itemName && BuiltInRegistries.ITEM.containsKey(ResourceLocation.parse(itemName)); + } + + @SubscribeEvent + static void onLoad(final ModConfigEvent event) + { + logDirtBlock = LOG_DIRT_BLOCK.get(); + magicNumber = MAGIC_NUMBER.get(); + magicNumberIntroduction = MAGIC_NUMBER_INTRODUCTION.get(); + + // convert the list of strings into a set of items + items = ITEM_STRINGS.get().stream() + .map(itemName -> BuiltInRegistries.ITEM.get(ResourceLocation.parse(itemName))) + .collect(Collectors.toSet()); + } +} diff --git a/src/main/java/com/example/examplemod/ExampleMod.java b/src/main/java/com/example/examplemod/ExampleMod.java new file mode 100644 index 0000000..835a48d --- /dev/null +++ b/src/main/java/com/example/examplemod/ExampleMod.java @@ -0,0 +1,136 @@ +package com.example.examplemod; + +import org.slf4j.Logger; + +import com.mojang.logging.LogUtils; + +import net.minecraft.client.Minecraft; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.world.food.FoodProperties; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.CreativeModeTabs; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.material.MapColor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.config.ModConfig; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; +import net.neoforged.neoforge.event.server.ServerStartingEvent; +import net.neoforged.neoforge.registries.DeferredBlock; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredItem; +import net.neoforged.neoforge.registries.DeferredRegister; + +// The value here should match an entry in the META-INF/neoforge.mods.toml file +@Mod(ExampleMod.MODID) +public class ExampleMod +{ + // Define mod id in a common place for everything to reference + public static final String MODID = "examplemod"; + // Directly reference a slf4j logger + private static final Logger LOGGER = LogUtils.getLogger(); + // Create a Deferred Register to hold Blocks which will all be registered under the "examplemod" namespace + public static final DeferredRegister.Blocks BLOCKS = DeferredRegister.createBlocks(MODID); + // Create a Deferred Register to hold Items which will all be registered under the "examplemod" namespace + public static final DeferredRegister.Items ITEMS = DeferredRegister.createItems(MODID); + // Create a Deferred Register to hold CreativeModeTabs which will all be registered under the "examplemod" namespace + public static final DeferredRegister CREATIVE_MODE_TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, MODID); + + // Creates a new Block with the id "examplemod:example_block", combining the namespace and path + public static final DeferredBlock EXAMPLE_BLOCK = BLOCKS.registerSimpleBlock("example_block", BlockBehaviour.Properties.of().mapColor(MapColor.STONE)); + // Creates a new BlockItem with the id "examplemod:example_block", combining the namespace and path + public static final DeferredItem EXAMPLE_BLOCK_ITEM = ITEMS.registerSimpleBlockItem("example_block", EXAMPLE_BLOCK); + + // Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2 + public static final DeferredItem EXAMPLE_ITEM = ITEMS.registerSimpleItem("example_item", new Item.Properties().food(new FoodProperties.Builder() + .alwaysEdible().nutrition(1).saturationModifier(2f).build())); + + // Creates a creative tab with the id "examplemod:example_tab" for the example item, that is placed after the combat tab + public static final DeferredHolder EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder() + .title(Component.translatable("itemGroup.examplemod")) //The language key for the title of your CreativeModeTab + .withTabsBefore(CreativeModeTabs.COMBAT) + .icon(() -> EXAMPLE_ITEM.get().getDefaultInstance()) + .displayItems((parameters, output) -> { + output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event + }).build()); + + // The constructor for the mod class is the first code that is run when your mod is loaded. + // FML will recognize some parameter types like IEventBus or ModContainer and pass them in automatically. + public ExampleMod(IEventBus modEventBus, ModContainer modContainer) + { + // Register the commonSetup method for modloading + modEventBus.addListener(this::commonSetup); + + // Register the Deferred Register to the mod event bus so blocks get registered + BLOCKS.register(modEventBus); + // Register the Deferred Register to the mod event bus so items get registered + ITEMS.register(modEventBus); + // Register the Deferred Register to the mod event bus so tabs get registered + CREATIVE_MODE_TABS.register(modEventBus); + + // Register ourselves for server and other game events we are interested in. + // Note that this is necessary if and only if we want *this* class (ExampleMod) to respond directly to events. + // Do not add this line if there are no @SubscribeEvent-annotated functions in this class, like onServerStarting() below. + NeoForge.EVENT_BUS.register(this); + + // Register the item to a creative tab + modEventBus.addListener(this::addCreative); + + // Register our mod's ModConfigSpec so that FML can create and load the config file for us + modContainer.registerConfig(ModConfig.Type.COMMON, Config.SPEC); + } + + private void commonSetup(final FMLCommonSetupEvent event) + { + // Some common setup code + LOGGER.info("HELLO FROM COMMON SETUP"); + + if (Config.logDirtBlock) + LOGGER.info("DIRT BLOCK >> {}", BuiltInRegistries.BLOCK.getKey(Blocks.DIRT)); + + LOGGER.info(Config.magicNumberIntroduction + Config.magicNumber); + + Config.items.forEach((item) -> LOGGER.info("ITEM >> {}", item.toString())); + } + + // Add the example block item to the building blocks tab + private void addCreative(BuildCreativeModeTabContentsEvent event) + { + if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS) + event.accept(EXAMPLE_BLOCK_ITEM); + } + + // You can use SubscribeEvent and let the Event Bus discover methods to call + @SubscribeEvent + public void onServerStarting(ServerStartingEvent event) + { + // Do something when the server starts + LOGGER.info("HELLO from server starting"); + } + + // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent + @EventBusSubscriber(modid = MODID, bus = EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) + public static class ClientModEvents + { + @SubscribeEvent + public static void onClientSetup(FMLClientSetupEvent event) + { + // Some client setup code + LOGGER.info("HELLO FROM CLIENT SETUP"); + LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().getUser().getName()); + } + } +} diff --git a/src/main/templates/META-INF/neoforge.mods.toml b/src/main/templates/META-INF/neoforge.mods.toml index 8f25741..1b9f6e9 100644 --- a/src/main/templates/META-INF/neoforge.mods.toml +++ b/src/main/templates/META-INF/neoforge.mods.toml @@ -14,7 +14,7 @@ loaderVersion="${loader_version_range}" #mandatory license="${mod_license}" # A URL to refer people to when problems occur with this mod -issueTrackerURL="https://github.com/Ecdcaeb/Redirector" #optional +#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional # A list of mods - how many allowed here is determined by the individual mod loader [[mods]] #mandatory @@ -32,7 +32,7 @@ displayName="${mod_name}" #mandatory #updateJSONURL="https://change.me.example.invalid/updates.json" #optional # A URL for the "homepage" for this mod, displayed in the mod UI -displayURL="https://www.curseforge.com/minecraft/mc-mods/redirectionor" #optional +#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional # A file name (in the root of the mod JAR) containing a logo for display #logoFile="examplemod.png" #optional