Jump to content

[1.8.9] [SOLVED] Custom log somehow gets wrong metadata


Daeruin

Recommended Posts

I'm making a custom log. The idea is that if the player sneaks while breaking vanilla logs, it drops bark and replaces the log with a stripped log. I have a custom log class that extends BlockLog. I'm using a HarvestDropsEvent for the drops and the log swap. I have textures and models for all the stripped logs.

 

Everything was working fine when I only had four variants (to match vanilla's BlockOldLog), but when I tried to add the two wood variants from BlockNewLog, that's when things went wrong. I had to do some weird things to make the metadata work for the block orientation while still grabbing the right texture. The code feels kludgy to me but I'm not sure what to do to make it better. Maybe two custom classes, one for BlockOldLog and one for BlockNewLog? Bitwise operators are new to me so I've been reluctant to mess with the switch statements for the log orientation.

 

Anyway, after making the changes, suddenly oak and jungle wood get swapped out with the acacia and dark oak textures. I've put in a ton of sysout statements to track the meta value. Everything looks right, the log has all the right metadata before and after I call event.world.setBlockState in the harvest drops event, and yet somehow, at some point after the harvest event places the correct block, it's getting changed to the wrong block.

 

I've removed all the sysout statements from the code below, but here's a pastebin to show what the logs look like: http://pastebin.com/dpTB2ZsQ. You can see the metadata is 0 (log_oak_stripped) all the way down until after the harvest event, when it suddenly switches to 4 (log_acacia_stripped).

 

My custom log class:

public class PrimalBlockStrippedLog extends BlockLog {

    public static final PropertyEnum VARIANT = PropertyEnum.create("variant", PrimalBlockStrippedLog.EnumWoodType.class, new Predicate()
    {
        public boolean apply(PrimalBlockStrippedLog.EnumWoodType type) {
            return type.getMetadata() < 6;
        }
        public boolean apply(Object p_apply_1_) {
            return this.apply((PrimalBlockStrippedLog.EnumWoodType)p_apply_1_);
        }
    });

    public PrimalBlockStrippedLog() {
        this.setDefaultState(this.blockState.getBaseState()
        		.withProperty(VARIANT, PrimalBlockStrippedLog.EnumWoodType.STRIPPEDOAK)
        		.withProperty(LOG_AXIS, BlockLog.EnumAxis.Y));
        setHardness(2.0F);
    	setResistance(0.5F);
    	//setStepSound(Block.soundTypeWood);
	this.setCreativeTab(PrimalCreativeTabs.tabPrimalcraft);
    }
    
    @SideOnly(Side.CLIENT)
    public void getSubBlocks(Item block, CreativeTabs tab, List list) {
	System.out.println("[getSubBlocks] called");
        list.add(new ItemStack(block, 1, PrimalBlockStrippedLog.EnumWoodType.STRIPPEDOAK.getMetadata()));
        list.add(new ItemStack(block, 1, PrimalBlockStrippedLog.EnumWoodType.STRIPPEDSPRUCE.getMetadata()));
        list.add(new ItemStack(block, 1, PrimalBlockStrippedLog.EnumWoodType.STRIPPEDBIRCH.getMetadata()));
        list.add(new ItemStack(block, 1, PrimalBlockStrippedLog.EnumWoodType.STRIPPEDJUNGLE.getMetadata()));
        list.add(new ItemStack(block, 1, PrimalBlockStrippedLog.EnumWoodType.STRIPPEDACACIA.getMetadata()));
        list.add(new ItemStack(block, 1, PrimalBlockStrippedLog.EnumWoodType.STRIPPEDDARKOAK.getMetadata()));
    }

    public IBlockState getStateFromMeta(int meta) {
    	int vanillaMeta = meta; // Used so vanilla functions still work
	if (meta > 3) vanillaMeta = meta - 4; // This is a BlockNewLog; adjust meta down to match vanilla log classes
        IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, PrimalBlockStrippedLog.EnumWoodType.byMetadata(meta));

        switch (vanillaMeta & 12) {
            case 0:
                iblockstate = iblockstate.withProperty(LOG_AXIS, BlockLog.EnumAxis.Y);
                break;
            case 4:
                iblockstate = iblockstate.withProperty(LOG_AXIS, BlockLog.EnumAxis.X);
                break;
            case 8:
                iblockstate = iblockstate.withProperty(LOG_AXIS, BlockLog.EnumAxis.Z);
                break;
            default:
                iblockstate = iblockstate.withProperty(LOG_AXIS, BlockLog.EnumAxis.NONE);
        }

        return iblockstate;
    }

    @SuppressWarnings("incomplete-switch")
    public int getMetaFromState(IBlockState state) {
	System.out.println("[getMetaFromState] called");
        int i = 0;
        int meta = ((PrimalBlockStrippedLog.EnumWoodType)state.getValue(VARIANT)).getMetadata();
	if (meta > 3) meta = meta - 4; // This is a BlockNewLog; adjust meta down to match vanilla log classes
        i = i | meta;
//        i = i | ((PrimalBlockStrippedLog.EnumWoodType)state.getValue(VARIANT)).getMetadata();

        switch ((BlockLog.EnumAxis)state.getValue(LOG_AXIS)) {
            case X:
                i |= 4;
                break;
            case Z:
                i |= 8;
                break;
            case NONE:
                i |= 12;
        }
        return i;
    }

    @Override
    protected BlockState createBlockState() {
        return new BlockState(this, new IProperty[] {VARIANT, LOG_AXIS});
    }

    protected ItemStack createStackedBlock(IBlockState state) {
        return new ItemStack(Item.getItemFromBlock(this), 1, ((PrimalBlockStrippedLog.EnumWoodType)state.getValue(VARIANT)).getMetadata());
    }

    public int damageDropped(IBlockState state) {
        return ((PrimalBlockStrippedLog.EnumWoodType)state.getValue(VARIANT)).getMetadata();
    }
    
    public static enum EnumWoodType implements IStringSerializable {
    	
        STRIPPEDOAK(0, "log_oak_stripped"),
        STRIPPEDSPRUCE(1, "log_spruce_stripped"),
        STRIPPEDBIRCH(2, "log_birch_stripped"),
        STRIPPEDJUNGLE(3, "log_jungle_stripped"),
        STRIPPEDACACIA(4, "log_acacia_stripped"),
        STRIPPEDDARKOAK(5, "log_dark_oak_stripped");
    	
        private static final PrimalBlockStrippedLog.EnumWoodType[] META_LOOKUP = new PrimalBlockStrippedLog.EnumWoodType[values().length];

        private final int meta;
        private final String name;
        private final String unlocalizedName;
        
        private EnumWoodType(int meta, String name) {
            this(meta, name, name);
        }

        private EnumWoodType(int meta, String name, String unlocalizedName) {
            this.meta = meta;
            this.name = name;
            this.unlocalizedName = unlocalizedName;
        }
       
        public int getMetadata() {
            return this.meta;
        }
        
        public String toString() {
        	return getName();
        }
       
        public static PrimalBlockStrippedLog.EnumWoodType byMetadata(int meta) {
        	if (meta < 0 || meta >= META_LOOKUP.length) {
                meta = 0;
            }
            return META_LOOKUP[meta];
        }

        public String getName() {
            return this.name;
        }

        public String getUnlocalizedName() {
            return this.unlocalizedName;
        }
        
        static {
        	PrimalBlockStrippedLog.EnumWoodType[] var0 = values();
            int var1 = var0.length;

            for (int var2 = 0; var2 < var1; ++var2)
            {
            	PrimalBlockStrippedLog.EnumWoodType var3 = var0[var2];
                META_LOOKUP[var3.getMetadata()] = var3;
            }
        }

    }
}

 

