Jump to content

Recommended Posts

Posted (edited)

I am trying to replace TileEntityA by another mod with TileEntityB, for I would like to make hoppers extract items from a certain slot of the tile entities.
TileEntityA is registered as "moda:tileentitya" and TileEntityB is registered as "modb:tileentityb," like:

@SubscribeEvent
public static void registerTileEntities(final RegistryEvent.Register<TileEntityType<?>> event) {
	TileEntityType<TileEntityB> TILEENTITY_B = TileEntityType.Builder.create(TileEntityB::new, BLOCK_A);
	TILEENTITY_B.setRegistryName(new ResourceLocation(ModB.MODID, "tileentityb");
    event.getRegistry().register(TILEENTITY_B);
}

So far, this registration and EntityPlaceEvent as below work well enough:

@SubscribeEvent
public static void onBlockPlaced(BlockEvent.EntityPlaceEvent event) {
    IWorld world = event.getWorld();
    BlockPos pos = event.getPos();
    if (world != null) {
        Block block = event.getPlacedBlock().getBlock();
        if (block.getRegistryName().equals(new ResourceLocation("moda:blocka"))) {
            TileEntityB tileEntityB = new tileEntityB();
            world.getWorld().setTileEntity(pos, tileEntityB);
        }
    }
}

However, I haven't found out a way to replace tileentities when the chunk loads.

I tried some codes like:

@SubscribeEvent
public static void onChunkLoad(ChunkEvent.Load event) {
    IChunk chunk = event.getChunk();
    IWorld iWorld = event.getWorld();
    if ((chunk != null)&&(iWorld != null)) {
        if (iWorld.isRemote()) return;
        for (BlockPos pos: chunk.getTileEntitiesPos()) {
            TileEntity tileEntity = chunk.getTileEntity(pos);
            if (tileEntity instanceof TileEntityA && !(tileEntity instanceof TileEntityB)) {
                TileEntityB tileEntityB = new TileEntityB();
                chunk.removeTileEntity(pos);
                chunk.addTileEntity(pos, tileEntityB);
            }
        }
    }
}

which prevented tileEntityB.tick() from firing (I confirmed it with the Logger), and

@SubscribeEvent
public static void onChunkLoad(ChunkEvent.Load event) {
    IChunk chunk = event.getChunk();
    IWorld iWorld = event.getWorld();
    if ((chunk != null)&&(iWorld != null)) {
        if (iWorld.isRemote()) return;
        World world = iWorld.getWorld();
        for (BlockPos pos: chunk.getTileEntitiesPos()) {
            TileEntity tileEntity = world.getTileEntity(pos);
            if (tileEntity instanceof TileEntityA && !(tileEntity instanceof TileEntityB)) {
                TileEntityB tileEntityB = new TileEntityB();
                world.setTileEntity(pos, tileEntityB);
            }
        }
    }
}

which made Minecraft freeze just after 100 % display.
Though I think I need an event fired after chunk loading or a way to make TileEntityB totally override TileEntityA, I have not come up with any idea.
 

Thank you

Edited by Sabotember
Posted

Thank you for your reply. I am now trying to attach my capability to TileEntityA, but no other methods than attachMyCapability(), MyCapabilityProvider.serializeNBT(), MyCapabilityProvider.deserializeNBT() were called.
Here is the main point of my capability:

@Mod.EventBusSubscriber(modid = ModB.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
public class MyCapability implements ISidedInventory {
    private static final ResourceLocation CAP_ID = new ResourceLocation(ModB.MODID, "capB");
    public static final Callable<MyCapability> FACTORY = new Factory();
    public static final Capability.IStorage<MyCapability> STORAGE = new Storage();
    /* Constructors and fields here */

    @SubscribeEvent
    public static void attachMyCapability(@Nonnull AttachCapabilitiesEvent<TileEntity> event) {
        if(event.getCapabilities().containsKey(CAP_ID)) return;
        if(event.getObject() instanceof TileEntityA) {
            event.addCapability(CAP_ID, new MyCapability((TileEntityA) event.getObject()));
        }
    }
  
    @Override
    public final boolean canExtractItem(int slot, ItemStack itemStack, Direction direction) {/* Implementation here */}
    /* clear(), decrStackSize(), getSizeInventory(), getSlotsForFace(), getStackInSlot(), isEmpty(), isUsableByPlayer, markDirty(), removeStackFromSlot(), setInventolySlotContents here */
  
    private static class Factory implements Callable<MyCapability> {
        public MyCapability call() throws Exception {
            return new MyCapability();
        }
    }
  
    private static class MyCapabilityProvider extends MyCapability implements ICapabilityProvider, INBTSerializable<CompoundNBT> {
        /* getCapability(), serializeNBT(), deserializeNBT() here */
    }
  
    private static class Storage implements Capability.IStorage<MyCapability> {
        /* readNBT, writeNBT here */
    }
}

and the registration is like:

public ModB() { // Mod Constructor
    FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
    MinecraftForge.EVENT_BUS.register(this);
}

private void setup(final FMLCommonSetupEvent event) {
    CapabilityManager.INSTANCE.register(MyCapability.class, MyCapability.STORAGE, MyCapability.FACTORY);
}

Though I read the Forge documentation and some examples using AttachCapabilitiesEvent, I have not found a way to enable my capability...

Posted

I am trying to attach my capability to TileEntityA by another mod so that hoppers extract items from only a certain slot of TileEntityA. Without capability they extract items from any slot.

Posted (edited)
6 hours ago, loordgek said:

that is never going to work

 

1 tileB needs to extend tileA

2 change the code you need to change

3 in registerTileEntities register tileB as tileA

I tried this way, but probably because BlockA returns TileA in its createTileEntity() method, a "missing a mapping" error occurs in loading the world. Do I need "BlockB" class which extends BlockA in addition to TileB?
 

 

On 2/3/2021 at 5:09 PM, diesieben07 said:

This will break completely, as the mod will expect the correct tile entity to be there. Also Minecraft will fight you every step of the way to keep the correct tile entity in place.

Just use AttachCapabilityEvent to attach the IItemHandler capability to the tile entity and hoppers will happily use it.

Well, I just find out that I did not implement IItemHandler in MyCapability. I will try this way again.

Edited by Sabotember
Posted
2 hours ago, Sabotember said:

I tried this way, but probably because BlockA returns TileA in its createTileEntity() method, a "missing a mapping" error occurs in loading the world. Do I need "BlockB" class which extends BlockA in addition to TileB?

yes

Posted

Thank you for your replies. I am now trying to override TileA and BlockA with TileB and BlockB and it seems to be partially successful.

I confirmed with PlayerInteractEvent.RightClickBlock that TileB and BlockB replace TileA and BlockA.

However, I mean by "partially" that the methods "canExtractItem" and "canInsertItem" are never called though TileB implements ISidedInventory and there are two Hoppers on and below a BlockB in the world.

I guess that somehow some data of TileA remain in the world which prevents HopperTileEntity from judging TileB to be an ISidedInventory...

Posted

I am afraid that I do not understand to enable my capability.

Now my capability is like:

public class MyCapability implements IItemHandler {
  	private final TileEntityA tile;
  
    public MyCapability(TileEntityA tile) {
        super();
        this.tile = tile;
    }
  
    public MyCapability() {
        super();
        this.tile = new TileEntityA();
    }
  
    @Override
    @Nonnull
    public ItemStack extractItem(int slot, int amount, boolean simulate) {
        /* implementation */
    }
    /* getSlotLimit, getSlots, getStackInSlot, insertItem, isItemValid */
  
    public static class Storage implements Capability.IStorage<MyCapability> {
        /* readNBT, writeNBT */
    }
}

and the provider is like:

public class MyCapabilityProvider implements ICapabilityProvider {

    @CapabilityInject(MyCapability.class)
    public static Capability<MyCapability> CAP = null;
  
    private final TileEntityA tile;
  
    public MyCapabilityProvider(TileEntityA tile) {
        this.tile = tile;
    }
  
    @Override
    @Nonnull
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap.getClass.equals(CAP.getclass())) {
            return LazyOptional.of(() -> new MyCapability(tile)).cast();
        }
        return LazyOptional.empty();
    }
}

I registered it by calling the following method in my FMLCommonSetupEvent method:

public static void registerCapabilities() {
    CapabilityManager.INSTANCE.register(MyCapability.class, new MyCapability.Storage(), MyCapability::new);
}

Lastly, my AttachCapabilitiesEvent is:

@SubscribeEvent
public static void onAttachCapability(AttachCapabilitiesEvent<TileEntity> event) {
    TileEntity tile = event.getObject();
    if (tile instanceof TileEntityA) {
        event.addCapability(new ResourceLocation(ModB.MODID, "mycapability"), new MyCapabilityProvider((TileEntityA) tile));
    }
}

I confirmed that the AttachCapabilitiesEvent fired and that a MyCapabilityProvider instance created, but neither any methods in MyCapability class nor getCapability() in my provider was called...

Posted
2 hours ago, diesieben07 said:
  • dafuq is this? This makes zero sense and should not even compile. Compare Capability instances using ==.

  • Do not create a new LazyOptional every time.

Okay, I fixed getCapability().

2 hours ago, diesieben07 said:

Does the TileEntity alredy expose an IItemHandler by default?

I think so, because it extends LockableTileEntity.

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



×
×
  • Create New...

Important Information

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