Jump to content

[SOLVED] Synchronizing ItemStack NBT during onItemUse method


coolAlias

Recommended Posts

I've recently been trying to update my Structure Generation Toolhttps://github.com/coolAlias/StructureGenerationTool to be compatible with multi-player; as such, I've changed to a KeyHandler and storing the Item variables in NBT.

 

Each key press changes a variable in the item's NBT, but this is only client side. I know I can send packets, but I was hoping not to spam packets because the data is only needed when the item is used. I've been trying to send a packet from client to server onItemUse, which works, but it's too late to the party and the Item activates with the data from the previous time instead of the current data.

 

I played around with synchronized variable and wait/notify, but it results in thread lock since the server side is waiting for the information but it can't get it until the onItemUse method is called client side, which obviously doesn't happen while the thread is waiting.

 

Here's my item code with my failed attempts:

 

public class ItemStructureSpawner extends BaseModItem
{
/** Enumerates valid values for increment / decrement offset methods */
public static enum Offset { OFFSET_X, OFFSET_Y, OFFSET_Z }

/** List of all structures that can be generated with this item */
private static final List<Structure> structures = new LinkedList();

private static final StructureGeneratorBase gen = new WorldGenStructure();

/** String identifiers for NBT storage and retrieval */
private static final String[] data = {"Structure", "Rotations", "OffsetX", "OffsetY", "OffsetZ", "InvertY"};

/** Indices for data variables */
private static final int STRUCTURE_INDEX = 0, ROTATIONS = 1, OFFSET_X = 2, OFFSET_Y = 3, OFFSET_Z = 4, INVERT_Y = 5;

public ItemStructureSpawner(int par1)
{
	super(par1);
	setMaxDamage(0);
	setMaxStackSize(1);
	setCreativeTab(CreativeTabs.tabMisc);
	// constructor should only be called once anyways
	init();
	LogHelper.log(Level.INFO, "ItemStructureSpawner initialized structures.");
}

/**
     * Called when item is crafted/smelted. Not called from Creative Tabs.
     */
@Override
    public void onCreated(ItemStack itemstack, World world, EntityPlayer player)
    {
	initNBTCompound(itemstack);
    }

/**
 * Increments the appropriate Offset and returns the new value for convenience.
 */
public int incrementOffset(ItemStack itemstack, Offset type)
{
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);

	int offset;

	switch(type) {
	case OFFSET_X:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_X]) + 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_X], offset);
		return offset;
	case OFFSET_Y:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Y]) + 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Y], offset);
		return offset;
	case OFFSET_Z:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Z]) + 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Z], offset);
		return offset;
	default: return 0;
	}
}

/**
 * Decrements the appropriate Offset and returns the new value for convenience.
 */
public int decrementOffset(ItemStack itemstack, Offset type)
{
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);

	int offset;

	switch(type) {
	case OFFSET_X:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_X]) - 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_X], offset);
		return offset;
	case OFFSET_Y:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Y]) - 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Y], offset);
		return offset;
	case OFFSET_Z:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Z]) - 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Z], offset);
		return offset;
	default: return 0;
	}
}

/**
 * Returns true if y offset is inverted (i.e. y will decrement)
 */
public boolean isInverted(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	return itemstack.stackTagCompound.getBoolean(data[iNVERT_Y]);
}

/**
 * Inverts Y axis for offset adjustments; returns new value for convenience.
 */
public boolean invertY(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	boolean invert = !itemstack.stackTagCompound.getBoolean(data[iNVERT_Y]);
	itemstack.stackTagCompound.setBoolean(data[iNVERT_Y], invert);
	return invert;
}

/**
 * Resets all manual offsets to 0.
 */
public void resetOffset(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	itemstack.stackTagCompound.setInteger(data[OFFSET_X], 0);
	itemstack.stackTagCompound.setInteger(data[OFFSET_Y], 0);
	itemstack.stackTagCompound.setInteger(data[OFFSET_Z], 0);
}

/**
 * Rotates structure's facing by 90 degrees clockwise; returns number of rotations for convenience.
 */
public int rotate(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	int rotations = (itemstack.stackTagCompound.getInteger(data[ROTATIONS]) + 1) % 4;
	itemstack.stackTagCompound.setInteger(data[ROTATIONS], rotations);
	return rotations;
}

