Jump to content

[Solved] Can you access the capability data of a player that is offline? AND How to properly use a weak reference of an Entity.


Recommended Posts

Posted

I'm having trouble with the readingNBT method of an entity.

Here is the code:

Spoiler

	protected void readEntityFromNBT(NBTTagCompound compound)
	{
		System.out.println("*********Reading NBT**************");
		
		this.setCasterId(UUID.fromString(compound.getString("caster_uuid")));
		this.caster = getCaster();
		this.setSpellData(this.caster);

        if (compound.hasKey("direction", 9) && compound.getTagList("direction", 6).tagCount() == 3)
        {
            NBTTagList nbttaglist1 = compound.getTagList("direction", 6);
            this.motionX = nbttaglist1.getDoubleAt(0);
            this.motionY = nbttaglist1.getDoubleAt(1);
            this.motionZ = nbttaglist1.getDoubleAt(2);
        }
        else
        {
            this.setDead();
        }
	}

	public void setSpellData(EntityLivingBase caster)
	{
		this.spellData = caster.getCapability(SpellDataProvider.SPELL_DATA, null);
	}

 

When it gets to the line: this.setSpellData(this.caster) this.caster is null so I get an error trying to get the capability.

I was thinking of having the entity keep going after cast, even if the player logs off and still level up the spell in the players capability if it hits an entity.

I think i'm just going to have the entity die if the player logs off.

Posted (edited)

So I shouldn't have:

private EntityLivingBase caster;

In my entity class at all, and should instead use either PlayerList::getPlayerByUUID or World::GetPlayerEntityByUUID anytime I reference the caster? PlayerList::getPlayerByUUID also seems to return null if the player isn't online though, So I think I'm going to go with setting the entity to dead if PlayerList::getPlayerByUUID or World::GetPlayerEntityByUUID returns null.

No idea how to use a WeakReference but I'll look into it. Why use a WeakReference over private EntityLivingBase caster

Edited by Kriptikz
Posted

A WeakReference points to an object that can be collected by the GC.
Storing the player object directly, even after the player logs out, keeps it in memory, when it is no longer required. As such, overuse of this practice can and will lead to "memory leaks".

  • Like 1

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted

For example:

Imagine both player use the spell that holds the reference to the other.  These two EntityPlayer objects now have hard references to each other.

Both players then log out.

The garbage collector comes along and sees that EntityPlayerA holds a reference to EntityPlayerB and EntityPlayerB holds a reference to EntityPlayerA.  Both objects still reference the other and therefor cannot be GC'd without potentially breaking something, so GC leaves them alone.  GC has no way to determine that this is a closed and isolated loop due to the space-time complexity of making that determination.  See: https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Reference_counting

Both players log back on again and repeat the process.  Every time they do, it allocates two new EntityPlayer objects that can never be GC'd.

  • Like 1

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.

Posted (edited)

So if I want to cache the entity I will use a weak reference like this? :

Spoiler

	private WeakReference<EntityLivingBase> caster;

	public EntitySpellBase(World world, EntityLivingBase caster)
	{
		this(world);
		
		this.caster = new WeakReference<EntityLivingBase>(caster);
		this.setCasterId(caster.getUniqueID());
		this.setSpellData(caster);
		this.setPositionAndDirection(caster);
	}

 

From what I understand so far, using a weak reference can get GC'd at any moment correct? 

So anytime I use caster I would need to check if it is null and if it is use:

this.caster = new WeakReference<EntityLivingBase>(caster);

Correct?

OR, Should I put the weak reference inside the entities onUpdate() method as well as the doSpell() method because these are the two places where the caster is referenced. I'm still worried about it getting GC'd in the middle of using it though, can it get GC'd in the middle of a method that it was created in?

Here is the code, the WeakReference isn't implemented but this is what I'm working with:

https://github.com/Kriptikz/Archmage/blob/1.11.2/src/main/java/kriptikz/archmage/entity/EntitySpellBase.java

Edited by Kriptikz
Posted

Awesome Thanks! I'm still trying to wrap my head around why using a WeakReference is necessary though.

