Jump to content

[1.17.1] Forge Capability - How to save?


chickenwand3

Recommended Posts

Hey guys I have created a mod that assigns levels to mobs and scales them up using capabilities, everything works great but because of the recent changes to capabilities I am unable to find examples on how to save the level of my mobs so that it remains the same if I restart the server. I will upload all my files relating to the capability and hope you guys can lead me in the right direction :)
Β 

package com.chickenwand3.rpgmod.core.capabilities.entity;

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

@SuppressWarnings("removal")
public class CapabilityMobLevel {

    @CapabilityInject(MobLevel.class)
    public static Capability<MobLevel> MOB_LEVEL_CAPABILITY = null;

    public static void register() {
        CapabilityManager.INSTANCE.register(MobLevel.class);
    }
}
package com.chickenwand3.rpgmod.core.capabilities.entity;

public class DefaultMobLevel implements MobLevel {

    public int mobLevel;
    public float mobMaxHealth;
    public float mobCurrentHealth;
    public boolean crazy;
    
    public boolean isCrazy() {
    	return crazy;
    }
    
    public float getMaxHealth() {
    	return mobMaxHealth;
    }
    
    public float getCurrentHealth() {
    	return mobCurrentHealth;
    }
}
package com.chickenwand3.rpgmod.core.capabilities.entity;

public interface MobLevel {
}
package com.chickenwand3.rpgmod.core.capabilities.entity;

import com.chickenwand3.rpgmod.RPGMod;

import net.minecraft.resources.ResourceLocation;

import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.monster.Zombie;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber(modid = RPGMod.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class MobLevelEventHandler {
	@SubscribeEvent
	public static void onAttachCapabilitiesEvent(AttachCapabilitiesEvent<Entity> event) {
		if (event.getObject() instanceof Mob && !event.getObject().getCommandSenderWorld().isClientSide) {
			MobLevelProvider providerMobLevel = new MobLevelProvider();
			event.addCapability(new ResourceLocation(RPGMod.MODID, "moblevel"), providerMobLevel);
			event.addListener(providerMobLevel::invalidate);
		}
	}

	@SubscribeEvent
	public static void OnSpawn(final EntityJoinWorldEvent event) {
		if (event.getEntity()instanceof Mob target && !event.getWorld().isClientSide) {
			target.getCapability(CapabilityMobLevel.MOB_LEVEL_CAPABILITY).ifPresent(mobLevel -> {
				DefaultMobLevel actualMobLevel = (DefaultMobLevel) mobLevel;
				actualMobLevel.mobLevel = (randomizeMobLevel());

				if (superCrazy(actualMobLevel.mobLevel)) {
					actualMobLevel.crazy = true;
				}

				if (actualMobLevel.crazy) {

					if (!target.getMainHandItem().isEmpty()) {
						target.getMainHandItem().enchant(Enchantments.FIRE_ASPECT, 1);
					}
					if (event.getEntity()instanceof Zombie zombie) {
						zombie.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(0.99D);
					}
					System.out.println("Super Crazy " + target.getName() + " has spawned!");
				}

				actualMobLevel.mobMaxHealth = (target.getMaxHealth() * actualMobLevel.mobLevel * 2);
				actualMobLevel.mobCurrentHealth = actualMobLevel.mobMaxHealth;
				target.getAttribute(Attributes.MOVEMENT_SPEED)
						.setBaseValue(target.getAttributeValue(Attributes.MOVEMENT_SPEED)
								* (1 + (actualMobLevel.mobLevel - 1.0) / 10.0));

				if (target.getAttribute(Attributes.ATTACK_DAMAGE) != null) {
					target.getAttribute(Attributes.ATTACK_DAMAGE)
							.setBaseValue(target.getAttributeValue(Attributes.ATTACK_DAMAGE)
									* (1 + (actualMobLevel.mobLevel - 1.0) / 2.0));
				}

			});
		}
	}

	private static int randomizeMobLevel() {
		boolean roll = true;
		int level = 1;
		while (roll) {
			if (Math.random() > .5) {
				level += 1;
				roll = true;
			} else {
				roll = false;
			}
		}
		return level;
	}

	private static boolean superCrazy(int level) {
		boolean result = false;
		if (level >= 5) {
			if (Math.random() < .25) {
				result = true;
			} else
				result = false;
		}
		return result;
	}

}
package com.chickenwand3.rpgmod.core.capabilities.entity;

import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;

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

public class MobLevelProvider implements ICapabilitySerializable<CompoundTag> {
    private final DefaultMobLevel mobLevel = new DefaultMobLevel();
    private final LazyOptional<MobLevel> mobLevelOptional = LazyOptional.of(() -> mobLevel);

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

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

    @Override
    public CompoundTag serializeNBT() {
        if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY == null) {
            return new CompoundTag();
        } else {
            CompoundTag compoundNBT = new CompoundTag();
            compoundNBT.putInt("mobLevel", mobLevel.mobLevel);
            compoundNBT.putFloat("mobCurrentHealth", mobLevel.mobCurrentHealth);
            compoundNBT.putFloat("mobMaxHealth", mobLevel.mobMaxHealth);
            compoundNBT.putBoolean("crazy", mobLevel.crazy);
            return compoundNBT;
        }
    }
    

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY != null) {
            mobLevel.mobLevel = (nbt.getInt("mobLevel"));
            
            float mobCurrentHealth = nbt.getFloat("mobCurrentHealth");
            mobLevel.mobCurrentHealth = (mobCurrentHealth);
            
            float mobMaxHealth = nbt.getFloat("mobMaxHealth");
            mobLevel.mobMaxHealth = (mobMaxHealth);
            
            boolean crazy = nbt.getBoolean("crazy");
            mobLevel.crazy = (crazy);
        }
    }
}