/**
 * Increments the structure index and returns the new value for convenience.
 */
public int nextStructure(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	int index = itemstack.stackTagCompound.getInteger(data[sTRUCTURE_INDEX]) + 1;
	if (index == structures.size()) index = 0;
	itemstack.stackTagCompound.setInteger(data[sTRUCTURE_INDEX], index);
	return index;
}

/**
 * Decrements the structure index and returns the new value for convenience.
 */
public int prevStructure(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	int index = itemstack.stackTagCompound.getInteger(data[sTRUCTURE_INDEX]) - 1;
	if (index < 0) index = this.structures.size() - 1;
	itemstack.stackTagCompound.setInteger(data[sTRUCTURE_INDEX], index);
	return index;
}

/**
 * Returns the name of the structure at provided index, or "" if index out of bounds
 */
public String getStructureName(int index) {
	return (index < structures.size() ? structures.get(index).name : "");
}

/**
 * Returns index of currently selected structure
 */
public int getCurrentStructureIndex(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	return itemstack.stackTagCompound.getInteger(data[sTRUCTURE_INDEX]);
}

/**
 * Toggles between generate and remove structure setting. Returns new value for convenience.
 */
public boolean toggleRemove() {
	return gen.toggleRemoveStructure();
}

@Override
public int getMaxItemUseDuration(ItemStack par1ItemStack)
    {
        return 1;
    }

@Override
public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int par7, float par8, float par9, float par10)
    {
	// Need to update server with correct information
	if (world.isRemote) {
		if (itemstack.stackTagCompound == null)
			initNBTCompound(itemstack);
		PacketDispatcher.sendPacketToServer(SGTPacketNBTItem.getPacket(itemstack));
	}
	// NOTE: It isn't absolutely necessary to check if the world is not remote here,
	// but I recommend it as the client will be notified automatically anyway.
	if (!world.isRemote && structures.size() > 0)
	{
		//new SyncThread(itemstack);
		/*
		while (itemstack.stackTagCompound == null)
		{
			try {
				System.out.println("Waiting...");
				wait();
			} catch (InterruptedException e) {
				System.out.println("Interrupted.");
				//e.printStackTrace();
				//return false;
			}
			System.out.println("Finished waiting.");
		}
		*/
		/*
		if (itemstack.stackTagCompound == null) {
			LogHelper.log(Level.SEVERE, "Item Structure Spawner's NBT Tag is null.");
			//initNBTCompound(itemstack);
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
				return false;
			}
		}
		*/
		NBTTagCompound tag = itemstack.stackTagCompound;
		// LogHelper.log(Level.INFO, "Preparing to generate structure");
		gen.setPlayerFacing(player);
		//gen.addBlockArray(StructureArrays.blockArrayNPCBlackSmith);
		Structure structure = structures.get(tag.getInteger(data[sTRUCTURE_INDEX]));
		// LogHelper.log(Level.INFO, "Structure size: " + structure.blockArrayList().size());
		gen.setBlockArrayList(structure.blockArrayList());
		gen.setStructureFacing(structure.getFacing() + tag.getInteger(data[ROTATIONS]));
		// LogHelper.log(Level.INFO, "Default offsets: " + structure.getOffsetX() + "/" + structure.getOffsetZ());
		//structure.setDefaultOffset(this.offsetX, this.offsetY, this.offsetZ);
		gen.setDefaultOffset(structure.getOffsetX() + tag.getInteger(data[OFFSET_X]), structure.getOffsetY() + tag.getInteger(data[OFFSET_Y]), structure.getOffsetZ() + tag.getInteger(data[OFFSET_Z]));
		// adjust for structure generating centered on player's position (including height)
		//gen.setDefaultOffset(structure.getOffsetX() + this.offsetX, structure.getOffsetY() + this.offsetY, structure.getOffsetZ() + this.offsetZ); // adjust down one for the buffer layer
		gen.generate(world, world.rand, x, y, z);

		// reset for next time
		itemstack.stackTagCompound = null;
	}

        return true;
    }