So why I'm using a WeakReference variable in the entity rather than a StrongReference, such as,

private EntityLivingBase caster; Is because of possible memory leak. Does this mean that even if the entity is setDead() and in World::updateEntities() , I believe this is where the entity is removed if Entity::isDead, the entity is removed but may not be set up so it can be GC'd?

Another way to put this is, shouldn't any variables/references inside the entity, weak or strong, and the entity itself be set to be GC'd when it is removed?

  • Like 1
Posted
21 minutes ago, diesieben07 said:

If you have a strong reference to the caster, your entity will keep that caster loaded, even if the caster has already died. Say a player spawns your entity and then logs out. Your caster entity will still be loaded and reference the (now dead) player entity. Because of that the dead player entity cannot be garbage collected, a memory leak.

If you have a WeakReference, the player entity can be garbage collected, your reference will just turn to null.

My EntitySpell should only last about 10-20 seconds max and then it gets setDead(). So the player spawns the EntitySpell and then logs out. The EntitySpell is referencing the player entity, which means the player entity cannot be GC'd. The EntitySpell keeps existing for 10 more seconds, then gets setDead(). Now that EntitySpell is dead, its strong reference to the player entity should be removed when EntitySpell is GC'd, thus allowing player entity to also be GC'd, is this correct?

 Also, back to the capability, if I have a strong reference to the players capability in EntitySpell and the player logs out the EntitySpell will still be holding that reference, right? So if I change some of the players capability data in EntitySpell using its strong reference to the players capability, when the player is logged out, will that actually effect the players capability data? Will that change in the capability data when the player was logged out hold true when the player logs back in?

Posted
2 minutes ago, diesieben07 said:

Reference to what I said above, you cannot interact with an EntityPlayer object in a reasonable way if that player has logged out. Why do you need this capability access?

In my mod the player has spells. Each spell has a level and xp associated with it. So taking the fireball spell for example, if the player casts a fireball spell and it hits an entity it will damage the entity relative to the level of the spell, higher level spell does more damage. I also want the players SpellData capability to increase the xp for the fireball spell so the spell can level up and get stronger. Why I wanted to access the capability after the player logged out is because if the player casts the fireball spell, which will spawn an EntitySpell for the fireball, and then the player logs out I wanted the fireball to continue going until it impacts something. When it impacts an entity I need the SpellData capability to get the fireball spells level so it knows how much damage to do. Also, when it impacts an entity, I need to get the players SpellData capability and increase the fireball spells xp. The problem is the player is logged out, so I was wondering if I could modify the capability when the player was logged out so this would still work. It seems I probably shouldn't do it this way, but I was curious if it was possible. What I'm going to do instead is if the player is logged off the spell will die.

I wanted to store the player in a strong reference because I don't like the idea of creating an EntityLivingBase and ISpellData object every tick because it seems like overkill but I guess it is necessary:

    @Override
    public void onUpdate()
    { 
	EntityLivingBase caster = getCaster();
    	
    	if (caster == null)
    	{
    		this.setDead();
    		return;
    	}
    	
    	ISpellData spellData = caster.getCapability(SpellDataProvider.SPELL_DATA, null);

	// Do spell movement updates and logic 

 

Posted (edited)
46 minutes ago, diesieben07 said:

Ehm... nothing in that code is creating an ISpellData or EntityLivingBase object.

I shouldn't have said creating an object, I mean by creating the reference the computer has to allocate more memory to store that reference. I was thinking why recreate another reference every tick if I can just have one main reference. It seems I may be misunderstanding a fundamental programming concept, as allocating memory for the reference is probably too negligible to really matter. Every reference does allocate more memory though, right?

 

46 minutes ago, diesieben07 said:

As for your issue, how about you make it so the spell just does not give XP when the player logs out? That even makes sense outside of the game-mechanics: If you can't witness the event, you can't really gain experience from it, can you?

Interesting, now I'm torn between 3 possible implementations lol.

1. When the player logs off the spells energy source is then gone so the spell vanishes doing nothing. 

2. When the player logs off the spell continues going and does its effects but the player will not get xp from it.

3. Have the player gain xp when the spell is initially spawned.

 

Probably going to test all 3 and see how it goes. This is all pretty much off topic now though, so thanks for all the help I really appreciate you sticking with me and helping me wrap my head around this stuff.

Edited by Kriptikz
Posted
6 minutes ago, diesieben07 said:

Even if you had the reference stored in a field, the code would eventually still go to main memory, fetch the object reference and store it in a CPU register. It boils down to the same thing. This is very much premature optimization, if it is an optimization at all.

Didn't even know premature optimization was a thing lol. I've gotta be careful with that.

Posted
7 hours ago, diesieben07 said:

Ehm, this is untrue and not how Java's GC works. It starts at very specific "root objects" (for example everything that's currently in a local variable) and from there just follows every reference. In the end it collects everything that was not visited. Loops are not a problem for the GC.