My harvest event (this isn't the whole thing, just the relevant part):

public void onDrop(HarvestDropsEvent event) {

	Block block = event.state.getBlock();

	if (event.harvester != null) {
		boolean blockIsLog = false;
		int meta = 0;
		EntityPlayer player = event.harvester;
		boolean holdingTool = false;
		boolean holdingNonTool = false;
		boolean holdingNothing = false;
		boolean isSneaking = false;

		if (player.getHeldItem() != null) {
			if (player.getHeldItem().getItem() instanceof ItemTool) holdingTool = true;
			else holdingNonTool = true;
		} else holdingNothing = true;

		if (player.isSneaking()) isSneaking = true;

		// Regular log
		if (block == Blocks.log) {
			blockIsLog = true;
			meta = block.getMetaFromState(event.state);
		}
		if (block == Blocks.log2) {
			blockIsLog = true;
			meta = block.getMetaFromState(event.state) + 4; // Adjust meta to match my PrimalBlockStrippedLog class
		}
		if (blockIsLog) {
			if (holdingTool) {
				if (!isSneaking) {
					return; // Allow to drop log as normal
				}
				else if (isSneaking) {
					event.drops.clear(); // Don't drop log
					event.drops.add(new ItemStack(PrimalItemRegistry.ItemBarkOak, 4)); // Drop 4 bark
					event.world.setBlockState(event.pos, PrimalBlockRegistry.log_stripped.getStateFromMeta(meta)); // Replace log with stripped log
				}
			}

 

Blockstate JSON:

 

{
    "variants": {
        "axis=y,variant=log_oak_stripped":    { "model": "primalcraft:log_oak_stripped" },
        "axis=z,variant=log_oak_stripped":     { "model": "primalcraft:log_oak_stripped_side" },
        "axis=x,variant=log_oak_stripped":     { "model": "primalcraft:log_oak_stripped_side", "y": 90 },
        "axis=none,variant=log_oak_stripped":   { "model": "primalcraft:log_oak_stripped_bare" },
        "axis=y,variant=log_spruce_stripped":    { "model": "primalcraft:log_spruce_stripped" },
        "axis=z,variant=log_spruce_stripped":     { "model": "primalcraft:log_spruce_stripped_side" },
        "axis=x,variant=log_spruce_stripped":     { "model": "primalcraft:log_spruce_stripped_side", "y": 90 },
        "axis=none,variant=log_spruce_stripped":   { "model": "primalcraft:log_spruce_stripped_bare" },
        "axis=y,variant=log_birch_stripped":    { "model": "primalcraft:log_birch_stripped" },
        "axis=z,variant=log_birch_stripped":     { "model": "primalcraft:log_birch_stripped_side" },
        "axis=x,variant=log_birch_stripped":     { "model": "primalcraft:log_birch_stripped_side", "y": 90 },
        "axis=none,variant=log_birch_stripped":   { "model": "primalcraft:log_birch_stripped_bare" },
        "axis=y,variant=log_jungle_stripped":    { "model": "primalcraft:log_jungle_stripped" },
        "axis=z,variant=log_jungle_stripped":     { "model": "primalcraft:log_jungle_stripped_side" },
        "axis=x,variant=log_jungle_stripped":     { "model": "primalcraft:log_jungle_stripped_side", "y": 90 },
        "axis=none,variant=log_jungle_stripped":   { "model": "primalcraft:log_jungle_stripped_bare" },
        "axis=y,variant=log_acacia_stripped":    { "model": "primalcraft:log_acacia_stripped" },
        "axis=z,variant=log_acacia_stripped":     { "model": "primalcraft:log_acacia_stripped_side" },
        "axis=x,variant=log_acacia_stripped":     { "model": "primalcraft:log_acacia_stripped_side", "y": 90 },
        "axis=none,variant=log_acacia_stripped":   { "model": "primalcraft:log_acacia_stripped_bare" },
        "axis=y,variant=log_dark_oak_stripped":    { "model": "primalcraft:log_dark_oak_stripped" },
        "axis=z,variant=log_dark_oak_stripped":     { "model": "primalcraft:log_dark_oak_stripped_side" },
        "axis=x,variant=log_dark_oak_stripped":     { "model": "primalcraft:log_dark_oak_stripped_side", "y": 90 },
        "axis=none,variant=log_dark_oak_stripped":   { "model": "primalcraft:log_dark_oak_stripped_bare" }
    }
}

 

Link to comment
Share on other sites

There's a reason vanilla only has up to four variants per log class: 4 types * 4 axes = 16 possible combinations. Metadata is limited to the range [0, 15], which allows up to 16 combinations to be saved.

 

If you want more than four variants, create a separate class for each set of 1-4 variants like vanilla does.

 

If you're using the same variants as vanilla wood, consider extending

BlockOldLog

/

BlockNewLog

and only overriding the necessary methods.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

Dang. I think I read that somewhere but forgot about it. I kept wondering why vanilla had two log classes.

 

What about using a tile entity instead? I've been thinking about adding some of my own wood types in the future. It seems ridiculous to keep creating new log classes just because of that.

Link to comment
Share on other sites

What about using a tile entity instead? I've been thinking about adding some of my own wood types in the future. It seems ridiculous to keep creating new log classes just because of that.

 

That's possible:

  • Store the
    EnumWoodType

    in the

    TileEntity

    .

  • Override
    Block#getActualState

    to retrieve the

    TileEntity

    at the specified position and set the value of the

    VARIANT

    property to the stored value.

  • Override
    Block#getMetaFromState

    to return 0.

 

 

 

 

 

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

OTOH, TileEntities are more expensive than regular blocks, which is why Vanilla has two logs and two leaves rather than a TE.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

OTOH, TileEntities are more expensive than regular blocks, which is why Vanilla has two logs and two leaves rather than a TE.

You also can't push TileEntities with pistons (or at least not until Mojang ports MCPE 0.15.0's piston changes, which may not be until 1.11), so there's that, too.

Colore - The mod that adds monochrome blocks in every color of the rainbow!

http://www.minecraftforge.net/forum/index.php?topic=35149

 

If you're looking to learn how to make mods for 1.9.4, I wrote a helpful article with links to a lot of useful resources for learning Minecraft 1.9.4 modding!

 

http://supergeniuszeb.com/mods/a-helpful-list-of-minecraft-1-9-4-modding-resources/

Link to comment
Share on other sites

I got around to reading about TileEntities today. It looks like each tile entity block is a separate object in memory. Is that what you mean by TileEntities being more expensive? I wonder how it would affect performance if every block of wood in the world was a TileEntity.

Link to comment
Share on other sites

I got around to reading about TileEntities today. It looks like each tile entity block is a separate object in memory. Is that what you mean by TileEntities being more expensive? I wonder how it would affect performance if every block of wood in the world was a TileEntity.

Link to comment
Share on other sites

Blocks as x/y/z are saved in byte arrays to be cheap. TileEntity requires object and few references which cost memory, it also creates network overhead.

 

If you are after such common blocks as wooden logs then no - TE is not a good tool for that.

Use multiple blocks like vanilla does.

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

Blocks as x/y/z are saved in byte arrays to be cheap. TileEntity requires object and few references which cost memory, it also creates network overhead.

 

If you are after such common blocks as wooden logs then no - TE is not a good tool for that.

Use multiple blocks like vanilla does.

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

I got around to reading about TileEntities today. It looks like each tile entity block is a separate object in memory. Is that what you mean by TileEntities being more expensive? I wonder how it would affect performance if every block of wood in the world was a TileEntity.

 

I've accidentally turned the entire world into chests once.  It was awful.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I got around to reading about TileEntities today. It looks like each tile entity block is a separate object in memory. Is that what you mean by TileEntities being more expensive? I wonder how it would affect performance if every block of wood in the world was a TileEntity.

 

I've accidentally turned the entire world into chests once.  It was awful.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I would expect the bottleneck here to be the TESR, not the TileEntity itself. A flat-world out of furnaces actually runs decently well (until you walk around and the game has to load and unload chunks).

 

In that case, it probably was.  Non-running TEs (furnaces would still have an update tick) would run pretty fast, but there is memory overhead.

 

Note that we're not saying "Don't use a TE for this" but "TEs do require extra resources: be careful."

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I would expect the bottleneck here to be the TESR, not the TileEntity itself. A flat-world out of furnaces actually runs decently well (until you walk around and the game has to load and unload chunks).

 

In that case, it probably was.  Non-running TEs (furnaces would still have an update tick) would run pretty fast, but there is memory overhead.

 

Note that we're not saying "Don't use a TE for this" but "TEs do require extra resources: be careful."

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Got it. I am planning to add many types of wood to my mod eventually. Each would have a regular version and a version stripped of bark. That's why I was considering using TE in the first place.

 

Another factor is referring to all these types of wood in events. The Ore Dictionary makes multiple wood types easy to use for recipes. Can it be used in events? Or is there some other easy way to avoid messiness if you have four or five different log classes to refer to?

Link to comment
Share on other sites

Got it. I am planning to add many types of wood to my mod eventually. Each would have a regular version and a version stripped of bark. That's why I was considering using TE in the first place.

 

Another factor is referring to all these types of wood in events. The Ore Dictionary makes multiple wood types easy to use for recipes. Can it be used in events? Or is there some other easy way to avoid messiness if you have four or five different log classes to refer to?

Link to comment
Share on other sites

This is what I came up with. It seems to be working well. What if I need to do something similar in another event, like a harvest event? Would it make sense to create the list somewhere else, like in my Main class, and then iterate through it separately in each event?

 

public class BreakSpeedEvent {

List woodList = OreDictionary.getOres("logWood");
boolean isLog = false;

@SubscribeEvent

public void onDig(BreakSpeed event) {

	Block block = iblockstate.getBlock();

	for (int i=0; i < woodList.size(); i++) {
		if (OreDictionary.itemMatches((ItemStack) woodList.get(i), new ItemStack(block), false)) {
			isLog = true;
			break;
		}
	}
}
}

Link to comment
Share on other sites

1) that boolean shouldn't be a class property: there may be multiple players breaking blocks at the same time.

2) you never modify the break speed.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

1) I didn't include my entire class and misplaced the isLog variable as I was copying the code into my post. isLog was actually part of the onDig method. But your comment made me realize I could do everything without that variable, so thanks for that.

 