Β 

Link to comment
Share on other sites

4 hours ago, chickenwand3 said:

I will upload all my files relating to the capability and hope you guys can lead me in the right direction

Is that a question?

If yes,Β your capability should be saved since your CapabilityProvider implementsΒ ICapabilitySerializable

Link to comment
Share on other sites

Yeah its a question sorry for phrasing it weird, currently everytime I restart the server the mobs .mobLevel is being reset because it isn't saving. Im trying to decipher why this is happening and how to make it so that the .mobLevel for all the mobs in the server persists after a server restart :)

Link to comment
Share on other sites

https://pastebin.com/LvSbvYhL
Β 

@Override
    public CompoundTag serializeNBT() {
    	System.out.println("It serialized");
        if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY == null) {
        	System.out.println("It made a new compound");
            return new CompoundTag();
        } else {
        	System.out.println("It serialized the values");
            CompoundTag compoundNBT = new CompoundTag();
            compoundNBT.putInt("mobLevel", mobLevel.mobLevel);
            compoundNBT.putFloat("mobCurrentHealth", mobLevel.mobCurrentHealth);
            compoundNBT.putFloat("mobMaxHealth", mobLevel.mobMaxHealth);
            compoundNBT.putBoolean("crazy", mobLevel.crazy);
            return compoundNBT;
        }
    }
    

    @Override
    public void deserializeNBT(CompoundTag nbt) {
    	System.out.println("It deserialized");
        if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY != null) {
        	System.out.println("It deserialized the values");
            mobLevel.mobLevel = (nbt.getInt("mobLevel"));
            
            float mobCurrentHealth = nbt.getFloat("mobCurrentHealth");
            mobLevel.mobCurrentHealth = (mobCurrentHealth);
            
            float mobMaxHealth = nbt.getFloat("mobMaxHealth");
            mobLevel.mobMaxHealth = (mobMaxHealth);
            
            boolean crazy = nbt.getBoolean("crazy");
            mobLevel.crazy = (crazy);
        }
    }

It seems like CapabilityMobLevel.MOB_LEVEL_CAPABILITY is always null and that is why it is acting like its a new entity and generating new values
Β 

Link to comment
Share on other sites

It worked thanks a lot ❀️ I'm gonna paste all of my code for anyone in the future looking to do capabilities

package com.chickenwand3.rpgmod.core.capabilities.entity;

import javax.annotation.Nullable;

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

public class CapabilityMobLevel{
	
    public static Capability<MobLevel> MOB_LEVEL_CAPABILITY = CapabilityManager.get(new CapabilityToken<>() {});
    
    public static void register() {
        CapabilityManager.INSTANCE.register(MobLevel.class);
    }
    

}
package com.chickenwand3.rpgmod.core.capabilities.entity;

public class DefaultMobLevel implements MobLevel {

    public int mobLevel;
    public float mobMaxHealth;
    public float mobCurrentHealth;
    public boolean crazy;
    
    public boolean isCrazy() {
    	return crazy;
    }
    
    public float getMaxHealth() {
    	return mobMaxHealth;
    }
    
    public float getCurrentHealth() {
    	return mobCurrentHealth;
    }
}
package com.chickenwand3.rpgmod.core.capabilities.entity;

public interface MobLevel {
}
package com.chickenwand3.rpgmod.core.capabilities.entity;

import com.chickenwand3.rpgmod.RPGMod;

import net.minecraft.resources.ResourceLocation;

