Java Code Examples for net.minecraft.util.math.MathHelper#clamp()

The following examples show how to use net.minecraft.util.math.MathHelper#clamp() . 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 check out the related API usage on the sidebar.
Example 1
Source File: ContainerMSU.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void addCustomInventorySlots()
{
    int customInvStart = this.inventorySlots.size();
    int tier = MathHelper.clamp(this.temsu.getStorageTier(), 0, 1);

    int posX = tier == 1 ? 8 : 80;
    int posY = 23;
    int slots = tier == 1 ? 9 : 1;

    for (int slot = 0; slot < slots; slot++)
    {
        this.addSlotToContainer(new SlotItemHandlerGeneric(this.inventory, slot, posX + slot * 18, posY));
    }

    this.customInventorySlots = new MergeSlotRange(customInvStart, slots);
}
 
Example 2
Source File: AbstractFurnaceBlockEntityMixin_RealTime.java    From Galaxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Redirect(
    method = "tick",
    at = @At(
        value = "FIELD",
        target = "Lnet/minecraft/block/entity/AbstractFurnaceBlockEntity;cookTime:I",
        opcode = Opcodes.PUTFIELD
    ),
    slice = @Slice(
        from = @At(
            value = "INVOKE",
            target = "Lnet/minecraft/util/math/MathHelper;clamp(III)I"
        ),
        to = @At(
            value = "INVOKE",
            target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;I)Z"
        )
    )
)
private void realTimeImpl$adjustForRealTimeCookTimeCooldown(final AbstractFurnaceBlockEntity self, final int modifier) {
    final int ticks = (int) ((RealTimeTrackingBridge) this.getWorld()).realTimeBridge$getRealTimeTicks();
    this.cookTime = MathHelper.clamp(this.cookTime - (2 * ticks), 0, this.cookTimeTotal);
}
 
Example 3
Source File: ExcavatorHack.java    From Wurst7 with GNU General Public License v3.0 6 votes vote down vote up
private Area(BlockPos start, BlockPos end)
{
	int startX = start.getX();
	int startY = start.getY();
	int startZ = start.getZ();
	
	int endX = end.getX();
	int endY = end.getY();
	int endZ = end.getZ();
	
	minX = Math.min(startX, endX);
	minY = Math.min(startY, endY);
	minZ = Math.min(startZ, endZ);
	
	sizeX = Math.abs(startX - endX);
	sizeY = Math.abs(startY - endY);
	sizeZ = Math.abs(startZ - endZ);
	
	totalBlocks = (sizeX + 1) * (sizeY + 1) * (sizeZ + 1);
	scanSpeed = MathHelper.clamp(totalBlocks / 30, 1, 16384);
	iterator = BlockUtils.getAllInBox(start, end).iterator();
}
 
Example 4
Source File: TileEntityMemoryChest.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setStorageTier(int tier)
{
    this.chestTier = MathHelper.clamp(tier, 0, 2);
    this.invSize = INV_SIZES[this.chestTier];

    this.initStorage(this.invSize);
}
 
Example 5
Source File: GuiScrollable.java    From WearableBackpacks with MIT License 5 votes vote down vote up
public void setScroll(Direction direction, int value) {
	value = MathHelper.clamp(value, 0, getMaxScroll(direction));
	if (direction == Direction.HORIZONTAL) {
		if (value == _scrollX) return;
		_scrollX = value;
	} else {
		if (value == _scrollY) return;
		_scrollY = value;
	}
	onScrollChanged(direction);
}
 
