Jump to content

Recommended Posts

Posted (edited)

I want to store a true boolean in an entity (something like "isUpgraded:1b" in NBT), but I am not sure whats the correct way to do that in forge. I wanted to use NBT, but I don't know how to read and write it in forge.
I saw that there's something called "Capabilities". it seems like it could be a better alternative, but I am not sure how to use it either.

What would be the better approach?

Edited by MaiTheLord
Posted

There are at least 2 different ways to do this.

 

net.minecraft.world.entity.ai.attributes.Attributes

This is not something I've not played with. So I can't say much about it.

The basic idea is each entity has a set of attributes. Which can also have permanent or transient AttributeModifiers. These modifiers are linked to ArmorItems or MobEffects, or they could be "ad hoc".

Forge has some events that let you configure attributes for entities: EntityAttribute(Creation/Modification)Event. Of course you need to register any custom attributes you make.

From what I can tell, these attributes are meant to be number ranges.

 

Forge's capabilities: https://forge.gemwire.uk/wiki/Capabilities

These are much more general and let you attach any data to most important in game things, but they also provide an "interface" for mod communication.

It is good to learn this system, things like item handling across mods or FE (forge energy) uses capabilities.

The major drawback with capabilities is they don't automatically synchronize with the client, so you have to do this yourself. Which is something people can struggle with until they understand it. The issue is due to capabilities being flexible, forge can't really know what/how/when you want to synchronize.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted

In game you just use a normal boolean field like normal in your capability class.

Its only if you want to send it across the network or save it you need to turn it into a ByteTag (there is no BooleanTag).

Wrapping it in a CompoundTag would future proof it, so you can add other data/tags later.

A plain byte tag is 1b, the compound tag gives it a name {name:1b} in future it might be {name:1b,another:"foobar"}

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted

Click on the link above about capabilities and read it, in particular the attaching and the simple example at the end which has serialization.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted

I must be doing something wrong then.

 

CompoundTag tag = entity.serializeNBT();
tag.putBoolean("IsUpgraded", true);
entity.deserializeNBT(tag);

System.out.println(entity.serializeNBT().getBoolean("IsUpgraded")); // prints false
Posted (edited)

I did read it, and a capability seems like an overkill for what I want to do.

4 hours ago, warjort said:

Click on the link above about capabilities and read it, in particular the attaching and the simple example at the end which has serialization.

I might be wrong, but I think the person wanted me to look at this particular piece of code

        @Override
        public IntTag serializeNBT() {
            return backend.serializeNBT();
        }

        @Override
        public void deserializeNBT(IntTag tag) {
            backend.deserializeNBT(tag);
        }

 

Edited by MaiTheLord
Posted

Thanks. that works. I need to sync it to the client though, as rendering depends on its value, and I have no idea how to implement that.

I should note that I am familiar with TCP packets, but never used packets with java or minecraft.

Posted

On that same wiki you used for capabilities you can read about networking. Here's the main page: https://forge.gemwire.uk/wiki/Main_Page

 

For your requirements, you need to use the PlayerEvent.StartTracking. This is fired when an entity comes into range of the player. Clients only see entities in range of the player.

When this event fires, you need to send your capability data to the player using a custom packet. The data would be entityId and your capability serialized as nbt.

On the client side you would find the entity (warning untested pseudo code)

LocalPlayer player = Minecraft.getInstance().player;
Level level = player.level;
Entity entity = level.getEntity(entityIdFromThePacket);

Then update your capability.

Additionally, if your capability data changes, you broadcast your packet to all players tracking the entity using the following distributor strategy 

PacketDistributor.TRACKING_ENTITY.with(() -> entity)

which sends the packet to all players tracking the entity.

 

For other explanations of these concepts see this recent thread.

It has a completely different synchronization requirement, so you won't be able to just copy the code.

https://forums.minecraftforge.net/topic/113225-1165-syncing-player-capabilities-to-client/

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

Posted
3 hours ago, diesieben07 said:

Note that you should not just use the same format as saving to disk for this. Only sync to the client what is necessary and if possible use a more compact format.

That is an optimisation that has its drawbacks.

Using the same code for network/disk serialization makes it easier/less error prone (you don't have to maintain 2 pieces of code that can get of step). You also don't have to worry about some method in your capability referencing data that is not there on the client.

Since capabilities are also meant for intermod communication, if another mod wants to use your capability for something else on the client, they may want a different bit of data that you are not sending. But then you can always say you don't support that on the client.

 

In this case, its not relevant since there is only one piece of data and its not meant to be used by other mods.

Boilerplate:

If you don't post your logs/debug.log we can't help you. For curseforge you need to enable the forge debug.log in its minecraft settings. You should also post your crash report if you have one.

If there is no error in the log file and you don't have a crash report then post the launcher_log.txt from the minecraft folder. Again for curseforge this will be in your curseforge/minecraft/Install

Large files should be posted to a file sharing site like https://gist.github.com  You should also read the support forum sticky post.

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'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.