Jump to content

Container does task 2 times


invizzble

Recommended Posts

Hello,

 

I've been having a problems with my custom machine in it's interface. Whenever i try to do something with a container (for example add an item), it does that task 2 times. So if i put 1 item in, there are 2 items in the container. And if i right click, it takes a fourth of the stack. My conclussion was that it should excecute 2 times (probably serverside and clientside), but i can't seem to find where. Could you guys please take a look and help me? Anyway thanks for reading.

 

Main class:

package com.invizzble.SC;

import com.invizzble.SC.block.ModBlocks;
import com.invizzble.SC.handler.ConfigurationHandler;
import com.invizzble.SC.handler.GUIHandler;
import com.invizzble.SC.item.ModItems;
import com.invizzble.SC.lib.Info;
import com.invizzble.SC.proxies.CommonProxy;
import com.invizzble.SC.recipes.ShapedRecipes;
import com.invizzble.SC.tileEntities.ModTileEntities;

import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;

@Mod(modid = Info.MOD_ID , name=Info.MOD_NAME,version = Info.MOD_VERSION)

public class SC {

@SidedProxy(clientSide = Info.PROXY_CLIENT, serverSide = Info.PROXY_SERVER)
public static CommonProxy proxy;

@Instance(Info.MOD_ID)
public static SC instance;

@EventHandler
public void preInit(FMLPreInitializationEvent event){

	ConfigurationHandler.init(event.getSuggestedConfigurationFile());

	FMLCommonHandler.instance().bus().register(new ConfigurationHandler());

	//adds the Blocks
	ModBlocks.init();

	//adds the Items
	ModItems.init();

}

@EventHandler
public void init(FMLInitializationEvent event){
	//registers the tile entities
	ModTileEntities.registerTileEntities();

	//registers the recipes for my mod's Items
	ShapedRecipes.init();

	//registers the creativeTab(s) <- at this point there's only one buth there's room for expansion if i implement the different sciences

	//register the gui handler
	new GUIHandler();

}

@EventHandler
public void postInit(FMLPostInitializationEvent event){

}
}

 

GUIHandler:

package com.invizzble.SC.handler;

import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.world.World;

import com.invizzble.SC.SC;
import com.invizzble.SC.client.gui.ContainerMachine;
import com.invizzble.SC.client.gui.GUISciPad;
import com.invizzble.SC.client.gui.GuiMachine;
import com.invizzble.SC.item.ItemSciPad;
import com.invizzble.SC.tileEntities.TileEntityMachine;
import com.invizzble.SC.util.LogHelper;

import cpw.mods.fml.common.network.IGuiHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class GUIHandler implements IGuiHandler{

public GUIHandler(){
	NetworkRegistry.INSTANCE.registerGuiHandler(SC.instance, this);
}

public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	switch(ID){
	case 1:
		TileEntity te = world.getTileEntity(x, y, z);
		if(te != null && te instanceof TileEntityMachine){
			return new ContainerMachine(player.inventory, (TileEntityMachine)te);
		}
		break;
	}
	return null;
}

public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	switch(ID){
	case 1:
		TileEntity te = world.getTileEntity(x, y, z);
		if(te != null && te instanceof TileEntityMachine){
			return new GuiMachine(new ContainerMachine(player.inventory, (TileEntityMachine)world.getTileEntity(x, y, z)), (TileEntityMachine)world.getTileEntity(x, y, z));
		}
		break;
	case 2:
		Item it = player.getCurrentEquippedItem().getItem();
		if(it != null && it instanceof ItemSciPad){
			return new GUISciPad();
		}
	}
	return null;
}

}

 

MachineContainer:

package com.invizzble.SC.client.gui;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;

import com.invizzble.SC.tileEntities.TileEntityMachine;

public class ContainerMachine extends Container{

private TileEntityMachine machine;

public ContainerMachine(InventoryPlayer invPlayer, TileEntityMachine machine){
	this.machine = machine;
	//Slot(IInventory (the machine),int slotId, xCord, yCord)
	addSlotToContainer(new SlotMachine(machine, 0, 26, 17));

	addSlotToContainer(new SlotMachine(machine, 1, 26, 53));

	addSlotToContainer(new SlotMachine(machine, 2, 116, 35));

	//hotbar
	for(int i = 0; i < 9; i++){
		addSlotToContainer(new Slot(invPlayer, i, i*18+8, 142));
	}

	//player inv
	for (int y = 0; y < 3; y++){
		for(int x = 0; x < 9; x++){
			addSlotToContainer(new Slot(invPlayer, (x+9)+y*9, x*18+8, y*18+84));
		}
	}
}


@Override
public boolean canInteractWith(EntityPlayer entityplayer) {
	// TODO Auto-generated method stub
	return machine.isUseableByPlayer(entityplayer);
}

@Override 
public ItemStack transferStackInSlot(EntityPlayer player, int i){
	return null;
}
}

 

