Skip to content

Commit

Permalink
optimize code.
Browse files Browse the repository at this point in the history
  • Loading branch information
12345-mcpython committed Dec 14, 2024
1 parent 3373adc commit 743f8c8
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 115 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@

This mod changes the maximum stacking limit of items to 1 / group. You will not be able to stack any items.

![image](https://user-images.githubusercontent.com/63326494/163698038-fb59d9f3-efa4-490a-a458-c17b7b80d637.png)


![image](https://user-images.githubusercontent.com/63326494/163698038-fb59d9f3-efa4-490a-a458-c17b7b80d637.png)
2 changes: 0 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
buildscript {
repositories {
maven { url 'https://maven.aliyun.com/repository/public/' }
jcenter()
maven { url = "https://files.minecraftforge.net/maven" }
}
}
Expand Down
47 changes: 4 additions & 43 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,59 +1,20 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.jvmargs=-Xmx6G
org.gradle.daemon=false


## Environment Properties

# The Minecraft version must agree with the Forge version to get a valid artifact
# mapping config
minecraft_version=1.20.1
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[1.20.1,1.21)
# The Forge version must agree with the Minecraft version to get a valid artifact
forge_version=47.2.0
# The Forge version range can use any version of Forge as bounds or match the loader version range
forge_version_range=[47,)
# The loader version range can only use the major version of Forge/FML as bounds
loader_version_range=[47,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
# |-----------|----------------------|--------------------------------------------------------------------------------|
# | official | MCVersion | Official field/method names from Mojang mapping files |
# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official |
#
# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=official
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=1.20.1


## 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 config
mod_id=stackone
# The human-readable display name for the mod.
mod_name=Stack One Mod
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=Apache License 2.0
# The mod version. See https://semver.org/
mod_version=1.20.1-1.0.6
# 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_version=1.20.1-1.0.7
mod_group_id=com.laosun.stackone
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=Laosun
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=You can't stack anything.
1 change: 0 additions & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven { url 'https://maven.aliyun.com/repository/public/' }
maven {
name = 'MinecraftForge'
url = 'https://maven.minecraftforge.net/'
Expand Down
54 changes: 19 additions & 35 deletions src/main/java/com/laosun/stackone/IgnoreItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,58 +4,42 @@
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.mojang.logging.LogUtils;
import org.slf4j.Logger;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;

import static com.laosun.stackone.StackOneMod.LOGGER;

public class IgnoreItem {
public static final Logger LOGGER = LogUtils.getLogger();
public String item;

public static ArrayList<String> getIgnoreItems() {
File dir = new File("config/stackone");
if (!dir.exists()) {
dir.mkdirs();
if (!dir.exists() && dir.mkdirs()) {
LOGGER.info("Fail to create config directory.");
}
File file = new File(dir, "ignore_item.json");
if (!file.isFile()) {
try {
if (!file.createNewFile()) {
throw new IOException("Failed to create file!");
}
} catch (IOException e) {
LOGGER.error("Failed to create file!");
e.printStackTrace();
}
}
char[] a1 = null;
try (FileReader fileReader = new FileReader(file);) {
a1 = new char[(int) file.length()];
fileReader.read(a1);
} catch (IOException e) {
LOGGER.error("Failed to open file!");
e.printStackTrace();
}

Gson gson = new Gson();
JsonArray jsonArray;
ArrayList<String> ignoreItems = new ArrayList<>();
try {
if (a1 != null) {
jsonArray = JsonParser.parseString(String.copyValueOf(a1)).getAsJsonArray();
for (JsonElement user : jsonArray) {
IgnoreItem ignore = gson.fromJson(user, IgnoreItem.class);
ignoreItems.add(ignore.item);
}
if (!file.exists() && !file.createNewFile()) {
LOGGER.info("Fail to create config file.");
} else {
Files.writeString(file.toPath(), "[]", StandardCharsets.UTF_8);
}

} catch (Exception e) {
LOGGER.error("Failed to read JSON file!");
e.printStackTrace();
String jsonString = Files.readString(file.toPath());
JsonArray jsonArray = JsonParser.parseString(jsonString).getAsJsonArray();
for (JsonElement user : jsonArray) {
IgnoreItem ignore = gson.fromJson(user, IgnoreItem.class);
ignoreItems.add(ignore.item);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return ignoreItems;
}
Expand Down
76 changes: 76 additions & 0 deletions src/main/java/com/laosun/stackone/ItemStackSizeModifier.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.laosun.stackone;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import net.minecraft.world.item.Item;
import net.minecraftforge.registries.ForgeRegistries;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// written by chinese "doubao" ai
public class ItemStackSizeModifier {

private static final Logger LOGGER = LoggerFactory.getLogger(ItemStackSizeModifier.class);

@FunctionalInterface
interface MaxStackSizeFieldGetter {
Field get(Item item) throws NoSuchFieldException;
}

private static final MaxStackSizeFieldGetter defaultMaxStackSizeFieldGetter = item -> {
try {
return Item.class.getDeclaredField("maxStackSize");
} catch (NoSuchFieldException e) {
return null;
}
};

private static final MaxStackSizeFieldGetter alternativeMaxStackSizeFieldGetter = item -> {
try {
return Item.class.getDeclaredField("f_41370_");
} catch (NoSuchFieldException e) {
return null;
}
};

@SuppressWarnings("deprecation")
public static void modifyItemStackSizes() {
ArrayList<String> ignoreItems = IgnoreItem.getIgnoreItems();
List<Item> itemsToModify = new ArrayList<>();

for (Item i : ForgeRegistries.ITEMS) {
if (!ignoreItems.contains(i.builtInRegistryHolder().key().location().toString())) {
itemsToModify.add(i);
}
}

List<MaxStackSizeFieldGetter> fieldGetterStrategies = List.of(defaultMaxStackSizeFieldGetter, alternativeMaxStackSizeFieldGetter);

for (Item item : itemsToModify) {
Field maxStackSizeField = null;
for (MaxStackSizeFieldGetter strategy : fieldGetterStrategies) {
try {
maxStackSizeField = strategy.get(item);
if (maxStackSizeField != null) {
break;
}
} catch (NoSuchFieldException ignored) {
}
}

if (maxStackSizeField == null) {
LOGGER.error("Could not find valid maxStackSize field for item {}", item);
continue;
}

maxStackSizeField.setAccessible(true);
try {
maxStackSizeField.set(item, 1);
} catch (IllegalAccessException e) {
LOGGER.error("Failed to set maxStackSize field for item {}", item, e);
}
}
}
}
33 changes: 2 additions & 31 deletions src/main/java/com/laosun/stackone/StackOneMod.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,14 @@
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerContainerEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraft.world.item.Item;
import org.slf4j.Logger;

import java.lang.reflect.Field;
import java.util.ArrayList;

@Mod(StackOneMod.MODID)
public class StackOneMod {
public static final String MODID = "stackone";
Expand All @@ -28,34 +22,11 @@ public StackOneMod() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
modEventBus.addListener(this::commonSetup);
MinecraftForge.EVENT_BUS.register(this);
LOGGER.info("StackOneMod loaded");
}

@SuppressWarnings("deprecation")
private void commonSetup(final FMLCommonSetupEvent event) {
ArrayList<String> ignoreItems = IgnoreItem.getIgnoreItems();
for (Item i : ForgeRegistries.ITEMS) {
if (ignoreItems.contains(i.builtInRegistryHolder().key().location().toString())) {
continue;
}
Field a;

try {
a = Item.class.getDeclaredField("maxStackSize");
} catch (NoSuchFieldException e) {
try {
a = Item.class.getDeclaredField("f_41370_");
} catch (NoSuchFieldException ex) {
LOGGER.error("Failed to get field!!!");
return;
}
}
a.setAccessible(true);
try {
a.set(i, 1);
} catch (IllegalAccessException e) {
LOGGER.error("Failed to set field!!!");
}
}
ItemStackSizeModifier.modifyItemStackSizes();
}

@SubscribeEvent(priority = EventPriority.HIGH)
Expand Down

0 comments on commit 743f8c8

Please sign in to comment.