2) I only included the part of my code I wanted feedback on. I'm actually going to cancel the event if the player isn't using a specific tool, along with a few other things that aren't really relevant to the question at hand.

 

Any advice on where to create the OreDictionary list if I need to use it in multiple events? Or do I create a separate list in each event class? Does it even matter?

 

New code, in case it matters:

 

public class BreakSpeedEvent {

List woodList = OreDictionary.getOres("logWood");

@SubscribeEvent

public void onDig(BreakSpeed event) {

	Block block = iblockstate.getBlock();

	for (int i=0; i < woodList.size(); i++) {
		if (OreDictionary.itemMatches((ItemStack) woodList.get(i), new ItemStack(block), false)) {
			// Code to cancel event if player is holding wrong tool, and other stuff
		}
	}
}
}

Link to comment
Share on other sites

The options I've thought, and don't like, are:

 

a. Make the log list static and keep it in BreakEvent, then simply refer to it from HarvestEvent when I need to check if something is a log. I don't like this idea because it feels messy. There's no particular reason why the list should reside in one or the other.

 

b. Put both events in the same class. I don't like this idea because I've been keeping each event in its own class. It feels more organized and keeps my classes from getting really huge.

 

c. Create a new class to hold the list. This feels slightly better, because it would provide a place to keep code that's common to multiple event classes. But so far I only have the one tiny thing to put in it.

Link to comment
Share on other sites

Put both events in the same class. Which, by the way, is badly named.  What you have is an event handler class, not an event class.  You can have as many event handler methods in the same class as you want.  Some of my handler classes are huge.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

What's the advantage of having a dozen event handler methods in the same class versus different classes? I'm not trying to be difficult, I just want to learn. It seems like using multiple classes is better organized and easier to find things.

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.