Machine gui:

package com.invizzble.SC.client.gui;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.util.ResourceLocation;

import org.lwjgl.opengl.GL11;

import com.invizzble.SC.block.BlockAtomizer;
import com.invizzble.SC.lib.BlockInfo;
import com.invizzble.SC.tileEntities.TileEntityMachine;

public class GuiMachine extends GuiContainer {

static String textureName;
private static final ResourceLocation texture=new ResourceLocation(BlockInfo.TEXTURE_LOCATION, "textures/gui/machine.png");

TileEntityMachine machine;

public GuiMachine(Container container, TileEntityMachine _machine) {
	super(container);
	xSize = 176;
	ySize = 166;		
	machine = _machine;
}

@Override
protected void drawGuiContainerBackgroundLayer(float f, int i, int j) {
	GL11.glColor4f(1, 1, 1, 1);

	Minecraft.getMinecraft().getTextureManager().bindTexture(texture);

	drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);

	if(machine.getBlockType() instanceof BlockAtomizer){

	}

}

}

 

BlockMachine :

package com.invizzble.SC.block;

import net.minecraft.block.material.Material;
import net.minecraft.client.gui.inventory.GuiFurnace;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;

import com.invizzble.SC.SC;
import com.invizzble.SC.lib.Info;
import com.invizzble.SC.tileEntities.TileEntityMachine;

import cpw.mods.fml.common.network.internal.FMLNetworkHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public abstract class SCBlockMachine extends SCBlock{
IIcon front;
IIcon defaultIcon;
String frontName;
String defaultName;

int guiId;

TileEntityMachine machine;

public SCBlockMachine(){
	super(Material.iron);
	machine = new TileEntityMachine();
	GuiFurnace f;
}

public void setIcons(String _frontName, String _defaultName){
	frontName = _frontName;
	defaultName = _defaultName;
}

@SideOnly(Side.CLIENT)
@Override
public void registerBlockIcons(IIconRegister p_149651_1_)
{
	front= p_149651_1_.registerIcon(Info.MOD_ID+":"+frontName);
	defaultIcon = p_149651_1_.registerIcon(Info.MOD_ID+":"+defaultName);
}

/**
 * Side: 
 * 		0:Top
 * 		1:Bottom
 * 		2:North
 * 		3:East
 * 		4:South
 * 		5:West
 **/
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int meta)
    {
	return (side != 1 && side != 0)?front:defaultIcon;
    }

protected abstract void setMachineProperties();

@Override
public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) {
	return machine;
}

protected void setGuiId(int id){
	guiId = id;
}

@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ){
	if(!world.isRemote){
		FMLNetworkHandler.openGui(player, SC.instance, guiId, world, x, y, z);
	}
	return true;	
}

}

 

TileEntityMachine

package com.invizzble.SC.tileEntities;

import java.util.ArrayList;

import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;

import com.invizzble.SC.block.BlockAtomizer;
import com.invizzble.SC.util.LogHelper;

public class TileEntityMachine extends TileEntity implements ISidedInventory {

private ItemStack[] items;

private ArrayList<ItemStack> allowedItems;
int maxStackSize;
String name;

int powerCapacity;
int powerAmount;
int powerUsage;
int maxPowerTransfer;

public TileEntityMachine(){
	 items = new ItemStack[3];
}

public void setMachineName(String _name) {
	name = _name;
}

public void addAllowedItem(ItemStack item) {
	allowedItems.add(item);
}

/**
 * 
 * @param maxTransfer
 *            the maximum amount power that can be transported at one time
 */
public void setMaxTransfer(int maxTransfer) {
	maxPowerTransfer = maxTransfer;
}

public void setMaxStackSize(int _maxStackSize) {
	maxStackSize = _maxStackSize;
}

public void setPowerCapacity(int capacity) {
	powerCapacity = capacity;
}

public void setPowerUsage(int usage) {
	powerUsage = usage;
}

@Override
public int getSizeInventory() {
	return items.length;
}

@Override
public ItemStack getStackInSlot(int slot) {
	return items[slot];
}

@Override
public ItemStack decrStackSize(int i, int count) {
	ItemStack itemstack = getStackInSlot(i);
	if (itemstack != null) {
		if (itemstack.stackSize <= count) {
			setInventorySlotContents(i, null);
		}else{
			itemstack = itemstack.splitStack(count);
		}
	}

	return itemstack;
}


@Override
public ItemStack getStackInSlotOnClosing(int slot) {
	if (items[slot] != null) {
		ItemStack stack = items[slot];
		items[slot] = null;
		return stack;
	} else {
		return null;
	}
}

@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
	items[slot] = stack;

