Jump to content

[1.19] Packet Handler for Forge Capability Not Working


ChickenWand33

Recommended Posts

package com.mysticalmod.capabilities.item;

import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;

public class CapabilityItemLvl {

    public static Capability<ItemLvl> ITEM_LVL_CAPABILITY = CapabilityManager.get(new CapabilityToken<>() {});

}
package com.mysticalmod.capabilities.item;

import com.mysticalmod.capabilities.ColorConstants;

import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;

public class DefaultItemLvl implements ItemLvl {

    private int itemLvl;
    
    private int itemRarity;
    public String itemRarityName = "Bruh";

    public void determineLvl(int xp, Player player, ItemStack item) {
    	itemLvl = xp;
    	ItemLvlProvider.levelClientUpdate(player, item);
    }
    
    public String getRarity() {
    	return itemRarityName;
    }
    
    public int getItemLvl() {
    	return itemLvl;
    }
    
    public void setItemLvl(int amount) {
    	this.itemLvl = amount;
    }
    
    public int getItemRarity() {
    	return itemRarity;
    }
    
    public void setItemRarity(int amount) {
    	this.itemRarity = amount;
    }
    
    public String getRarityAndColor() {
    	if (itemRarityName == null) {
    		setRarityName();
    	}
    	if (itemRarityName == "Mythical") {
    		return ColorConstants.RED + ColorConstants.BOLD + "Mythical";
    	} if (itemRarityName == "Legendary") {
    		return ColorConstants.GOLD + "Legendary";
    	} else if(itemRarityName == "Epic") {
    		return ColorConstants.DARK_PURPLE + "Epic";
    	} else if (itemRarityName == "Rare") {
    		return ColorConstants.BLUE + "Rare";
    	} else if (itemRarityName == "Uncommon") {
    		return ColorConstants.GREEN + "Uncommon";
    	} else {return ColorConstants.GRAY + "Common";}
    }
    
    
    public void generateRarity() {
    	double i = Math.random();
    	if (i > .999d) {
    		itemRarity = 5;
    	} else if (i > .99d) {
    		itemRarity = 4;
    	} else if (i > .95d) {
    		itemRarity = 3;
    	} else if (i > .80d) {
    		itemRarity = 2;
    	} else if (i > .50d) {
    		itemRarity = 1;
    	} else {
    		itemRarity = 0;
    	}
    	setRarityName();
    }
    
    public float getRarityMultiplier() {
    	setRarityName();
    	if (itemRarity == 5) {
    		return 2.0f;
    	} else if (itemRarity == 4) {
    		return 1.5f;
    	} else if(itemRarity == 3) {
    		return 1.35f;
    	} else if (itemRarity == 2) {
    		return 1.25f;
    	} else if (itemRarity == 1) {
    		return 1.1f;
    	} else {return 1f;}
    }
    
    private void setRarityName() {
    	if (itemRarity == 5) {
    		itemRarityName = "Mythical";
    	} else if (itemRarity == 4) {
			itemRarityName = "Legendary";
    	} else if(itemRarity == 3) {
    		itemRarityName = "Epic";
    	} else if (itemRarity == 2) {
    		itemRarityName = "Rare";
    	} else if (itemRarity == 1) {
    		itemRarityName = "Uncommon";
    	} else {itemRarityName = "Common";}
    }


    
}
package com.mysticalmod.capabilities.item;

import com.mysticalmod.MysticalMod;
import com.mysticalmod.capabilities.ColorConstants;

import net.minecraft.network.chat.Component;
//import net.minecraft.world.entity.player.Player;
//import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber(modid = MysticalMod.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class GameplayEvents {
	
	
	@SubscribeEvent
	public static void displayAttributes(final ItemTooltipEvent event) {
		event.getItemStack().getCapability(CapabilityItemLvl.ITEM_LVL_CAPABILITY).ifPresent(lvl -> {
			DefaultItemLvl lvl1 = (DefaultItemLvl) lvl;
			event.getToolTip().add(Component.literal(ColorConstants.BOLD + "Level " + lvl1.getItemLvl()));
			event.getToolTip().add(Component.literal(lvl1.getRarityAndColor() + " " + Math.round((lvl1.getRarityMultiplier()-1)*100) + "% Boost"));
		});
		
	}

	

} 
package com.mysticalmod.capabilities.item;

import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;

public interface ItemLvl {
    void determineLvl(int xp, Player player, ItemStack item);
    
    int getItemLvl();
    void setItemLvl(int amount);
    int getItemRarity();
    void setItemRarity(int amount);
    
    String getRarity();
    String getRarityAndColor();
    
    void generateRarity();
    
    float getRarityMultiplier();

}
package com.mysticalmod.capabilities.item;

import java.util.Collection;
import java.util.UUID;

import com.mysticalmod.MysticalMod;
import com.mysticalmod.capabilities.player.CapabilityPlayerSkills;
import com.mysticalmod.capabilities.player.DefaultPlayerSkills;

