Jump to content

Recommended Posts

Posted

I'm rather new to modding and I want to create a tech mod. I was using for all my machines FE but it seems like I've been doing something wrong because it doesn't work with other mods that use FE. My implementation works like this:

I have a machine tile entity that has an energy storage as the capability. When it's an energy generator it has a max receive of 0 and a max extract of a non 0 number. If it is a energy consumer it has a max receive of a non 0 number and a max extract of 0. My cable check if there's a tile entitiy with energy capability and remove/give it energy based on the max receive and max extract.

I tried to use one of my generators with my cable and connected it with a Mekanism machine. But it seems like the Mekansim machine has a max receive of 0 so my cable doesn't give any energy to it.

What have I understood wong?

Posted

In the TileEntity:

public abstract class CoalGeneratorTileEntity extends TileEntity implements INamedContainerProvider {

    protected ITextComponent customName;
    protected I inventory;
	protected BaseEnergyStorage energy = new BaseEnergyStorage(getCapacity(), getMaxReceive(), getMaxExtract(), getStartEnergy());
 	public int currentProcessingTime;
	protected boolean isProcessing = false;

    public static final String CURRENT_PROCESSING_TIME = "CurrentProcessingTime";
    public static final String CUSTOM_NAME = "CustomName";

    public CoalGeneratorTileEntity(TileEntityType<?> tileEntityTypeIn) {
        super(tileEntityTypeIn);
		inventory = new BaseItemHandler(1);
    }

	@Override
    public Container createMenu(int windowId, PlayerInventory playerInventory, PlayerEntity player) {
        return new CoalGeneratorContainer(windowId, playerInventory, this, ModContainerTypes.COAL_GENERATOR);
    }

    @Override
    public ITextComponent getDisplayName() {
        return getName();
    }

    public void setCustomName(ITextComponent name) {
        customName = name;
    }

    public ITextComponent getName() {
        return customName != null ? customName : getDefaultName();
    }

    private ITextComponent getDefaultName() {
        return new TranslationTextComponent("container." + TodayAndTomorrow.MOD_ID + "." + "coal_generator");
    }

    @Override
    public void read(CompoundNBT compound) {
        super.read(compound);
        if (compound.contains(CUSTOM_NAME, Constants.NBT.TAG_STRING)) {
            customName = ITextComponent.Serializer.fromJson(compound.getString(CUSTOM_NAME));
        }
        NonNullList<ItemStack> inv = NonNullList.withSize(inventory.getSlots(), ItemStack.EMPTY);
        ItemStackHelper.loadAllItems(compound, inv);
        inventory.setNonNullList(inv);
		energy.readFromNBT(compound);
		currentProcessingTime = compound.getInt(CURRENT_PROCESSING_TIME);
    }

    @Override
    public CompoundNBT write(CompoundNBT compound) {
        super.write(compound);
        if (customName != null) {
            compound.putString("CustomName", ITextComponent.Serializer.toJson(this.customName));
        }

        ItemStackHelper.saveAllItems(compound, inventory.toNonNullList());
		energy.writeToNBT(compound);
		compound.putInt(CURRENT_PROCESSING_TIME, currentProcessingTime);
        return compound;
    }

    public I getInventory() {
        return inventory;
    }

    @Override
    public SUpdateTileEntityPacket getUpdatePacket() {
        CompoundNBT nbt = new CompoundNBT();
        this.write(nbt);
        return new SUpdateTileEntityPacket(this.pos, 0, nbt);
    }

