Java Code Examples for net.minecraft.world.World#mayPlace()

The following examples show how to use net.minecraft.world.World#mayPlace() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Check if the given block can be placed in the given position.
 * Note: This method is a functional copy of ItemBlock.func_150936_a() which is client side only.
 */
public static boolean checkCanPlaceBlockAt(World world, BlockPos pos, EnumFacing side, Block blockNew)
{
    Block blockExisting = world.getBlockState(pos).getBlock();

    if (blockExisting == Blocks.SNOW_LAYER && blockExisting.isReplaceable(world, pos))
    {
        side = EnumFacing.UP;
    }
    else if (blockExisting.isReplaceable(world, pos) == false)
    {
        pos = pos.offset(side);
    }

    return world.mayPlace(blockNew, pos, false, side, (Entity) null);
}
 
Example 2
@NotNull
@Override
public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) {
	ItemStack stack = player.getHeldItem(hand);
	if (stack.getItemDamage() != 1) {
		BlockPos offset = pos.offset(side);
		IBlockState offsetState = world.getBlockState(offset);
		if (offsetState.getBlock().isAir(offsetState, world, offset) || offsetState.getBlock().isReplaceable(world, offset)) {

			if (!world.mayPlace(ModBlocks.JAR, offset, false, side, player)) return PASS;

			boolean replacable = world.getBlockState(pos).getBlock().isReplaceable(world, pos);
			boolean success = world.setBlockState(replacable ? pos : offset, ModBlocks.JAR.getDefaultState());
			if (success) {
				world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.BLOCK_GLASS_PLACE, SoundCategory.BLOCKS, 1, 1, false);

				if (!player.isCreative())
					stack.shrink(1);

				TileEntity tileEntity = world.getTileEntity(replacable ? pos : offset);
				if (tileEntity instanceof TileJar) {
					TileJar jar = (TileJar) tileEntity;
					jar.fairy = FairyData.deserialize(NBTHelper.getCompound(stack, "fairy"));
					jar.markDirty();
					world.checkLight(replacable ? pos : offset);
				}
			}

			return SUCCESS;
		}
	}
	return PASS;
}
 
Example 3
Source Project: OpenModsLib   File: ItemOpenBlock.java    License: MIT License 5 votes vote down vote up
/**
 * Replicates the super method, but with our own hooks
 */
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
	final IBlockState clickedBlockState = world.getBlockState(pos);
	final Block clickedBlock = clickedBlockState.getBlock();

	if (!clickedBlock.isReplaceable(world, pos)) pos = pos.offset(facing);

	ItemStack stack = player.getHeldItem(hand);

	if (!isStackValid(stack, player)) return EnumActionResult.FAIL;
	if (!player.canPlayerEdit(pos, facing, stack)) return EnumActionResult.FAIL;
	if (!world.mayPlace(this.block, pos, false, facing, (Entity)null)) return EnumActionResult.FAIL;

	final int itemMetadata = getMetadata(stack.getMetadata());

	if (this.block instanceof OpenBlock) {
		final OpenBlock openBlock = (OpenBlock)this.block;
		if (!openBlock.canBlockBePlaced(world, pos, hand, facing, hitX, hitY, hitZ, itemMetadata, player)) return EnumActionResult.FAIL;
	}

	final IBlockState newBlockState = this.block.getStateForPlacement(world, pos, facing, hitX, hitY, hitZ, itemMetadata, player, hand);

	if (placeBlockAt(stack, player, world, pos, facing, hitX, hitY, hitZ, newBlockState)) {
		final SoundType soundType = this.block.getSoundType(newBlockState, world, pos, player);
		world.playSound(player, pos, soundType.getPlaceSound(), SoundCategory.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F);
		afterBlockPlaced(stack, player, world, pos);
	}

	return EnumActionResult.SUCCESS;
}
 
