#help-development
1 messages ยท Page 837 of 1
Ok what are the methods? (I can't use anything outside of coreprotect due to server having over 100 days worth of structures)
Lets explore one straight forward method.
When a chunk loads, query placed blocks in this chunk, create a small data structure like a
record BlockPos(int x, int y, int z){}
And throw them in a HashSet you can check sync in your BlockBreakEvent or whatever.
You can query async as chunks rarely get interacted with in the first few hundred millis after loading.
Just prevent interaction with chunks that have not been synced.
wouldnt this still have the same performance issues? You're still doing database lookups on every block in that chunk. Maybe this would be even more laggy
Doesnt CoreProtect have a query for all blocks within a chunk?
one of my favorite things to do is comment every line of code in my plugins, the most verbose shit too :)
personally I hate comments, I try to remove all comments
That is literally counter productive. Write code that needs no comments instead.
๐
no
Your choice ๐คท
i javadoc my bitch to high hrothgar
Some people just love writing unclean code i guess
If you comment every line then it is stained as hell.
Ok the API is pretty atrocious. See if you can come up with a better DB query for a single chunk.
Btw CoreProtect is used for logback, not prevention. Youll have a hard time either way.
Ik
Im not trying to cancel any events
what happens if I try to cancel an event after the event has passed
Nothing
ok chatgpt told me to do this, lets hope it didnt lie
(this is a temporary fix until I figure out how to do that chunk loading thing)
What data structures are those 3 "queues"?
Hm. calling remove on an arraylist iterator is really not that great.
Rip
should work tho
Wait they are public, static, mutable and not even final?
This is the highest order of static abuse.
you can
I thought final means cannot be modified anymore?
Do you add elements from the main thread, and poll elements from other threads?
because final only makes read-only the very defined object
you cannot override the List to be anything else
but you can perform methods on it
including add/remove
yes (I think)
so like list = new LinkedList() after it's been initialized
Use a ConcurrentLinkedQueue then. It allows adding elements by a single thread and removing elements from it
by multiple threads, while not blocking either the producer nor consumer.
Let me write a quick example.
ok
private static final Queue<Alert> alertQueue = new ConcurrentLinkedQueue<>();
public static void addAlert(Alert alert) {
alertQueue.add(alert);
}
public static void processRemainingAlerts(Consumer<Alert> consumer) {
Alert next = alertQueue.poll();
while (next != null) {
consumer.accept(next);
next = alertQueue.poll();
}
}
Or if you dont have enough experience with Consumers you need to do the null check externally:
private static final Queue<Alert> alertQueue = new ConcurrentLinkedQueue<>();
public static void addAlert(Alert alert) {
alertQueue.add(alert);
}
public static Alert getNextAlert() {
return alertQueue.poll();
}
hello, i have a problem with a scoreboard
i have this code
inside a new BukkitRunnable() { public void run() {
my goal is to show life to the player and a sidebar scoreboard. The sidebar works fine, but for the health, it resets to 0 every seconds.
i thought that itwas because it was in the new BukkitRunnable() { public void run() { that updates every second, but idk how to fix it
Does getNextAlert return the list? or how does this Queue list work
From my workload distribution guide:
is deque deck or de-queue
add -> appends an element on the left
poll -> removes and gets the element from the right
GET SHIT ON @river oracle MD AGRESS WITH ME
deck
It's actually pronouned Dairy Queen
any idea?
String previousOwner;
List<String[]> lookup = CoreProtect.getInstance().getAPI().blockLookup(i.getBlock(), 2147483647);
if (lookup != null) {
boolean hasPlaced = CoreProtect.getInstance().getAPI().hasPlaced(i.getGriefer(), i.getBlock(), 2147483647, 0);
boolean hasRemoved = CoreProtect.getInstance().getAPI().hasRemoved(i.getGriefer(), i.getBlock(), 2147483647, 0);
if (!hasRemoved && !hasPlaced) {
for (String[] result : lookup) {
CoreProtectAPI.ParseResult parseResult = CoreProtect.getInstance().getAPI().parseResult(result);
if (parseResult.getActionId() == 1 && !parseResult.getPlayer().startsWith("#") && !parseResult.isRolledBack()) {
previousOwner = parseResult.getPlayer();
finalDoAlerts.add(new Alert(Bukkit.getPlayer(i.getGriefer()), i.getBlock(), previousOwner, i.getMaterial(), i.getDrops(), i.getBlockData()));
break;
}
}
}
}
}```
Where/how should I use the queue in this area?
Not done reading but...
this line was here idk why lol
but i know where the bug is from, idk how to fix it tho
You should not create a new scoreboard each time. Get the current players scoreboard and update it.
so ok it does not create a new one every time, but how do i modify the lines of the scoreboard?
cuz when i do what i did usually , it does this
do i need to delete the old score?
if iirc yes
since the display set treats it like a player's name
so either reset all and set your info once again
how do i do that?
or reset only one and have it set
only one what? one line?
so either Scoreboard#resetScores
yeah
what do i put in the String value?
does this look about right?
not the value shown on the very right
but the display name
like reset the previous line
and add a new one with the same order value
but how do i get the last line?
store it
the value has changed, how do i get the last one
in maybe an array
store each change
in the array
and reset the previous array's element
bro are you sure there is no other way? this seems way too complicated for nothing
if null then don't
I never worked with scoreboards
also isn't that complicated
so i store whats shown as a in a String list?
and right here before it loops again i store all the values?
store it
right after you update
the value
and before updating again
get the previous string stored
reset the scoreboard object
and store your new value
and show it on the scoreboard
no
what??
don't use a List
are you sure?
Static abooose!
that's a List
String[] array = new String[14];
like you can
you just don't need it
and it's more clear to use an array in this case
yay it worked with no stacktraces this time
ok but i still can?
/\
Not that type of static silly
array[11] = s12.getEntry();
I don't rememeber exactly
ill put it as an array after, but would this work?
but probably with the Scoreboard#resetScores
this won't work
ok ill do ur thing
since the scores returned will be immutable
like scoreboard.resetScores(scores.get(11));
what?
also not that
why???
#clear will throw an error
oh wait
why not this
it's a list
yeah
then it should work
but make sure to check for nullability
if it's null don't reset the score
cuz another error
i love you
why would they do this
it works?
niiice
thank you SO MUCH
I was totally guessing
YOU HAVE no idea how much things i tried
ur still a pro for this moove
no problem
ai no problem
?
i had to redo the whole thing cuz using ArrayList didnt work, so i used scored[] like u said
should have listened to you from the begening lol
but thx man
Wait this is a thing? since when
I've been setting hashmaps and checking playedamageevent
since like
1.8
it's an Entity thing
but should work for players as well
Does anyone know an alternative way to do entity.damage(1, player); work?
I'm trying to give a glowing effect to an entity visible only to a player, does anyone know why my code doesn't work?
EntityPlayer entityPlayer = ((CraftPlayer) p).getHandle();
PacketPlayOutEntityEffect packet = new PacketPlayOutEntityEffect(
silverfish.getEntityId(),
new MobEffect(MobEffects.x, 10, 1, false, false)
);
entityPlayer.c.a(packet);
any libs for handling pages on gui's? or is it simple enough to do?
It was fairly simple for me. took me an entire day though
other public apis:
one of the ways to do it yourself https://www.youtube.com/watch?v=e80NO9Pgz7s
but their code is horrible from what i can see
that code is rough
im sure theres better examples
listen from 12:35 to 12:41
instead of MobEffects.x try the method of getting it by id, and input 24
How to use textcomponent and how to show hover text on book on version 1.8.8?
I've tried many different approaches I could find online, none worked
is it actually possible to have a book with hover even on 1.8.8?
you could just do it with commands
dunno, but I think not
1.8.8 lacks a lot of QoL features
cool nickname
How?
that is, if it even was a thing in 1.8
Yh I agree. It's the most optimized version but for development it's digsget
but I don't think that it was
it's what
It's the most optimized version if you've written your own lol. It's nowhere near as optimized as what we have today
Technically every version was more optimized than the next
Less features = less cpu usage
The current version is extremely optimized compared to what came before. However, the feature creep has slowed it down. The correct description would be "it's the version that has a dedicated PvP community" that's the only reason it's used so much
99.9% of 1.8.8 servers fail because they rehash the same experience that other larger more active servers provide. You'd have more success attempting a unique experience on the new versions with cool mechanics unavailable to the 1.8 experience.
is there a different kick packet for the login phase?
Maybe we just remove everything but the main method as a brand new optimization feature
bet that'd make it like 1000x faster

anyway
lmao
@ivory sleet I actually got a working parser ๐ฅณ my MiniMessage syntax clone is functioning!!! the parse time is pretty decent too
W
<yellow>random <gradient:red:blue><bold><%name></gradient></bold><click:run_command:test command><underline><red>click here</click><blue> to <bold>FEEL</underline> it idk how I feel about my placeholders but they work pretty well for now
there are for some reason
you could use string substitutor from apache commond-text
That's how I handle it, it comes with a default prefix/suffix of ${...}
hmm I don't think so because its not consistent with the rest of the syntax but I think I'm going to use a $ instead of a % on the inside
Excuse me papi has made it so you legally have to use % with minecraft
I donโt make the rules
I'm not following papi guidelines anyways ๐
otherwise my tags would look like
%yellow%
and that's dumbn
I'm a criminal
Exposed
Snitch exposed
Fuck
how can I get the user's ip address from the Channel object?
has anyone here used mockbukkit before
yes
is it good
Depends what you are looking for
Anyone here have experience with Guice (DI)?
Yep
But we switched to dagger
Is this correctly implemented?
imo a better di framework
since guice can sometimes be giving overhead during runtime
like if you have a class thats frequently created
But it looks fine
Tho I suggest reading up about DOs and DONTs for guice
For instance field injection is generally something you want to avoid
iirc
In dagger github they say its for android, I guess android it's not required, or I am looking to the wrong repo
Yes tho its not particularly useful for unit tests imo
Ugh idk lol, I mean I used it for a small reverse proxy backend
๐
:^)
Anyway, thanks for the advise
Yeah gl
How do I test something that's bukkit related
On a unit level, just mock the bukkit interfaces with mockito
On an integration or system level, use mockbukkit
**
Alr
Also for tdd am I making a test for every single class
I've found this
You might be interested on it
lol
for tdd you not only write a test for every single class, you isolate every public method with tests, and you write your tests to fail before making them work by first writing the test before implementing the class
Which is time consuming if youโre not used to tdd
But it makes your program sustainable right
There are also issues regarding ur test infrastructure that will appear if youโre new to tdd like the fragile test problem
Or bug free
Well you prove that your code is not incorrect
And it can serve as a quality check for when u change stuff in ur code
And when u refactor stuff
And it serves as a documentation source
wdym documentation
Your tests document ur code
Like how an impl should work?
Nah but for instance if I have a vector test class
And I have tests like
givenZeroVector_doesReturnZeroVectorWhenMultipliedWithScalar
givenANonUnitVector_doesHaveMagnitudeOfOneWhenNormalized
these document what my methods do, in particular Vector#magnitude() and #multiplyScalar()
Oh ok
I have a question about how to use BuildTools
how do I get the version of it with all the CraftBukkit stuff
is it this? adding the compile CraftBukkit?
You only want the craftbukkit stuff or what exactly?
?nms
awesome thank you ๐
how do I know which file in the work folder is the right one to use?
there's multiple called like "server" and "minecraft_server" and "mapped"
Use maven or gradle
to be fair my orginal question was about what i wanted
how to get NMS
wooooo! got it thanks all
๐คฉ
๐
I want to report a spigot programmer
could just use the report button on the site
But not why you wanted it
I want CraftCreature for pathfinding
for the getHandle()
could someone please help, how can i check if the player head item has following texture from this site: https://minecraft-heads.com/custom-heads/head/56968-redstone-purple i just dont understand how to use the developer values
Cast ItemMeta to SkullMeta then getOwnerProfile from profile get texture and compare it using signature & value.
signature and value? where do i get those tho? do i need to deserialize the base64 value into json and get the url?
25.12 07:58:29 [Server] Server thread/ERROR Could not load 'plugins/images-2.3.0.jar' in folder 'plugins'
Does anyone know why this happens?
how create spawn item in vanila structure system
i mean i can get structure location?
or for it need custom generation?
what would be something like .setInvisible(), but it also hides their armour and doesn't remove the player from tab?
uh .hide will do the first part but not the second
Perhaps you could add them through nms
Hide them and add temporary entity in tab?
Hello! Right now I save all my projectiles in an "ArrayList", but I thought I'd add so I can see what coords each projectile has passed with a BukkitRunnable task that adds a projectiles coords every tick from when it's fired. How could I do this?
why are you saving entities in a list?
nothing wrong with that
make a hashmap
<Entity, List> then you can have the entity as the key and all the cords in the list
My point is there may be a MUCH better way than tracking transient Entities
Which is why I asked why he was doing that
Where do I specify which command I want to complete tab for?
are you trying to do multiple command tab complete in one completer?
I'm trying to suggest those things when I run a command
Where would I specify that command name?
Oh I didn't notice, afaik completer doesn't work for base command
implement TabExecutor instead of CommandExecutor
your code you shoudl add any which partial match
you can do that with a string partial match, sec
Thanks, also, how would I put a suggestion inside of a suggestion?
for example if they type tp I want to suggest a few things
Nvm I'm tripping, first arg isn't base command in spigot
true, but is it even possible to use interactive book on 1.8.8?
Because I can't use components.
https://i.imgur.com/0aBpdjx.png
Interactive books seems to be 1.14
is that using Bungee chat component?
No clue when iut was available in Spigot https://www.spigotmc.org/wiki/interactive-books/
man, who codes for christmas? yall need to take a break
Sitting here waiting for the family to flock in
an hour or two, then I can be a hermit again
xDD
I do
I don't got christmas, I got a family with covid
Muslims don't celebrate Christmas ;)
player.teleport puts me on the corner of a block. How could I make it put me in the center?
Ok epic
Also: Is it possible to save things such as Location Block etc with sqlite? With json I couldn't
it's ConfigurationSerializable so saves straight to yaml
it's just 3 doubles and a name
hi does anyone know how to use the FAWE api with 1.8 (java 8) in a project and specifically use it to paste schematics asynchronously? ik this probably isnt the appropriate discord but i cant find the fawe discord and im wondering if there is someone who may have experience with this
right now i parse the schematic and complete the paste synchronously, which lags the server for like 10 seconds
public CompletableFuture<EventContainer> pasteMapAsync(EventMap map, boolean canReuse) {
if (canReuse && this.presentValidMap == map) {
return CompletableFuture.completedFuture(this); // nothing to do
}
if (this.presentValidMap != null) {
resetMap();
}
final WorldData worldData = LegacyWorldData.getInstance();
final com.sk89q.worldedit.world.World world = new BukkitWorld(getWorld());
try {
ClipboardFormat format = ClipboardFormat.findByFile(map.getSchematic().toFile());
if (format == null)
format = ClipboardFormat.SCHEMATIC;
ClipboardReader reader = format.getReader(Files.newInputStream(map.getSchematic()));
Clipboard clipboard = reader.read(worldData);
// perform paste of the new schematic
Operation pasteOperation = new ClipboardHolder(clipboard, worldData)
.createPaste(world, worldData)
.to(new BlockVector(0, 0, 0))
.ignoreAirBlocks(false)
.build();
Operations.complete(pasteOperation);
map.onPaste(this);
presentValidMap = map;
} catch (Throwable t) {
throw new RuntimeException("Failed to paste map `" + map.getName() + "` into event container `" + world.getName() + "`", t);
}
return CompletableFuture.completedFuture(this);
}
current code
ive used a completeable future here to make it future proof for when itll be asynchronous
what enum need for enchantments
why in bukkit enchantments that are not in the game
Like DAMAGE_ALL
that's sharpness
lol
its reaaaaaaaaly boring
saving money for Christmas
On christmass?
yweezg]]

Why is event.getConnection().getUniqueId() null in PreLoginEvent? (BungeeCord)
preLogin = not yet logged in, so no clue who it is, so can;t have a uniqueID
I am confused
bro
hello, im trying to do smth wich is to prevent certain types of items to drop when a player dies. BUt there is not a e.setDrops() for PlayerDeathEvent. Any idea on how to do it?
You can just remove the drops you don't want from the list
ooo olivo booster again
I won Nitro giveaway 
fancy
1 month pink
get it from helpchat or somewhere else
Somewhere else
so like e.getDrops.remove ?
yes
you win anything on helpchat giveaways?
Okey thx
Yes I won a plugin
can anyone explain?
I am confused all of the time
so what's the question
wondering if anyone knows how to use the FAWE api in 1.8 to paste a schematic asynchronously
Just use the api async
didnt work for me but thats probably because i was using pure worldedit api
using the BukkitWorld wrapper
what about it didn't work?
idk how to import the FAWE api into my project as its for java 17
i basically did
CompleteableFuture.runAsync(() -> {
// ...
Operations.complete(pasteOperation);
});
using BukkitWorld from the worldedit api as the world adapter, which appereantly uses Block#setType from the bukkit api to set each block which the async op catcher caught
uh I believe that's all I had to do last time I tried FAWE
don't remember though
go ask in their discord
would this work?
?tas
I love this video
.
Why does the first person that types something in Chat after I canceled 1 ChatEvent Message get kicked?
yes
How did you cancel the message
and what version is the server running
@EventHandler
public void onMessage(ChatEvent event) {
if(event.isCommand()) return;
if(!(event.getSender() instanceof ProxiedPlayer)) {
return;
}
ProxiedPlayer player = (ProxiedPlayer) event.getSender();
if(module.getManager().isBanned(player.getUniqueId(), true)) {
if(module.getManager().isBanActive(player.getUniqueId(), true)) {
event.setCancelled(true);
player.sendMessage(new TextComponent(module.getPrefix() + "ยงcDu wurdest aus dem Chat gebannt!\nยง7Verbliebene Zeit: ยงa" + module.getManager().formatRemainingTime(module.getManager().getTime(player.getUniqueId(), module.getManager().getReasonID(player.getUniqueId(), true)))));
} else {
event.setCancelled(true);
module.getManager().unmute(player.getUniqueId(), UUID.randomUUID());
}
}
}``` 1.20.1
Don't cancel messages on the proxy
Or disable chat verification
how
Server.properites I believe
If I want to get the Player's ip from a Channel object, do I just use Channel#remoteAddress?
previews-chat=false thats the only thing with chat

Olivo is pink!!!
Hello! Right now I'm running this code to check if a Location is valid for a player, i.e. that player fits in and can be teleported to the position. But it seems that it gives different results when the Player's bouding box is changed, is it possible to make it fixed and if so what dimensions etc. should it have?
public boolean isLocationValid(Player player, Location location) {
Location tempLocation = location.clone();
BoundingBox playerBox = player.getBoundingBox();
boolean a = !playerBox.overlaps(tempLocation.getBlock().getBoundingBox());
boolean b = !playerBox.overlaps(tempLocation.add(0, 1, 0).getBlock().getBoundingBox());
Log.info("Location: " + location + "isLocationValid: " + (a && b));
Log.info("PlayerBox: " + playerBox);
return a && b;
}```
hey. how to know if a player is moving or standing?
i check if the length of the velocity vector is 0, but it doesnt always work
playermoveevent?
@young knoll staff how make faster
https://paste.md-5.net/tupumoruzi.cs
@staff @staff
uhh
if (end == -1) {
throw new IllegalStateException("the token that started a capture at index %d never ended. Capturing: %s".formatted(start, string.substring(start)));
}
Remove that, unnecessary if statement
okayyy
@Staff @staff my code isn't working
@young knoll @staff its not working
I will set you on fire
LOL
whast the difference between PlayerProfile and GameProfile?
What is the best way to save Bukkit objects persistently (like ItemStack Location etc)?
I am trying to give a glowing effect to an entity visible by one specific player with protocollib but the player crash when the pack is sent.
PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA);
packet.getIntegers().write(0, silverfish.getEntityId());
WrappedDataWatcher watcher = new WrappedDataWatcher();
WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class);
watcher.setEntity(silverfish);
byte index0Value = watcher.getByte(0) != null ? watcher.getByte(0) : 0;
watcher.setObject(0, serializer, (byte) (index0Value | 0x40));
packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects());
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(p, packet);
} catch (InvocationTargetException enT) {
throw new RuntimeException("[X] ", enT);
}
Packet encoding of packet ClientboundSetEntityDataPacket (ID: 84) threw (skippable? false)
java.lang.ClassCastException: class net.minecraft.network.syncher.DataWatcher$Item cannot be cast to class net.minecraft.network.syncher.DataWatcher$b (net.minecraft.network.syncher.DataWatcher$Item and net.minecraft.network.syncher.DataWatcher$b are in unnamed module of loader java.net.URLClassLoader @504bae78)
lost connection: Internal Exception: io.netty.handler.codec.EncoderException: java.lang.ClassCastException: class net.minecraft.network.syncher.DataWatcher$Item cannot be cast to class net.minecraft.network.syncher.DataWatcher$b (net.minecraft.network.syncher.DataWatcher$Item and net.minecraft.network.syncher.DataWatcher$b are in unnamed module of loader java.net.URLClassLoader @504bae78)
Why it sais "Required type: capture of ? extends Player"
@EventHandler
public void CreateNPC(PlayerJoinEvent event) {
for (Player p : Bukkit.getOnlinePlayers()) {
if (p != event.getPlayer()) {
Bukkit.getOnlinePlayers().add(p);
}
}
}
I am saving my own object, which contains Bukkit objects
(ItemStack Location)
would there be a better approach without using reflection?
so how I understand AsyncPlayerChatEvent is fired on an external thread?
So I can do some things on there that wouldnt harm the main one?
yes
Spigot 1.18.1 added the new PlayerProfiles class, which finally allows us to use custom heads without needing any reflection! You can obtain them as normal items, or actually place them down into the world. Iโll show you how both works: Creating a new PlayerProfile First, we gotta create a new PlayerProfile object. To do so,...
for 1.18.1+
ty
That does not answer my question
An alerting/reporting system to staff, that requires saving of ItemStack and Location. Also ItemFrame in some cases and some other objects
You can use a database
Ok I'll do SQLite
as its stored on disc
Whats better?
I need to get a player's face from craftar.com api for discord relay, should I use PlayerChatEvent and open an async task, or just use AsyncPlayerChatEvent?
I would use a completable future
completable? do you mean compatible?
no
promise is such a bad name
It is a future that can be explicitly completed (via #complete), as it's name implies.
who would call it a promise
is it called promise because they promise to run it or some shit
Java Script javas disabled younger brother everyone pretends to like because they feel bad
well yeah, the first person using it for their website environment just made a mistake and now the www hinges on it
They really are 2 different things
idk why they share a name
I know lol
My friend once told me it was to boost js' popularity
Since java was popular at the time
hmm could be
now we are still seeing the consequences xD
one thing js got us though is json
which is handy from time to time
Js isn't bad but Node is a mistake
I cannot use spawnParticle in spigot 1.8?
My main complaint is using it for things it's not meant for
?1.8
Too old! (Click the link to get the exact time)
Old version old problems
nvm I'll just execute a command :)
Hello, does anyone know how to do send a custom map to a player like this only using packet ? (in 1.8)
I made this but for 1.14+
is the code public?
or I can just use protocollib actually
Yep
thank
Just go into the constructor classes
If a method is deprecated, what could I use to find the nonprecated alternative?
Depends
Some deprecated can be used just fine
this.itemInHand = player.getItemInHand().clone();
Can you set a blocks damage?
Blocks dont do damage, or do they? Or what do you mean?
getInventory().getItemInMainHand();
do you have the link of the lib you use to create the itemPacket pls?
The craxks in a block are blockdamagr
is this better than GetitemInHand?
It's built-in
I made it by hand
Yep. Since it's from the time there was no offhand
But should work just fine
i have a question
if i run 2 SyncRepeatingTasks does the timer of the second task override the first one?
i have 2 tasks, one running every 5 seconds and one every 100 milliseconds but it seems like both are running every 5 seconds
It does not
show us the code you used to create the tasks
give me a sec
np
int schedulerID1 = Bukkit.getScheduler().scheduleSyncRepeatingTask(testPlugin, () -> {
//task 1
}, 0L, 100L);
int schedulerID2 = Bukkit.getScheduler().scheduleSyncRepeatingTask(testPlugin, () -> {
//task 2
}, 0, 5L * 20);
Bukkit.getScheduler().runTaskLater(testPlugin, () -> {
Bukkit.getScheduler().cancelTask(schedulerID);
Bukkit.getScheduler().cancelTask(schedulerID2);
}, 16L * 20L);
20 * 5 is 100
^^
So both are running at 100 tick intervals
ah i see now
sorry about that lol
I never used protocollib before; is it FOSS?
Yes
Bukkit runs off of ticks instead of milliseconds, so the best you could do is set it to run every 2 ticks.
1 tick = 50ms
2 ticks = 100ms
gotcha
Is it possible to set a blocks breakstate (the cracks when you break it?)
With packets yes.
thanks this is very good
the api can do that too I believe
yeah no need for packets https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/entity/Player.html#sendBlockDamage(org.bukkit.Location,float)
declaration: package: org.bukkit.entity, interface: Player
Noice. When was that added?
A while ago
Thx
There is no way to get the blocks damage tho, right?
There is
Cuz this only makes it look like mined to a degree
So do you want to know the spoofed one or the actual?
Just so you know, you can still use that to break the block
Hmm
I would like to have the break value rhat the player sees
So i guess the spoofed
Then save it into a map
Or even a map map
I guess persistentblockdata from fnalex would be good for this, thanks for block pdc to alex
And listen to like, dig event? (I don't remember the name)
Blockdamageevent
Yeah thats probably the best way
Block#breakNaturally and remove the stored value
Or else update the stored value and send the last spoofed + current mined
Thanks
You might sometimes need to wait for a sec tho
Any way to make links clickable in chat? For example when a player sends a link others can click on it
My chat system sends a message to all online players, instead of using the vanilla one
due to chat reporting
Use components and send the message to everyone.
This is already enabled in the chat if an url follows a proper format. eg. If you send https://www.google.com to the chat everyone will be able to click on it
Not when you manually muck with chat
https://www.spigotmc.org/wiki/the-chat-component-api/#events use a ClickEvent.Action.OPEN_URL
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
thats not what im trying to do. Im trying to make URLs clickable in chat when a player sends a URL in their chat message. Not have a custom chatcomponent with a url
where's the difference? check what they send, parse (e.g. with regex) for valid URLs, and replace that part with a clickable component
hey does anybody know how I can have like moving blocks/items? I don't know if you guys have ever played in a prison game mode, but there is an enhancement that is called boomerang and it's just a gold plate floating around that breaks blocks. Do you have any idea on how it can be done?
Display Entities
Create whatever block or item you need, scale it to whatever size you want, then when it intersects with a block, break it.
If I'm going to calculate if a player will take fall damage from a position, what do I need to think about more than the height?
Potion effects
Blocks that could slow them either at the buttom or on the way down
Velocity
About like this then? Will add velocity and may fix a little better structure, etc. for which materials
public boolean shouldTakeFallDamage(Player player, Location location) {
World world = player.getWorld();
int topBlockY = world.getHighestBlockYAt(location);
for (PotionEffect effect : player.getActivePotionEffects()) {
if (effect.getType().equals(PotionEffectType.JUMP) || effect.getType().equals(PotionEffectType.SLOW_FALLING)) {
return false;
}
}
for (int y = topBlockY + 1; y < location.getBlockY(); y++) {
Location tempLocation = location.clone();
tempLocation.setY(y);
Material blockMaterial = tempLocation.getBlock().getType();
if(blockMaterial == Material.WATER || blockMaterial == Material.LAVA || blockMaterial == Material.COBWEB || blockMaterial == Material.SLIME_BLOCK) {
return false;
}
}
return location.getY() - topBlockY > 3;
}```
What does this mean translated to english?
u can do it shorter ;d
ah ok
Bukkit.getScheduler().runTaskLater(GriefAlert3.getInstance(), hologram::delete, 5 * 20);
^ in english
yeah, usually the blue text is clickable and will do what its saying, the one starting with "Replace lambda ..."
Yes
then you can see what its changing
If it can be shortened, shorten it
y'all call this clean code?
clean code is a dumb goal, but this, this can be improved
Clean code doesn't exist
https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 go get brainwashed or something or something
which is something you cant call my code (this is on prod with 10+ players)
its easier than component build stuff
not if you use MineDown or make your own chat parser
if it aint broken, dont fix it
its alright it works for me
1.8?
About like this then? Will add velocity and may fix a little better structure, etc. for which materials
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class MenuListener implements Listener {
@EventHandler
public void onMenuClick(InventoryClickEvent e){
if(e.getView().getTitle().equalsIgnoreCase(ChatColor.GRAY + "Land Shop")){
//Make sure the player clicked on an item and not on the inventory
if(e.getCurrentItem() == null) {
return;
//make it so that players cannot move items in the inventory
e.setCancelled(true);
}
}
}
}```
not sure on why it wont work
Man, that poor thing don't got money?
is my coding style good or bad?
nested runnables 
how can i avoid it
id prolly use Futures
what are those
can anyone help?
- Did you register the listener?
- You should compare inventory instances instead of titles.
uugh use ?paste pls
^
hellow shadow
yeah this is terrible to view on mobile
Hi, im coding something and need a little inspiration:
What im trying to do is save Inventories, 2 to be exact.
A "json" format of what im trying to do is something like this:
UUID:
"world_name":
buildmode: boolean
Inventory_build: Inventory
Inventory_normal: Inventory
Im trying to save that data and dont really get how i could do that. Could someone give me a bit start help. This data should be saved permantently, so for example in a file. But i also need to be able to set it using functions in java. Im going to provide these functions here:
- Boolean hasBuildMode(UUID, world_name) = returns buildmode
- Inventory getnormalInventory(UUID, world_name) = returns Inventory_normal
- Inventory getbuildInventory(UUID, world_name) = returns Inventory_build
- Boolean hasEntry(UUID, world_name) = if data of this uuid and world exists
- void setBuildMode(UUID, world_name, boolean)
- void saveInventory(UUID, world, Inventory_normal/ Inventory_build) = saves the inventory, when switching between build mode and normal mode
- void addEntry(UUID, world_name, boolean, Inventory_normal) = adds a entry to the file system and creates a empty inventory for the inventory_build variable
Thanks again for any help. Im really frustrated about this, because ive been trying to get a solution for this for ages
Hemlo
hamlet
if you're using YamlConfigurations, it can easily store ItemStacks, so you could just turn your Inventory into an ItemStack[] and use that
This looks like yaml format. :p
how does this look guys for a custom item config
{
"damageMultiplier": 5,
"material": "DIAMOND_SWORD",
"name": "<red>Yo",
"lore": [
"My lore <yellow>XD"
],
"unbreakable": false
}
I'd use yaml instead, it's easier to edit
i dont even know how to start tbh. I just never worked with something this "complicated" before. Like saving this much data with this many functions, how could i achieve that?
since ItemStacks already implement ConfigurationSerializable, why not just use that? ItemStack#serialize() and #deserialize()
first you need to just worry about creating a class to do this for your without any files
just use a YamlConfiguration. Then you can just save your items inside
YamlConfiguration storage = new YamlConfiguration();
ItemStack[] buildItems = myBuildInventory.getContents();
storage.set(uuid + "." + worldName + ".inventory_build", buildItems);
If you use yaml files and use the API to read and write from them, then you'll have what you are looking for.
You'll likely want to cache your changes then write it to disk at certain intervals since disk I/O is taxing.
then later you can add config file stuff to it to actually load save to file, but usually you dont have to do anything fancy
unless it doesnt change much, then I wouldnt worry about caching anything
ok. can i also make it so it saves it on OnDisable and every 5 seconds?
why
You can make it save however often you want, it's just important to know that writing to disk every time will result in a performance hit.
I would just save and load whenever players change dimensions or log in / out and when the server gets restarted
wouldnt it be the best then to ONLY save on Disable
Not necessarily
whats pro and con there
It's better to save on both disable and on an interval.
That way if the server ever crashes, it'll only be however long the interval is behind.
ok
onDisable isnt called if the server crashes (or someone quits it with Ctrl+C etc)
the same way you save it
By using the #getX() methods provided.
but you get instead of set
you load a config using YamlConfiguration.loadConfiguration(File) and then you can use any of the getWhatever() methods
okay, and to save to file id guess u use saveConfiguration?
#save() but yea
@tender shard
im looking at the itemstack serialize thing rn
and
is there a way to have it include all possible fields
like lets say the item wasn't unbreakable
then is there a way for it to include the value unbreakable: false still
Okay, ive also got a Question. Right now i am saving the following:
UUID + world + buildmode, Inventory
The problem i see here is that there are 2 Inventories PER world, so i need to save the 2nd inventory too, how could that work?
Save it as a second subsection. You had the structure, you just gotta use it. :p
uuid:
world:
build_inventory: <data>
normal_inventory: <data>
Yeah i know, but how could i use .set to set it?
Currently im using this for 1 Inventory:
uuid + "." + worldName + "." + buildmode, build_Inventory
You'd just point to the second one you want to save to.
uuid.world.build_inventory
uuid.world.normal_inventory
The dot just denotes that you want to access a subsection.
Just serialize it yourself then
ohh, so uuid.worldname.buildmode, buildinventory sets the buildinventory and uuid.worldname.buildmode, normal_inventory sets the normal inventory
thank u
yeah but commas is for setting the value isnt it?
For the function yea, but in the path string no.
config.set("uuid.world.build_inventory", inventoryData);
So should i rather use this:
uuid.worldname.buildmode.inventory_build, Inventory
uuid.worldname.buildmode.inventory_normal, Inventory
or rather
uuid.worldname.buildmode, Inventory_normal
uuid.worldname.buildmode, Inventory_build
So should i add another subsection, does that make it easier getting the inventory later, because otherwise 2 items would be in the same subsection
You'd use the first 2.
okay, thanks
how would i do that
PluginManager#registerEvents()
the class works fine I guess
it's just that
the get returns negative numbers
after incrementation
Isn't there atomic long in jdk?
there is
You can't add floats that way
Honestly, I'd use a Varhandle for this, no need to to use an AtomicInteger in the background with FloatToIntBits
Just make sure that the underlying field is volatile
They probably meant AtomicFloat in JDK; which does not exist strangely enough
Probably because few CPUs support atomic addition of floats (given that floating-point arithmetic operations takes a few cycles)
what are atomic objects even for
Basically wrapping a field in a way that can only be accessed and written to in an atomic manner.
Useful in thread-safe environments as atomic operations do not suffer from race conditions by definition (however, that does not grant you immunity from programmer mistakes. While a single operation is atomic, a block of operations may need to be locked anyways depending on the situation)
Yeah I meant float lol
Anyways, @grim hound - if you have not figured it out on your own (or if you implemented it without too much thought):
The easiest non-atomic way of adding two floats together would be as follows:
public void add(float f) {
this.bits.set(Float.floatToRawIntBits(Float.intToFloatBits(this.bits.get()) + f));
}
however, as I said that is not atomic. So either you need to synchronize stuff - which in your case is nonsensical - or use CAS as follows:
public void add(float f) {
int bits, result;
do {
bits = this.bits.get();
result = Float.floatToRawIntBits(Float.intToFloatBits(bits) + f);
} while (!this.bits.compareAndSet(bits, result));
}
I found my impl on the internet
Whoever wrote that impl has no idea what he wrote
Hi, im back just to make sure this is gonna work:
public static YamlConfiguration storage = new YamlConfiguration();
public static void loadBuildMode() {
YamlConfiguration.loadConfiguration(new File("buildData.yml"));
}
public static void saveBuildMode() throws IOException {
storage.save(new File("buildData.yml"));
}```
Like, this impl is extremely terrible as A) it is factually wrong and B) it should be using varhandles instead, but I digress.
you never store the result of YamlConfiguration.loadConfiguration(File)
can you write me a working one?
uh yeah that is not how you add floats lol
cuz I don't really get how the atomic operations work
Uh I could try but I'd make the one or the other mistake. But I shall see.
But if you don't get how atomic ops work, are you sure you should be using atomic objects in the first place?
I do understand how they work
I worded it wrongly
I don't get how their implemented
so how should i load and save the data then?
ah well then. Have some patience - I'll try to whack up something
appreciate it G
storage = YamlConfiguration.loadConfiguration(...)
thats it?
also you should use a File inside Plugin#getDataFolder()
YamlConfiguration#save(File file)
so this would make sense?
public static void saveBuildMode() throws IOException {
storage.save(new File("buildData.yml"));
}
nope
the path is wrong
yeah, with plugin.getDataFolder
and File.seperator
?
just do ```java
new File(plugin.getDataFolder(), "buildData.yml");
or this
okay, finally:
public static final Plugin plugin = mondlw.laserserver.laserservermanager.LaserServerManager.getPlugin(mondlw.laserserver.laserservermanager.LaserServerManager.class);
public static YamlConfiguration storage = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "buildData.yml"));
public static void saveBuildMode() throws IOException {
storage.save(new File(plugin.getDataFolder(), "buildData.yml"));
a bit too static, but we can fix that
i think u can just do JavaPlugin.getPlugin
why unamused @tender shard
because everythingโs static
still waiting for a tutorial why static abuse is bad ๐
@silent slate
read it, the part i understood that its not garbage collected and fills up ram, so bad performance
@grim hound Okay, honestly it is actually completely pointless to do so as you can simply use VarHandle to wrap all your atomic operations.
So it would basically look like
public class AtomicFloatVarhandle {
private static final VarHandle VALUE;
private volatile float value;
public float get() {
return this.value;
}
public void set(float value) {
this.value = value;
}
static {
try {
VALUE = MethodHandles.lookup().findVarHandle(AtomicFloatVarhandle.class, "value", float.class);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Unable to obtain varhandle of object", e);
}
}
}
all other operations (e.g. setOpaque can be easily converted to their VarHandle equivalents. Since the methods of VarHandle are signature polymorphic, no overhead is incurred through autoboxing.)
So getAndAdd would look like:
public float getAndAdd(float value) {
return (float) VALUE.getAndAdd(this, value);
}
yeah...
The problem for me i think is that its soo easy and so helpful and i havent really had a problem with it ever, because my code isnt that complicated
yooo thaaanks
I knew varhandle was the way to go, but I did not imagine it to be that easy tbh
?paste
i get this error
It says something about casting ItemStack to inventory. tell me what code u need
Why are you casting itemsrack to inventory
well i dont really know where and why and how
i think its the setBuildMode method, im gonna send that
The line after the caused by: line should show it (unless you logger is broken)
What type is "storage"
public static YamlConfiguration storage = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "buildData.yml"));
Yaml
?jd-s
So it gives you itemstackd
each single one?
Save it as array of itemstack
Yea
Yeah, Inventory is not serializable
so i can i do a function that loops through the inventory and adds the Itemstacks to a ArrayList?
Quick tip, Inventory#getContent already returns array of itemstack
ok
Quick tip turned to important tip
this ?
storage.set(uuid + "." + world + "." + "normalinventory", player.getInventory().getContents());
?tas
I gotta get used to these stuff
3rd time that i tried to use a cmd today and failed
Hi, its my first time using SQLite. I'm trying to save an index+a custom object (alert). What should I type near the "alert" ?
unless im doing everything wrong
uh don't make sql statements in the constructor
In this video, I show you how to use SQLite Databases with your Minecraft plugins. It is a lightweight and popular type of SQL Database that many people use.
Code: https://github.com/Spigot-Plugin-Development-Tutorial/sqlite-demo
SQLite: https://www.sqlite.org/index.html
Maven Dependency: https://mvnrepository.com/artifact/org.xerial/sqlite-jdb...
It's always kody
indeed
.
It is in fact true
Rip
That is where you have to learn sql and normalizations
Bro that bot has less knowledge than a carrot
Imagine following a spigot tutorial about sql... just follow a normal one
A problem with constructors is that you are rarely aware that it is doing network IO.
So you can easily find yourself doing blocking network IO on the main thread if you do such network IO in the constructor.
https://youtu.be/On9eSN3F8w0?si=R4aZ7xn2afbBoluj
Watch this or smth
SQL Tutorial for Beginners - Learn complete SQL from basics to advance in one video.
This course is for beginners (with zero knowledge in sql) and through this course we'll be learning various topics including sql basics in hindi, data types, database structure, basic CRUD operations, functions, operators, aggregation, nested queries, joins, cte...
I dont understand what he is speaking but ye
Ok
I think
*there might be few syntax differences between sqlite and mysql
But can SQLite store things such as ItemStack Location etc?
No, you have to make tales yourself
._.
Tables
so I have to deserialize literally everything into strings/integers
Not everything is out of the box
Only thing with built in serialisation is yaml
Maybe I should go with yml then
Sql is good learning experience
My code has lots of bukkit objects inside of custom objects
I aint deserialising all that
Just save the yml in sql then, its stupid but good for learning
The contents of the yml
why cant I just save the yml in my plugin's configuration folder?
Just use ObjectOutputStream/BukkitObjectInputStream then
But dont forget to do SerialId or smth
Java's serialization API is a dangerous choice anyways lol
I had issues in the past cuz i forgot
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
Good resource
My suggestion was more of a half-joke than something to take seriously
Is there a way to use packets in 1.20.2? cuz i dont find any protocolLib version for 1.20
Like, you use that API if you want to write something and be done with it.
But if you want to write a stable and secure application, ObjectOutputStream is incredibly dangerous
Like, you can easily find yourself making a mistake somewhere
People need to pay less atention to this thing
what?
Could spigot please remove the supported minecraft versions list?
so there is a 1.20.2 version?
Hehe i like unstable stuff
You get the latest release of from their CI instance (probably a jenkins server), as is the case with most plugins
whats a good website to decompile a .db file?
It usually does support any version that has been released a few weeks ago
What...
You cannot decompile it. But there are plenty of viewers out there
found this page but i cant click on the 1.20.2 thing
I swear to god, if I find the link in under a minute
Geol going in rage mode
chill man, i juste wanted to know if there is a version for 1.20.2, cuz i didnt find it
thank you
what is this?
ok epic I have a .db file, what could I use to view it?
Okay, ive gotten it working (partly)
If i turn buildmode from on to off the inventory doesnt get loaded correctly (doesnt change). If im going off to on it loads it correctly.
Also i dont see a file in the folder so im unsure if its being saved correctly or saved at all.
There are no errors in the console when changing the buildmode from off -> on or from on -> off
This is my new code:
Check yo path if its correct
The amount of times I need to hunt down links for people and find it in a matter of seconds is horrifying.
Yes, I don't expect less knowledgeable people to know what a jenkins is, but seriously?
Feels relatable
the worst questions are still IJ-specific questions though
HediSQL 
i dont see anything wrong here and i really dont find it in my data
Yo how does intellij work
Ij means intellij right
S a r c a s m
well it is more akin to "why does this application not start?", when stuff is obviously missing from the runtime classpath while being present on the compile-time classpath
here you go, whole thing
(toggleBuildMode isnt converted yet and doesnt get used)
Do you even call your save function
yes
Where
in a timed functioin in my main class
scheduler.runTaskTimer(this, () -> {
try {
BuildUtils.saveBuildMode();
} catch (IOException e) {
e.printStackTrace();
}}, 0L, 20L);
saving every second? A bit extreme
temporary
I would save the runnable in a variable, and after toggle start it to save
But taskLater
i dont understand
...
it doesnt
...
Now i got this
Caused by: java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class [Lorg.bukkit.inventory.ItemStack; (java.util.ArrayList is in module java.base of loader 'bootstrap'; [Lorg.bukkit.inventory.ItemStack; is in unnamed module of loader java.
Gtg sleep wait for someone else to answer
good night and thanks for all the help
bros working on an anticheat barely knows java
thats a bug
a beginner one
ItemStack[] stacks = ((List) whatever).toArray(ItemStack[]::new);
i was learning some code (trying to understand it) from another anticheat and its staying this ever since
im not even working on that anticheat rn
but where in my code is that
I donno, read the stacktrace
probs line 42 and line 43 though
whatever would then be your storage.get(...) call