import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.animal.Animal;
import net.minecraft.world.entity.monster.Zombie;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber(modid = RPGMod.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class MobLevelEventHandler {
	@SubscribeEvent
	public static void onAttachCapabilitiesEvent(AttachCapabilitiesEvent<Entity> event) {
		if (event.getObject() instanceof Mob && !event.getObject().getCommandSenderWorld().isClientSide) {
			MobLevelProvider providerMobLevel = new MobLevelProvider();
			event.addCapability(new ResourceLocation(RPGMod.MODID, "moblevel"), providerMobLevel);
			event.addListener(providerMobLevel::invalidate);
		}
	}
	
	@SubscribeEvent
	public void registerCaps(RegisterCapabilitiesEvent event) {
	    event.register(MobLevel.class);
	}
	
	
	

	@SubscribeEvent
	public static void OnSpawn(final EntityJoinWorldEvent event) {
		if (event.getEntity()instanceof Mob target && !event.getWorld().isClientSide) {
			target.getCapability(CapabilityMobLevel.MOB_LEVEL_CAPABILITY).ifPresent(mobLevel -> {
				DefaultMobLevel actualMobLevel = (DefaultMobLevel) mobLevel;
				
				if (actualMobLevel.mobLevel < 1) {
					actualMobLevel.mobLevel = (randomizeMobLevel());
				}

				if (superCrazy(actualMobLevel.mobLevel)) {
					actualMobLevel.crazy = true;
				}

				if (actualMobLevel.crazy) {

					if (!target.getMainHandItem().isEmpty()) {
						target.getMainHandItem().enchant(Enchantments.FIRE_ASPECT, 1);
					}
					if (event.getEntity()instanceof Zombie zombie) {
						zombie.getAttribute(Attributes.SPAWN_REINFORCEMENTS_CHANCE).setBaseValue(0.99D);
					}
					System.out.println("Super Crazy " + target.getName() + " has spawned!");
				}

				actualMobLevel.mobMaxHealth = (target.getMaxHealth() * actualMobLevel.mobLevel * 2);
				actualMobLevel.mobCurrentHealth = actualMobLevel.mobMaxHealth;
				target.getAttribute(Attributes.MOVEMENT_SPEED)
						.setBaseValue(target.getAttributeValue(Attributes.MOVEMENT_SPEED)
								* (1 + (actualMobLevel.mobLevel - 1.0) / 10.0));

				if (target.getAttribute(Attributes.ATTACK_DAMAGE) != null) {
					target.getAttribute(Attributes.ATTACK_DAMAGE)
							.setBaseValue(target.getAttributeValue(Attributes.ATTACK_DAMAGE)
									* (1 + (actualMobLevel.mobLevel - 1.0) / 2.0));
				}

			});
		}
	}

	private static int randomizeMobLevel() {
		boolean roll = true;
		int level = 1;
		while (roll) {
			if (Math.random() > .5) {
				level += 1;
				roll = true;
			} else {
				roll = false;
			}
		}
		return level;
	}

	private static boolean superCrazy(int level) {
		boolean result = false;
		if (level >= 5) {
			if (Math.random() < .25) {
				result = true;
			} else
				result = false;
		}
		return result;
	}

}
package com.chickenwand3.rpgmod.core.capabilities.entity;

import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;

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

public class MobLevelProvider implements ICapabilitySerializable<CompoundTag> {
    private final DefaultMobLevel mobLevel = new DefaultMobLevel();
    private final LazyOptional<MobLevel> mobLevelOptional = LazyOptional.of(() -> mobLevel);

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

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

    @Override
    public CompoundTag serializeNBT() {
    	System.out.println("It serialized");
        if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY == null) {
        	System.out.println("It made a new compound");
            return new CompoundTag();
        } else {
        	System.out.println("It serialized the values");
            CompoundTag compoundNBT = new CompoundTag();
            compoundNBT.putInt("mobLevel", mobLevel.mobLevel);
            compoundNBT.putFloat("mobCurrentHealth", mobLevel.mobCurrentHealth);
            compoundNBT.putFloat("mobMaxHealth", mobLevel.mobMaxHealth);
            compoundNBT.putBoolean("crazy", mobLevel.crazy);
            return compoundNBT;
        }
    }
    

    @Override
    public void deserializeNBT(CompoundTag nbt) {
    	System.out.println("It deserialized");
        if (CapabilityMobLevel.MOB_LEVEL_CAPABILITY != null) {
        	System.out.println("It deserialized the values");
            mobLevel.mobLevel = (nbt.getInt("mobLevel"));
            
            float mobCurrentHealth = nbt.getFloat("mobCurrentHealth");
            mobLevel.mobCurrentHealth = (mobCurrentHealth);
            
            float mobMaxHealth = nbt.getFloat("mobMaxHealth");
            mobLevel.mobMaxHealth = (mobMaxHealth);
            
            boolean crazy = nbt.getBoolean("crazy");
            mobLevel.crazy = (crazy);
        }
    }
}