Example 6
Source File: SchematicUtils.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Nullable
public static BlockPos getSchematicContainerPositionFromWorldPosition(BlockPos worldPos, ISchematic schematic, String regionName,
        SchematicPlacement schematicPlacement, SubRegionPlacement regionPlacement, ILitematicaBlockStateContainer container)
{
    ISchematicRegion region = schematic.getSchematicRegion(regionName);

    if (region == null)
    {
        return null;
    }

    BlockPos boxMinRel = getReverseTransformedWorldPosition(worldPos, schematic, schematicPlacement, regionPlacement, region.getSize());

    if (boxMinRel == null)
    {
        return null;
    }

    final int startX = boxMinRel.getX();
    final int startY = boxMinRel.getY();
    final int startZ = boxMinRel.getZ();
    Vec3i size = container.getSize();

    /*
    if (startX < 0 || startY < 0 || startZ < 0 || startX >= size.getX() || startY >= size.getY() || startZ >= size.getZ())
    {
        System.out.printf("DEBUG ============= OUT OF BOUNDS - region: %s, startX: %d, startY %s, startZ: %d - size x: %d y: %s z: %d =============\n",
                regionName, startX, startY, startZ, size.getX(), size.getY(), size.getZ());
        return null;
    }

    return boxMinRel;
    */

    return new BlockPos(MathHelper.clamp(startX, 0, size.getX() - 1),
                        MathHelper.clamp(startY, 0, size.getY() - 1),
                        MathHelper.clamp(startZ, 0, size.getZ() - 1));
}
 
Example 7
Source File: ToolMetaItemListener.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SubscribeEvent
public static void onAnvilChange(AnvilUpdateEvent event) {
    ItemStack firstStack = event.getLeft();
    ItemStack secondStack = event.getRight();
    if (!firstStack.isEmpty() && !secondStack.isEmpty() && firstStack.getItem() instanceof ToolMetaItem) {
        ToolMetaItem<?> toolMetaItem = (ToolMetaItem<?>) firstStack.getItem();
        MetaToolValueItem toolValueItem = toolMetaItem.getItem(firstStack);
        if (toolValueItem == null) {
            return;
        }
        SolidMaterial toolMaterial = ToolMetaItem.getToolMaterial(firstStack);
        OrePrefix solidPrefix = getSolidPrefix(toolMaterial);
        UnificationEntry unificationEntry = OreDictUnifier.getUnificationEntry(secondStack);
        double toolDamage = toolMetaItem.getItemDamage(firstStack) / (toolMetaItem.getMaxItemDamage(firstStack) * 1.0);
        double materialForFullRepair = toolValueItem.getAmountOfMaterialToRepair(firstStack);
        int durabilityPerUnit = (int) Math.ceil(toolMetaItem.getMaxItemDamage(firstStack) / materialForFullRepair);
        int materialUnitsRequired = Math.min(secondStack.getCount(), (int) Math.ceil(toolDamage * materialForFullRepair));
        int repairCost = (MathHelper.clamp(toolMaterial.harvestLevel, 2, 3) - 1) * materialUnitsRequired;

        if (toolDamage > 0.0 && materialUnitsRequired > 0 && unificationEntry != null &&
            unificationEntry.material == toolMaterial && unificationEntry.orePrefix == solidPrefix) {
            int durabilityToRegain = durabilityPerUnit * materialUnitsRequired;
            ItemStack resultStack = firstStack.copy();
            toolMetaItem.regainItemDurability(resultStack, durabilityToRegain);
            event.setMaterialCost(materialUnitsRequired);
            event.setCost(repairCost);
            event.setOutput(resultStack);
        }
    }
}
 
Example 8
Source File: SpellRing.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get a modifier in this ring between the range. Returns the attribute value, modified by burnout and multipliers, for use in a spell.
 *
 * @param world
 * @param attribute The attribute you want. List in {@link AttributeRegistry} for default attributeModifiers.
 * @param data      The data of the spell being cast, used to get caster-specific modifiers.
 * @return The {@code double} potency of a modifier.
 */
public final float getAttributeValue(World world, Attribute attribute, SpellData data) {
	if (module == null) return 0;

	float current = FixedPointUtils.getDoubleFromNBT(informationTag, attribute.getNbtName());

	AttributeRange range = module.getAttributeRanges().get(attribute);

	current = MathHelper.clamp(current, range.min, range.max);
	current = data.getCastTimeValue(attribute, current);
	current *= getPlayerBurnoutMultiplier(world, data);
	current *= getPowerMultiplier();

	return current;
}
 
Example 9
Source File: TileEntityHandyChest.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setStorageTier(World world, int tier)
{
    this.chestTier = MathHelper.clamp(tier, 0, MAX_TIER);
    this.invSize = INV_SIZES[this.chestTier];

    this.initStorage(this.invSize, world.isRemote);
}
 