	if (stack != null && stack.stackSize > this.getInventoryStackLimit()) {
		stack.stackSize = this.getInventoryStackLimit();
	}
}

@Override
public String getInventoryName() {

	return name;
}

@Override
public boolean hasCustomInventoryName() {

	return name != null ? true : false;
}

@Override
public int getInventoryStackLimit() {
	return 64;
}

@Override
public boolean isUseableByPlayer(EntityPlayer player) {
	return player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) <= 64;
}

@Override
public void openInventory() {
}

@Override
public void closeInventory() {
}

@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
	return slot == 2?false:true;
}

@Override
public int[] getAccessibleSlotsFromSide(int side) {
	return null;
}

@Override
public boolean canInsertItem(int slot, ItemStack stack, int side) {
	return isItemValidForSlot(slot, stack);
}

@Override
public boolean canExtractItem(int p_102008_1_, ItemStack p_102008_2_,
		int p_102008_3_) {
	return true;
}

@Override
public void updateEntity() {
	//processItem();

}

@Override
public void writeToNBT(NBTTagCompound tag) {
	super.writeToNBT(tag);
	NBTTagList list = new NBTTagList();
	for (int i = 0; i < items.length; i++) {
		if(getStackInSlot(i) != null){
			NBTTagCompound nbtTag = new NBTTagCompound();
			nbtTag.setByte("Slot", (byte) i);
			items[i].writeToNBT(nbtTag);
			list.appendTag(nbtTag);
		}
	}
	tag.setTag("Items", list);
}

@Override
public void readFromNBT(NBTTagCompound tag) {
	super.readFromNBT(tag);
	NBTTagList tagList = tag.getTagList("Items", 10);

	for (int i = 0; i < tagList.tagCount(); i++) {
		NBTTagCompound nbttagcompound1 = tagList.getCompoundTagAt(i);
		byte slot = nbttagcompound1.getByte("Slot");

		if (slot >= 0 && slot < items.length) {
			items[slot] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
		}
	}
}