Β 

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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • BabaΒ  Serege [[+27-73 590 8989]] has experience of 27 years in helping and guiding many people from all over the world. His psychic abilities may help you answer and resolve many unanswered questions. He specialize in helping women and men from all walks of life.. 1) – Bring back lost lover. even if lost for a long time. 2) – My lover is abusing alcohol, partying and cheating on me I urgently need help” 3) – Divorce or court issues. 4) – Is your love falling apart? 5) – Do you want your love to grow stronger? 6) – Is your partner losing interest in you? 7) – Do you want to catch your partner cheating on you? – We help to keep your partner faithful and loyal to you. 9) – We recover love and happiness when relationship breaks down. 10) – Making your partner loves you alone. 11) – We create loyalty and everlasting love between couples. 12) – Get a divorce settlement quickly from your ex-partner. 13) – We create everlasting love between couples. 14) – We help you look for the best suitable partner. 15) – We bring back lost lover even if lost for a long time. 16) – We strengthen bonds in all love relationship and marriages 17) – Are you an herbalist who wants to get more powers? 18) – Buy a house or car of your dream. 19) – Unfinished jobs by other doctors come to me. 20) – I help those seeking employment. 21) – Pensioners free treatment. 22) – Win business tenders and contracts. 23) – Do you need to recover your lost property? 24) – Promotion at work and better pay. 25) – Do you want to be protected from bad spirits and nightmares? 26) – Financial problems. 27) – Why you can’t keep money or lovers? 28) – Why you have a lot of enemies? 29) – Why you are fired regularly on jobs? 30) – Speed up money claim spell, delayed payments, pension and accident funds 31) – I help students pass their exams/interviews. 33) – Removal of bad luck and debts. 34) – Are struggling to sleep because of a spiritual wife or husband. 35- ) Recover stolen property
    • OLXTOTOΒ adalah situs bandar togel online resmi terbesar dan terpercaya di Indonesia. Bergabunglah dengan OLXTOTO dan nikmati pengalaman bermain togel yang aman dan terjamin. Koleksi toto 4D dan togel toto terlengkap di OLXTOTO membuat para member memiliki pilihan taruhan yang lebih banyak. Sebagai situs togel terpercaya, OLXTOTO menjaga keamanan dan kenyamanan para membernya dengan sistem keamanan terbaik dan enkripsi data. Transaksi yang cepat, aman, dan terpercaya merupakan jaminan dari OLXTOTO. Nikmati layanan situs toto terbaik dari OLXTOTO dengan tampilan yang user-friendly dan mudah digunakan. Layanan pelanggan tersedia 24/7 untuk membantu para member. Bergabunglah dengan OLXTOTO sekarang untuk merasakan pengalaman bermain togel yang menyenangkan dan menguntungkan.
    • BabaΒ  Serege [[+27-73 590 8989]] has experience of 27 years in helping and guiding many people from all over the world. His psychic abilities may help you answer and resolve many unanswered questions. He specialize in helping women and men from all walks of life.. 1) – Bring back lost lover. even if lost for a long time. 2) – My lover is abusing alcohol, partying and cheating on me I urgently need help” 3) – Divorce or court issues. 4) – Is your love falling apart? 5) – Do you want your love to grow stronger? 6) – Is your partner losing interest in you? 7) – Do you want to catch your partner cheating on you? – We help to keep your partner faithful and loyal to you. 9) – We recover love and happiness when relationship breaks down. 10) – Making your partner loves you alone. 11) – We create loyalty and everlasting love between couples. 12) – Get a divorce settlement quickly from your ex-partner. 13) – We create everlasting love between couples. 14) – We help you look for the best suitable partner. 15) – We bring back lost lover even if lost for a long time. 16) – We strengthen bonds in all love relationship and marriages 17) – Are you an herbalist who wants to get more powers? 18) – Buy a house or car of your dream. 19) – Unfinished jobs by other doctors come to me. 20) – I help those seeking employment. 21) – Pensioners free treatment. 22) – Win business tenders and contracts. 23) – Do you need to recover your lost property? 24) – Promotion at work and better pay. 25) – Do you want to be protected from bad spirits and nightmares? 26) – Financial problems. 27) – Why you can’t keep money or lovers? 28) – Why you have a lot of enemies? 29) – Why you are fired regularly on jobs? 30) – Speed up money claim spell, delayed payments, pension and accident funds 31) – I help students pass their exams/interviews. 33) – Removal of bad luck and debts. 34) – Are struggling to sleep because of a spiritual wife or husband. 35- ) Recover stolen property
    • BD303 merupakan salah satu situs slot mudah scatter paling populer dan digemari oleh kalangan slot online di tahun 2024 mainkan sekarang dengan kesempatan yang mudah menang jackpot jutaan rupiah.
  • Topics

×
×
  • Create New...

Important Information

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