private final void initNBTCompound(ItemStack itemstack)
{
	if (itemstack.stackTagCompound == null)
		itemstack.stackTagCompound = new NBTTagCompound();

	for (int i = 0; i < INVERT_Y; ++i) {
    		itemstack.stackTagCompound.setInteger(data[i], 0);
    	}
    	
    	itemstack.stackTagCompound.setBoolean(data[iNVERT_Y], false);
    	
    	LogHelper.log(Level.INFO, "NBT Tag initialized for ItemStructureSpawner");
}

private final void init()
{
	Structure structure = new Structure("Hut");
	structure.addBlockArray(StructureArrays.blockArrayNPCHut);
	structure.setFacing(StructureGeneratorBase.EAST);
	// has a buffer layer on the bottom in case no ground; spawn at y-1 for ground level
	structure.setStructureOffset(0, -1, 0);
	structures.add(structure);

	structure = new Structure("Blacksmith");
	structure.addBlockArray(StructureArrays.blockArrayNPCBlackSmith);
	structure.setFacing(StructureGeneratorBase.NORTH);
	structures.add(structure);

	structure = new Structure("Viking Shop");
	structure.addBlockArray(StructureArrays.blockArrayShop);
	structure.setFacing(StructureGeneratorBase.WEST);
	structures.add(structure);

	structure = new Structure("Redstone Dungeon");
	structure.addBlockArray(StructureArrays.blockArrayRedstone);
	//structure.setFacing(StructureGeneratorBase.EAST);
	structures.add(structure);

	structure = new Structure("Offset Test");
	structure.addBlockArray(StructureArrays.blockArraySpawnTest);
	structure.setFacing(StructureGeneratorBase.NORTH);
	structures.add(structure);
}
}
// mangled attempt at multi-threading...
class SyncThread implements Runnable
{
Thread t;

private final ItemStack itemstack;

public SyncThread(ItemStack itemstack) {
	t = new Thread();
	this.itemstack = itemstack;
	t.start();
}

@Override
public void run()
{
	//synchronized (itemstack)
	{
		while (itemstack.stackTagCompound == null)
		{
			try {
				wait();
			} catch (InterruptedException e) {

			}
		}
	}
}
}

 

And my PacketHandler with custom packet class:

 

public class SGTPacketHandler implements IPacketHandler
{
/** Packet IDs */
public static final byte PACKET_NBT_ITEM = 1;

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player)
{
	System.out.println("[sERVER] Received client packet.");
	DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data));
	byte packetType;

	try {
		packetType = inputStream.readByte();
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	switch(packetType) {
	case PACKET_NBT_ITEM: handlePacketNBTItem(packet, (EntityPlayer) player, inputStream); break;
	default: LogHelper.log(Level.SEVERE, "Unhandled packet exception for packet id " + packetType);
	}
}

private void handlePacketNBTItem(Packet250CustomPayload packet, EntityPlayer player, DataInputStream inputStream)
{
	short size;

	try {
		size = inputStream.readShort();
		if (size > 0) {
			byte[] abyte = new byte[size];
			inputStream.readFully(abyte);
			player.getHeldItem().stackTagCompound = CompressedStreamTools.decompress(abyte);
		}
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	//notifyAll();
}
}

