Jump to content

Recommended Posts

Posted (edited)

In my capability's Provider class, I set JUICED_ITEM_CAPABILITY to null.

This caused the NullPointerException, which I half expected, but only half

because that was how it was done for CapabilityEnergy, and I'm not sure

why. I've tried making it final, and I've tried leaving it unassigned, but neither

worked. I'm relatively new to the capability system and I clearly still don't

understand it in full. I've read through this topic in full, as well as the docs,

but nothing I read lead me to any other possible fix.

 

Here's my capability's provider class:

package zorochase.oneirocraft.capability;

import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;

public class JuicedItemProvider implements ICapabilitySerializable<INBT> {

    @CapabilityInject(IJuicedItem.class)
    public static Capability<IJuicedItem> JUICED_ITEM_CAPABILITY = null;
    private LazyOptional<IJuicedItem> instance = LazyOptional.of(JUICED_ITEM_CAPABILITY::getDefaultInstance);

    @Override
    public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
        return cap == JUICED_ITEM_CAPABILITY ? instance.cast() : LazyOptional.empty();
    }

    @Override
    public INBT serializeNBT() {
        return JUICED_ITEM_CAPABILITY.getStorage().writeNBT(JUICED_ITEM_CAPABILITY, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null);
    }

    @Override
    public void deserializeNBT(INBT nbt) {
        JUICED_ITEM_CAPABILITY.getStorage().readNBT(JUICED_ITEM_CAPABILITY, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null, nbt);
    }
}

 

I tried attaching the capability to a custom sword like so:

@Override
public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
    return new JuicedItemProvider();
}

 

I also registered the capability in my main mod class like so:

@SubscribeEvent
public static void onCommonSetup(FMLCommonSetupEvent event) {
    CapabilityManager.INSTANCE.register(IJuicedItem.class, new JuicedItemStorage(), JuicedItemImpl::new);
}

 

Here is the full crash report, if necessary.

If I do get any help, I'd really appreciate it.

Edited by Zorochase
Posted

I discovered with my mod that due to the order of class loading (item registration depending on the ItemGroup from my main class) my initCapabilities method was being called before my capability instance was set, so it was attempting to call null.getDefaultInstance and throwing the error.

I resolved the issue by wrapping it in an additional supplier, so the capability was definitely set by the time it was used.

  • Like 1
Posted
2 hours ago, Alpvax said:

I discovered with my mod that due to the order of class loading (item registration depending on the ItemGroup from my main class) my initCapabilities method was being called before my capability instance was set, so it was attempting to call null.getDefaultInstance and throwing the error.

I resolved the issue by wrapping it in an additional supplier, so the capability was definitely set by the time it was used.

Thanks for your response. I understand what you mean, but I couldn't quite figure out how to wrap it correctly. Would you be able to show me an example of how you did it?

Posted
class Provider implements ICapabilityProvider {
    private Supplier<IMultitool> multitoolSup;

    Provider() {
      this(() -> Capabilities.MULTITOOL_CAPABILITY.getDefaultInstance());
    }
    Provider(Supplier<IMultitool> sup) {
      multitoolSup = sup;
    }

    private LazyOptional<IMultitool> capability = LazyOptional.of(() -> multitoolSup.get());

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
      return cap == Capabilities.MULTITOOL_CAPABILITY ? capability.cast() : LazyOptional.empty();
    }
  }

I had the advantage that my capability currently just acts as a flag, so I don't care about storing it for later use (i.e. I can just create a new instance every time with no issues).

You will probably want to save the value of `supplier.get()` if you interact with it outside of the LazyOptional.

Posted
1 hour ago, Alpvax said:

class Provider implements ICapabilityProvider {
    private Supplier<IMultitool> multitoolSup;

    Provider() {
      this(() -> Capabilities.MULTITOOL_CAPABILITY.getDefaultInstance());
    }
    Provider(Supplier<IMultitool> sup) {
      multitoolSup = sup;
    }

    private LazyOptional<IMultitool> capability = LazyOptional.of(() -> multitoolSup.get());

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
      return cap == Capabilities.MULTITOOL_CAPABILITY ? capability.cast() : LazyOptional.empty();
    }
  }

I had the advantage that my capability currently just acts as a flag, so I don't care about storing it for later use (i.e. I can just create a new instance every time with no issues).

You will probably want to save the value of `supplier.get()` if you interact with it outside of the LazyOptional.

Alright, so applying your suggestion to my code did fix the error. However, there's another problem, and I'm not sure exactly what's causing it. It could be an issue with my capability's storage class, it could be that I'm not attaching the capability properly, or something else, but when I went to check my custom sword in-game, instead of printing the amount of "juice" it was supposed to store (juice is just another word for energy; it's just an int value) in the sword's tooltip, it just printed this: https://imgur.com/a/vOUhiDo

 

Here's my updated Provider class, in case that could have an effect on the above issue:

package zorochase.oneirocraft.capability;

import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.LazyOptional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.Supplier;

public class JuicedItemProvider implements ICapabilityProvider {

    private Supplier<IJuicedItem> juicedItemSupplier;

    @CapabilityInject(IJuicedItem.class)
    public static Capability<IJuicedItem> JUICED_ITEM_CAPABILITY = null;

    public JuicedItemProvider() {
        this(() -> JUICED_ITEM_CAPABILITY.getDefaultInstance());
    }
    JuicedItemProvider(Supplier<IJuicedItem> sup) {
        this.juicedItemSupplier = sup;
    }