Example 4
@Override
public EnumActionResult onItemUse(EntityPlayer playerIn, World worldIn, BlockPos origPos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ)
{
	ItemStack stack = playerIn.getHeldItem(hand);
	IBlockState iblockstate = worldIn.getBlockState(origPos);
	Block block = iblockstate.getBlock();
	BlockPos pos = origPos.offset(side);

	if (stack.getMaxStackSize() == 0)
	{
		return EnumActionResult.FAIL;
	}
	if (!playerIn.canPlayerEdit(pos, side, stack))
	{
		return EnumActionResult.FAIL;
	}
	if (worldIn.mayPlace(this.block, pos, false, side, (Entity)null))
	{
		int meta = getMetadata(stack.getMetadata());
		IBlockState scanState;
		//Scan out to make sure there is another beam in the facing direction 
		int range = WoodType.getTypeFromMeta(stack.getItemDamage()).getSupportRange();
		BlockPos scanPos;
		int foundRange = -1;
		if(side == EnumFacing.UP || side == EnumFacing.DOWN)
		{
			foundRange = 1;
		}
		for(int i = 1; i <= range && foundRange == -1; i++)
		{
			scanPos = origPos.offset(side, i);
			scanState = worldIn.getBlockState(scanPos);
			scanState = scanState.getBlock().getActualState(scanState, worldIn, scanPos);
			if(scanState.getBlock() instanceof BlockWoodSupport)
			{
				if(!scanState.getValue(BlockWoodSupport.SPAN))
				{
					foundRange = i;
					break;
				}
			}
			else if(scanState.getBlock().isReplaceable(worldIn, pos))
			{
				continue;
			}
			else
			{
				break;
			}
		}

		if(foundRange != -1 && stack.getMaxStackSize() >= foundRange)
		{
			for(int i = 1; i <= foundRange; i++)
			{
				scanPos = origPos.offset(side, i);
				IBlockState iblockstate1 = this.block.getStateForPlacement(worldIn, scanPos.offset(side.getOpposite()), side, hitX, hitY, hitZ, meta, playerIn);
				if (placeBlockAt(stack, playerIn, worldIn, scanPos, side, hitX, hitY, hitZ, iblockstate1))
				{
					worldIn.playSound(scanPos.getX() + 0.5F, scanPos.getY() + 0.5F, scanPos.getZ() + 0.5F, this.block.getSoundType().getPlaceSound(), SoundCategory.BLOCKS, (this.block.getSoundType().getVolume() + 1.0F) / 2.0F, this.block.getSoundType().getPitch() * 0.8F, true);
					stack.shrink(1);
				}
			}
		}

		return EnumActionResult.SUCCESS;
	}


	return EnumActionResult.PASS;
}
 
Example 5
private boolean tryPlaceDownBlock(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side)
{
    pos = pos.offset(side);

    if (this.isCarryingBlock(stack) == false || world.isBlockModifiable(player, pos) == false)
    {
        return false;
    }

    NBTTagCompound tagCarrying = NBTUtils.getCompoundTag(stack, "Carrying", false);
    String name = tagCarrying.getString("Block");
    int meta = tagCarrying.getByte("Meta");
    Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(name));

    try
    {
        if (block != null && block != Blocks.AIR && world.mayPlace(block, pos, false, side, player))
        {
            @SuppressWarnings("deprecation")
            IBlockState state = block.getStateFromMeta(meta);
            EnumFacing pickupFacing = EnumFacing.byIndex(tagCarrying.getByte("PickupFacing"));
            EnumFacing currentFacing = EntityUtils.getHorizontalLookingDirection(player);
            Rotation rotation = PositionUtils.getRotation(pickupFacing, currentFacing);
            state = state.withRotation(rotation);

            if (world.setBlockState(pos, state))
            {
                TileEntity te = world.getTileEntity(pos);

                if (te != null && tagCarrying.hasKey("te", Constants.NBT.TAG_COMPOUND))
                {
                    NBTTagCompound nbt = tagCarrying.getCompoundTag("te");
                    TileUtils.createAndAddTileEntity(world, pos, nbt, rotation, Mirror.NONE);
                }

                NBTUtils.removeCompoundTag(stack, null, "Carrying");
                return true;
            }
        }
    }
    catch (Exception e)
    {
        EnderUtilities.logger.warn("Failed to place down a block from the Dolly", e);
    }

    return false;
}
 
Example 6
private boolean extendOneBlock(int position, FakePlayer player, boolean playPistonSoundInsteadOfPlaceSound)
{
    final int invPosition = this.isAdvanced() ? position : 0;
    World world = this.getWorld();
    BlockPos pos = this.getPos().offset(this.getFacing(), position + 1);
    ItemStack stack = this.itemHandlerDrawbridge.getStackInSlot(invPosition);
    IBlockState placementState = this.getPlacementStateForPosition(position, world, pos, player, stack);

    if (placementState != null &&
        stack.isEmpty() == false &&
        world.isBlockLoaded(pos, world.isRemote == false) &&
        world.getBlockState(pos).getBlock().isReplaceable(world, pos) &&
        world.mayPlace(placementState.getBlock(), pos, true, EnumFacing.UP, null) &&
        ((playPistonSoundInsteadOfPlaceSound && world.setBlockState(pos, placementState)) ||
         (playPistonSoundInsteadOfPlaceSound == false && BlockUtils.setBlockStateWithPlaceSound(world, pos, placementState, 3))))
    {
        // This extract will also clear the blockInfoTaken, if the slot becomes empty.
        // This will prevent item duping exploits by swapping the item to something else
        // after the drawbridge has taken the state and TE data from the world for a given block.
        stack = this.itemHandlerDrawbridge.extractItem(invPosition, 1, false);

        this.blockStatesPlaced[position] = placementState;
        this.numPlaced++;

        NBTTagCompound nbt = this.getPlacementTileNBT(position, stack);

        if (nbt != null && placementState.getBlock().hasTileEntity(placementState))
        {
            TileUtils.createAndAddTileEntity(world, pos, nbt);
        }

        if (playPistonSoundInsteadOfPlaceSound)
        {
            world.playSound(null, pos, SoundEvents.BLOCK_PISTON_EXTEND, SoundCategory.BLOCKS, 0.5f, 0.8f);
        }

        return true;
    }
    else if (stack.isEmpty() == false)
    {
        this.failedPlacements++;
    }

    return false;
}
 