import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.ItemAttributeModifierEvent;
import net.minecraftforge.event.entity.player.PlayerEvent.ItemCraftedEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber(modid = MysticalMod.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class ItemLvlEventHandler {
	
	protected static final UUID BASE_ATTACK_DAMAGE_UUID = UUID.fromString("CB3F55D3-645C-4F38-A497-9C13A33DB5CF");
	
	@SubscribeEvent
	public static void onAttachCapabilitiesEvent(AttachCapabilitiesEvent<ItemStack> event) {
		if (event.getObject().isEnchantable()) {
			ItemLvlProvider providerlvl = new ItemLvlProvider();
			event.addCapability(new ResourceLocation(MysticalMod.MODID, "mysticalmod"), providerlvl);
		}
	}

	@SubscribeEvent
	public void registerCaps(RegisterCapabilitiesEvent event) {
		event.register(ItemLvl.class);
	}
	
	
	
	
	
	
	@SubscribeEvent
	public static void setLevel(final ItemCraftedEvent event) {
		if (event.getCrafting().isEnchantable() && !event.getEntity().level.isClientSide) {
			event.getCrafting().getCapability(CapabilityItemLvl.ITEM_LVL_CAPABILITY).ifPresent(lvl -> {
				event.getEntity().getCapability(CapabilityPlayerSkills.PLAYER_STATS_CAPABILITY).ifPresent(skills -> {
					DefaultItemLvl lvl1 = (DefaultItemLvl) lvl;
					DefaultPlayerSkills actualSkills = (DefaultPlayerSkills) skills;
					lvl1.determineLvl(actualSkills.combatLvl, event.getEntity(), event.getCrafting());
					lvl1.generateRarity();
					
					//Display
					String oldName = event.getCrafting().getDisplayName().getString();
					event.getCrafting().setHoverName(Component.literal("Lvl " + lvl1.getItemLvl() + " " + lvl1.getRarityAndColor() + " " + oldName));
					System.out.println(lvl1.getRarity());
				});
			});
		}
	}
	
	@SubscribeEvent
	public static void updateItemAttributes(ItemAttributeModifierEvent event) {
		event.getItemStack().getCapability(CapabilityItemLvl.ITEM_LVL_CAPABILITY).ifPresent(lvl -> {
			DefaultItemLvl lvl1 = (DefaultItemLvl) lvl;
			if (event.getSlotType() == EquipmentSlot.MAINHAND) {
				event.clearModifiers();
				double baseDamage = getAttribute(event.getItemStack(), event, Attributes.ATTACK_DAMAGE);
				//double baseSpeed = getAttribute(event.getItemStack(), event, Attributes.ATTACK_SPEED);
				//System.out.println(baseSpeed);
				double actualDamage = (baseDamage+(lvl1.getItemLvl()*0.25))*lvl1.getRarityMultiplier()-baseDamage;
				event.addModifier(Attributes.ATTACK_DAMAGE, new AttributeModifier("Weapon modifier", actualDamage, AttributeModifier.Operation.ADDITION));
				//event.addModifier(Attributes.ATTACK_SPEED, new AttributeModifier("Weapon modifier", 4+baseSpeed, AttributeModifier.Operation.ADDITION));
			}
		});
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	private static double getAttribute(ItemStack stack, ItemAttributeModifierEvent event, Attribute attribute) {
		Collection<AttributeModifier> collection = event.getOriginalModifiers().get(attribute);
		if (!collection.isEmpty()) {
			AttributeModifier attributemodifier = collection.iterator().next();
			double damage = attributemodifier.getAmount();
			return damage;
		}
		return 0;
		}
	

	
	
	
	
	
}
package com.mysticalmod.capabilities.item;

import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.network.PacketDistributor;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.mysticalmod.network.ClientboundItemLvlUpdateMessage;
import com.mysticalmod.network.SimpleNetworkHandler;

public class ItemLvlProvider implements ICapabilitySerializable<CompoundTag> {
    private final DefaultItemLvl lvl = new DefaultItemLvl();
    private final LazyOptional<ItemLvl> itemLvlOptional = LazyOptional.of(() -> lvl);

    public void invalidate() {
    	itemLvlOptional.invalidate();
    }

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        return itemLvlOptional.cast();
    }
    

    @Override
    public CompoundTag serializeNBT() {
        if (CapabilityItemLvl.ITEM_LVL_CAPABILITY == null) {
            return new CompoundTag();
        } else {
            CompoundTag compoundNBT = new CompoundTag();
            compoundNBT.putInt("itemLvl", lvl.getItemLvl());
            compoundNBT.putInt("itemRarity", lvl.getItemRarity());

            return compoundNBT;
        }
    }

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        if (CapabilityItemLvl.ITEM_LVL_CAPABILITY != null) {
            int itemLvl = nbt.getInt("itemLvl");
            int itemRarity = nbt.getInt("itemRarity");
            lvl.setItemLvl(itemLvl);
            lvl.setItemRarity(itemRarity);

        }
    }
    
    public static void levelClientUpdate(Player player, ItemStack updateItem) {
        if (!player.level.isClientSide()) {
            ServerPlayer serverPlayer = (ServerPlayer) player;
            ItemStack item = updateItem;
            item.getCapability(CapabilityItemLvl.ITEM_LVL_CAPABILITY).ifPresent(cap ->
                    SimpleNetworkHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> serverPlayer),
                            new ClientboundItemLvlUpdateMessage(cap.getItemLvl(), cap.getItemRarity())));
        }
    }
}
package com.mysticalmod;

