#development

1 messages · Page 69 of 1

torpid raft
#

since players are able to change their names

heady orbit
#

ok

#

well its a short fix

#

but the whole system is Fcked if i can say so

sacred nebula
#

A few things I noticed:

  • You don't have to use replace if it has the key and put otherwise, doing only put will achieve the same functionality regardless

The following:

  if(inventories.containsKey(player.getName() + "_" + world + "_" + "normal")) {
      inventories.replace(player.getName() + "_" + world + "_" + "normal", oldInventory);
  } else {
      inventories.put(player.getName() + "_" + world + "_" + "normal", oldInventory);
  }

can be reduced to this:

inventories.put(player.getName() + "_" + world + "_" + "normal", oldInventory);
  • As mode already contains either build or normal you can also use that when specifying the hashmap key (rather than doing an if statement checking the mode type, you could also use an enum for this)

For your specific issue there isn't something immediately wrong I could see--could you share how you're using those three methods?

craggy zealot
#

Can someone help with updating a packet without removing it and adding it back?

#

another user here sugested I update the packet but that didint work it just didint even show up in the lab list

#

sorry I am talking about a fake player in a tablist

#
n = new FakePlayer(new FakePlayerUtil().getNextLetter(s), x.getHealth() + "", true);
        n.getTablistAddPacket().sendPacketOnce(x);
        updateFakePlayer(x);
    }

    @Override
    public void updateFakePlayer(Player player) {
        new BukkitRunnable() {
            @Override
            public void run() {
                if(!player.isOnline()) {
                    this.cancel();
                }
                //add
                n.getTabListUpdateFakePlayer(new FakePlayerUtil().getNextLetter(s), player.getHealth() + "").sendPacketOnce(player); // Update instead of adding or removing
            }
        }.runTaskTimer(MafanaNetwork.getInstance(), 0L, 20L);
    }``` my code at the moment
#
protected TabListUpdateDisplayNamePacket(UUID uuid, String playerName, String displayText) {
        super(uuid, playerName, displayText);
        WrappedGameProfile gameProfile = new WrappedGameProfile(uuid, playerName);
        PacketContainer packet = getProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO);
        setPacket(packet);
        PlayerInfoData data = new PlayerInfoData(FakePlayerPacket.changeGameProfileSkin(gameProfile), 20, EnumWrappers.NativeGameMode.CREATIVE, WrappedChatComponent.fromText(displayText));
        List<PlayerInfoData> infoLists = Collections.singletonList(data);

        EnumSet<EnumWrappers.PlayerInfoAction> actions = EnumSet.noneOf(EnumWrappers.PlayerInfoAction.class);

        actions.add(EnumWrappers.PlayerInfoAction.UPDATE_DISPLAY_NAME);

        packet.getPlayerInfoActions().write(0, actions);
        packet.getPlayerInfoDataLists().write(1, infoLists);
    }```
#
protected TabListAddFakePlayerPacket(UUID uuid, String playerName, String displayText) {
        super(uuid, playerName, displayText);
        WrappedGameProfile gameProfile = new WrappedGameProfile(uuid, playerName);
        PacketContainer packet = getProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO);
        setPacket(packet);
        PlayerInfoData data = new PlayerInfoData(FakePlayerPacket.changeGameProfileSkin(gameProfile), 20, EnumWrappers.NativeGameMode.CREATIVE, WrappedChatComponent.fromText(displayText));
        List<PlayerInfoData> infoLists = Collections.singletonList(data);
        if (VersionUtil.isNewTabList()) {
            EnumSet<EnumWrappers.PlayerInfoAction> actions = EnumSet.of(
                    EnumWrappers.PlayerInfoAction.ADD_PLAYER,
                    EnumWrappers.PlayerInfoAction.UPDATE_LATENCY,
                    EnumWrappers.PlayerInfoAction.UPDATE_LISTED, EnumWrappers.PlayerInfoAction.UPDATE_DISPLAY_NAME);
            packet.getPlayerInfoActions().write(0, actions);
            packet.getPlayerInfoDataLists().write(1, infoLists);
            return;
        }
        packet.getPlayerInfoAction().write(0, EnumWrappers.PlayerInfoAction.ADD_PLAYER);
        packet.getPlayerInfoDataLists().write(0, infoLists);
    }```
heady orbit
#

Hi, thanks so much.

To be honest with you, I’ve used enums, but never really understood them before. Currently I have school, so I can’t send you the code, but the best thing I can do right now is first learn enums and then u can show me a way you found using them.

I’ll send the code in around 8 hours when school is finished

hoary scarab
sonic nebula
#

game doesnt detect

#

when breaking door top?

#

blockbreakevent doesnt fire even

#

nvm i found the reason!

#

nah nvm i didnt ifnd

#

0 sense

#

wtf is this

#

k this time ill also print what block his is

#

if not door

river solstice
sonic nebula
#

no no

#

i need help

neat pierBOT
#

There is no time to wait! Ask your question @sonic nebula!

sonic nebula
#

what the fuck

#

tell me

#

should i check for string instead of material?

sonic nebula
river solstice
#

dog says its stinky

sonic nebula
#

no no but why doesnt work

#

ill check ffor string value

#

200IQ

#

i break game mechanics his way

#

if (block.getType().name().contains("WOODEN_DOOR") || block.getType().name().contains("IRON_DOOR")) {😎 thonking

#

still doesnt work

#

it legit prints

#

WOODEN_DOOR

craggy zealot
icy shadow
# sonic nebula

Probably the 1.13 compatibility fuckery fucking something up

sonic nebula
#

it make 0 sense

#

like even after checking for string it prints

#

it still don't fire

#

event fires but its not the same shit as it prints

#

and it doesnt pass anything

#

idfk

heady orbit
sonic nebula
#

wtf is this code not sure if its a troll or not

#

but please learn java basics

heady orbit
#

dont know if this is a serious answer or only a troll

#

u are the troll u dont have a big pp just bc u maybe can code "better". So stop trolling and let me learn

river solstice
#

I mean, the code isnt perfect to say the least, there is a lot of room for improvement, I guess it will come with practice, but you really should put more time into learning the OOP/Java basics, if you havent already.

heady orbit
#

its not like i have 3 years of in person training with weekly progress and projects. I wanna have fun coding and dont get a hardcore nerd that feels like the king of the world, because he can say others on a discord server how bad their code is. (not meant towards u btw.)

hoary scarab
# craggy zealot can you show me a example i never worked with packets and I tried to stay away a...

For example you're methods constantly run getProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO);
You should be caching it and modifying it.
Here is a sample class...```java
public class CachedPacket {
public ProtocolContainer packet;
public WrappedGameProfile profile;
public PlayerInfoData data;

public void generateFakePlayer(UUID uuid, String playerName, String displayName) {
    profile = new WrappedGameProfile(uuid, playerName);
    packet = getProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO);
}

}

royal hedge
#

at least be constructive

#

id also wouldnt be talking cuz the "troll" seems to know more about conventions than you

heady orbit
#

well i know as much as i have learned and that is much in specific areas and not much overall

#

i like to concrentrate and learn everything in a specific area first and then start learning something new

#

so ive stopped coding on the old version and tried using a custom class.

Can i just save the PlayerData to a json file and return the json data to the PlayerData custom class if i need to edit it?
And if yes, how would that work. well i know Json.stringify would work, but how to convert it back to json afterwards and then back to the custom class?

heady orbit
#

Hi, ive created this but i see a few problems and am unsure to solve them

https://pastebin.com/5kc9aUrf

  1. I can change the world but there is no instance of inventory/buildmode PER world. How it is now i can change the value of world and the others but i want to save inventory/buidmode PER world.
    The json would look somethign like this:

UUID:
"lobbyworld":
buildmode: true
Inventory: Inventory
"citybuild":
buildmode: true
Inventory: Inventory

  1. I want there to be 2 inventories, but right now im only saving 1. If the player changes worlds the inventories should also change, but that would mean that i need 2 "slots" in my save file for the inventories. So 1 buildinventory and 1 normalinventory

I appreciate any help and critic, thanks

hoary scarab
#

🤦 Spot the issue...```java
double x = x() - pos.x();
double y = x() - pos.y();
double z = x() - pos.z();

return (xx) + (yy) + (z*z);

flint kernel
#

the repeated x()?

hoary scarab
#

Yeap. Only took me 2 hours xD

flint kernel
#

sounds like my sort of error

gilded imp
#

lol

hoary scarab
#

Do maps keep their order?

spiral prairie
spiral prairie
hoary scarab
#

Yeah having a weird issue where a list keeps its order but the map won't

spiral prairie
#

Lists do, maps should

#

Maps aren't meant to hold an order of entries

#

Since it's k/v

pure crater
#

What type of map

spiral prairie
#

Hashmap pretty sure

hoary scarab
#

Normal (not tree)

pure crater
#

A hashmap def does not maintain order

#

I know that for sure

#

Tree map should tho

spiral prairie
#

Should it?

flint kernel
#

doesn't a linked map maintain order

pure crater
#

A hashmap never maintains order because it uses order for hashing

#

A tree map does though

spiral prairie
hoary scarab
#

👍

spiral prairie
#

I've once researched what LinkedMaps are for

#

I forgor

pure crater
#

Wait

#

Tree maps don’t guarantee order either

hoary scarab
pure crater
#

It only guarantees sorting order I meant

#

Yeah

spiral prairie
#

What do you need the order for?

#

Sounds like an xy problem

hoary scarab
#

Yeah like```java
sorted = sorted.entrySet().stream()
.sorted(compare)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));

