Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[1.17.1] Forge Capability - How to save?


chickenwand3
 Share

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
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.

 Share



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • @poopoodice Thanks! So, assuming that I got your comment correctly, would this be a proper way to apply an effect:   @Override public void doPostAttack(LivingEntity pAttacker, Entity pTarget, int pLevel) { // IF: Code is executing on the client. if (pAttacker.level.isClientSide()) { return; } // IF: Entity is not living entity. if (!(pTarget instanceof LivingEntity)) { return; } // Cast entity to living entity. LivingEntity mob = (LivingEntity)pTarget; // IF: Player already has effect. if (mob.hasEffect(PlayerMobEffects.STUNNED.get())){ return; } // Calculate hit chance. int hitChance = pLevel * 10; // Create random generator. Random random = new Random(); // Get number between 0 and 99. int roll = random.nextInt(100); // IF: Apply on hit chance was missed. if (roll >= hitChance) { return; } // Calculate duration of the effect int duration = 20 * pLevel; // Create instance of effect. MobEffectInstance effect = new MobEffectInstance(PlayerMobEffects.STUNNED.get(), duration, pLevel); // Apply effect to mob. mob.addEffect(effect); }   I have tested the code and it works, although I am not sure if there is smarter way to apply effect. Still need to figure out how to make mob die after it gets stunned.  
    • Hey,   Is it already possible to login and authenticate when your account has been migrated? Currently I just get the error Migrated.
    • Amplifier is like the strength of the effect, for example movement speed boost with amplifier 0 will be Speed I, and 1 will be Speed II, 2 will be Speed III. Effect is just an...effect type, EffectInstance contains all information for the actual effect being applied to the entity (duration, amplifier...etc). For example there's only an effect type "Speed", but for an EffectInstance it could be: "Level 2 Speed for 10 seconds" "Level 4 Speed for 2 seconds"...   The first method applyEffectTick is called when a effect is impacting the entity, the first arg is the entity that has the effect/is affected by the effect, and amplifier is the strength of the effect. The second method isDurationEFfectTick is to check whether the effect should impact/affect the entity this tick (the effects usually don't trigger every tick!), if true, then the first method is called.  
    • Hi, I have enchantment named "Stun" that can be applied to weapon and that has 3 levels: Level 1 - 10% chance to stun mob for 1 sec Level 2 - 20% chance to stun mob for 2 secs Level 3 - 30% chance to stun mob for 3 secs Plan is to apply MobEffect named StunnedMobEffect on doPostAttack in enchantment. StunnedMobEffect should have variable duration based on the level of enchantment that was applied on weapon. I am trying to find an example on how to do the following: How can I set duration of effect dynamically? How can I track whether duration has expired? I have found these two methods that can be overriden:   public void applyEffectTick(LivingEntity pLivingEntity, int pAmplifier) { public boolean isDurationEffectTick(int pDuration, int pAmplifier) { But looking at the source code of MobEffect class, I can't figure out what pAmplifier is? Any hints / samples on this would be appreciated.          
    • 2022-01-22 07:41:00,800 main WARN Advanced terminal features are not available in this environment [07:41:00] [main/INFO] [cp.mo.mo.Launcher/MODLAUNCHER]: ModLauncher running: args [--gameDir, ., --launchTarget, fmlserver, --fml.forgeVersion, 36.2.23, --fml.mcpVersion, 20210115.111550, --fml.mcVersion, 1.16.5, --fml.forgeGroup, net.minecraftforge, nogui] [07:41:00] [main/INFO] [cp.mo.mo.Launcher/MODLAUNCHER]: ModLauncher 8.0.9+86+master.3cf110c starting: java version 17.0.2 by Oracle Corporation Exception in thread "main" java.lang.IllegalAccessError: class cpw.mods.modlauncher.SecureJarHandler (in unnamed module @0x7ff95560) cannot access class sun.security.util.ManifestEntryVerifier (in module java.base) because module java.base does not export sun.security.util to unnamed module @0x7ff95560         at cpw.mods.modlauncher.SecureJarHandler.lambda$static$1(SecureJarHandler.java:41)         at cpw.mods.modlauncher.api.LamdbaExceptionUtils.uncheck(LamdbaExceptionUtils.java:95)         at cpw.mods.modlauncher.SecureJarHandler.<clinit>(SecureJarHandler.java:41)         at cpw.mods.modlauncher.Launcher.lambda$new$6(Launcher.java:55)         at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1708)         at cpw.mods.modlauncher.api.TypesafeMap.computeIfAbsent(TypesafeMap.java:52)         at cpw.mods.modlauncher.api.TypesafeMap.computeIfAbsent(TypesafeMap.java:47)         at cpw.mods.modlauncher.Environment.computePropertyIfAbsent(Environment.java:62)         at cpw.mods.modlauncher.Launcher.<init>(Launcher.java:55)         at cpw.mods.modlauncher.Launcher.main(Launcher.java:66)         at net.minecraftforge.server.ServerMain$Runner.runLauncher(ServerMain.java:63)         at net.minecraftforge.server.ServerMain$Runner.access$100(ServerMain.java:60)         at net.minecraftforge.server.ServerMain.main(ServerMain.java:57) i have the same how do i fix it  
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.