    private LazyOptional<IJuicedItem> capability = LazyOptional.of(() -> juicedItemSupplier.get());

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        return cap == JUICED_ITEM_CAPABILITY ? capability.cast() : LazyOptional.empty();
    }

}

 

Here's the storage class:

package zorochase.oneirocraft.capability;

import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;

import javax.annotation.Nullable;

public class JuicedItemStorage implements Capability.IStorage<IJuicedItem> {

    @Nullable
    @Override
    public INBT writeNBT(Capability<IJuicedItem> capability, IJuicedItem instance, Direction side) {
        CompoundNBT tag = new CompoundNBT();
        tag.putInt("juice", instance.getJuice());
        tag.putInt("maxJuiceTransferable", instance.getMaxJuiceTransferable());
        tag.putBoolean("empowered", instance.getIsEmpowered());
        return tag;
    }

    @Override
    public void readNBT(Capability<IJuicedItem> capability, IJuicedItem instance, Direction side, INBT nbt) {
        CompoundNBT tag = (CompoundNBT) nbt;
        instance.setJuice(tag.getInt("juice"));
        instance.setJuiceTransferLimit(tag.getInt("maxJuiceTransferable"));
        instance.setEmpowered(tag.getBoolean("empowered"));
    }
}

 

Here's how I'm printing the sword's "juice":

    @Override
    public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
        tooltip.add(
                new TranslationTextComponent(
                        String.valueOf(
                                stack.getCapability(JuicedItemProvider.JUICED_ITEM_CAPABILITY).map(IJuicedItem::getJuice)
                        )
                ).applyTextStyle(TextFormatting.AQUA)
        );
    }

 

And here's what I did to attach it in my main class:

    @SubscribeEvent
    public static void onAttachCapabilities(AttachCapabilitiesEvent<ItemStack> event) {
        Item item = event.getObject().getItem();
        if (item instanceof DreamsteelSwordItem) {
            event.addCapability(new ResourceLocation(Oneirocraft.MOD_ID, "juiceditem"), new JuicedItemProvider());
        }
    }

 

Again, I really do appreciate your help. I apologize for requesting it continually, it's only because I'm having a hard time wrapping my head around this concept.

Posted

After messing with the code a little more, (I think) I figured out I wasn't supposed to use .map to access the getJuice method. However, I tried a few variations of the following code, and it only, funny enough, produced another NullPointerException. Here's what I last tried:

    @Override
    public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
        if (stack.getCapability(JuicedItemProvider.JUICED_ITEM_CAPABILITY).isPresent()) {
            stack.getCapability(JuicedItemProvider.JUICED_ITEM_CAPABILITY).ifPresent(juicedItem -> {
                int storedJuice = juicedItem.getJuice();
                tooltip.add(new TranslationTextComponent(String.valueOf(storedJuice)).applyTextStyle(TextFormatting.AQUA));
            });
        }
    }

 

I'm pretty sure there's no reason for me to check isPresent first. I left that out, produced the same error. I moved tooltip.add outside the lambda and made storedJuice an AtomicInteger, same error. I'm still using the same updated provider from the above reply. Here's the new error: https://pastebin.com/LJkhRes3

Posted
18 hours ago, Zorochase said:

@SubscribeEvent
public static void onAttachCapabilities(AttachCapabilitiesEvent<ItemStack> event) {
    Item item = event.getObject().getItem();
    if (item instanceof DreamsteelSwordItem) {
        event.addCapability(new ResourceLocation(Oneirocraft.MOD_ID, "juiceditem"), new JuicedItemProvider());
    }
}

 

This is not how you should add capabilities to your own items, you should override IForgeItem#initCapabilities: 

@Nullable
@Override
public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
    return new IMultitool.Provider();
}

I can't really tell from the snippets you have posted, do you have a git repository?

Use your IDE to set breakpoints to try and find what is actually null when that function is called.

Posted (edited)
13 hours ago, Alpvax said:

I can't really tell from the snippets you have posted, do you have a git repository?

My project was a bit messy, so I didn't have one. I cleaned it up a bit and made one, here's the link: https://github.com/Zorochase/Oneirocraft

 

13 hours ago, Alpvax said:

Use your IDE to set breakpoints to try and find what is actually null when that function is called.

I found out that the same issue from before wasn't totally fixed; wrapping the provider in a supplier only worked for initCapabilities (which I actually always had, I just added attachCapabilities later on because I wasn't sure whether it was necessary). That didn't actually ensure that the capability was set before the sword's other methods (I.E. addInformation) were called.

 

 

EDIT: As of this edit, the code you see on Github now correctly prints the amount of juice stored in the custom sword... but it doesn't update when I kill an entity, even though it should. It only updates when you leave the world and come back. This is the only known issue now.

Edited by Zorochase
Posted
23 hours ago, Zorochase said:

It only updates when you leave the world and come back. 

Sounds like you need to sync the changes to the client when it changes.

Posted (edited)
1 hour ago, Alpvax said:

Sounds like you need to sync the changes to the client when it changes.

I thought so, but I don't know how... been looking around for ways to do that but I haven't found anything specific to my situation, just for PlayerEntities.

 

EDIT: Nevermind, I've got myself on the right path now. Once again, thank you so much for your help. It will take me time to fully understand all the concepts I've come across but I know where to take it from here.

Edited by Zorochase
  • Like 1

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

    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

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