pure crater
#

Oh ok

hoary scarab
spiral prairie
#

Then put the distance as the key and sort

hoary scarab
#

I do

spiral prairie
#

When retrieving or when setting

hoary scarab
#

Sorry read that wrong... I have a compare to test distances of the keys

pure crater
#

Isn’t that what he’s doing?

#

Oh

spiral prairie
#

Now I'm confused

hoary scarab
#

Not exact code;

Map<Location, Data> unsorted = collectLocations();

if(sort) {
    Comparator<Entry<Location, Data>> compare = new Comparator<Entry<Location, Data>>() {
        public int compare(Entry<Location, Data> first, Entry<Location, Data> second) {
            return new Double(first.getKey().distanceSquared(minimum)).compareTo(second.getKey().distanceSquared(minimum));
        }
    };
                                
    return sorted.entrySet().stream()
        .sorted(compare)
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}else {
    return unsorted;
}
```This is basically what I was doing because I thought maps held their order.
spiral prairie
#

Oh

#

Any reason you aren't doing ArrayList<Pair<Location, Data>>

#

Or just include the loc in the data itself

pure crater
#

Because he needs to get data from location and he probably doesn’t want to loop

spiral prairie
#

Mh

hoary scarab
#

Map was easier, and dido to pulsebeat lol

spiral prairie
#

Also I'm unsure if it makes sense to compare the distances to 2 locations tbh

hoary scarab
#

I can of course sort it later but was hoping to pass it sorted while it was still async.

#

Give me a sec

pure crater
spiral prairie
#

I read wrong

#

Yeah

hoary scarab
#

Unsorted vs sorted

spiral prairie
#

Hmmm

hoary scarab
#

My old method was```java
List<Entry<Location, Data>> sortedEntries = new ArrayList<Entry<Location, Data>>(blockData.entrySet());
if(sort) {
Collections.sort(sortedEntries, new Comparator<Entry<Location, Data>>() {
public int compare(Entry<Location, Data> e1, Entry<Location, Data> e2) {
return new Double(e1.getKey().distanceSquared(minimum)).compareTo(e2.getKey().distanceSquared(minimum));
}
});
}

blissful plinth
#

Hello, I might be blind, but I don't find the Java Docs for the 1.20.0->1.20.3 on https://helpch.at/docs/. I only see LATEST for 1.20.4 version.
I specially need those versions, because if I don't make mistake there was some changments between these versions
Thanks in advance !

sonic nebula
#

The guy says

#

He codes for 3 years

#

U don’t probably don’t know me because when someone really needs help I’ll help him and do my best if I do

#

But when someone seem to not understand starter level shit

#

No reason to even help

river solstice
graceful hedge
blissful plinth
graceful hedge
#

🤨

blissful plinth
#

I didn't understand something ?

sonic nebula
#

People should first try till failure and only then ask for help

#

Or ask about API or general questions

#

Not about their code

#

In some forums not gonna name them for such a question ur post won’t get posted and u will be banned

proud pebble
#

tje bug fixed was to stop decorated pots from being deleted on world reload

dusky harness
#

Iirc 1.20.4 came out like 1 or 2 days after 1.20.3 lol

blissful plinth
dusky harness
#

Why don't you upgrade directly to 1.20.4? You don't have to update each minor version

#

You should use the layest version

blissful plinth
#

I make a plugin that support multiple version of Spigot

dusky harness
#

Then you should use the lowest version you want to support

#

Assuming you're not using nms

#

Or craftbukkit

molten venture
#

You can just use 1.20.4

#

And is more stable than others

blissful plinth
#

There was difference between 1.20.1 and 1.20.4 that I cannot ignore

dusky harness
#

What difference?

blissful plinth
#

TrialSpawner for example

dusky harness
#

Trialspawner?

proud pebble
blissful plinth
strong canopy
#

hey, everyone!
i'm a Reverse Engineering and Full Stack developer.
if you wanna get my help, dm me.

proud pebble
heady orbit
#

This might be a very easy question but i really dont get it. If i wanna create a double chest and put the players inventory onDeath, how to place the double chest. Im trying but it doesnt work..

https://pastebin.com/tsnGyuXT

#

it places 2 chest next to each other with the same rotation but not connected

molten venture
#
chest1.setBlockData(Material.CHEST.createBlockData("[facing=east,type=right]"));
chest2.setBlockData(Material.CHEST.createBlockData("[facing=east,type=left]"));
heady orbit
#

but thats the exact thing i did in the code too

#

oh shi

molten venture
#

Sorry

#

2 locations

#
Block chest1 = location.getBlock();
Block chest2 = location2.getBlock();
heady orbit
#

i had
Block chest1 = location.getBlock();
Block chest2 = location.getBlock();

#

yeah

molten venture
#

location2.getBlock

heady orbit
#

incompetence at its best

#

still the same BS

molten venture
# heady orbit still the same BS
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
    Bukkit.broadcastMessage("killed event");
    ItemStack[] items = event.getEntity().getInventory().getContents();

    Player player = event.getEntity();

    Location location = player.getLocation();
    Location location2 = new Location(player.getWorld(), player.getLocation().getX() + 1, player.getLocation().getY(), player.getLocation().getZ());
    location.getBlock().setType(Material.CHEST);
    location2.getBlock().setType(Material.CHEST);

    Block chest1 = location.getBlock();
    Block chest2 = location2.getBlock();

    Chest chest = (Chest) chest1.getState();
    chest.getInventory().setContents(items);
    chest.update();

    chest1.setBlockData(Material.CHEST.createBlockData("[facing=east,type=right]"));
    chest2.setBlockData(Material.CHEST.createBlockData("[facing=east,type=left]"));

    chest1.getState().update();
    chest2.getState().update();
}
heady orbit
#

lets try

#

2 single chests

#

i dont know

#

what are we doing wrong

molten venture
# heady orbit what are we doing wrong

can you try one second that:

@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
    Bukkit.broadcastMessage("killed event");
    ItemStack[] items = event.getEntity().getInventory().getContents();

    Player player = event.getEntity();

    Location location = player.getLocation();
    Location location2 = new Location(player.getWorld(), player.getLocation().getX() + 1, player.getLocation().getY(), player.getLocation().getZ());

    BlockData chest1Data = Material.CHEST.createBlockData();
    BlockData chest2Data = Material.CHEST.createBlockData();

    ((Directional) chest1Data).setFacing(BlockFace.EAST);
    ((Chest) chest1Data).setType(Type.RIGHT);
    ((Directional) chest2Data).setFacing(BlockFace.EAST);
    ((Chest) chest2Data).setType(Type.LEFT);

    location.getBlock().setBlockData(chest1Data);
    location2.getBlock().setBlockData(chest2Data);

    Chest chest1 = (Chest) location.getBlock().getState();
    chest1.getInventory().setContents(items);
    chest1.update();
}
heady orbit
#

.setType requires material not a type

hoary scarab
#
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
    Player player = event.getEntity();
    Location deathLocation = player.getLocation();

    Block block = deathLocation.getBlock();
    block.setType(Material.CHEST);
    deathLocation.clone().add(1,0,0).getBlock().setType(Material.CHEST);

    Chest chest = (Chest) block.getState();
    Inventory chestInventory = chest.getInventory();
    Inventory inventory = chestInventory instanceof DoubleChestInventory ? ((DoubleChest) chestInventory.getHolder()).getInventory() : chestInventory;
    
    // Collect & store
}
royal hedge
sterile hinge
#

its not like Tony has 3 years of in person training when it comes to reading

royal hedge
graceful hedge
sonic nebula
#

😉

#

It’s just pretty often here when people want get spoon feed

#

I don’t have big problem with spoon feed when it make sense

#

Not when the guy ask us to devolop and fix his code after language model which generates bullshit

sonic nebula
#

also when i ask for help

#

no one help me

#

because when i ask for help there literally no answer on google for my problems

#

usually shit related to the API

royal hedge
#

Youre always telling people misunderstanding an api (usually bukkit) to learn java

sonic nebula
#

Dudę the guy Herę

#

Used Break instead of return

#

And ton of wierd code

#

No sense code

#

Probably generated by language model

#

I will never support someone who doesn’t want to help him self in first place

#

anyway u cant understand simple api functions with java in garbage level

#

his commands thing

#

basically language model garbage

#

he has no clue what he does only spoonfeed appears here

#

he doesnt need help with the API he needs us to be his code slaves

#

i will never support never someone who did try did put his valuable time studying java

royal hedge
#

sounds like someone needs to learn java

sonic nebula
#

u do return

#

instead

#

if its the end

royal hedge
#

bud doesn't know java

sonic nebula
#

