Jump to content

Recommended Posts

Posted

Hi,

Is there i way to add a field to a base class?

I read this tutorial http://www.minecraftforge.net/wiki/Using_Access_Transformers.

The auhtor writes about editing field, but not adding a field.

I'm not really in this topic, i just started, because since 1.6 jar mods are really hard to install.

So i have to transform my both jar mods to core mods:

http://www.minecraftforum.net/topic/1795185-162universalrandom-additions-v056-pillar-air-jump-jetpack-and-much-more-2000-downloads/#entry22245488

http://www.minecraftforum.net/topic/1879772-162-world-generation-manager-v02-regenerate-a-specific-mod/

 

Thanks previously  :D

Posted

I believe you can, but you should make sure you know what you are doing before attempting to use ASM :)

 

 

Also if you feel there's a very good and valid reason for the change to forge, please do write a post about it explaining the change and why it's useful, there may be that this change could be added later if it's useful to more than just your specific case :)

  Quote

If you guys dont get it.. then well ya.. try harder...

Posted

First, you probadly think that I'm not so much experienced in programming, but i had just no clue about this specific topic.

(Don't understand that wrong!!!!!!!!! ;))

So my mod RandomAdditions adds a new items physic, to see how it works just visit my mod topic.

Therefore i only have to overwrite some methods, but for my second mod this isn't possible.

 

It allows you to regenerate a mod's worldgenerator. So i have to edit GameRegistry and overwrite the method registerWorldGenerator and change the field worldgenerators to public (need it for other things).

I also have to replace the class Chunk because i have to add a new field for the mods that were generated in it.

The last methods are the onChunkLoad and onChunkUnload (or some thing like that) in the AnvilChunkLoader class.

 

I hope i could give you a little overview about this problem.

Posted
  On 8/22/2013 at 9:42 PM, GotoLink said:

You may want to look at the ChunkEvent.

Yes, i'm using it, but for regnerate the needed mods. I have no access to the NBTData of the chunk so i can't save the information in the chunks data.

 

So far so good, i will have to try it out. Thanks for fast and good answers.

Posted

you could also maybe use only reflection, maybe this would be simpler then ASM (which usually hit people like a truck)

how to debug 101:http://www.minecraftforge.net/wiki/Debug_101

-hydroflame, author of the forge revolution-

Posted

First of all, you need to create a coremod. One of the pages people linked probably already show you how to do that.

 

Then you'll have to have a class that implements IClassTransformer. The only method this interface defines is transform:

 

public class Transformer implements IClassTransformer 
{
@Override
        //Imagine we wanted to add the field to the EntityPlayer class
public byte[] transform(String className, String dontKnowWhatThisIs, byte[] bytecodeForClass)
{
                //note that this will only work in a non obfuscated environment (i.e. running minecraft from eclipse). To make it work within an
                //obfuscated envirionment, you'll have to find out the obfuscated name for the class you want to add your field to. If you don't know
                //how to do that, I can elaborate the answer to show you how.
	if(className.equals("net.minecraft.entity.player.EntityPlayer"))
	{
		return patchEntityPlayer(bytecodeForClass);
	}

                //note that we return the bytecodes for every class other than the one(s) we need to alter unchanged
	return bytecodeForClass;
}


private byte[] patchEntityPlayer(byte[] bytecode, boolean isObfuscated)
{
                //A ClassNode represents a class in a tree-like structure
	ClassNode classNode = new ClassNode();
                //A ClassReader is able to read the java bytecode. It kinda foward events to the ClassVisitor it receaves through it's accept method.
	ClassReader classReader = new ClassReader(bytecode);
                //the method accept of the ClassReader let's a ClassVisitor in (ClassNode is a subclass of the abstract class ClassVisitor)
                //he ClassReader will now read the bytecode on behalf of the ClassVisitor (ClassNode) and call a lot of visit*something* method for it
	classReader.accept(classNode, 0);

                //to create a field we instantiate a FieldNode. The first argument is mandatory, the second is the access flag to the field, the third is
                //the name of the field, the fourth is the descriptor of the field (basically, you need to call Type.getDescriptor and pass the class of
                //the field as argument. In this case, we're creating a field of type String. The fifth argument is the signature of the field. Since I don't
                //know what's a signature in the context of a field, and since there's no problem in letting it be null, I set it as null.
                //The last argument is the initial value of the field. Since this value isn't inherited (I don't know why), we can't set it,
                //because EntityPlayer is, in game, EntityPlayerSP or EntityPlayerMP
	FieldNode newField = new FieldNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC, "TheNewField",
            Type.getDescriptor(String.class), null, null);

                //ClassNode has a List<FieldNode> that you can access through it's "fields" field. I add my new field to it.
	classNode.fields.add(newField);

                //the ClassWriter will actually write the new bytecode. Think of this as a chain. from ClassReader to ClassNode to ClassWriter
	ClassWriter writer = new ClassWriter(0);
	classNode.accept(writer);

                //here we actually return the new bytecode for EntityPlayer, containing the new Field.
	return writer.toByteArray();
}

 

I made a very basic item to test this Transformer:

public class TestItem extends Item
{
public TestItem(int par1) {
	super(par1);
	setMaxDamage(100);
}


@Override
public ItemStack onItemRightClick(ItemStack par1ItemStack, World world, EntityPlayer player)
        {
	par1ItemStack.setItemDamage(par1ItemStack.getItemDamage() + 1);
	Field theField;
	try
	{
		theField = player.getClass().getField("TheNewField");
		String theFieldValue = (String)theField.get(player);
		player.addChatMessage("TheNewField had the value of " + theFieldValue);
		player.addChatMessage("Altering the TheNewField value to \"MAAATHEMATICAL!!\"");
		theField.set(player, "MAAATHEMATICAL!!");
		theFieldValue = (String)theField.get(player);
		player.addChatMessage("TheNewField now has the value had the value of " + theFieldValue);
	}
	catch (Exception e)
	{
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return par1ItemStack;
    }
}

 

Of course, using reflection everytime you'd need to access the item may not be a good idea. To minimize this problem we could at least make a field of type Field in our item class, and we'd avoid the call to Class.getField everytime, by making it just once and storing the return in our field of type Field. All sets and gets would still need reflection though (probably).

Posted
  On 8/23/2013 at 7:08 AM, diesieben07 said:

ILuvYouCompanionCube: How I solve this particular problem:

Make an Interface which contains an abstract setter and getter method for your new field.

Then with ASM not only add the field but also implement the interface (quite easy: just 2 new methods one GETFIELD one PUTFIELD).

In your code you can then cast the minecraft class you transformed to your interface and call the getter/setter methods without needing reflection.

Would look something like this:

World world = // whatever
String awesomeField = ((WorldProxy)world).getMyAwesomeField();
awesomeField = awesomeField.toLowerCase();
((WorldProxy)world).setMyAwesomeField(awesomeField);

 

I said it once and I'll say it again. You, my friend, are very smart. Loved the interface idea.

Posted
  On 8/23/2013 at 7:35 AM, CreativeMD said:

Hm, i think you understood me wrong, i have an idea how this could work, but i just have to try it out. This could take some time.

But thanks for every help.

 

I did understand you wrong. If you know how to do it, I have no idea why you made this question then...  :o

Posted

@dies, you could also make the change in your dev env, so that it compiles thinking there will be a field called "myAwesomeField" and make sure the coremod insert that field.

 

 

this is how I would solve that.

how to debug 101:http://www.minecraftforge.net/wiki/Debug_101

-hydroflame, author of the forge revolution-

  • 2 weeks later...
Posted

@ILuvYouCompanionCube

Sorry, that it takes me so long to answer:

You already give me the solution to this problem, so i didn't understand why you still helped me.

Thanks to all, for the fast and really god help.

Posted

number 1 youre right

 

number 2 you can prevent by overriding the "finalize" method and removing the object

 

just saying hashmap are easier to use then asm

how to debug 101:http://www.minecraftforge.net/wiki/Debug_101

-hydroflame, author of the forge revolution-

Posted
  Quote
Therefore you would need to edit the class again. And also: ewww finalizers.

oh .... right .... DERP MODE ACTIVATE !!

how to debug 101:http://www.minecraftforge.net/wiki/Debug_101

-hydroflame, author of the forge revolution-

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

    • After some time minecraft crashes with an error. Here is the log https://drive.google.com/file/d/1o-2R6KZaC8sxjtLaw5qj0A-GkG_SuoB5/view?usp=sharing
    • The specific issue is that items in my inventory wont stack properly. For instance, if I punch a tree down to collect wood, the first block I collected goes to my hand. So when I punch the second block of wood to collect it, it drops, but instead of stacking with the piece of wood already in my hand, it goes to the second slot in my hotbar instead. Another example is that I'll get some dirt, and then when I'm placing it down later I'll accidentally place a block where I don't want it. When I harvest it again, it doesn't go back to the stack that it came from on my hotbar, where it should have gone, but rather into my inventory. That means that if my inventory is full, then the dirt wont be picked up even though there should be space available in the stack I'm holding. The forge version I'm using is 40.3.0, for java 1.18.2. I'll leave the mods I'm using here, and I'd appreciate it if anybody can point me in the right direction in regards to figuring out how to fix this. I forgot to mention that I think it only happens on my server but I&#39;m not entirely sure. PLEASE HELP ME! LIST OF THE MODS. aaa_particles Adorn AdvancementPlaques AI-Improvements AkashicTome alexsdelight alexsmobs AmbientSounds amwplushies Animalistic another_furniture AppleSkin Aquaculture aquamirae architectury artifacts Atlas-Lib AutoLeveling AutoRegLib auudio balm betterfpsdist biggerstacks biomancy BiomesOPlenty blockui blueprint Bookshelf born_in_chaos Botania braincell BrassAmberBattleTowers brutalbosses camera CasinoCraft cfm (MrCrayfish’s Furniture Mod) chat_heads citadel cloth-config Clumps CMDCam CNB cobweb collective comforts convenientcurioscontainer cookingforblockheads coroutil CosmeticArmorReworked CozyHome CrabbersDelight crashexploitfixer crashutilities Create CreativeCore creeperoverhaul cristellib crittersandcompanions Croptopia CroptopiaAdditions CullLessLeaves curios curiouslanterns curiouslights Curses' Naturals CustomNPCs CyclopsCore dannys_expansion decocraft Decoration Mod DecorationDelightRefurbished Decorative Blocks Disenchanting DistantHorizons doubledoors DramaticDoors drippyloadingscreen durabilitytooltip dynamic-fps dynamiclights DynamicTrees DynamicTreesBOP DynamicTreesPlus Easy Dungeons EasyAnvils EasyMagic easy_npc eatinganimation ecologics effective_fg elevatorid embeddium emotecraft enchantlimiter EnchantmentDescriptions EnderMail engineersdecor entityculling entity_model_features entity_texture_features epicfight EvilCraft exlinefurniture expandability explosiveenhancement factory-blocks fairylights fancymenu FancyVideo FarmersDelight fast-ip-ping FastSuite ferritecore finsandtails FixMySpawnR Forge Middle Ages fossil FpsReducer2 furnish GamingDeco geckolib goblintraders goldenfood goodall H.e.b habitat harvest-with-ease hexerei hole_filler huge-structure-blocks HunterIllager iammusicplayer Iceberg illuminations immersive_paintings incubation infinitybuttons inventoryhud InventoryProfilesNext invocore ItemBorders itemzoom Jade jei (Just Enough Items) JetAndEliasArmors journeymap JRFTL justzoom kiwiboi Kobolds konkrete kotlinforforge lazydfu LegendaryTooltips libIPN lightspeed lmft lodestone LongNbtKiller LuckPerms Lucky77 MagmaMonsters malum ManyIdeasCore ManyIdeasDoors marbledsarsenal marg mcw-furniture mcw-lights mcw-paths mcw-stairs mcw-trapdoors mcw-windows meetyourfight melody memoryleakfix Mimic minecraft-comes-alive MineTraps minibosses MmmMmmMmmMmm MOAdecor (ART, BATH, COOKERY, GARDEN, HOLIDAYS, LIGHTS, SCIENCE) MobCatcher modonomicon mods_optimizer morehitboxes mowziesmobs MutantMonsters mysticalworld naturalist NaturesAura neapolitan NekosEnchantedBooks neoncraft2 nerb nifty NightConfigFixes nightlights nocube's_villagers_sell_animals NoSeeNoTick notenoughanimations obscure_api oculus oresabovediamonds otyacraftengine Paraglider Patchouli physics-mod Pillagers Gun PizzaCraft placeableitems Placebo player-animation-lib pneumaticcraft-repressurized polymorph PrettyPipes Prism projectbrazier Psychadelic-Chemistry PuzzlesLib realmrpg_imps_and_demons RecipesLibrary reeves-furniture RegionsUnexplored restrictedportals revive-me Scary_Mobs_And_Bosses selene shetiphiancore ShoulderSurfing smoothboot
    • Hi everyone, I'm currently developing a Forge 1.21 mod for Minecraft and I want to display a custom HUD overlay for a minigame. My goal: When the game starts, all players should see an item/block icon (from the base game, not a custom texture) plus its name/text in the HUD – similar to how the bossbar overlay works. The HUD should appear centered above the hotbar (or at a similar prominent spot), and update dynamically (icon and name change as the target item changes). What I've tried: I looked at many online tutorials and several GitHub repos (e.g. SeasonHUD, MiniHUD), but most of them use NeoForge or Forge versions <1.20 that provide the IGuiOverlay API (e.g. implements IGuiOverlay, RegisterGuiOverlaysEvent). In Forge 1.21, it seems that neither IGuiOverlay nor RegisterGuiOverlaysEvent exist anymore – at least, I can't import them and they are missing from the docs and code completion. I tried using RenderLevelStageEvent as a workaround but it is probably not intended for custom HUDs. I am not using NeoForge, and switching the project to NeoForge is currently not an option for me. I tried to look at the original minecraft source code to see how elements like hearts, hotbar etc are drawn on the screen but I am too new to Minecraft modding to understand. What I'm looking for: What is the correct way to add a custom HUD element (icon + text) in Forge 1.21, given that the previous overlay API is missing? Is there a new recommended event, callback, or method in Forge 1.21 for custom HUD overlays, or is everyone just using a workaround? Is there a minimal open-source example repo for Forge 1.21 that demonstrates a working HUD overlay without relying on NeoForge or deprecated Forge APIs? My ideal solution: Centered HUD element with an in-game item/block icon (from the base game's assets, e.g. a diamond or any ItemStack / Item) and its name as text, with a transparent background rectangle. It should be visible to the players when the mini game is running. Easy to update the item (e.g. static variable or other method), so it can change dynamically during the game. Any help, code snippets, or up-to-date references would be really appreciated! If this is simply not possible right now in Forge 1.21, it would also help to know that for sure. Thank you very much in advance!
    • The simple answer is there is not an easy way. You would need to know how to program in Java, as well as at least some familiarity with how Forge works so you could port the differences. You would also need the sourcecode for the original mod, and permission from the author to modify it, if they did not use some sort of open source license. So it's not impossible, but it would take some effort, but doing so would open up a whole new world of possibilities for you!
  • Topics

×
×
  • Create New...

Important Information

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