Jump to content

Recommended Posts

Posted (edited)

Hello,

I want to create a command to give an item with the structure that it get's from a file.

This worked properly with all vanilla items, after some tests i tried it with a mod and it crashed.

Whenever i use the card wich i get from the command it crashes but if i create it without the file in a block it works, i checked the NBT data of the players inventory and everything is exact the same.

 

What am i doing wrong ?

NBTUtil#readBlockState crashes with modBlocks

 

Commands.java - private void giveMemorycard gives error

Spoiler

package com.kyproject.justcopyit.commands;

import com.kyproject.justcopyit.JustCopyIt;
import com.kyproject.justcopyit.init.ModItems;
import com.kyproject.justcopyit.templates.StructureTemplate;
import com.kyproject.justcopyit.tileentity.TileEntityBuilder;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.NumberInvalidException;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class JciCommands extends CommandBase {

    @Nonnull
    @Override
    public String getName() {
        return "jci";
    }

    @Nonnull
    @Override
    public String getUsage(ICommandSender sender) {
        return "/jci <memorycard|reload>";
    }

    @Override
    public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
        if(args.length > 0) {
            switch (args[0]) {
                case "memorycard":
                    this.giveMemorycard(args, sender);
                    break;
                case "?":
                case "help":
                    sender.sendMessage( new TextComponentString("§cUsage: " +  this.getUsage(sender)));
                    break;
                case "reload":
                    this.reloadFitler(sender);
                    break;
                default:
                    break;
            }
        }
    }

    @Nonnull
    @Override
    public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) {
        if (args.length == 1)
        {
            return getListOfStringsMatchingLastWord(args, "memorycard", "reload");
        }

        return super.getTabCompletions(server, sender, args, targetPos);
    }

    private void reloadFitler(ICommandSender sender) {
        TileEntityBuilder tileEntityBuilder = new TileEntityBuilder();
        TileEntityBuilder.filter = tileEntityBuilder.readJsonFilter();
        StructureTemplate structureTemplate = new StructureTemplate();
        structureTemplate.loadBlockItemFilter();

        sender.sendMessage( new TextComponentString("§2[JCI] Filter is updated!"));
        sender.sendMessage( new TextComponentString("§2[JCI] Layer filter is updated!"));

    }

    private void giveMemorycard(String[] args, ICommandSender sender) {
        if(args.length > 1) {
            if(!args[1].equals("?") && !args[1].equals("help")) {
                EntityPlayer player = (EntityPlayer) sender;
                World world = ((EntityPlayer) sender).world;
                StructureTemplate structureTemplate = new StructureTemplate();

                NBTTagCompound nbt = structureTemplate.getNBT(args[1]);


                if(args.length > 2) {
                    if(this.tryParseInt(args[2]) != null) {
                        int durability = Integer.parseInt(args[2]);
                        if(durability <= 0) {
                            nbt.setInteger("durability", -1);
                        } else {
                            nbt.setInteger("durability", durability);
                        }
                    } else {
                        sender.sendMessage( new TextComponentString("§cUsage: /jci memorycard <file name> <usages> <creative>"));
                    }
                } else {
                    nbt.setInteger("durability", -1);
                }

                if(nbt != null) {
                    ItemStack item;
                    if(args.length > 3) {
                        if(args[3].equals("true")) {
                            item = new ItemStack(ModItems.MEMORY_CARD_CREATIVE);
                        } else {
                            item = new ItemStack(ModItems.MEMORY_CARD);
                        }
                    } else {
                        item = new ItemStack(ModItems.MEMORY_CARD);
                    }

                    if(nbt.hasKey("name")) {
                        NBTTagList tagList = nbt.getTagList("blocks", Constants.NBT.TAG_COMPOUND);

                        String test = nbt.getString("name"); <-- is working fine from the file
                        System.out.println(NBTUtil.readBlockState(tagList.getCompoundTagAt(0))); <-- line 131 crashes
                        System.out.println(test);
                    }


                    item.setTagCompound(nbt);
                    if (player.inventory.getFirstEmptyStack() != -1) {
                        //player.inventory.addItemStackToInventory(item);
                    } else {
                        world.spawnEntity(new EntityItem(world, player.posX, player.posY, player.posZ, item));
                    }
                } else {
                    JustCopyIt.logger.warn("File doesn't exist!!");
                    sender.sendMessage( new TextComponentString("§cFile doesn't exist!!"));
                }
            } else {
                sender.sendMessage( new TextComponentString("§cUsage: /jci memorycard <file name> <usages> <creative>"));
            }
        } else {
            this.getUsage(sender);
            sender.sendMessage( new TextComponentString("§cUsage: /jci memorycard <file name> <usages> <creative>"));
        }
    }

    private Integer tryParseInt(String text) {
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            return null;
        }
    }

}

 

 

 