sparky there no reason to break if its the end of the code block

royal hedge
#

blud doesn't know about switch fall through and is telling someone who does to learn java

sonic nebula
#

he doesnt know java

#

at all

#

he uses language model

royal hedge
#

the breaks are perfectly correct breaks lmao

sonic nebula
#

i do know how switch cases work

#

so u wanna say our lad here knows what he is doing?

#

to be clear its his code?

#

0/1

#

no or yes

royal hedge
#

bud thinks hes a programmer cuz he said 0/1 💀

sonic nebula
#

i do code for years i dont say im something

#

u assume that u piece of sh7t

#

u cant even say yes or no

gilded imp
#

ur acting cocky

sonic nebula
#

because u know its model language sh7t

gilded imp
#

take ur ego somewhere else

#

no one is complaining like u

sonic nebula
#

go to plugins help

gilded imp
#

even if hes using ai generated shit

sonic nebula
#

u not welcome hee

#

u r not welcome here

gilded imp
#

ur the biggest yapper here

sonic nebula
#

milad this chat is ffor people who need help

gilded imp
#

doesnt matter

#

the guy was asking for help

sonic nebula
#

he doesnt deserve any help if he didnt put afford and time to study basics

#

if it was stackoverflow post was denied lol

gilded imp
#

he is being taught here

royal hedge
gilded imp
#

ikr

#

and why do u care even

sonic nebula
#

from same reason as u came here

#

make sense?

gilded imp
#

what

#

i only replied cause u been crying for the past 2 days

royal hedge
#

idk abt milad but im here to tell u to not be a dick

gilded imp
#

pretty much

sonic nebula
#

dude why do u care even

#

u have mental problems or something read ur answer and ur question

royal hedge
#

what.

sonic nebula
#

Sparky im aint a dick but i dont support model language people here and highly against giving any help to them

#

he claims he did it , its not like something advanced tbh but anyway the reason behind is very clear

#

and that milad is a wierd idiot who join our conversation it took him couple of messages to just prove his poin

#

point

#

look at that

#

he came here because i was "crying for 2 days" , "why do you care even"

#

many people dont support spoon feeding

#

its not helping person

#

its like giving homeless a fish everyday instead of teaching him to fish fishes

#

u get what i mean?

royal hedge
#

im guessing you hunt for each of your meals rather than buying them

royal hedge
#

i know the saying im just pointing out that u got it wrong

sonic nebula
#

maybe its not the most correct way ur right i should ignore those homeless idiots who ask people to code for them

#

ur right

#

they are not homeless but yeah ill just ignore the lazy 2 digits who appear here its a big group should be a common thing not every road rage i break people car mirrors

dense drift
#

@sonic nebula how come I always come here and see walls of text from you?

river solstice
#

classic tonyfalk schizo rant activities

gilded imp
#

fr

#

biggest yapper award should be given to him

spiral prairie
#

@hoary scarab you're now officially the number 2

grave sky
#

💀

hoary scarab
#

😆

spiral prairie
hoary scarab
#

Anyone know why EntityDamageByEntityEvent(Entity damager, Entity damagee, EntityDamageEvent.DamageCause cause, double damage) was deprecated in 1.8?
Its not in later versions.

sterile hinge
#

Probably because it doesn’t mention any damage modifiers at all

#

But generally event constructors aren’t really api

hoary scarab
#

Its not deprecated in later versions though.

sterile hinge
#

Then it’s probably just md5 things

hoary scarab
#

👍

sterile hinge
#

If it didn’t exist in 1.7, it’s probably rather to mark it as experimental api

graceful hedge
spiral prairie
#

Just read the whole conversation and dude what the actual fuck

hoary scarab
#

I'm trying to find how EntityDeathEvent has the drops added to it.
I foundjava CraftEventFactory.callEntityDeathEvent(this, this.drops); this.drops = new ArrayList(); in LivingEntity but I don't see anywhere drops is modified or added to...

night nacelle
#

Can someone help me? I have a vanilla resource pack and my textures for some items don't want to work, and when I try to merge two packs into one... it breaks completely. If someone can guide me on these fixes, it would be greatly appreciated!

sand bane
#

net.minecraft.data.loot.EntityLoot

#
this.add(EntityType.SPIDER, LootTable
    .lootTable()
    .withPool(
        LootPool.lootPool()
        .setRolls(ConstantValue.exactly(1.0F))
        .add(
            LootItem
            .lootTableItem(Items.STRING)
            .apply(SetItemCountFunction.setCount(UniformGenerator.between(0.0F, 2.0F)))
            .apply(LootingEnchantFunction.lootingMultiplier(UniformGenerator.between(0.0F, 1.0F)))))
    .withPool(
        LootPool.lootPool()
        .setRolls(ConstantValue.exactly(1.0F))
        .add(
            LootItem
            .lootTableItem(Items.SPIDER_EYE)
            .apply(SetItemCountFunction.setCount(UniformGenerator.between(-1.0F, 1.0F)))
            .apply(LootingEnchantFunction.lootingMultiplier(UniformGenerator.between(0.0F, 1.0F))))
            .when(LootItemKilledByPlayerCondition.killedByPlayer())
        )
    );
#

type deal

#

for each mob

hoary scarab
#

👍 will look into it. Thanks.

craggy zealot
#

someone help me with updating my fake player in the tab list I tried sending and then removing but I had a issue of a defualt minecraft skin flickering as the fake player skin which made it look bad YapperApps gave me a suggestion of caching it and modifying it but it dosnt update ```java
CachedPacket cachedPacket = new CachedPacket(UUID.randomUUID(), new FakePlayerUtil().getNextLetter(s), "");

@Override
public void updateFakePlayer(Player player) {
    new BukkitRunnable() {
        @Override
        public void run() {
            if (!player.isOnline()) {
                this.cancel();
                return;
            }

            cachedPacket.updateDisplayName(player.getHealth() + "");

            cachedPacket.sendPacketOnce(player);
        }
    }.runTaskTimer(MafanaNetwork.getInstance(), 0L, 20L);
}```
#
public class CachedPacket {

    private final ProtocolManager manager;
    private final UUID uuid;
    private final WrappedGameProfile profile;

    public CachedPacket(UUID uuid, String playerName, String displayName) {
        this.manager = ProtocolLibrary.getProtocolManager();
        this.uuid = uuid;
        this.profile = new WrappedGameProfile(uuid, playerName);
        updateDisplayName(displayName);
    }

    public void sendPacketOnce(Player player) {
        PacketContainer packet = createPacket();
        this.manager.sendServerPacket(player, packet);
    }