import com.mojang.logging.LogUtils;
import com.mysticalmod.network.SimpleNetworkHandler;
import com.mysticalmod.painting.ModPaintings;

import net.minecraft.client.Minecraft;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.ForgeRegistries;
import org.slf4j.Logger;

@Mod(MysticalMod.MODID)
public class MysticalMod
{
    public static final String MODID = "mysticalmod";
    
    private static final Logger LOGGER = LogUtils.getLogger();


    public MysticalMod()
    {
        IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
        
        ModPaintings.register(modEventBus);

        
        modEventBus.addListener(this::commonSetup);

        MinecraftForge.EVENT_BUS.register(this);
    }

    private void commonSetup(final FMLCommonSetupEvent event)
    {
    	event.enqueueWork(SimpleNetworkHandler::init);
        LOGGER.info("HELLO FROM COMMON SETUP");
        LOGGER.info("DIRT BLOCK >> {}", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));
    }

    @SubscribeEvent
    public void onServerStarting(ServerStartingEvent event)
    {
        LOGGER.info("HELLO from server starting");
    }

    @Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
    public static class ClientModEvents
    {
        @SubscribeEvent
        public static void onClientSetup(FMLClientSetupEvent event)
        {
            LOGGER.info("HELLO FROM CLIENT SETUP");
            LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().getUser().getName());
        }
    }
}
package com.mysticalmod.capabilities;

import com.mysticalmod.MysticalMod;
import com.mysticalmod.capabilities.item.ItemLvlEventHandler;
import com.mysticalmod.capabilities.player.PlayerSkillsEventHandler;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;

@Mod.EventBusSubscriber(modid = MysticalMod.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class CommonEBS {
	
	@SubscribeEvent
	public static void onStaticCommonSetup(FMLCommonSetupEvent event) {
		MinecraftForge.EVENT_BUS.register(new ItemLvlEventHandler());
		MinecraftForge.EVENT_BUS.register(new PlayerSkillsEventHandler());
	}
}
package com.mysticalmod.network;

import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

import com.mysticalmod.capabilities.item.CapabilityItemLvl;

public class ClientboundItemLvlUpdateMessage implements INormalMessage {
    int ITEM_LVL;
    int ITEM_RARITY;

    public ClientboundItemLvlUpdateMessage(int level, int mining_xp) {
        this.ITEM_LVL = level;
        this.ITEM_RARITY = mining_xp;
    }

    public ClientboundItemLvlUpdateMessage(FriendlyByteBuf buf) {
    	ITEM_LVL = buf.readInt();
    	ITEM_RARITY = buf.readInt();
    }

    @Override
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeInt(ITEM_LVL);
        buf.writeInt(ITEM_RARITY);
    }

    @Override
    public void process(Supplier<NetworkEvent.Context> context) {
        //This method is for when information is received by the intended end (i.e, client in this case)
        //We can ignore login to server/client for NetworkDirection, its used for internal forge stuff
        //Remember that client/server side rules apply here
        //Access client stuff only in client, otherwise you will crash MC
        if (context.get().getDirection() == NetworkDirection.PLAY_TO_CLIENT) {
            context.get().enqueueWork(() -> Minecraft.getInstance().player.getMainHandItem()
            		.getCapability(CapabilityItemLvl.ITEM_LVL_CAPABILITY).
                    ifPresent(cap -> {
                        //do stuff with the info, such as mainly syncing info for the client-side gui
                        cap.setItemLvl(ITEM_LVL);
                        cap.setItemRarity(ITEM_RARITY);
                    }));
        }
    }
}
package com.mysticalmod.network;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

//A helper class to make packets easier
public interface INormalMessage {

    //FriendlyByteBuffer is nbt, fancy nbt basically
    void toBytes(FriendlyByteBuf buf);

    void process(Supplier<NetworkEvent.Context> context);

}

😄

 

 

Hello recently started on an RPG styled mod and I have a capability all set up and works great in Eclipse, after booting up a server however and finding that the capabilites were not synced I messed around with creating a packet handler based off of somebody elses code but can't figure out what isn't working, no errors my items levels just aren't synced at all. The name on the server has the correct level and rarity but then the attributes that are based off of the capability are just the defaults.

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.



×
×
  • Create New...

Important Information

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