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

    • They were already updated, and just to double check I even did a cleanup and fresh update from that same page. I'm quite sure drivers are not the problem here. 
    • i tried downloading the drivers but it says no AMD graphics hardware has been detected    
    • Update your AMD/ATI drivers - get the drivers from their website - do not update via system  
    • As the title says i keep on crashing on forge 1.20.1 even without any mods downloaded, i have the latest drivers (nvidia) and vanilla minecraft works perfectly fine for me logs: https://pastebin.com/5UR01yG9
    • Hello everyone, I'm making this post to seek help for my modded block, It's a special block called FrozenBlock supposed to take the place of an old block, then after a set amount of ticks, it's supposed to revert its Block State, Entity, data... to the old block like this :  The problem I have is that the system breaks when handling multi blocks (I tried some fix but none of them worked) :  The bug I have identified is that the function "setOldBlockFields" in the item's "setFrozenBlock" function gets called once for the 1st block of multiblock getting frozen (as it should), but gets called a second time BEFORE creating the first FrozenBlock with the data of the 1st block, hence giving the same data to the two FrozenBlock :   Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=head] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@73681674 BlockEntityData : id:"minecraft:bed",x:3,y:-60,z:-6} Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=3, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=2, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} here is the code inside my custom "freeze" item :    @Override     public @NotNull InteractionResult useOn(@NotNull UseOnContext pContext) {         if (!pContext.getLevel().isClientSide() && pContext.getHand() == InteractionHand.MAIN_HAND) {             BlockPos blockPos = pContext.getClickedPos();             BlockPos secondBlockPos = getMultiblockPos(blockPos, pContext.getLevel().getBlockState(blockPos));             if (secondBlockPos != null) {                 createFrozenBlock(pContext, secondBlockPos);             }             createFrozenBlock(pContext, blockPos);             return InteractionResult.SUCCESS;         }         return super.useOn(pContext);     }     public static void createFrozenBlock(UseOnContext pContext, BlockPos blockPos) {         BlockState oldState = pContext.getLevel().getBlockState(blockPos);         BlockEntity oldBlockEntity = oldState.hasBlockEntity() ? pContext.getLevel().getBlockEntity(blockPos) : null;         CompoundTag oldBlockEntityData = oldState.hasBlockEntity() ? oldBlockEntity.serializeNBT() : null;         if (oldBlockEntity != null) {             pContext.getLevel().removeBlockEntity(blockPos);         }         BlockState FrozenBlock = setFrozenBlock(oldState, oldBlockEntity, oldBlockEntityData);         pContext.getLevel().setBlockAndUpdate(blockPos, FrozenBlock);     }     public static BlockState setFrozenBlock(BlockState blockState, @Nullable BlockEntity blockEntity, @Nullable CompoundTag blockEntityData) {         BlockState FrozenBlock = BlockRegister.FROZEN_BLOCK.get().defaultBlockState();         ((FrozenBlock) FrozenBlock.getBlock()).setOldBlockFields(blockState, blockEntity, blockEntityData);         return FrozenBlock;     }  
  • Topics

×
×
  • Create New...

Important Information

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