    @Override
    public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) {
        this.read(pkt.getNbtCompound());
    }

    @Override
    public CompoundNBT getUpdateTag() {
        CompoundNBT nbt = new CompoundNBT();
        this.write(nbt);
        return nbt;
    }

    @Override
    public void handleUpdateTag(CompoundNBT nbt) {
        this.read(nbt);
    }

    @Override
    public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
        LazyOptional<T> inventory = CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.orEmpty(cap, LazyOptional.of(() -> inventory));
		if (inventory.isPresent()) {
            return inventory;
        }
        return CapabilityEnergy.ENERGY.orEmpty(cap, LazyOptional.of(() -> energy));
    }

    @Override
    public Container createMenu(int windowId, PlayerInventory playerInventory, PlayerEntity player) {
        return createMenu(windowId, playerInventory, player);
    }

	@Override
    public void tick() {
        boolean dirty = false;

        if (world != null && !world.isRemote()) {
            if ((energy.getMaxEnergyStored() > energy.getEnergyStored() && inventory.getStackInSlot(0).getCount() > 0)
				|| isProcessing) {
                if (currentProcessingTime < getProcessingTime()) {
                    if (currentProcessingTime == 0) {
                        inventory.decrStackSize(0, 1);
        				isProcessing = true;
                    }
                    energy.receiveEnergyRaw(ENERGY_PER_TICK, false);
                    setLit(true);
                    currentProcessingTime++;
                    dirty = true;
                } else {
                    currentProcessingTime = 0;
                    isProcessing = false;
                }
            } else {
                currentProcessingTime = 0;
                setLit(false);
            }
        }

        if (dirty) {
            markDirty();
            world.notifyBlockUpdate(getPos(), getBlockState(), getBlockState(), Constants.BlockFlags.BLOCK_UPDATE);
        }
    }

    protected void setLit(boolean lit) {
        if (getBlockState().getBlock() instanceof LitGuiBlock) {
            world.setBlockState(getPos(), getBlockState().with("lit", lit));
        }
    }
}

BaseEnergyStorage is a class that extends EnergyStorage.

 

In the wire I've gone through all connected wires and checked if a tile entity with energy capacity is there.

public class CopperWireTileEntity extends TileEntity implements ITickableTileEntity {

    boolean[] machineAt = new boolean[6];

    public CopperWireTileEntity(TileEntityType<?> tileEntityTypeIn) {
        super(tileEntityTypeIn);

        Arrays.fill(machineAt, false);
    }

    public CopperWireTileEntity() {
        this(ModTileEntityTypes.COPPER_WIRE.get());
    }

    @Override
    public void tick() {
        updateSide(0, getPos().north(), Direction.NORTH);
        updateSide(1, getPos().east(), Direction.EAST);
        updateSide(2, getPos().south(), Direction.SOUTH);
        updateSide(3, getPos().west(), Direction.WEST);
        updateSide(4, getPos().up(), Direction.UP);
        updateSide(5, getPos().down(), Direction.DOWN);

        int energyAvailable = getEnergyAvailable();
        if (energyAvailable != 0) {
            int takeAway = scatterEnergy(energyAvailable);
            takeAwayEnergy(takeAway, energyAvailable);
        }
    }

    protected void updateSide(int index, BlockPos pos, Direction direction) {
        if (!machineAt[index]) {
            TileEntity tileEntity = world.getTileEntity(pos);
            if (tileEntity != null && tileEntity.getCapability(CapabilityEnergy.ENERGY).isPresent()) {
                machineAt[index] = true;
            }
        } else if (world.getBlockState(pos).getBlock() == Blocks.AIR) {
            machineAt[index] = false;
        }
    }

    protected int getEnergyAvailable() {
        AtomicInteger energyAvailable = new AtomicInteger();
        for (int i = 0; i < machineAt.length; i++) {
            if (machineAt[i]) {
                world.getTileEntity(getBlockPosByIndex(pos, i)).getCapability(CapabilityEnergy.ENERGY).ifPresent((e) -> energyAvailable.addAndGet(e.extractEnergy(Integer.MAX_VALUE, true)));
            }
        }
        return energyAvailable.get();
    }

    protected int scatterEnergy(int energyAvailable) {
        ArrayList<BlockPos> visited = new ArrayList<>();
        ArrayList<IEnergyStorage> outputMachinePositions = new ArrayList<>();
        getOutputMachinesEnergy(getPos(), visited, outputMachinePositions);

        int maxReceives = 0;
        for (IEnergyStorage energy : outputMachinePositions) {
            maxReceives += energy.receiveEnergy(Integer.MAX_VALUE, true);
        }

        if (maxReceives <= energyAvailable) {
            for (IEnergyStorage energy : outputMachinePositions) {
                int sent = energy.receiveEnergy(Integer.MAX_VALUE, false);
            }
            return maxReceives;
        }

        int energyGiven = 0;
        for (IEnergyStorage energy : outputMachinePositions) {
            int energyNeeded = energy.receiveEnergy(Integer.MAX_VALUE, true);
            int energyToGive = (int)((float)energyNeeded / (float)maxReceives * (float)energyAvailable);
            energyGiven += energyToGive;
            int a = energy.receiveEnergy(energyToGive, false);
        }

        return energyGiven;
    }