// The custom packet class:
public class SGTPacketNBTItem
{
public static Packet250CustomPayload getPacket(ItemStack itemstack)
{
	NBTTagCompound compound = itemstack.stackTagCompound;
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	DataOutputStream outputStream = new DataOutputStream(bos);

	try {
		outputStream.writeByte(SGTPacketHandler.PACKET_NBT_ITEM);
		if (compound == null) {
			outputStream.writeShort(-1);
        } else {
            byte[] abyte = CompressedStreamTools.compress(compound);
            outputStream.writeShort((short) abyte.length);
            outputStream.write(abyte);
        }
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	Packet250CustomPayload packet = new Packet250CustomPayload();
	packet.channel = ModInfo.CHANNEL;
	packet.data = bos.toByteArray();
	packet.length = bos.size();

	return packet;
}
}

 

 

Link to comment
Share on other sites

Heh, yeah I know. I was just trying to figure a way around sending so many packets, but I guess there's no help for it in this situation. I was really hoping to be able to just send one packet with all the information, but since the keyboard is handled client side, that's impossible (as far as I know) without editing NBT from there, which isn't good practice. Thanks for the reply anyway.

Link to comment
Share on other sites

The way I have it set up now is to send packets to the server with the key pressed information, but I also directly edit the NBT client side for display purposes only. When the NBT is actually needed for processing, it only uses the NBT stored on the server. Would this be considered acceptable, or should I not edit the NBT at all client side without requesting the data from the server?

 

I'll show you what I mean:

 

@Override
public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat)
{
	if (tickEnd && SGTKeyBindings.SGTKeyMap.containsKey(kb.keyCode) && FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
	{
		EntityClientPlayerMP player = FMLClientHandler.instance().getClient().thePlayer;

		if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemStructureSpawner)
		{
// This packet tells the server what key was pressed so it can update server-side NBT:
PacketDispatcher.sendPacketToServer(SGTPacketKeyPress.getPacket((byte) SGTKeyBindings.SGTKeyMap.get(kb.keyCode)));

			ItemStructureSpawner spawner = (ItemStructureSpawner) player.getHeldItem().getItem();

// This switch changes NBT client side to display a message only:
			switch (SGTKeyBindings.SGTKeyMap.get(kb.keyCode)) {
			case SGTKeyBindings.PLUS_X: player.addChatMessage("[sTRUCTURE GEN] Incremented x offset: " + spawner.incrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_X)); break;
			case SGTKeyBindings.MINUS_X: player.addChatMessage("[sTRUCTURE GEN] Decremented x offset: " + spawner.decrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_X)); break;
			case SGTKeyBindings.PLUS_Z: player.addChatMessage("[sTRUCTURE GEN] Incremented z offset: " + spawner.incrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Z)); break;
			case SGTKeyBindings.MINUS_Z: player.addChatMessage("[sTRUCTURE GEN] Decremented z offset: " + spawner.decrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Z)); break;
			case SGTKeyBindings.OFFSET_Y:
				if (spawner.isInverted(player.getHeldItem()))
					player.addChatMessage("[sTRUCTURE GEN] Decremented y offset: " + spawner.decrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Y));
				else
					player.addChatMessage("[sTRUCTURE GEN] Incremented y offset: " + spawner.incrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Y));
				break;
			case SGTKeyBindings.INVERT_Y: player.addChatMessage("[sTRUCTURE GEN] y offset will now " + (spawner.invertY(player.getHeldItem()) ? "decrement." : "increment.")); break;
			case SGTKeyBindings.RESET_OFFSET:
				spawner.resetOffset(player.getHeldItem());
				player.addChatMessage("[sTRUCTURE GEN] Offsets x/y/z reset to 0.");
				break;
			case SGTKeyBindings.ROTATE: player.addChatMessage("[sTRUCTURE GEN] Structure orientation rotated by " + (spawner.rotate(player.getHeldItem()) * 90) + " degrees."); break;
			case SGTKeyBindings.PREV_STRUCT: player.addChatMessage("[sTRUCTURE GEN] Selected structure: " + spawner.getStructureName(spawner.prevStructure(player.getHeldItem())) + " at index " + (spawner.getCurrentStructureIndex(player.getHeldItem()) + 1)); break;
			case SGTKeyBindings.NEXT_STRUCT: player.addChatMessage("[sTRUCTURE GEN] Selected structure: " + spawner.getStructureName(spawner.nextStructure(player.getHeldItem())) + " at index " + (spawner.getCurrentStructureIndex(player.getHeldItem()) + 1)); break;
			case SGTKeyBindings.TOGGLE_REMOVE: player.addChatMessage("[sTRUCTURE GEN] Structure will " + (spawner.toggleRemove() ? "be removed" : "generate") + " on right click."); break;
			}
		}
	}
}

 

Then in the Item onItemUse, I only get NBT data from the server:

 

@Override
public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int par7, float par8, float par9, float par10)
    {
	if (!world.isRemote)
	{
// since world is not remote, the NBT tag is from the server; I don't use any of the client-side information
		NBTTagCompound tag = itemstack.stackTagCompound;
		gen.setPlayerFacing(player);
		Structure structure = structures.get(tag.getInteger(data[sTRUCTURE_INDEX]));
		gen.setBlockArrayList(structure.blockArrayList());
		gen.setStructureFacing(structure.getFacing() + tag.getInteger(data[ROTATIONS]));
		gen.setDefaultOffset(structure.getOffsetX() + tag.getInteger(data[OFFSET_X]), structure.getOffsetY() + tag.getInteger(data[OFFSET_Y]), structure.getOffsetZ() + tag.getInteger(data[OFFSET_Z]));
		gen.generate(world, world.rand, x, y, z);
	}

        return true;
    }

 

 