Example 7
Source Project: WearableBackpacks   File: BackpackHelper.java    License: MIT License 4 votes vote down vote up
/** Attempts to place down a backpack, unequipping it
 *  if the specified entity is currently wearing it. */
public static boolean placeBackpack(World world, BlockPos pos, ItemStack stack,
                                    EntityLivingBase entity, boolean ignoreEntities) {
	
	EntityPlayer player = ((entity instanceof EntityPlayer) ? (EntityPlayer)entity : null);
	if ((player != null) && !player.canPlayerEdit(pos, EnumFacing.UP, stack))
		return false;
	// TODO: Should permission things be handled outside the API method?
	// TODO: For mobs, use mob griefing gamerule?
	
	Item item = stack.getItem();
	// Would use this instead, but gotta avoid depending on the rest of WearableBackpacks.
	//Block block = MiscUtils.getBlockFromItem(item);
	Block block = Block.REGISTRY.getObject(item.getRegistryName());
	if (ignoreEntities ? !block.canPlaceBlockAt(world, pos)
	                   : !world.mayPlace(block, pos, false, EnumFacing.UP, null))
		return false;
	
	// Actually go ahead and try to set the block in the world.
	IBlockState state = block.getStateForPlacement(
		world, pos, EnumFacing.UP, 0.5F, 0.5F, 0.5F,
		item.getMetadata(stack.getMetadata()), player, EnumHand.MAIN_HAND);
	if (!world.setBlockState(pos, state, 3) ||
	    (world.getBlockState(pos).getBlock() != block)) return false;
	block.onBlockPlacedBy(world, pos, state, entity, stack);
	
	double x = pos.getX() + 0.5;
	double y = pos.getY() + 0.5;
	double z = pos.getZ() + 0.5;
	SoundType sound = block.getSoundType(state, world, pos, entity);
	world.playSound(x, y, z, sound.getPlaceSound(), SoundCategory.BLOCKS,
	                (sound.getVolume() + 1.0F) / 2.0F, sound.getPitch() * 0.8F, false);

	// This is used to transfer the BlockEntityTag from Ctrl+pick-blocking to the world.
	boolean alreadyConfigured = ItemBlock.setTileEntityNBT(world, player, pos, stack);

	TileEntity tileEntity = world.getTileEntity(pos);
	if (tileEntity == null) return true;
	IBackpack placedBackpack = BackpackHelper.getBackpack(tileEntity);
	if (placedBackpack == null) return true;
	
	IBackpack carrierBackpack = BackpackHelper.getBackpack(entity);
	boolean isEquipped = ((carrierBackpack != null) && (carrierBackpack.getStack() == stack));
	
	ItemStack stackOrig = stack;
	// Create a copy of the stack with stackSize set to 1 and transfer it.
	stack = stack.copy();
	stack.setCount(1);
	if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag")) {
		stack.getTagCompound().removeTag("BlockEntityTag");
	}
	placedBackpack.setStack(stack);
	
	if (!alreadyConfigured) {
		// If the carrier had the backpack equipped, transfer data and unequip.
		if (isEquipped) {
			
			IBackpackType type = carrierBackpack.getType();
			IBackpackData data = carrierBackpack.getData();
			if ((data == null) && !world.isRemote) {
				LOG.error("Backpack data was null when placing down equipped backpack");
				data = type.createBackpackData(stack);
			}
			
			placedBackpack.setData(data);
			
			if (!world.isRemote)
				BackpackHelper.setEquippedBackpack(entity, ItemStack.EMPTY, null);
			
			type.onUnequip(entity, tileEntity, placedBackpack);
			
		// Otherwise create a fresh backpack data on the server.
		} else if (!world.isRemote) placedBackpack.setData(
			placedBackpack.getType().createBackpackData(stack));
	}
	
	// We only shrink the original stack here instead of earlier
	// as its information is still needed for other checks, and
	// shrinking it from 1 to 0 would effectively empty the stack.
	stackOrig.shrink(1);
	return true;
	
}