Error log:

Spoiler

[21:06:42] [Server thread/WARN]: Couldn't process command: jci memorycard test2 -1
java.lang.IllegalArgumentException: Cannot set property PropertyStringTemp{name=type, clazz=class java.lang.String, values=[flux, fluid]} to flux on block draconicevolution:flow_gate, it is not an allowed value
	at net.minecraft.block.state.BlockStateContainer$StateImplementation.withProperty(BlockStateContainer.java:233) ~[BlockStateContainer$StateImplementation.class:?]
	at net.minecraft.nbt.NBTUtil.setValueHelper(NBTUtil.java:293) ~[NBTUtil.class:?]
	at net.minecraft.nbt.NBTUtil.readBlockState(NBTUtil.java:278) ~[NBTUtil.class:?]
	at com.kyproject.justcopyit.commands.JciCommands.giveMemorycard(JciCommands.java:131) ~[JciCommands.class:?]
	at com.kyproject.justcopyit.commands.JciCommands.execute(JciCommands.java:53) ~[JciCommands.class:?]
	at net.minecraft.command.CommandHandler.tryExecute(CommandHandler.java:126) [CommandHandler.class:?]
	at net.minecraft.command.CommandHandler.executeCommand(CommandHandler.java:98) [CommandHandler.class:?]
	at net.minecraft.network.NetHandlerPlayServer.handleSlashCommand(NetHandlerPlayServer.java:1001) [NetHandlerPlayServer.class:?]
	at net.minecraft.network.NetHandlerPlayServer.processChatMessage(NetHandlerPlayServer.java:977) [NetHandlerPlayServer.class:?]
	at net.minecraft.network.play.client.CPacketChatMessage.processPacket(CPacketChatMessage.java:47) [CPacketChatMessage.class:?]
	at net.minecraft.network.play.client.CPacketChatMessage.processPacket(CPacketChatMessage.java:8) [CPacketChatMessage.class:?]
	at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:21) [PacketThreadUtil$1.class:?]
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_151]
	at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_151]
	at net.minecraft.util.Util.runTask(Util.java:53) [Util.class:?]
	at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:796) [MinecraftServer.class:?]
	at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:741) [MinecraftServer.class:?]
	at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:192) [IntegratedServer.class:?]
	at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:590) [MinecraftServer.class:?]
	at java.lang.Thread.run(Thread.java:748) [?:1.8.0_151]
[21:06:42] [main/INFO]: [CHAT] An unknown error occurred while attempting to perform this command

 

 

Edited by KYPremco
Posted

This is due to the property used. The way Minecraft handles things means that it expects the exact value used to create the property, so unless you're being particularly careful, strings won't work here.

Posted
15 minutes ago, quadraxis said:

This is due to the property used. The way Minecraft handles things means that it expects the exact value used to create the property, so unless you're being particularly careful, strings won't work here.

 

I use NBTUtil#readBlockState & NBTUtil#writeBlockState

 

After some more testeing: not all blocks will let it crash probably only a small amount.

But what bugs me is why is it working without the command while it's setup exact the same

 

This is the player data saved, one card from the command left, the other from the block right.

BCkb3vr.png

Posted
19 minutes ago, diesieben07 said:

Like @quadraxis eluded to, unfortunately Minecraft does not check equals when comparing properties in certain circumstances, it uses ==.

In this case (and many other cases where String is used) this can be circumvented by callingString::intern on the property values before passing them into IBlockState::withProperty. This works, because the IProperty instances are created using string literals, which always resolve to interned strings.

Ah okay didn't understand the first time, well sad but true.

Then i'll just check if they going to cause errors and remove that type of block before passing into the item.

I hope not to much blocks have this problem, but thanks for the help anyway

Posted
25 minutes ago, diesieben07 said:

Ok... well then. Just ignore my perfectly valid fix and just ignore the problem. Sure, why not.

Oh sorry i misunderstood it because i tought i could not change the NBTUtils#readBlockState

Now i have copied that code in the command and changed 

Optional<T> optional = p_193590_1_.parseValue(p_193590_3_.getString(p_193590_2_));

To:

Optional<T> optional = p_193590_1_.parseValue(p_193590_3_.getString(p_193590_2_).intern());

 

And it's workign fine now indeed