(And sorry about spamming the tutorials - I thought they were relevant to the topics, though some were a few days old they didn't look resolved yet, except for one... my bad.)

Link to comment
Share on other sites

"So many packets"? As in one packet per keypress? What is wrong with that?

I was only trying to think of a way to minimize traffic. Guess it's not a big deal, though.

You should never do any calculations client-sided if they affect the game data in any way. If you have to give the player an Item, don't rely on the client to do it. Never trust the client, it never does what you want and always sends wrong data (that's what you have to assume to make your mod save against hacks).

You seem to overcomplicate things. Just send a packet when a key gets pressed, then on the server change the NBT data when the key-pressed packet arrives. That NBT will be automatically synced by minecraft.

Yes, but it won't be synced quickly enough to display the correct values immediately, which is why I did what I did above. As you can tell, I'm no expert in Java, and I couldn't think of an easy way to display the information immediately without changing the client-side NBT. As I mentioned, it's only used for the display, not any actual calculations that affect the world, player or anything else. I only send the key pressed to the server, not the client side NBT data. Is this still bad form? What would you suggest, then, to display the information?

Link to comment
Share on other sites

Solved it. Don't know why I didn't think of this earlier, but I can just send the chat message from the server upon receipt of the packet. Now the client side doesn't have to handle any of the NBT data at all.

 

Thanks for the clarifications, and sorry for troubling you. I was indeed making it too complicated.

Link to comment
Share on other sites

Heh, yeah I know. I was just trying to figure a way around sending so many packets, but I guess there's no help for it in this situation.

"So many packets"? As in one packet per keypress? What is wrong with that?

 

In regards to this, in the Minecraft I use to play (not develop) which has around 45 mods in it including heavy hitters such as Mo'Creatures, I often see something such as this:

 

"Memory connection overburdened after processing packets with 2500 still to go"

 

Isn't this an artifact of modders spamming too many packets as coolAlias was indicating?

 

 