Simplified example is simplified for ease of comprehension.

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.

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

    • Reach Out To Rapid Digital: What sapp Info: +1 41 4 80 7 14 85 Email INFO: rap iddi gita lrecov ery @ exe cs. com Hello, my name is Jayson, and I’m 35 years old from the United Kingdom. My family and I recently endured an incredibly challenging experience that I wouldn’t wish on anyone. We became victims of a cryptocurrency investment fraud scheme that saw us lose a staggering $807,000 in USDT and Bitcoins. The fraudsters had created a convincing facade, and we were lured into investing, only to discover later that the platform was a complete scam. We were left devastated, not just financially, but emotionally, as we had trusted these people and believed in the legitimacy of the investment. After the initial shock wore off, we desperately searched for ways to recover the lost funds. It seemed like an impossible task, and we felt as though there was no hope. That’s when, by sheer luck, we stumbled across a post about Rapid Digital Recovery, a cryptocurrency and funds recovery organization with a proven track record in cybersecurity and fraud recovery. We decided to reach out to them, and from the first interaction, we were impressed with their professionalism and transparency. They explained the recovery process in detail and reassured us that they had the skills and expertise to track down the perpetrators and recover our funds. This gave us a renewed sense of hope, something we hadn’t felt in months. What truly stood out during our experience with Rapid Digital Recovery was their dedication to the recovery process. The team went above and beyond, using sophisticated tracking tools and cyber forensics to gather critical information. Within a matter of weeks, they had successfully located the funds and traced the scam back to the fraudsters responsible. They worked with the authorities to ensure the criminals were held accountable for their actions. To our relief, the team at Rapid Digital Recovery was able to recover every single penny we had lost. The funds were returned in full, and the sense of closure we felt was invaluable. We couldn’t have imagined such a positive outcome in the early stages of our recovery journey, and we are deeply grateful for the work they did. If you ever find yourself in a similar situation, I highly recommend contacting Rapid Digital Recovery. Their expertise, transparency, and dedication to their clients make them the go-to choice for anyone seeking to recover lost cryptocurrency or funds. They truly gave us back our financial future.  
    • This is my first time modding anything, so maybe just skill issue. I'm using Forge 54.0.12 and Temurin 21.0.5+11-LTS I wanted to create a custom keybind and to check whether it works I'd like to send a chat message. I tried using Minecraft.getInstance().player.sendSystemMessage(Component.literal("test")); but IntelliJ couldnt resolve sendSystemMessage(...). Since I saw people using it in earlier versions, I tried the same thing with 1.20.6(- 50.1.0), where it works fine, now I can't figure out if this is intentional and whether there are other options for sending chat messages. On that note, is there more documentation than https://docs.minecraftforge.net/en/1.21.x/? It seems very incomplete compared to something like the Oracle Java docs
    • Hi, i'm having this error and I wanna fix it. we try: -Reload drivers -Eliminate .minecraft -Eliminate Java -Restart launcher -Verify if minecraft is using gpu -Mods  in .minecraft is empty -Install the latest and recomended version of forge idk what i have to do, help me pls. the lastest log is: https://mclo.gs/WAMao8x  
    • Read the FAQ, Rule #2. (https://forums.minecraftforge.net/topic/125488-rules-and-frequently-asked-questions-faq/)  
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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