Example 10
Source File: SliderWidget.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void handleClientAction(int id, PacketBuffer buffer) {
    if (id == 1) {
        this.sliderPosition = buffer.readFloat();
        this.sliderPosition = MathHelper.clamp(sliderPosition, 0.0f, 1.0f);
        this.responder.apply(getSliderValue());
    }
}
 
Example 11
Source File: TileEntityTeleportRail.java    From Signals with GNU General Public License v3.0 5 votes vote down vote up
public Pair<MCPos, MCPos> getAllowedDestinationRange(World destinationDimension){
    if(destinationDimension == null) return null;

    double moveFactor = getWorld().provider.getMovementFactor() / destinationDimension.provider.getMovementFactor();
    double destX = MathHelper.clamp(getPos().getX() * moveFactor, destinationDimension.getWorldBorder().minX() + 16.0D, destinationDimension.getWorldBorder().maxX() - 16.0D);
    double destZ = MathHelper.clamp(getPos().getZ() * moveFactor, destinationDimension.getWorldBorder().minZ() + 16.0D, destinationDimension.getWorldBorder().maxZ() - 16.0D);
    destX = MathHelper.clamp((int)destX, -29999872, 29999872);
    destZ = MathHelper.clamp((int)destZ, -29999872, 29999872);

    int maxDiff = 8;
    MCPos min = new MCPos(destinationDimension, new BlockPos(destX - maxDiff, 0, destZ - maxDiff));
    MCPos max = new MCPos(destinationDimension, new BlockPos(destX + maxDiff, destinationDimension.getActualHeight(), destZ + maxDiff));
    return new ImmutablePair<MCPos, MCPos>(min, max);
}
 
Example 12
Source File: TileEntityDrawbridge.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void changeInventorySize(int changeAmount)
{
    int newSize = MathHelper.clamp(this.getSlotCount() + changeAmount, 1, MAX_LENGTH_ADVANCED);

    // Shrinking the inventory, only allowed if there are no items in the slots-to-be-removed
    if (changeAmount < 0)
    {
        int changeFinal = 0;

        for (int slot = this.getSlotCount() - 1; slot >= newSize && slot >= 1; slot--)
        {
            if (this.itemHandlerDrawbridge.getStackInSlot(slot).isEmpty())
            {
                changeFinal--;
            }
            else
            {
                break;
            }
        }

        newSize = MathHelper.clamp(this.getSlotCount() + changeFinal, 1, MAX_LENGTH_ADVANCED);
    }

    if (newSize >= 1 && newSize <= MAX_LENGTH_ADVANCED)
    {
        this.setMaxLength(newSize);
    }
}
 
Example 13
Source File: ScrollBar.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean move(int amount, boolean playSound)
{
    this.position = MathHelper.clamp(this.position + amount, 0, this.positionMax);
    this.parent.scrollbarAction(this.id, ScrollbarAction.MOVE, -1);

    if (playSound)
    {
        this.playPressSound();
    }

    return true;
}
 
Example 14
Source File: BlockFrame.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) {
    entityIn.motionX = MathHelper.clamp(entityIn.motionX, -0.15, 0.15);
    entityIn.motionZ = MathHelper.clamp(entityIn.motionZ, -0.15, 0.15);
    entityIn.fallDistance = 0.0F;
    if (entityIn.motionY < -0.15D) {
        entityIn.motionY = -0.15D;
    }
    if (entityIn.isSneaking() && entityIn.motionY < 0.0D) {
        entityIn.motionY = 0.0D;
    }
    if (entityIn.collidedHorizontally) {
        entityIn.motionY = 0.2;
    }
}
 
Example 15
Source File: TileRailgun.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
@Override
public void onModuleUpdated(ModuleBase module) {
	if(module == textBox) {
		if(textBox.getText().isEmpty())
			minStackTransferSize = 1;
		else
			minStackTransferSize = MathHelper.clamp(Integer.parseInt(textBox.getText()),1, 64);
		PacketHandler.sendToServer(new PacketMachine(this, (byte)4));
	}
}
 