Note: I'm not blaming Mo'Creatures, just illustrating that the mods I use don't just add a block.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • rp.crazyheal.xyz mods  
    • I'm developing a dimension, but it's kinda resource intensive so some times during player teleporting it lags behind making the player phase down into the void, so im trying to implement some kind of pregeneration to force the game loading a small set of chunks in the are the player will teleport to. Some of the things i've tried like using ServerLevel and ServerChunkCache methods like getChunk() dont actually trigger chunk generation if the chunk isn't already on persistent storage (already generated) or placing tickets, but that doesn't work either. Ideally i should be able to check when the task has ended too. I've peeked around some pregen engines, but they're too complex for my current understanding of the system of which I have just a basic understanding (how ServerLevel ,ServerChunkCache  and ChunkMap work) of. Any tips or other classes I should be looking into to understand how to do this correctly?
    • https://mclo.gs/4UC49Ao
    • Way back in the Forge 1.17 days, work started for adding JPMS (Java Platform Module Support) to ModLauncher and ForgeModLoader. This has been used internally by Forge and some libraries for a while now, but mods (those with mods.toml specifically) have not been able to take advantage of it. As of Forge 1.21.1 and 1.21.3, this is now possible!   What is JPMS and what does it mean for modders? JPMS is the Java Platform Module System, introduced in Java 9. It allows you to define modules, which are collections of packages and resources that can be exported or hidden from other modules. This allows for much more fine-tuned control over visibility, cleaner syntax for service declarations and support for sealed types across packages. For example, you might have a mod with a module called `com.example.mod` that exports `com.example.mod.api` and `com.example.mod.impl` to other mods, but hides `com.example.mod.internal` from them. This would allow you to have a clean API for other mods to use, while keeping your internal implementation details hidden from IDE hints, helping prevent accidental usage of internals that might break without prior notice. This is particularly useful if you'd like to use public records with module-private constructors or partially module-private record components, as you can create a sealed interface that only your record implements, having the interface be exported and the record hidden. It's also nice for declaring and using services, as you'll get compile-time errors from the Java compiler for typos and the like, rather than deferring to runtime errors. In more advanced cases, you can also have public methods that are only accessible to specific other modules -- handy if you want internal interactions between multiple of your own mods.   How do I bypass it? We understand there may be drama in implementing a system that prevents mods from accessing each other's internals when necessary (like when a mod is abandoned or you need to fix a compat issue) -- after all, we are already modding a game that doesn't have explicit support for Java mods yet. We have already thought of this and are offering APIs from day one to selectively bypass module restrictions. Let me be clear: Forge mods are not required to use JPMS. If you don't want to use it, you don't have to. The default behaviour is to have fully open, fully exported automatic modules. In Java, you can use the `Add-Opens` and `Add-Exports` manifest attributes to selectively bypass module restrictions of other mods at launch time, and we've added explicit support for these when loading your Forge mods. At compile-time, you can use existing solutions such as the extra-java-module-info Gradle plugin to deal with non-modular dependencies and add extra opens and exports to other modules. Here's an example on how to make the internal package `com.example.examplemod.internal` open to your mod in your build.gradle: tasks.named('jar', Jar) { manifest { attributes([ 'Add-Opens' : 'com.example.examplemod/com.example.examplemod.internal' 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors // (...) ]) } } With the above in your mod's jar manifest, you can now reflectively access the classes inside that internal package. Multiple entries are separated with a space, as per Java's official spec. You can also use Add-Exports to directly call without reflection, however you'd need to use the Gradle plugin mentioned earlier to be able to compile. The syntax for Add-Exports is the same as Add-Opens, and instructions for the compile-time step with the Gradle plugin are detailed later in this post. Remember to prefer the opens and exports keywords inside module-info.java for sources you control. The Add-Opens/Add-Exports attributes are only intended for forcing open other mods.   What else is new with module support? Previously, the runtime module name was always forced to the first mod ID in your `mods.toml` file and all packages were forced fully open and exported. Module names are now distinguished from mod IDs, meaning the module name in your module-info.java can be different from the mod ID in your `mods.toml`. This allows you to have a more descriptive module name that doesn't have to be the same as your mod ID, however we strongly recommend including your mod ID as part of your module name to aid troubleshooting. The `Automatic-Module-Name` manifest attribute is now also honoured, allowing you to specify a module name for your mod without needing to create a `module-info.java` file. This is particularly useful for mods that don't care about JPMS features but want to have a more descriptive module name and easier integration with other mods that do use JPMS.   How do I use it? The first step is to create a `module-info.java` file in your mod's source directory. This file should be in the same package as your main mod class, and should look something like this: open module com.example.examplemod { requires net.minecraftforge.eventbus; requires net.minecraftforge.fmlcore; requires net.minecraftforge.forge; requires net.minecraftforge.javafmlmod; requires net.minecraftforge.mergetool.api; requires org.slf4j; requires logging; } For now, we're leaving the whole module open to reflection, which is a good starting point. When we know we want to close something off, we can remove the open modifier from the module and open or export individual packages instead. Remember that you need to be open to Forge (module name net.minecraftforge.forge), otherwise it can't call your mod's constructor. Next is fixing modules in Gradle. While Forge and Java support modules properly, Gradle does not put automatic modules on the module path by default, meaning that the logging module (from com.mojang:logging) is not found. To fix this, add the Gradle plugin and add a compile-time module definition for that Mojang library: plugins { // (...) id 'org.gradlex.extra-java-module-info' version "1.9" } // (...) extraJavaModuleInfo { failOnMissingModuleInfo = false automaticModule("com.mojang:logging", "logging") } The automatic module override specified in your build.gradle should match the runtime one to avoid errors. You can do the same for any library or mod dependency that is missing either a module-info or explicit Automatic-Module-Name, however be aware that you may need to update your mod once said library adds one. That's all you need to get started with module support in your mods. You can learn more about modules and how to use them at dev.java.
    • Faire la mise à jour grâce à ce lien m'a aider personnellement, merci à @Paint_Ninja. https://www.amd.com/en/support 
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.