But could i do this more smooth then copy paste that code ?(sorry i'm still a beginner)

 

Full code added:

Spoiler

private static IBlockState readBlockState(NBTTagCompound tag)
    {
        if (!tag.hasKey("Name", 8))
        {
            return Blocks.AIR.getDefaultState();
        }
        else
        {
            Block block = Block.REGISTRY.getObject(new ResourceLocation(tag.getString("Name")));
            IBlockState iblockstate = block.getDefaultState();

            if (tag.hasKey("Properties", 10))
            {
                NBTTagCompound nbttagcompound = tag.getCompoundTag("Properties");
                BlockStateContainer blockstatecontainer = block.getBlockState();

                for (String s : nbttagcompound.getKeySet())
                {
                    IProperty<?> iproperty = blockstatecontainer.getProperty(s);

                    if (iproperty != null)
                    {
                        iblockstate = setValueHelper(iblockstate, iproperty, s, nbttagcompound, tag);
                    }
                }
            }

            return iblockstate;
        }
    }

    private static <T extends Comparable<T>> IBlockState setValueHelper(IBlockState p_193590_0_, IProperty<T> p_193590_1_, String p_193590_2_, NBTTagCompound p_193590_3_, NBTTagCompound p_193590_4_)
    {
        Optional<T> optional = p_193590_1_.parseValue(p_193590_3_.getString(p_193590_2_).intern());

        if (optional.isPresent())
        {
            return p_193590_0_.withProperty(p_193590_1_, optional.get());
        }
        else
        {
            JustCopyIt.logger.warn("Unable to read property: {} with value: {} for blockstate: {}", p_193590_2_, p_193590_3_.getString(p_193590_2_), p_193590_4_.toString());
            return p_193590_0_;
        }
    }

 

 

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

    • Ah, it appears I spoke too soon, I still need a little help here. I now have the forceloading working reliably.  However, I've realized it's not always the first tick that loads the entity.  I've seen it take anywhere from 2-20ish to actually go through, in which time my debugging has revealed that the chunk is loaded, but during which time calling  serverLevelIn.getEntity(uuidIn) returns a null result.  I suspect this has to do with queuing and how entities are loaded into the game.  While not optimal, it's acceptable, and I don't think there's a whole ton I can do to avoid it. However, my concern is that occasionally teleporting an entity in this manner causes a lag spike.  It's not every time and gives the appearance of being correlated with when other chunks are loading in.  It's also not typically a long spike, but can last a second or two, which is less than ideal.  The gist of how I'm summoning is here (although I've omitted some parts that weren't relevant.  The lag occurs before the actual summon so I'm pretty confident it's the loading, and not the actual summon call). ChunkPos chunkPos = new ChunkPos(entityPosIn); if (serverLevelIn.areEntitiesLoaded(chunkPos.toLong())) { boolean isSummoned = // The method I'm using for actual summoning is called here. Apart from a few checks, the bulk of it is shown later on. if (isSummoned) { // Code that runs here just notifies the player of the summon, clears it from the queue, and removes the forceload } } else { // I continue forcing the chunk until the summon succeeds, to make sure it isn't inadvertently cleared ForgeChunkManager.forceChunk(serverLevelIn, MODID, summonPosIn, chunkPos.x, chunkPos.z, true, true); } The summon code itself uses serverLevelIn.getEntity(uuidIn) to retrieve the entity, and moves it as such.  It is then moved thusly: if (entity.isAlive()) { entity.moveTo(posIn.getX(), posIn.getY(), posIn.getZ()); serverLevelIn.playSound(null, entity, SoundEvents.ENDERMAN_TELEPORT, SoundSource.NEUTRAL, 1.0F, 1.0F); return true; } I originally was calling .getEntity() more frequently and didn't have the check for whether or not entities were loaded in place to prevent unnecessary code calls, but even with those safety measures in place, the lag still persists.  Could this just be an issue with 1.18's lack of optimization in certain areas?  Is there anything I can do to mitigate it?  Is there a performance boosting mod I could recommend alongside my own to reduce the chunk loading lag? At the end of the day, it does work, and I'm putting measures in place to prevent players from abusing the system to cause lag (i.e. each player can only have one queued summon at a time-- trying to summon another replaces the first call).  It's also not an unacceptable level of lag, IMO, given the infrequency of such calls, and the fact that I'm providing the option to toggle off the feature if server admins don't want it used.  However, no amount of lag is ideal, so if possible I'd love to find a more elegant solution-- or at least a mod recommendation to help improve it. Thanks!
    • When i start my forge server its on but when i try to join its come a error Internal Exception: java.lang.OutOfMemoryError: Requested array size exceeds VM limit Server infos: Linux Minecraft version 1.20.1 -Xmx11G -Xms8G
    • Also add the latest.log from your logs-folder
    • Add the mods in groups
  • Topics

×
×
  • Create New...

Important Information

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