Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updates all utils #347

Merged
merged 1 commit into from
Dec 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList;
import net.minecraft.registry.Registry;
import net.minecraft.registry.Registries;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.state.property.Property;
import net.minecraft.util.Identifier;
Expand All @@ -34,7 +34,7 @@ public static NbtCompound toNBT(BlockState state) {
}

NbtCompound root = new NbtCompound();
root.putString("Id", Registry.BLOCK.getId(state.getBlock()).toString());
root.putString("Id", Registries.BLOCK.getId(state.getBlock()).toString());

// serialize properties
if (!state.getProperties().isEmpty()) {
Expand Down Expand Up @@ -69,7 +69,7 @@ public static BlockState fromNBT(NbtCompound compound) {
// we use new Identifier(...) here to allow it to throw exceptions
// instead of getting a cryptic NPE
Identifier identifier = new Identifier(compound.getString("Id"));
Block block = Registry.BLOCK.get(identifier);
Block block = Registries.BLOCK.get(identifier);

// deserialize properties
BlockState state = block.getDefaultState();
Expand All @@ -96,7 +96,7 @@ public static BlockState fromNBT(NbtCompound compound) {
* or returns the given default if the tag is null/empty.
*
* @param compound The NBT tag.
* @param def The default.
* @param def The default.
* @return The block state or {@code def} if the tag is null/empty.
*/
public static BlockState fromNBT(NbtCompound compound, BlockState def) {
Expand Down Expand Up @@ -171,9 +171,7 @@ public static BlockState getPlacementState(ItemStack stack) {
return null;
}

BlockState def = stack.getItem() instanceof BlockItem blockItem ?
blockItem.getBlock().getDefaultState() :
null;
BlockState def = stack.getItem() instanceof BlockItem blockItem ? blockItem.getBlock().getDefaultState() : null;
return fromNBT(nbt.getCompound(EXACT_STATE_KEY), def);
}

Expand Down
36 changes: 21 additions & 15 deletions src/main/java/tools/redstone/redstonetools/utils/ColoredBlock.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package tools.redstone.redstonetools.utils;

import net.minecraft.block.Block;
import net.minecraft.registry.Registry;
import net.minecraft.registry.Registries;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.NotNull;

Expand All @@ -11,17 +11,20 @@

public class ColoredBlock {
private static final Pattern COLORED_BLOCK_REGEX = Pattern.compile(
"^minecraft:(\\w+?)_(wool|stained_glass|concrete_powder|concrete|glazed_terracotta|terracotta)$"
);
"^minecraft:(\\w+?)_(wool|stained_glass|concrete_powder|concrete|glazed_terracotta|terracotta)$");

private static final HashMap<String, ColoredBlock> COLORLESS_BLOCKS = new HashMap<>() {{
put("minecraft:glass", new ColoredBlock("minecraft:%s_stained_glass", BlockColor.WHITE));
put("minecraft:terracotta", new ColoredBlock("minecraft:%s_terracotta", BlockColor.WHITE));
}};
private static final HashMap<String, ColoredBlock> COLORLESS_BLOCKS = new HashMap<>() {
{
put("minecraft:glass", new ColoredBlock("minecraft:%s_stained_glass", BlockColor.WHITE));
put("minecraft:terracotta", new ColoredBlock("minecraft:%s_terracotta", BlockColor.WHITE));
}
};

private static final HashMap<String, ColoredBlock> COLORED_BLOCK_CACHE = new HashMap<>() {{
putAll(COLORLESS_BLOCKS);
}};
private static final HashMap<String, ColoredBlock> COLORED_BLOCK_CACHE = new HashMap<>() {
{
putAll(COLORLESS_BLOCKS);
}
};

private final String blockIdFormat;
public final BlockColor color;
Expand Down Expand Up @@ -60,23 +63,26 @@ public String toBlockId() {
}

public static ColoredBlock fromBlock(@NotNull Block block) {
var blockId = Registry.BLOCK.getId(block).toString();
var blockId = Registries.BLOCK.getId(block).toString();
if (COLORED_BLOCK_CACHE.containsKey(blockId)) {
return COLORED_BLOCK_CACHE.get(blockId);
}

var coloredBlock = fromBlockId(blockId);

// The reason we only cache nulls here and not in the fromBlockId method is because the fromBlockId method would
// also cache invalid block ids (literally any string) which would make the cache massive. This method however
// only accepts actual blocks which means that the cache will never grow bigger than the amount of mc blocks.
// The reason we only cache nulls here and not in the fromBlockId method is
// because the fromBlockId method would
// also cache invalid block ids (literally any string) which would make the
// cache massive. This method however
// only accepts actual blocks which means that the cache will never grow bigger
// than the amount of mc blocks.
COLORED_BLOCK_CACHE.put(blockId, coloredBlock);

return coloredBlock;
}

public Block toBlock() {
return Registry.BLOCK.get(Identifier.tryParse(toBlockId()));
return Registries.BLOCK.get(Identifier.tryParse(toBlockId()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package tools.redstone.redstonetools.utils;

import com.mojang.brigadier.exceptions.CommandSyntaxException;

import net.minecraft.server.command.ServerCommandSource;

public class CommandSourceUtils {
private CommandSourceUtils() {
}

public static void executeCommand(ServerCommandSource source, String command) {
source.getServer().getCommandManager().execute(source, command);
public static void executeCommand(ServerCommandSource source, String command) throws CommandSyntaxException {
source.getServer().getCommandManager().getDispatcher().execute(command, source);
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package tools.redstone.redstonetools.utils;


import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.Direction;
import net.minecraft.command.CommandException;
import net.minecraft.text.Text;
import org.jetbrains.annotations.NotNull;

Expand All @@ -17,7 +16,7 @@ public static Direction firstOrdinal(Direction playerFacing) {
default -> playerFacing;
};
}

public static DirectionArgument relativeToAbsolute(DirectionArgument direction, Direction playerFacing) {
return switch (direction) {
case ME, FORWARD -> switch (firstOrdinal(playerFacing)) {
Expand Down Expand Up @@ -74,9 +73,11 @@ public static DirectionArgument relativeToAbsolute(DirectionArgument direction,
};
}

// big evil match direction function, there might be a better way to do this but i don't know how
// big evil match direction function, there might be a better way to do this but
// i don't know how
@NotNull
public static Direction matchDirection(DirectionArgument direction, Direction playerFacing) throws CommandException {
public static Direction matchDirection(DirectionArgument direction, Direction playerFacing)
throws CommandException {
var absoluteDirection = relativeToAbsolute(direction, playerFacing);
return switch (absoluteDirection) {
case NORTH -> Direction.NORTH;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
package tools.redstone.redstonetools.utils;

import org.joml.Vector3f;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3f;
import net.minecraft.world.RaycastContext;

public class RaycastUtils {
private RaycastUtils() {
}

public static BlockHitResult getBlockHitNeighbor(BlockHitResult hit) {
var sideOffset = hit.getSide().getUnitVector();
Vector3f sideOffset = hit.getSide().getUnitVector();

var newBlockPos = hit.getBlockPos().add(sideOffset.getX(), sideOffset.getY(), sideOffset.getZ());
var newBlockPos = hit.getBlockPos().add((int) sideOffset.x(), (int) sideOffset.y(), (int) sideOffset.z());

return hit.withBlockPos(newBlockPos);
}

public static BlockHitResult rayCastFromEye(PlayerEntity player, float reach) {
return player.method_48926().raycast(new RaycastContext(
return player.getWorld().raycast(new RaycastContext(
player.getEyePos(),
player.getEyePos().add(player.getRotationVector().multiply(reach)),
RaycastContext.ShapeType.COLLIDER,
RaycastContext.FluidHandling.NONE,
player
));
player));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.text.LiteralText;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.math.MathHelper;

Expand Down Expand Up @@ -38,12 +39,15 @@ static SignalBlockSupplier container(int slots) {
int itemsNeeded = Math.max(0, signalStrength == 1
? 1
: (int) Math.ceil(slots * (signalStrength - 1) / 14D * item.getMaxCount()));
String itemId = Registry.ITEM.getId(item).toString();
String itemId = Registries.ITEM.getId(item).toString();

// Check that the calculated number of items is correct.
// This is to prevent problems with items that have a maximum stack size of 1 but stackSize > 1.
// TODO: This can be improved by removing an item and adding stackable items up to the desired signal strength.
// Even with the improvement, this will still fail for inventories with no available slots.
// This is to prevent problems with items that have a maximum stack size of 1
// but stackSize > 1.
// TODO: This can be improved by removing an item and adding stackable items up
// to the desired signal strength.
// Even with the improvement, this will still fail for inventories with no
// available slots.
if (calculateComparatorOutput(itemsNeeded, slots, item.getMaxCount()) != signalStrength)
throw new IllegalStateException("This signal strength cannot be achieved with the selected container");

Expand Down Expand Up @@ -95,7 +99,7 @@ private static boolean isInvalidSignalStrength(int signalStrength, int maxSignal

private static int calculateComparatorOutput(int items, int slots, int item$getMaxCount) {
float f = (float) items / (float) item$getMaxCount;
return MathHelper.floor((f /= (float)slots) * 14.0f) + (items > 0 ? 1 : 0);
return MathHelper.floor((f /= (float) slots) * 14.0f) + (items > 0 ? 1 : 0);
}

private static Item getBestItem(int signalStrength, int slots) {
Expand Down Expand Up @@ -123,7 +127,7 @@ private static void setCompoundNbt(ItemStack item, NbtCompound nbt) {
}

private static void setItemName(ItemStack item, int signalStrength) {
MutableText text = new LiteralText(String.valueOf(signalStrength));
MutableText text = Text.literal(String.valueOf(signalStrength));
text.setStyle(text.getStyle().withColor(Formatting.RED));
item.setCustomName(text);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
import tools.redstone.redstonetools.features.feedback.Feedback;
import com.mojang.datafixers.util.Either;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.fabric.FabricAdapter;
import com.sk89q.worldedit.fabric.FabricPlayer;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.World;
import net.minecraft.server.network.ServerPlayerEntity;

import java.util.function.Consumer;
Expand All @@ -26,11 +23,11 @@ public class WorldEditUtils {
*
* TODO: maybe make an async version of this somehow
*
* @param region The region.
* @param region The region.
* @param consumer The function to run.
*/
public static void forEachBlockInRegion(Region region,
Consumer<BlockVector3> consumer) {
Consumer<BlockVector3> consumer) {
if (!DependencyLookup.WORLDEDIT_PRESENT) {
throw new IllegalStateException("WorldEdit is not loaded.");
}
Expand Down
Loading