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



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • log: https://mclo.gs/QJg3wYX as stated in the title, my game freezes upon loading into the server after i used a far-away waystone in it. The modpack i'm using is better minecraft V18. Issue only comes up in this specific server, singleplayer and other servers are A-okay. i've already experimented with removing possible culprits like modernfix and various others to no effect. i've also attempted a full reinstall of the modpack profile. Issue occurs shortly after the 'cancel' button dissapears on the 'loading world' section of the loading screen.   thanks in advance.
    • You would have better results asking a more specific question. What have you done? What exactly do you need help with? Please also read the FAQ regarding posting logs.
    • Hi, this is my second post with the same content as no one answered this and it's been a long time since I made the last post, I want to make a client-only mod, everything is ok, but when I use shaders, none of the textures rendered in RenderLevelStageEvent nor the crow entity model are rendered, I want them to be visible, because it's a horror themed mod I've already tried it with different shaders, but it didn't work with any of them and I really want to add support for shaders Here is how i render the crow model in the CrowEntityRenderer<CrowEntity>, by the time i use this method, i know is not the right method but i don't think this is the cause of the problem, the renderType i'm using is entityCutout @Override public void render(CrowEntity p_entity, float entityYaw, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight) { super.render(p_entity, entityYaw, partialTick, poseStack, bufferSource, packedLight); ClientEventHandler.getClient().crow.renderToBuffer(poseStack, bufferSource.getBuffer(ClientEventHandler.getClient().crow .renderType(TEXTURE)), packedLight, OverlayTexture.NO_OVERLAY, Utils.rgb(255, 255, 255)); } Here renderLevelStage @Override public void renderWorld(RenderLevelStageEvent e) { horrorEvents.draw(e); } Here is how i render every event public void draw(RenderLevelStageEvent e) { for (HorrorEvent event : currentHorrorEvents) { event.tick(e.getPartialTick()); event.draw(e); } } Here is how i render the crow model on the event @Override public void draw(RenderLevelStageEvent e) { if(e.getStage() == RenderLevelStageEvent.Stage.AFTER_ENTITIES) { float arcProgress = getArcProgress(0.25f); int alpha = (int) Mth.lerp(arcProgress, 0, 255); int packedLight = LevelRenderer.getLightColor(Minecraft.getInstance().level, blockPos); VertexConsumer builder = ClientEventHandler.bufferSource.getBuffer(crow); Crow<CreepyBirdHorrorEvent> model = ClientEventHandler .getClient().crow; model.setupAnim(this); RenderHelper.renderModelInWorld(model, position, offset, e.getCamera(), e.getPoseStack(), builder, packedLight, OverlayTexture.NO_OVERLAY, alpha); builder = ClientEventHandler.bufferSource.getBuffer(eyes); RenderHelper.renderModelInWorld(model, position, offset, e.getCamera(), e.getPoseStack(), builder, 15728880, OverlayTexture.NO_OVERLAY, alpha); } } How i render the model public static void renderModelInWorld(Model model, Vector3f pos, Vector3f offset, Camera camera, PoseStack matrix, VertexConsumer builder, int light, int overlay, int alpha) { matrix.pushPose(); Vec3 cameraPos = camera.getPosition(); double finalX = pos.x - cameraPos.x + offset.x; double finalY = pos.y - cameraPos.y + offset.y; double finalZ = pos.z - cameraPos.z + offset.z; matrix.pushPose(); matrix.translate(finalX, finalY, finalZ); matrix.mulPose(Axis.XP.rotationDegrees(180f)); model.renderToBuffer(matrix, builder, light, overlay, Utils .rgba(255, 255, 255, alpha)); matrix.popPose(); matrix.popPose(); } Thanks in advance
    • I am trying to develop a modpack for me and my friends to use on our server. Does anyone know how to develop a modpack for a server or could they help take a look at my modpack to potentially help at all?
  • Topics

×
×
  • Create New...

Important Information

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