Jump to content

[1.15] Replacing tile entities


Sabotember

Recommended Posts

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
Link to comment
Share on other sites

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

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

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

    • Akun Pro Kamboja adalah pilihan terbaik bagi Anda yang mencari pengalaman bermain slot Maxwin dengan transaksi mudah menggunakan Bank Lampung. Berikut adalah beberapa alasan mengapa Anda harus memilih Akun Pro Kamboja: Slot Maxwin Terbaik Kami menyajikan koleksi slot Maxwin terbaik yang menawarkan kesenangan bermain dan peluang kemenangan besar. Dengan fitur-fitur unggulan dan tema-tema menarik, setiap putaran permainan akan memberikan Anda pengalaman yang tak terlupakan. Transaksi Mudah dengan Bank Lampung Kami menyediakan layanan transaksi mudah melalui Bank Lampung untuk kenyamanan dan keamanan Anda. Dengan proses yang cepat dan efisien, Anda dapat melakukan deposit dan penarikan dana dengan lancar dan tanpa hambatan. Anti Rungkat Akun Pro Kamboja memberikan jaminan "anti rungkat" kepada para pemainnya. Dengan fitur ini, Anda dapat merasakan sensasi bermain dengan percaya diri, karena kami memastikan pengalaman bermain yang adil dan menyenangkan bagi semua pemain.  
    • BINGO188: Destinasi Terbaik untuk Pengalaman Slot yang Terjamin Selamat datang di BINGO188, tempat terbaik bagi para pecinta slot yang mencari pengalaman bermain yang terjamin dan penuh kemenangan. Di sini, kami menawarkan fitur unggulan yang dirancang untuk memastikan kepuasan dan keamanan Anda. Situs Slot Garansi Kekalahan 100 Kami memahami bahwa kadang-kadang kekalahan adalah bagian dari permainan. Namun, di BINGO188, kami memberikan jaminan keamanan dengan fitur garansi kekalahan 100. Jika Anda mengalami kekalahan, kami akan mengembalikan saldo Anda secara penuh. Kemenangan atau uang kembali, kami memastikan Anda tetap merasa aman dan nyaman. Bebas IP Tanpa TO Nikmati kebebasan bermain tanpa batasan IP dan tanpa harus khawatir tentang TO (Turn Over) di BINGO188. Fokuslah pada permainan Anda dan rasakan sensasi kemenangan tanpa hambatan. Server Thailand Paling Gacor Hari Ini Bergabunglah dengan server terbaik di Thailand hanya di BINGO188! Dengan tingkat kemenangan yang tinggi dan pengalaman bermain yang lancar, server kami dijamin akan memberikan Anda pengalaman slot yang tak tertandingi. Kesimpulan BINGO188 adalah pilihan terbaik bagi Anda yang menginginkan pengalaman bermain slot yang terjamin dan penuh kemenangan. Dengan fitur situs slot garansi kekalahan 100, bebas IP tanpa TO, dan server Thailand paling gacor hari ini, kami siap memberikan Anda pengalaman bermain yang aman, nyaman, dan menguntungkan. Bergabunglah sekarang dan mulailah petualangan slot Anda di BINGO188!
    • Mengapa Memilih AlibabaSlot? AlibabaSlot adalah pilihan terbaik bagi Anda yang mencari slot gacor dari Pgsoft dengan transaksi mudah menggunakan Bank Panin. Berikut adalah beberapa alasan mengapa Anda harus memilih AlibabaSlot: Slot Gacor dari Pgsoft Kami menyajikan koleksi slot gacor terbaik dari Pgsoft. Dengan fitur-fitur unggulan dan peluang kemenangan yang tinggi, setiap putaran permainan akan memberikan Anda kesenangan dan keuntungan yang maksimal. Transaksi Mudah dengan Bank Panin Kami menyediakan layanan transaksi mudah melalui Bank Panin untuk kenyamanan dan keamanan Anda. Dengan proses yang cepat dan efisien, Anda dapat melakukan deposit dan penarikan dana dengan lancar dan tanpa masalah.  
    • Delete the jei-server.toml file in your config folder and test it again
    • java.util.ConcurrentModificationException at java.base/java.util.HashMap.computeIfAbsent(Unknown Source) at Genesis//com.moonsworth.lunar. ... Looks like an issue with the Launcher - Make a test with another Launcher like MultiMC, AT Launcher or Technic Launcher or try the original one
  • Topics

×
×
  • Create New...

Important Information

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