public boolean canProcess(){
	if(getStackInSlot(0) != null){
		ItemStack stack = null;
		if(getBlockType() instanceof BlockAtomizer){
			stack = FurnaceRecipes.smelting().getSmeltingResult(getStackInSlot(0));
		}

		if(stack != null){
			if(getStackInSlot(2) == null || (getStackInSlot(2) == stack && getStackInSlot(2).stackSize + stack.stackSize <= getInventoryStackLimit())){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}else{
		return false;
	}
}

 public void processItem()
    {
        if (this.canProcess())
        {
            ItemStack itemstack = FurnaceRecipes.smelting().getSmeltingResult(items[0]);

            if (items[2] == null)
            {
                items[2] = itemstack.copy();
            }
            else if (items[2].getItem() == itemstack.getItem())
            {
                items[2].stackSize += itemstack.stackSize; // Forge BugFix: Results may have multiple items
            }

            --items[0].stackSize;

            if (items[0].stackSize <= 0)
            {
                items[0] = null;
            }
        }
    }
}

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

    • When I launch the Forge installation (1.20.1-47.2.0) everything works fine until Forge tries to launch Minecraft. Usually the launcher crashes while "launching minecraft" or "loading bootstrap resources". I don't know why this happens as I only have two other mods in my mods folder, Create (1.20.1-0.5.1.f) and Rubidium (mc1.20.1-0.7.1) and it works fine with out them. 
    • Your mod is probably lagging during world generation due to how it replaces blocks around your custom ore. Right now, it randomly picks spots around the ore and changes blocks there. This process can be slow, especially if it's dealing with lots of blocks or a big area. To fix it, try replacing fewer blocks, picking spots more efficiently, and changing blocks in a smarter way. This should help your mod run smoother when generating worlds. Here is an example of how you can do this // Inside the if (placed) block if (placed) { BlockState surroundingBlockState = BlockInit.ABERRANT_MINERALOID.get().defaultBlockState(); int veinSize = ctx.config().size; int maxBlocksToReplace = (int) Math.ceil(veinSize * 0.1); // Replace 10% of vein size int numBlocksToCorrupt = Math.min(maxBlocksToReplace, 1000); // Limit to 1000 blocks List<BlockPos> positionsToReplace = new ArrayList<>(); // Loop until reaching the limit of blocks to replace while (positionsToReplace.size() < numBlocksToCorrupt) { BlockPos randomPos = offsetOrigin.offset( ctx.random().nextInt(2 * areaSizeX + 1) - areaSizeX, ctx.random().nextInt(2 * areaSizeY + 1) - areaSizeY, ctx.random().nextInt(2 * areaSizeZ + 1) - areaSizeZ ); if (world.getBlockState(randomPos).is(ModBlockTags.STONE_ABERRANTABLE)) { positionsToReplace.add(randomPos); } } // Replace blocks in bulk for (BlockPos pos : positionsToReplace) { world.setBlock(pos, surroundingBlockState, 2); } } If you've tried more effective ways to generate your blocks around your ores, it may also be because of issues on your side, not the mod. Adjust the parameters as needed based on your performance testing and requirements.
    • So i have a custom ore and, arround the ore, a bunch of randomly placed custom stone blocks should be placed. After applying it, i've found that it causes moderate to extreme world generation lag (new chunks refusing to load after moving for a while, height slices of the same chunk appearing and disappearing as I get into them instead of the usual long continous chunk, new chunks generating extremely close to me instead of to the set render distance...) I've been debugging for a while and I know for a fact this is causing the lag (and sometimes freeze of the world loading screen on a new world and/or the saving world screen when quitting), since comenting it just makes the worldgen work as usual and I want to see if its really that computationally expensive, if there are other ways of doing it or if the process can be simplfied or optimized. I've tried a lot of combinations for the same code but I am just stuck. Is it some kind of generation cascading im missing?   Here is the code for the class. The code inside the if (placed) is the one causing this mess. I can see that the code might not be the most optimized thing, but it does what's supposed to... but at the cost of causing all this. Any tips? package es.nullbyte.relativedimensions.worldgen.oregen.oreplacements; import es.nullbyte.relativedimensions.blocks.BlockInit; import es.nullbyte.relativedimensions.blocks.ModBlockTags; import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.OreFeature; import net.minecraft.world.level.levelgen.feature.configurations.OreConfiguration; import java.util.Optional; public class AberrantOreFeature extends OreFeature { public AberrantOreFeature() { super(OreConfiguration.CODEC); } @Override public boolean place(FeaturePlaceContext<OreConfiguration> ctx) { // Get the world and the position from the context WorldGenLevel world = ctx.level(); BlockPos origin = ctx.origin(); // Offset the origin by 8 in the x and z directions to avoid cascading chunk generation BlockPos offsetOrigin = origin.offset(8, 0, 8); // Create a new context with the offset origin FeaturePlaceContext<OreConfiguration> offsetCtx = new FeaturePlaceContext<>( Optional.empty(), world, ctx.chunkGenerator(), ctx.random(), offsetOrigin, ctx.config() ); // Generate the entire vein of ore at the offset origin boolean placed = super.place(offsetCtx); // If the vein was generated successfully if (placed) { // Define the block to replace surrounding blocks with BlockState surroundingBlockState = BlockInit.ABERRANT_MINERALOID.get().defaultBlockState(); // Generate a random size for the area of corruption int areaSizeX = ctx.random().nextInt(3) + 1; // between 1 and 4 int areaSizeY = ctx.random().nextInt(3) + 1; // between 1 and 4 int areaSizeZ = ctx.random().nextInt(3) + 1; // between 1 and 4 // Calculate the number of blocks to be corrupted based on the area size double numBlocksToCorrupt = (areaSizeX + areaSizeY + areaSizeZ / 2.0) ; // Counter for the number of blocks corrupted int numBlocksCorrupted = 0; // Loop for each block to be corrupted while (numBlocksCorrupted < numBlocksToCorrupt) { // Generate a random position within the area, using the offset origin BlockPos randomPos = offsetOrigin.offset( ctx.random().nextInt(2 * areaSizeX + 1) - areaSizeX, // between -areaSize and areaSize ctx.random().nextInt(2 * areaSizeY + 1) - areaSizeY, ctx.random().nextInt(2 * areaSizeZ + 1) - areaSizeZ ); // If the block at the random position is in the IS_ORE_ABERRANTABLE tag, replace it if (world.getBlockState(randomPos).is(ModBlockTags.STONE_ABERRANTABLE)) { world.setBlock(randomPos, surroundingBlockState, 2); numBlocksCorrupted++; } } } return placed; } }  
    • Here is a tutorial from this same forum that I tried and kinda made work. Take into account that you will have to manage the offset (like rotation, and the offset relative to things like the main hand, offhand etc) by yourself and that can get very troublesome at times.  
  • Topics

×
×
  • Create New...

Important Information

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