Jump to content

[1.12.2][SOLVED] Cannot set property


KYPremco

Recommended Posts

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
Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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_;
        }
    }

 

 

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



×
×
  • Create New...

Important Information

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