    protected void takeAwayEnergy(int takeAway, int energyAvailable) {
        for (int i = 0; i < machineAt.length; i++) {
            if (machineAt[i]) {
                world.getTileEntity(getBlockPosByIndex(pos, i)).getCapability(CapabilityEnergy.ENERGY).ifPresent((e) -> {
                    int energyProviding = e.extractEnergy(Integer.MAX_VALUE, true);
                    int energyToTakeAway = (int)((float)energyProviding / (float)energyAvailable * (float)takeAway);
                    e.extractEnergy(energyToTakeAway, false);
                });
            }
        }
    }

    protected void getOutputMachinesEnergy(BlockPos pos, ArrayList<BlockPos> visited, ArrayList<IEnergyStorage> outEnergies) {
        if (!visited.contains(pos)) {
            if (world.getBlockState(pos).getBlock() == BlockInit.COPPER_WIRE.get()) {
                visited.add(pos);
                getOutputMachinesEnergy(pos.north(), visited, outEnergies);
                getOutputMachinesEnergy(pos.east(), visited, outEnergies);
                getOutputMachinesEnergy(pos.south(), visited, outEnergies);
                getOutputMachinesEnergy(pos.west(), visited, outEnergies);
                getOutputMachinesEnergy(pos.up(), visited, outEnergies);
                getOutputMachinesEnergy(pos.down(), visited, outEnergies);
            } else if (world.getTileEntity(pos) != null && world.getTileEntity(pos).getCapability(CapabilityEnergy.ENERGY).isPresent()) {
                AtomicReference<IEnergyStorage> energy = new AtomicReference<>();
                world.getTileEntity(pos).getCapability(CapabilityEnergy.ENERGY).ifPresent(energy::set);
                outEnergies.add(energy.get());
            }
        }
    }

    protected BlockPos getBlockPosByIndex(BlockPos pos, int index) {
        switch (index) {
            case 0:
                return pos.north();
            case 1:
                return pos.east();
            case 2:
                return pos.south();
            case 3:
                return pos.west();
            case 4:
                return pos.up();
            case 5:
                return pos.down();
        }
        throw new IllegalArgumentException("Invalid index: " + index);
    }
}

I thought that the energy consuming machines from other Mods would have EnergyStorge with maxReceive from more that 0 so that I could give them energy. But when i tested it with Mekansim:

int energyNeeded = energy.receiveEnergy(Integer.MAX_VALUE, true);

and energyNeeded was 0 so the wire didn't extract any energy.

Posted
  On 10/31/2020 at 3:46 PM, loordgek said:
Expand  