    public void updateDisplayName(String newDisplayName) {
        PacketContainer packet = createPacket();
        List<PlayerInfoData> infoLists = new ArrayList<>();

        PlayerInfoData playerInfoData = new PlayerInfoData(profile, 20, EnumWrappers.NativeGameMode.CREATIVE, WrappedChatComponent.fromText(newDisplayName));

        infoLists.add(playerInfoData);

        packet.getPlayerInfoDataLists().write(1, infoLists);

        for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
            if (onlinePlayer.getUniqueId().equals(uuid)) {
                this.manager.sendServerPacket(onlinePlayer, packet);
                break;
            }
        }
    }

    private PacketContainer createPacket() {
        PacketContainer packet = this.manager.createPacket(PacketType.Play.Server.PLAYER_INFO);
        return packet;
    }
}```
tight junco
#

whats the reason for consistently sending the packet

hoary scarab
tight junco
#

hello yapperapps

graceful hedge
#

lol

river solstice
#

How can I detect the if the player is by X blocks close to the wall of a CuboidArea? and get that closest location

craggy zealot
#

No I am trying to display lets say coins of the player that updates every second on the tab list

craggy zealot
uneven needle
hoary scarab
craggy zealot
#

i fixed it but another thing sparked my mind

#

could I save a player object/offline player in mysql?

#

becuase lets say i have a friends plugin and you can see your friends

#

player 1 is friends with player 2 there are 2 servers player 2 has never logged on to server 2 but player 1 has and player 1 uses the command /friends list java OfflinePlayer oPlayer = Bukkit.getOfflinePlayer(uuid.getPlayerUUID()); player 2 wont be listed because he never logged on to server 2

dusky harness
craggy zealot
#

no I know that but that uuid is usless if the player never loggs on to the server

#

im talking about a waterfall setup btw

#

does the waterfall proxy have a offlinePlayer system?

river solstice
#

but it only works on the corners of the box

dense drift
#

Are the coordinates right?

river solstice
#

I would think so lol

#

also, if I add the 0 into the Math.max, then it doesnt work fsr

dense drift
river solstice
#

I mean I've been thinking about a wacky solution, just not sure how performance heavy would it

dense drift
#

Hmm, see the accepted answer, idk what "axis aligned" means

river solstice
#

on player move:
get the player new location
loop through the cuboid low X -> high X by increments of 2-3 to save some performance
in loop check if the new location is near one of those X points

#

same for z

dense drift
#

You could calculate the distance to the corners perhaps, depending how big this rectangle is ig

river solstice
#

the max the area would be is 70x70

dense drift
#

Welp

river solstice
#

time for some trigonometry

river solstice
#

eh kinda figured it out

#

now the tricky part is displaying the border correctly

#

fsr the blockX and Z are offset to one of the directions or my calculations are wrong

#

prob the latter

craggy zealot
#

can someone pleasee help me with my ordering so im trying to display fake players in the tab list and forthem to be in order the GameProfile name has to be in alphebtical order right so a..b..c..d..z after z it goes za.zb..zc..zz right.... but after zz its not zza SO WHAT IS IT????????

https://paste.helpch.at/bojowaluza.java

#

see??

sonic nebula
#

...

#

ur code make no sense comparinig to the display

proud pebble
#
  • the range to check
#

if its 0,0,0 10,10,10, check if the player's xyz is bigger/equal to -3 and is less/equal to 13

#

if your wanting a location thats inside the box thats closest to the player, then for each coord,
px >= bigX, closestX = bigX
px <= smallX, closestX = smallX
px between bigX and smallX? closestX = px set to int to remove decimal

#

do the same for each coord

#

i dont think theres a need to loop at all

sonic nebula
#

Just run a task instead every 5 ticks or so

#

Move event is executed even when player moves his head

sonic nebula
#

If it’s a sphere , cube , cylinder border and not something different

#

I would suggest u instead ; the center of the arena the shrings or what ever

#

And calculate the distance from the center each time instead of calculating how close the place is to the borders

#

U can run it on asynchrony and when ever player gets closer and closer to the border run the task more often

#

By that way u can save ton of performance

#

For example if he is at the center run it every 60 ticks as he gets closer to the border of the arena 40,20,10…

#

Also for a cube u it would be different calculation since it’s not same distance from center to different borders when I think about it

#

Bruh

#

But u still can calculate the max distance that possible from the center towards x z

#

Because u know the direction using the coordinates I’ll explain later on when I wake up it’s 9am 😭😭😭

#

And to get the closest player u can wether use a map/list or just constantly update all of them or the closest via the check if he is closer then the other player that was set to be the closest before ^^

river solstice
sonic nebula
river solstice
#

what number

small mango
#

i need help

neat pierBOT
#

There is no time to wait! Ask your question @small mango!

small mango
#

im currntly a dev for a anarchy server and the owner wants a ssh plugin

#

i tried

#

but hasnt succseded

#

its hard

#

pls help

#

hlep4

#

i mean

#

yes there is sshd

#

but he wants it that

#

its invisable

#

to other players

river solstice
#

what are you blabbing about

small mango
#

read bruh\

hoary scarab
#

SSH plugin?

small mango
#

yea

#

he wants me to create a plugin that he can ssh into it

river solstice
#

the fuck

#

and what does he want to do sshing into a plugin

small mango
#

shiii idk

#

i just work for him

#

i just want the pay check

dense drift
#

If you don't know what you have to do, how could we help? 🙂

minor summit
#

why not just ssh normally lol

small mango
flint kernel
#

the word "stealthy" there gives me "I want to backdoor my server so I can fuck over my co-owner friends" kinda vibes

small mango
minor summit
#

here's your ssh plugin
systemctl enable sshd.service

small mango
#

bruh

#

what do i do with this

minor summit
#

you run that on the server machine

small mango
#

nah nah you dont get it

#

im tryina fork this

#

to not

#

give out messages

#

when anything happens

minor summit
#

you are not receiving help installing a backdoor

junior shard
#

Why is that even a thing

small mango
#

it has a good purpose

#

its not even for me

junior shard
#

Remote access isn’t even that complex, if you have a windows VM its default, with Linux you 99% of the time have an SSH setup, and if you use a host they either use multicraft or ptero which can be accessed from your phone anywhere

small mango
#

listen idk

#

i just work for the guy

dense drift
small mango
#

he said he wanted so imma give

river solstice
#

do it yourself idk

junior shard
#

And I don’t understand why running console commands would print to the server chat, just disable the game rule in game and run commands through the server console

river solstice
#

dont ask for help for seemingly sketchy stuff

junior shard
#

There’s no need for a back door

small mango
river solstice
#

people are free to refuse helping you lol

dense drift
junior shard
#

You’re asking for help on something sketchy

river solstice
#

noone is obligated to help you, everyone is chipping in to help at no cost

small mango
junior shard
#

Simple, tell the owner to just use Pterodactyl and they can remote access anywhere from a website and a login Shrug

river solstice
#

or... hear me out

#

ssh

minor summit
#

why does it even have to be a plugin lmao

river solstice
#

not in a plugin

minor summit
#

regular ssh exists for a reason

junior shard
#

^^^

flint kernel
#

i think he should totally use shh instead of ssh

small mango
junior shard
#

Literally use a mobile app called Termius

small mango
#

listen are you gonna help me or nah

river solstice
#

no

minor summit
river solstice
#

magic vps

small mango
#

idk some kind of a website

river solstice
#

aternos

small mango
#

like apex hosting but diffrent

junior shard
#

Any vps can be accessed by ssh or a Remote Desktop depending on the OS

flint kernel
#

was about to say some sort of cpanel type shit but this is a MC server so that makes no sense

minor summit
#

you do realise how sketchy this sounds, right?

junior shard
#

Also isn’t there literally a game rule called ConsoleOutput that you can disable to make the console commands not print to the whole server / ops

minor summit
#

that's only for some things, like vanilla commands

junior shard
#

Ah

flint kernel
#

the way i read this, either ur client is trying to backdoor the MC server (and like, whytf?), or trying to do the sort of activity which at best is in violation of the hosting service's ToS, at worst a criminal offence

river solstice
#
  1. Use the actual ssh
  2. Use the already existing ssh plugin
  3. Fork the existing plugin and make your changes accordingly (license btw)
  4. Do it yourself but dont expect any help
small mango
#

now that i think about it

junior shard
#

small mango
#

chat gpt isnt a bad idea

#

cya

river solstice
#

💀

#

another chatgpt blud

junior shard
#

Lmao

small mango
#

thanks for wasting my time

river solstice
#

you too

junior shard
#

Don’t ask for help backdooring a server, easy

small mango
#

xd

#

tbh

#

i wasnt trying to make a backdoor

#

i was just following order for the paycheck

river solstice
#

surely chatgpt will give you fully working code

small mango
river solstice
small mango
#

i have to fix it my self

#

but it mostly does a good job

river solstice
#

either way, no 'elp

#

gl

junior shard
flint kernel
#

In other news, CompleteableFutures have broken my brain

#

so, can someone explain this to me:

if i run CompleteableFuture#runAsync without providing an executor (thereby using the common forkjoinpool) or using #join, the code never executes, but if i do the same thing except this time i provide a threadpoolexecutor as the executor, it runs

minor summit
#

sounds like the common pool is busy

#

potentially deadlocked

flint kernel
#

that's the thing, not only does the code never execute, the program just finishes as if it did run

#

also, it isn't/shouldn't be; this is a scratch program with nothing except this test program running

minor summit
#

do you have a reproducer..?

flint kernel
#

a what

minor summit
#

code that can reliably reproduce that behaviour

flint kernel
#
public static void main(String[] args) {
    final var scheduler = ForkJoinPool.commonPool(); // swap between this and new AsyncExecutor();

    final var startTime = System.currentTimeMillis();
    CompletableFuture.runAsync(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }, scheduler).thenRun(() -> {
        System.out.println("1: Hello from thread " + Thread.currentThread().getName());
        System.out.println("1: Took " + (System.currentTimeMillis() - startTime) + "ms");
    });

    CompletableFuture.runAsync(() -> {
        System.out.println("2: Hello from thread " + Thread.currentThread().getName());
        System.out.println("2: Took " + (System.currentTimeMillis() - startTime) + "ms");
    }, scheduler);
}

static final class AsyncExecutor extends ThreadPoolExecutor {

    private static final int MIN_ASYNC_THREADS = Math.min(Runtime.getRuntime().availableProcessors(), 2);
    private static final int MAX_ASYNC_THREADS = Runtime.getRuntime().availableProcessors();
    private static final int ASYNC_THREAD_TIMEOUT = 60;

    public AsyncExecutor() {
        super(MIN_ASYNC_THREADS, MAX_ASYNC_THREADS, ASYNC_THREAD_TIMEOUT, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        allowCoreThreadTimeOut(true);
    }

}
#

this environment is the only environment i'm testing it in

minor summit
#

threads from the common pool are daemon threads, meaning the jvm won't wait for them to finish execution to exit

#

so, you'd need to .join or some other waiting mechanism

flint kernel
#

so if i want to have "launch and forget" save methods for example, I definitely need them to run on a custom executor?

minor summit
#

well, yes and no, if you're maintaining your own pool of non-daemon threads you'd need to shut it down at, well, program shutdown, since the jvm would wait for those threads to finish but the pool is waiting for tasks to run, you need to signal to the pool to not accept any more jobs

#

the worse alternative is to spawn a new thread solely to run the task which is awful resource-wise

flint kernel
#

in this case, running shutdown on the pool in a plugin's onDisable

minor summit
#

yeah that works

#

onDisable is for cleanup and that kind of stuff

flint kernel
minor summit
#

spawning a new thread to run one task, multiple times is certainly a bad idea

flint kernel
#

for context: this executor, whatever form it takes, will only be used for my database stuff

minor summit
#

the common thread pool certainly does have its uses but it can easily be misused

flint kernel
#

and am i misusing it in this context

#

I barely understand a thing about concurrency, threads n pools n everything so i've just been going off of what i've seen others doing when it comes to these things

minor summit
#

well, i think CompletableFutures using the common pool is a misuse of the common pool

flint kernel
#

I meant using the custom executor i showed

minor summit
#

your issue is less about that and more about not ensuring your tasks run fully before shutting down

#

you don't really need a class extending TPE either, just create a new one

flint kernel
#

Yeah I don't really know why I did that

flint kernel
minor summit
#

yeah

flint kernel
#

ok so my other question with the whole forkjoin-TPE thing is:

If I have a CF stage which runs on the FJP, but later stages run on my TPE, could I run into the same issue of the code never executing due to the FJP

minor summit
#

it can be prevented

flint kernel
#

e.g., I have a name -> UUID async loading cache which lazy-loads UUIDs using Paper's Server#getPlayerUniqueId method, this part (atm) just runs on the common pool, but the database futures which will consume that UUID mapping are all running on the TPE

Some of these won't necessarily have #joins or #gets

minor summit
#

i don't know exactly how the server handles the executor that takes care of that, but if you want like complete control over that you can use a Phaser or some count-down mechanism

#

multithreading is not easy

flint kernel
#

I don't even know what a Phaser is and i'm not sure i want to know xD

minor summit
#

yeah the other option is, don't worry about it

flint kernel
#

oh actually to be clear, the server doesn't have the CF that runs that method here, that's the cache that creates the CF; afaik the Server's method just runs sync

#

Am using Caffeine/Guava's AsyncCacheLoader:

@Override
public CompletableFuture<UUID> asyncLoad(final String name, final Executor executor) throws Exception {
        return CompletableFuture.supplyAsync(() -> Bukkit.getPlayerUniqueId(name), executor);
    }

I haven't provided the Cache builder with an executor so it defaults to the common FJP

#

So the question is, should I continue using the common FJP, create my own FJP, use my database TPE, or?

sterile hinge
#

supplyAsync should run the task unless the common fjp is busy until the application is stopped

#

but early java 17 versions have a bug where that's not the case if you run your code on machines with only one core available to the jvm

flint kernel
#

so what i'm hearing is, just make my own FJP at least

sterile hinge
#

that might be a good idea

flint kernel
#

Looking at LP (which is kinda my go-to reference for a lot of things), they make their own for this exact type of situation (using the cache-loader)

dusty frost
#

Java 21 virtual threads 😌

graceful hedge
#

yeets kotlin coroutines

pulsar ferry
#

kotlin coroutines work with virtual threads

graceful hedge
minor summit
#

i mean virtual threads don't really solve anything in this situation lol

abstract ether
#

anyone here that can help with custom heads in itemmeta.yml?

- ==: SpawnItem
    item:
      ==: org.bukkit.inventory.ItemStack
      type: DIAMOND_SWORD
      meta:
        ==: ItemMeta
        meta-type: UNSPECIFIC
        display-name: §c§lKITPVP §r§f(Right-Click)
        lore:
          - §7Start fighting with the
          - §7premade kits and show
          - §7how strong you are.
          - ""
          - §7(§fRight-Click§7 to join the §f§oKitpvp§7!)

Like a base 64 head instead of the diamond sword

base64: eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODQ4OGIwMzQzOTgwZmNmMjE3ZDdjYmI3NWQ3MzBhZGNhMDRhOGI2YTdiMTM4Mzg2YWNhYTdmYzk5NGE4NThhMiJ9fX0=

marble heart
#

who i have to blame for making the libs.version file on deluxemenus? OKK

flint kernel
#

this sounds like a perfect opportunity to use git-blame

#

Oh, nvm, just realised it was the initial commit so there's no attribution

#

Oh well, Blitz made the initial commit so you can blame them

marble heart
#

i was trying to hook a plugin yesterday for 3 whole hours and i didnt succeed :/

#

skill issue? eh probably

west crystal
#

Hey just wondering is there a way to have my plugin check if a papi library is installed?

west crystal
#

Are you using intellij?

#

follow the procedure and THEN

marble heart
west crystal
#

ahh wait wont let me send ss ill dm u

marble heart
hushed badge
west crystal
#

Thank you!

west crystal
hushed badge
#

all identifiers for expansions in theory should be lowercased

west crystal
#

ah ok

#

also anyway for me to make my code run after placeholder api install

#

basically i'm trying to install the dependency expansions in the plugin

flint kernel
#

ExpansionManager or something

west crystal
#

where should i look for it?

flint kernel
#

there's 2 expansion managers in there

#

i think you need to go through and like, check if the expansion is already installed and if not download & install it using all the api methods

west crystal
#

thats what i'm thinking of doing

#

but i cant find the expansion manager

flint kernel
#

it's in PlaceholderAPIPlugin the getters

#

i feel like there should be a better way of doing it but im not sure

west crystal
#

dm'ing u an image cuz i cant send it to u here

flint kernel
#

ur trying to access it statically

west crystal
flint kernel
#

:/

west crystal
#

Like i understand the concept

#

kinda

#

shit

#

im dumb

#

its what i though

#

sorry abt that the 0039(time) is hitting hard

flint kernel
#

#straya

west crystal
#

fr fr

west crystal
#

this aint working

flint kernel
#

wut

west crystal
#
@NotNull Optional<CloudExpansion> vault = new PlaceholderAPIPlugin().getCloudExpansionManager().findCloudExpansionByName("vault");
new PlaceholderAPIPlugin().getCloudExpansionManager().downloadExpansion(vault);
flint kernel
#

you don't wanna call new on PlaceholderAPIPlugin

west crystal
#

brain die

flint kernel
#

you need to access an instance, if there's no static like #get or #getInstance methods then you should try the Bukkit#getPluginManager#getPlugin methods

west crystal
flint kernel
#

no

west crystal
#

well now im even more confused

#

💀

#

there is a static #getInstance method

#

OH

flint kernel
#

in PlaceholderAPIPlugin?

west crystal
#

U MEANT ON THE PlaceholderAPIPlugin

#

OH

flint kernel
#

yes

#

smh

west crystal
#

lmfao

#

my fault

#
@NotNull Optional<CloudExpansion> vault = PlaceholderAPIPlugin.getInstance().getCloudExpansionManager().findCloudExpansionByName("vault");
PlaceholderAPIPlugin.getInstance().getCloudExpansionManager().downloadExpansion((CloudExpansion) vault);
flint kernel
#

ur not using that optional properly

#

but yes that's the general idea

west crystal
#

The only problem i'm having is that its saying Optional<CloudExpansion> can't be cast to CloudExpansion

flint kernel
#

because it can't

west crystal
#

well yes i got that part-

flint kernel
#

i think u need sleep

west crystal
#

but what should i use instead

west crystal
flint kernel
#

you need to use the optional methods

#

to check if a result was returned

#

etc

#

go sleep u victorian/cockroach-nsw/ACT weirdo

#

;3

west crystal
#

lmfao once i get this coded

#

cuz i need to put it on the server before the automated restart

#

or i will get yelled at by players

#

@flint kernel Ok i feel like im somewhat close only problem is this one
'downloadExpansion(me.clip.placeholderapi.expansion.cloud.@org.jetbrains.annotations.NotNull CloudExpansion, me.clip.placeholderapi.expansion.cloud.CloudExpansion.@org.jetbrains.annotations.NotNull Version)' in 'me.clip.placeholderapi.expansion.manager.CloudExpansionManager' cannot be applied to '(me.clip.placeholderapi.expansion.cloud.CloudExpansion)'

if (!(PlaceholderAPI.isRegistered("vault"))) {
  @NotNull Optional<CloudExpansion> vault = PlaceholderAPIPlugin.getInstance().getCloudExpansionManager().findCloudExpansionByName("vault");
  if (!(vault.isPresent())) {
    plugin.getLogger().info("Vault Not Found!!!");
  } else {
    CloudExpansion vaultExpansion = vault.get();
    PlaceholderAPIPlugin.getInstance().getCloudExpansionManager().downloadExpansion(vaultExpansion);
  }
}
flint kernel
#

you need a version

#

isn't IDEA yelling at u cus of ur errors

west crystal
#

😢

#

i levelled up from asking for so much help

flint kernel
#

lel

west crystal
#

ok wait wtf is going on with my ide

#

we have this error

Cannot resolve method 'isPresne' in 'Optional'
#

then that line is

#
if (!(vault.isPresent())) {
#

HAHA

#

woo

#

i fixed it

#

i die now thanks for the help

thin tendon
#

hey! I'm working on a custom papi expansion for my plugin, this is the current code ```java
public class VampirismMCExpansion extends PlaceholderExpansion {

private final VampirismMCPlugin plugin;

public VampirismMCExpansion(final VampirismMCPlugin plugin) {
    this.plugin = plugin;
}

@NotNull
@Override
public String getAuthor() {
    return "OliviaTheVampire";
}

@NotNull
@Override
public String getIdentifier() {
    return "vampirismmc";
}

@NotNull
@Override
public String getVersion() {
    return plugin.getDescription().getVersion();
}

@Override
public boolean persist() {
    return true;
}

@Override
public String onRequest(final OfflinePlayer player, @NotNull final String params) {
    String[] paramArray = params.split(" ");
    String setName = paramArray[0];
    String[] paramArray2 = paramArray[1].split("_");
    String type = paramArray2[0];
    String field = paramArray2[1];
    return VampirismMCPlugin.INSTANCE.welcomeMessages.entrySet().stream().map(stringConfigurationSectionEntry -> {
        if (!Objects.equals(stringConfigurationSectionEntry.getKey(), setName)) return "null";
        return stringConfigurationSectionEntry.getValue().getConfigurationSection(type).getString(field);
    }).toString();
}

}``` but I was suggested to cache all the config info when it initialises

hoary scarab
#

return VampirismMCPlugin.INSTANCE.welcomeMessages.entrySet().stream().map(stringConfigurationSectionEntry -> {
if (!Objects.equals(stringConfigurationSectionEntry.getKey(), setName)) return "null";
return stringConfigurationSectionEntry.getValue().getConfigurationSection(type).getString(field);
}).toString();
All these values should be cached so you aren't constantly requesting them from the config.

tepid sequoia
#

well its all cached anyways

#

but caching it yourself is still nice since its more performant and readable

grim oasis
#

lol ya...

#

they were trying to ask for help on how to cache the values

#

since I told them they really should be

#

but good point, config is cached so

hoary scarab
#

Is there a legitimate reason for Entity.getNearByEntities(x,y,z) not being allowed to run async?
I was thinking concurrency but based on the source it creates a new list anyways.

sterile hinge
#

it still has to access chunks/the world

#

creating a new list doesn't matter at all there

#

(also source code isn't the specification)

hoary scarab
#

Welp... Gotta use my work around then. sigh

sterile hinge
#

that sounds like you're doing terrible stuff

hoary scarab
#

Nah I just grab the list of entities from the worlds entity manager.

sterile hinge
#

that's not thread safe either btw

hoary scarab
#

Havent had any issues with it. Its just a list I make a copy of.

sterile hinge
#

yeah, that's not thread safe

#

just because you haven't had any issues with it doesn't mean it might not randomly crash a server tomorrow

hoary scarab
#

That can be said for anything.
How is it not thread safe and how can I make it thread safe?

sterile hinge
#

"anything" isn't thread unsafe by design

#

you can run it on the main thread

hoary scarab
# sterile hinge you can run it on the main thread

I could but in this scenario I'm already running on async so I would be passing the data back and fourth between sync/async. Currently I'm using bukkit runnables so those can take multiple ticks to pass in which I could already be at the point where I need to collect the entities again.

sterile hinge
#

guess what, whenever you do something async it only might happen when you need to collect the entities again

#

sounds like whatever you're doing is conceptually flawed already

hoary scarab
#

That doesn't help make copying a list thread safe.

I do calculations, list modification etc async then pass it to sync so there is less the main thread has to do. If I go back and fourth between sync/async it could eventually overlap.

sterile hinge
#

you could even see data outdated by minutes or hours in theory if you copy the list like that

hoary scarab
#

If the server is lagging ofcourse. But I can also check for the time of list creation if I really thought it hasn't ran for that long.

sterile hinge
#

that has nothing to do with lags, it has to do with how the jvm memory model works

hoary scarab
#

Ok lets move back to thread safety.
I want to copy a list. What would you do to make that thread safe?

sterile hinge
#

prevent any other thread from modifying the list during that time

hoary scarab
#

So in my scenario... Should I just freeze the main thread while I make a copy of the list?

sterile hinge
#

not sure how you want to freeze the main thread, but in that case you can just sync on it

hoary scarab
#

So just clarifying, is reading lists not thread safe either? I thought just manipulating it wasn't (Adding, removing, setting).

sterile hinge
#

no it's not thread safe

#

not even reading an int is thread safe

hoary scarab
#

So nothing can be read on multiple threads?

sterile hinge
#

it depends

#

if you read from a constant with multiple threads, that's fine

#
class ShowStopper {
        static boolean running = true;
        public static void main(String[] args) throws Throwable {
                var t0 = new Thread(() -> {
                        try {
                                Thread.sleep(10_000);
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                        running = false;
                });
                var t1 = new Thread(() -> {
                        while (running);
                });
                t1.start();
                t0.start();
                t1.join();
        }
}

what would you expect this code to do?

hoary scarab
#

After 10 seconds t1 should stop running.

sterile hinge
#

you can try out and see if that's what happening

hoary scarab
#
public class Testing {

    private static boolean run = true;
    
    public static void main(String[] args) {
        //long startTime = System.currentTimeMillis();
        
        Thread first = new Thread(() -> {
            //System.out.println("Started: "+Thread.currentThread().getName());
            
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            //System.out.println("run = false");
            run = false;
        }, "First");
        
        Thread second = new Thread(() -> {
            while (run) {
                //long current = System.currentTimeMillis();
                //System.out.println("Elapsed: "+((current-startTime)/1000)+" "+Thread.currentThread().getName());
            }
        }, "Second");
        
        second.start();
        first.start();
        
        try {
            second.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
    }
    
}
```Wrote and tested stops after 10 seconds.
sterile hinge
#