Example 16
Source File: TileEntityASU.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void changeInventorySize(int changeAmount)
{
    int newSize = MathHelper.clamp(this.getInvSize() + changeAmount, 1, MAX_INV_SIZE);

    // Shrinking the inventory, only allowed if there are no items in the slots-to-be-removed
    if (changeAmount < 0)
    {
        int changeFinal = 0;

        for (int slot = this.getInvSize() - 1; slot >= newSize && slot >= 1; slot--)
        {
            if (this.itemHandlerLockable.getStackInSlot(slot).isEmpty())
            {
                changeFinal--;
            }
            else
            {
                break;
            }
        }

        newSize = MathHelper.clamp(this.getInvSize() + changeFinal, 1, MAX_INV_SIZE);
    }

    if (newSize >= 1 && newSize <= MAX_INV_SIZE)
    {
        this.setInvSize(newSize);

        this.notifyBlockUpdate(this.getPos());
    }
}
 
Example 17
Source File: TileEntityCreationStation.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Check if there are enough items on the crafting grid to craft once, and try to add more items
 * if necessary and the auto-use feature is enabled.
 * @param invId
 * @return
 */
public boolean canCraftItems(IItemHandler invCrafting, int invId)
{
    if (invCrafting == null)
    {
        return false;
    }

    invId = MathHelper.clamp(invId, 0, 1);
    int maskKeepOne = invId == 1 ? MODE_BIT_RIGHT_CRAFTING_KEEPONE : MODE_BIT_LEFT_CRAFTING_KEEPONE;
    int maskAutoUse = invId == 1 ? MODE_BIT_RIGHT_CRAFTING_AUTOUSE : MODE_BIT_LEFT_CRAFTING_AUTOUSE;

    this.craftingGridTemplates.set(invId, null);

    // Auto-use-items feature enabled, create a snapshot of the current state of the crafting grid
    if ((this.modeMask & maskAutoUse) != 0)
    {
        //if (invCrafting != null && InventoryUtils.checkInventoryHasAllItems(this.itemInventory, invCrafting, 1))
        this.craftingGridTemplates.set(invId, InventoryUtils.createInventorySnapshot(invCrafting));
    }

    // No requirement to keep one item on the grid
    if ((this.modeMask & maskKeepOne) == 0)
    {
        return true;
    }
    // Need to keep one item on the grid; if auto-use is disabled and there is only one item left, then we can't craft anymore
    else if ((this.modeMask & maskAutoUse) == 0 && InventoryUtils.getMinNonEmptyStackSize(invCrafting) <= 1)
    {
        return false;
    }

    // We are required to keep one item on the grid after crafting.
    // So we must check that either there are more than one item left in each slot,
    // or that the auto-use feature is enabled and the inventory has all the required items
    // to re-stock the crafting grid afterwards.

    int maskOreDict = invId == 1 ? MODE_BIT_RIGHT_CRAFTING_OREDICT : MODE_BIT_LEFT_CRAFTING_OREDICT;
    boolean useOreDict = (this.modeMask & maskOreDict) != 0;

    // More than one item left in each slot
    if (InventoryUtils.getMinNonEmptyStackSize(invCrafting) > 1 ||
        InventoryUtils.checkInventoryHasAllItems(this.itemInventory, invCrafting, 1, useOreDict))
    {
        return true;
    }

    return false;
}
 
Example 18
Source File: ItemEnderTool.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static CreativeBreaking fromStack(ItemStack stack)
{
    int mode = MathHelper.clamp(NBTUtils.getByte(stack, null, "CreativeBreaking"), 0, 1);
    return values()[mode];
}
 
Example 19
Source File: TileEntityDrawbridge.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setDelay(int delay)
{
    this.delay = MathHelper.clamp(delay, 1, 255);
}
 
Example 20
Source File: ItemEnderTool.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void setDamage(ItemStack stack, int damage)
{
    damage = MathHelper.clamp(damage, 0, this.material.getMaxUses());
    NBTUtils.setShort(stack, null, "ToolDamage", (short)damage);
}