Thank you! Using this method fixed many bugs. I also figured out that the generator should give the cable the energy instead of the cable taking away energy from the generator. After I fixed that everthing worked.

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

    • Hello All,  Relatively new to this and after playing for a few hours whenever someone enters the nether the entire server will crash and my friend and I are at a bit of a loss. Deleting player data solves the issues but it still persists whenever someone enters even after deleting the DIM-1 folder. Paste: https://pastebin.com/REbpJVqe Thanks!   -Mitchell
    • Add the crash-report or latest.log (logs-folder) with sites like https://mclo.gs/ and paste the link to it here  
    • Cracked Launchers are not supported
    • Hi, I have a problem in minecraft java (only in forge 1.20.1), When I start the game after a moment the game crashed with code 1 this only in forge 1.20.1 , I tried to reinstall java, Upgrade java to 17, update the drivers to the latest version, downgrade the drivers to the pervious version, deleting .minecraft and reinstall it , but none of these ways working.   here is the log:   [Launcher] Launching Minecraft... I'm hiding! mods after C:\Users\Windows\AppData\Roaming\.minecraft\mods\tl_skin_cape_forge_1.20_1.20.1-1.32.jar [InnerMinecraftServersImpl]  search changers of the servers read servers from servers.dat [] [InnerMinecraftServersImpl]  prepare inner servers save servers to servers.dat [Launcher] Game skin type: TLAUNCHER [Launcher] Starting Minecraft Forge 1.20.1... [Launcher] Launching in: C:\Users\Windows\AppData\Roaming\.minecraft Starting garbage collector: 96 / 227 MB Garbage collector completed: 60 / 214 MB [Launcher] Processing post-launch actions. Assist launch: true =============================================================================================== [05:29:03] [main/INFO]: ModLauncher running: args [--username, *********, --version, Forge 1.20.1, --gameDir, C:\Users\Windows\AppData\Roaming\.minecraft, --assetsDir, C:\Users\Windows\AppData\Roaming\.minecraft\assets, --assetIndex, 5, --uuid, *************************************, --accessToken, вќ„вќ„вќ„вќ„вќ„вќ„вќ„вќ„, --clientId, null, --xuid, null, --userType, mojang, --versionType, modified, --width, 925, --height, 530, --launchTarget, forgeclient, --fml.forgeVersion, 47.3.22, --fml.mcVersion, 1.20.1, --fml.forgeGroup, net.minecraftforge, --fml.mcpVersion, 20230612.114412] [05:29:04] [main/INFO]: ModLauncher 10.0.9+10.0.9+main.dcd20f30 starting: java version 17.0.12 by Oracle Corporation; OS Windows 10 arch amd64 version 10.0 [05:29:15] [main/INFO]: Loading ImmediateWindowProvider fmlearlywindow [05:29:24] [main/INFO]: Trying GL version 4.6 [05:29:60] [main/INFO]: Requested GL version 4.6 got version 4.6 [05:29:67] [main/INFO]: SpongePowered MIXIN Subsystem Version=0.8.5 Source=union:/C:/Users/Windows/AppData/Roaming/.minecraft/libraries/org/spongepowered/mixin/0.8.5/mixin-0.8.5.jar%23100!/ Service=ModLauncher Env=CLIENT FATAL ERROR in native method: Thread[pool-2-thread-1,5,main]: No context is current or a function that is not available in the current context was called. The JVM will abort execution.     at org.lwjgl.opengl.GL11C.nglGetString(org.lwjgl.opengl@3.3.1+7/Native Method)     at org.lwjgl.opengl.GL11C.glGetString(org.lwjgl.opengl@3.3.1+7/GL11C.java:978)     at net.minecraftforge.fml.earlydisplay.DisplayWindow.initRender(fmlearlydisplay@1.20.1-47.3.22/DisplayWindow.java:209)     at net.minecraftforge.fml.earlydisplay.DisplayWindow.lambda$start$5(fmlearlydisplay@1.20.1-47.3.22/DisplayWindow.java:292)     at net.minecraftforge.fml.earlydisplay.DisplayWindow$$Lambda$437/0x000001fab120a618.run(fmlearlydisplay@1.20.1-47.3.22/Unknown Source)     at java.util.concurrent.Executors$RunnableAdapter.call(java.base@17.0.12/Executors.java:539)     at java.util.concurrent.FutureTask.run(java.base@17.0.12/FutureTask.java:264)     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(java.base@17.0.12/ScheduledThreadPoolExecutor.java:304)     at java.util.concurrent.ThreadPoolExecutor.runWorker(java.base@17.0.12/ThreadPoolExecutor.java:1136)     at java.util.concurrent.ThreadPoolExecutor$Worker.run(java.base@17.0.12/ThreadPoolExecutor.java:635)     at java.lang.Thread.run(java.base@17.0.12/Thread.java:842) Here I am! [VersionManager] Refreshing versions locally... [VersionManager] Versions has been refreshed (6 ms) [Launcher] Launcher exited. [Launcher] Minecraft closed with exit code: 1 flush now [Launcher] [Crash] Signature "Bad video drivers" matches! [Crash] Signature "Bad video drivers" matches! [Launcher] [Crash] Crash has been recognized! [Crash] Crash has been recognized! flush now
  • Topics

  • Who's Online (See full list)

    • There are no registered users currently online
×
×
  • Create New...

Important Information

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