yep but that's different code

hoary scarab
#

Has debug but its the same code.

#

What were you expecting your code to do?

sterile hinge
#

my code never stops (at least on my machine)

hoary scarab
#

Yikes

sterile hinge
#

if you remove the debug stuff, that most likely happens with your code on your machine too

hoary scarab
#

I'll try it.

#

Edited the code above. Same thing stops after 10 seconds.

sterile hinge
#

interesting

#

how do you run it?

hoary scarab
#

Eclipse run

sterile hinge
#

ah, that might cause some differences I guess

#

but that's a good example how testing on one machine isn't a proof that something works when dealing with multithreading

hoary scarab
#
public class ShowStopper {
    static AtomicBoolean running = new AtomicBoolean(true);
    public static void main(String[] args) throws Throwable {
            var t0 = new Thread(() -> {
                    try {
                            Thread.sleep(10_000);
                    } catch (Exception e) {
                            e.printStackTrace();
                    }
                    running.set(false);
            });
            var t1 = new Thread(() -> {
                    while (running.get());
            });
            t1.start();
            t0.start();
            t1.join();
    }
}
```This should work for you.
sterile hinge
#

yes that will work, that's a thread safe program

hoary scarab
#

So why would this not be?

List<String> text = Arrays.asList("Test", "String", "Thread");
        
Thread first = new Thread(() -> text.forEach(s -> System.out.println("["+Thread.currentThread().getName()+"] "+s)), "First");

Thread second = new Thread(() -> {
    List<String> modfiable = new ArrayList<>(text);
    modfiable.addAll(Arrays.asList("String", "Thread", "Test"));
    modfiable.forEach(s -> System.out.println("["+Thread.currentThread().getName()+"] "+s));
}, "Second");
sterile hinge
#

that's thread safe too, because starting a thread always introduces a happens-before relationship with the code before it, in this case the list is created before the other threads are started, and when they start, they see the list as it is, and that list isn't modified anymore after that

hoary scarab
#

That code is basically what I'm doing with the entities list.

sterile hinge
#

no

hoary scarab
#

no what?

sterile hinge
#

it's not what you're doing with the entities list

hoary scarab
#

How is it not? I take a list make a copy modify the copy and use the copy elsewhere.

sterile hinge
#

yes, but the main thread can modify the list at the same time, and you don't have any happens-before relationship there anymore

hoary scarab
#

It can modify the original list not the copy. I don't care about the modifications until a later time anyways.

sterile hinge
#

but creating the copy isn't an atomic operation

river solstice
#

eclipse 💀

hoary scarab
#
Bukkit.getScheduler().runTaskAsynchronously(pl, () -> {
    WorldServer minecraftWorld = (WorldServer) ((CraftWorld) world).getHandle();
    Iterable<Entity> entities = minecraftWorld.M.d().a();
    CopyOnWriteArrayList<Entity> entityList = new CopyOnWriteArrayList<>();
    entities.forEach(entityList::add);

    // Pass entityList to sync
});
```So this wouldn't be thread safe?
sterile hinge
#

I don't know what M.d().a() is but most likely not

hoary scarab
#

M = EntityManager
d() = getEntityManager()
a() = getAll()

sterile hinge
#

not sure which mappings you're using there

#

but considering basically nothing is thread safe there, that most likely isn't either

analog moth
#

Hello, i have a problem

#

I'm writing code in IntelliJ IDEA

#
cannot find symbol
  symbol:   variable PlaceholderAPI
  location: class me.vexq.cubeplayportfel.Cubeplay_portfel```
#

Please help, I have all dependencies and repositories imported.

warm steppe
fast glade
#

I'm trying to open a custom inventory of an anvil, but i want to hide the players inventory contents from this gui, (without using any resource packs)

I couldn't find any way to do this easily, so I'm currently storing the players inventory contents, then clearing their inventory when opening the gui, then as they close it, im re-adding their items. This gets complicated pretty fast, cause i gotta make sure their items persist not in just memory (like if the server crashes when someone has the gui open) or handle player death, or itempickup when they got the inventory open

Basically what im asking, is there a better way to do this?
(note: i am using paper and not spigot, so im happy to use paper only methods that spigot doesnt have)

proud pebble
#

means they arent actually removed, but they wouldnt show up in the menu

fast glade
proud pebble
#

protocollib works too

#

or you could just do it with nms

#

any work

fast glade
#

i guess i still come to the issue of needing to stop incoming changes like if a player picks up an item

#

(or stop the packet)

proud pebble
fast glade
#

yeah, im guessing ill probably just stick with clearing and saving the items in the players pdc, then retrieving after inventory close, or player join (if the server crashed)
seems simpler, and probably has less issues

worn jasper
worn jasper
fast glade
#

comamndpanels just save their inventories to a file

#

so no different really than pdc

analog moth
worn jasper
#

I know that @scenic vapor did menus with packets and achieved exactly what you want. Maybe he can help?

fast glade
#

i think im just gonna store them, seems a lot less complicated

scenic vapor
#

ye but thats not safe at all

fast glade
#

how

scenic vapor
#

data lost

#

look

#

serializing is not instant

#
  • errors can be thrown while saving/loading
#

you would always have to use completable future

#

to make it so there's a little delay

#

to make sure everything went how it should

fast glade
#

im using pdc

scenic vapor
#

and what

#

thats still serialization

#
  • imagine that your server crashes
#

while a menu is opened

fast glade
#

im storing to pdc before opening

scenic vapor
#

if you are not doing it async

#

then you would have performance issues

fast glade
#

no different from a player putting an item in their inventory and the server crashing and them losing that item

scenic vapor
#

w custom items w some nbts, etc. etc.

fast glade
#

it uses pdc, so it saves the same time any inventory items are saved

scenic vapor
#
  • there could be a pontential dupe glitch
fast glade
#

how is there a dupe glitch

scenic vapor
#

what? 😄

#

to save it in pdc

#

you need to serialize whole inv

scenic vapor
fast glade
#

ok, then the inventory opens half a second later?

#

and thats it, the only delay

#

IF u have crazy nbt items

scenic vapor
#

but what if the actual saving throws an error

#

and disables the plugin

fast glade
#

then they dont lose any items?

#

u save then clear then open

scenic vapor
#

🤦‍♂️

#

but other people could

fast glade
#

could what?

scenic vapor
#

lose them

fast glade
#

how?

#

its not async

scenic vapor
#

yup well thats the worst scenario 😄

#

I mean thats really up to you

fast glade
#

the worst scenario still results in zero items lost

scenic vapor
#

how so

fast glade
#

how would it?

scenic vapor
#

other people can still have a menu opened

#

and meanwhile the error can be thrown

#

just make sure to make it as safe as possible shrug

#

bcs dupes and data lost is not fun

fast glade
#

no data is lost

#

in that sceneario

scenic vapor
#

that's why Ive chosen packets which are in this case the easiest

fast glade
#

and how is there any dupes ?

scenic vapor
#

like in any other plugins that are serializing items

fast glade
#

im not using some crazy method of saving, its using a spigot api using pdc

uncut fiber
#

hi, please tell me what should I do. I installed the plugin, at first everything was fine, but then when I entered the /donate command, the server wrote: unknown command

fast glade
#

worst case the player wiht crazy nbt opens the gui, it opens a second later cuz serializing takes long

if the plugin breaks/crashes at then no players lose any items, all players with inventory open have their items already saved, and the player who caused the crash inventory never got cleared

#

and where im saving is in pdc, of the specific player, so theres no contamination/breaking of the location

scenic vapor
#

if the plugin breaks/crashes as you tell

#

then players got free items shrug

fast glade
#

how?

scenic vapor
#

and they need to await for server restart

#

to await the plugin to re-enable again

fast glade
#

if ur plugin crashes the server with packets u have to wait for the server to restart

#

no different than any plugin that crashes a server

#

the server is dead it has to restart

scenic vapor
#

I didnt mean server

#

but just the plugin

fast glade
#

oh so if a server crashes, then you dont have to wait for the server to restart?

scenic vapor
worn jasper
#

if I understood correctly, you use packets to send fake empty slots or whatever, your items are still there, just visually invisible. You dont need the server to restart or anything, since the items never left the players inventory

fast glade
#

we're talking about a server crashing

#

which is independent of the plugin or method ur using

#

hes saying if the plugin crashes with his method, it doesnt lose data, which hes not wrong,
and im not arguing that, i fully understand his method

worn jasper
#

well, but if it crashes, in the rare case you want to access the players inventory or a plugin needs access to the players inv, imagine it gets the inventory before the items are back.

#

you have 0 control over that

fast glade
#

if the server is crashed... then none of what ur saying happens

worn jasper
#

💀

marble heart
worn jasper
#

anyways, tldr, get some common sense. Better a bug be an actual bug or visual bug? Take your answer, and apply it to this.

#

I am going to go catch my plane

#

adios

fast glade
#

idk, im just asking to explain how it causes issues, and ur reponse is how the packet method doesnt cause issues, (which i never said it didnt)
then when the explaination comes out, im saying how it doesnt happen with this method, and ur circling back to well the packet method works! without actually saying how the method i said causes issues

#

im not asking how the packet method is better, i understand how it works

worn jasper
#

god I am losing braincells

#

take me with you larkyy

#

shall we go get a cup of tea my friend?

fast glade
#

can we just stop saying comments like that?

#

like are w enot trying to help?

worn jasper
#

you seem to not want help

scenic vapor
fast glade
#

im just asking for an explaination

#

and no one is explaining, just saying theres an issue

worn jasper
scenic vapor
#

youuu? xD

worn jasper
worn jasper
scenic vapor
#

if you decide to use packets anyways, you can take a look into my repo where Ive done the exact thing
https://github.com/MrLarkyy/AquaticShopExtension

The code is not the best as it was the first try of playing around w ShopGUI+, but it was working fine shrug

worn jasper
#

TLDR of the holy explanation is that messing with files is unpredictable.

#

I am actually surprised command panels does it like that, about to delete it from my plugin list

fast glade
# worn jasper Larky already mentioned some and so did I lol.

all u both did was praise the packet method, not explain how the other method is "unsafe", when u finally attempted to i explained how ur reasoning (which is valid is certain situations) isn't applicable for my implementation, and u keep doubling down reverting to praising the packet method instead of actually explaining whats unsafe

glacial flower
scenic vapor
#

Oh its private

#

ye I got multiple repos for that

worn jasper
scenic vapor
#

now

scenic vapor
#

am only throwing you my opinions

graceful hedge
#

What’s the other method?

scenic vapor
#

which I guess are something that you wanted to hear

scenic vapor
fast glade
#

i fully understand performance at scale (like large nbt items taking time to serialize)

#

im just asking the security and what makes it unsecure,

you throw out "dupes" and im saying how is there dupes? and if you don't know, then why are u saying dupes? what is inclining u to think there is dupes?

worn jasper
#

tip: your own message contains information about how you dupe.

fast glade
#

what?

worn jasper
#

(the one you just sent above)

fast glade
#

how

#

i dont see it

#

thanks for the help guys, glad i joined here

graceful hedge
#

Why are you so upset, im sure they just wanted to help you out bud :>

spiral prairie
#

Okay but the storing and clearing thing doesn't seem too bad, does it?

hoary scarab
graceful hedge
dusky harness
dusky harness
dark garnet
#

1.19.4 through 1.20.4 r missing still

minor summit
#

1.20.4 is latest

dark garnet
#

yeye, but rest

robust crow
#

Looks like it just fell off our radar, no reason it cant be updated

dark garnet
#

ah alr good good ty

graceful hedge
#

Nicee

quaint shoal
#

_

analog moth
#

ooo, it turned out that after restarting the program and computer, it works, but thank you for your willingness to help! ❤️

unborn ivy
#

could anyone help me out with a slight issue? i have a class called MineStatus which handles if a plugin's feature is active (via isActivated() method, now the issue is that the isActivated() method does not return true even if it's already set to true by another class/method via the toggleState() method, does anyone know the issue?

public class MineStatus {
    public HashSet<String> activated = new HashSet<>();
    
    public void toggleState() {
        if (!activated.contains("activemine")) {
            activated.add("activemine");
            return;
        }
        if (activated.contains("activemine")) {
            activated.remove("activemine");
            return;
        }
    }
    
    public Boolean isActivated() {
        if (activated.contains("activemine")) {
            return true;
        }
        return false;
    }
}
``` MineStatus class
#

I know that it returns false because I have other classes that check if isActivated() is true

river solstice
#

are you sure you are calling that on correct object instance

spiral prairie
#

You're probably making a new MineStatuts class every time

unborn ivy
river solstice
#

you probably want a static map

unborn ivy
unborn ivy
#

yep, i had to have a static map for it to work, everything works fine now thanks

dense drift
#

well, that means you are having multiple instances of that class, which you shouldn't (in this case)

spiral prairie
#

Yep

river solstice
analog moth
#

Hi. I have a problem again, the placeholderAPI plugin does not recognize my placeholder.

#

it's my CubeCoinsPlaceholder class

#
package me.vexq.cubeplayportfel;

import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;

public class CubeCoinsPlaceholder extends PlaceholderExpansion {

    private Cubeplay_portfel plugin;

    public CubeCoinsPlaceholder(Cubeplay_portfel plugin) {
        this.plugin = plugin;
    }

    @Override
    public String getIdentifier() {
        return "cubecoins";
    }

    @Override
    public String getAuthor() {
        return "_VexQ"; // Zastąp "YourName" swoim nazwiskiem lub pseudonimem
    }

    @Override
    public String getVersion() {
        return "1.0";
    }

    @Override
    public String onPlaceholderRequest(Player player, String identifier) {
        if (player == null) {
            return "";
        }

        if (identifier.equals("balance")) {
            return String.valueOf(plugin.getCubeCoins(player.getName()));
        }

        return null;
    }
}```
#

it's my Main class (cubeplay_portfel)

public class Cubeplay_portfel extends JavaPlugin implements CommandExecutor, Listener {

    private CubeCoinsPlaceholder placeholderExpansion;
    @Override
    public void onEnable() {
        placeholderExpansion = new CubeCoinsPlaceholder(this);

        if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
            placeholderExpansion.register();
        }
    }
//...
dusky harness
analog moth
#

oooo its work

#

thank you ❤️

fading stag
neat pierBOT
fading stag
#

not a big fan of Java 8 but customer's always right :d
thanks

hearty beacon
#

Hey! Is there any way to create a custom NMS entity class which handles multiple entity types? I created one which worked perfectly in 1.20.2 but is now broken in 1.20.4 as I keep getting the error CustomEntity cannot be cast to class net.minecraft.world.entity.animal.EntityPig. I understand why the error happening but I am unsure of what changed between versions and I am just unsure of how to make the class generic again. Any help would be much appreciated (Please ping me if you can help so I dont miss it) tomatoheart

I can get the class to work by simply changing the extends EntityCreature to extends EntityPig for example but I wanted to keep it generic like it was and not need to make a class for each entity

public class CustomEntity extends EntityCreature {
  public CustomEntity(EntityTypes<? extends EntityCreature> entityType, Location location) {
          super(entityType, ((CraftWorld) location.getWorld()).getHandle());
          this.e(location.getX(), location.getY(), location.getZ());
          ((CraftWorld) location.getWorld()).addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM);
  }
  
  // ... Pathfinding and Behaviour modification

}

// Function I use in the spawning class to convert the spigot entity to the minecraft entity
public EntityTypes<? extends EntityCreature> convertEntityType(EntityType entityType) {
  return switch (entityType) {
    case PIG -> EntityTypes.aw;
    case COW -> EntityTypes.u;
    case CHICKEN -> EntityTypes.r;
    case SHEEP -> EntityTypes.aG;
    case HORSE -> EntityTypes.Z;
    case TURTLE -> EntityTypes.be;
    case BEE -> EntityTypes.h;
    case GOAT -> EntityTypes.V;
    case VILLAGER -> EntityTypes.bg;
    case POLAR_BEAR -> EntityTypes.aA;
    case WOLF -> EntityTypes.bp;
    case PARROT -> EntityTypes.au;
    //case BAT -> EntityTypes.g;
    default -> null;
  };
}

river solstice
#

is registering events and initializing the plugin ASYNC bad?

#

or even possible

#

basically making onEnable async if that makes sense

sterile hinge
#

might be a bad idea with little benefit

#

but depends on what you want to achieve I guess

dusty frost
#

whatever you want to do, you can most likely accomplish by just scheduling an async task in your onEnable

river solstice
#

any possible drawbacks?

#

Im kinda working on a dumb module system, where I upload a new jar file and it reloads the new module and reregisters the listeners and whatever

#

thing is its sometimes heavy and blocks the main thread, making players unhappy with tps drops

spiral prairie
#

Those things are most literally always try it and see

dusty frost
#

yeah I mean you should probably just like, restart the server and have scheduled maintenance when you want to change jars

#

even better if you're using a proxy cause you can just move people to another server or the hub during

river solstice
proud lodge
#

My issue not really into plugins but the map I have is not shown on 1.20
It works 1.8-1.19.4 but not 1.20
I spawn in a random generated map not the map I wanted

marble heart
#

is there an event for the spawn of the wandering trader, so i can cancel it and he wont show up randomly in islands :/ ?

dense drift
tight junco
#

theres a gamerule for it

fast glade
marble heart
#

lmao

wispy terrace
#

How can I make a placeholder expansion that will send requests via http to the api and receive a response from it without delaying the main thread

lyric gyro
#

Anyone a 5m dev?

minor summit
#

I'm only a 10x dev, sorry

dense drift
#

5 million $? Sure

heavy bluff
fading stag
merry knoll
dark garnet
#

is it possible to modify the NBT (PDC) of an offline player? maybe using something like item nbt api?

proud pebble
dark garnet
proud pebble
#

afaik player nbt data isnt fully loading till they are online to save on ram or smth

dark garnet
#

oh

dark garnet
dark garnet
proud pebble
#

like you could manually load the player's nbt data but if you arent already using nms then you cant

dark garnet
#

yeah that just sounds scary too lmao

proud pebble
#

json or some either sql or nosql db would be best

dark garnet
#

json better than yml?

proud pebble
#

yaml is just a modified version of json with some extra speed issues

#

ur better off just using json from the start

dense drift
#

I like hocon more for configs, json is annoying because you can't write comments shrug unless the lib you use can ignore them ig

graceful hedge
#

You could maybe parse it as yml and use yml semantical comments

autumn niche
#

Hi, I'm having some problems with my server launching. I can launch magma on its own, and i can launch my server files WITHOUT magma on its own, but when I try to use magma as the launch point for my start.bat on my server, i get this crash report: https://paste.helpch.at/cexobugude.yaml

#

I've already tried reconfiguring FoamFix, which is a mod I'm using, however even though it tends to hang on that line of code, it crashes despite removing it.

#

is this the right place ?

pure crater
#

You shouldn't use hybrids because you will experience issues like those -- it's likely some magma version issue

autumn niche
#

yeah.

#

i really just wanna be able to use voice chat on an existing modpack

#

i dont want my community to have to manually download from somewhere else

#

none of them are tech savvy lmao

pure crater
#

Oh wait nevermind it's fabric only

autumn niche
#

i think im just gonna make a custom modpack, itll be way easier

#

i feel bad because i already made the map for it and everything

hoary scarab
#

Anyone have an example of the new PlayerProfile portion of the API? Its not loading textures for me.

PlayerProfile profile = Bukkit.createPlayerProfile(uuid);
PlayerTextures playerTextures = profile.getTextures();
playerTextures.setSkin(url);
//profile.setTextures(playerTextures);
//profile.update();
headMeta.setOwnerProfile(profile);

getLogger().info("DEBUG (Skin-URL) >> "+url);
sterile hinge
#

you never call update on the profile

river solstice
#

odd question, is it possible access bukkit/my plugin data from springboot if they are in separate jar files?

hoary scarab
sterile hinge
#

well you need to wait until the future finishes, obviously

hoary scarab
#

Will try that. One sec

hoary scarab
#

Even just running profile = profile.update().get(); its not rendering.

sterile hinge
#

what's headMeta? and what do you do with it afterwards?

hoary scarab
dusty frost
# dusty frost uh, if you load it?

depends on what you're trying to load, like a copy of the code? the plugin data as yaml or something? or are you trying to like communicate with the server as it's running?

river solstice
# dusty frost uh, if you load it?

I mean if I run a separate instance of spring, outside the "plugin ecosystem".
If I add my plugin as a library/dependency. Will I be able to access the plugin data if the server is running? I'm not too familiar with java VM schenanigans

dusty frost
#

which one lol

river solstice
#

I'm aware of the built-in solutions like mcspring, springlify, just not what I'm looking for. I want a separate spring application, outside of the server.

river solstice
#

are you trying to like communicate with the server as it's running?

dusty frost
#

depends on the direction you want, I use HTTP/REST to communicate from servers -> website

#

if you want the other way around, RCON is probably your best bet

#

we use Pterodactyl Panel, so I end up using their REST API to send commands to the proxy sometimes

#

I also ended up using the LuckPerms REST API thingy for doing role changes and stuff, since you can just directly interact with it and get validation

river solstice
#

if this makes any sense

dusty frost
#

oh I see, so you want to fetch data from the servers

river solstice
#

I've been using Spark, had some problems with it so I switched to Javalin, but ideally I'd like to run the HTTP server outside the server

dusty frost
#

ah yeah I was gonna say, Javalin is probably your best bet

#

just runnign it on a single thread per server should be pretty light

#

but I guess it depends on what you're doing, if you just want getOnlinePlayers or similar, you could store the data in Redis or something and keep it up to date