Confirmed fix for itemframes not showing up. Based on the code in
CraftPainting.
Besids this fix we now pass null itemstacks directly to the
EntityItemFrame to allow the removal of items in ItemFrames.
If the server crashes during chunk generation then the chunk would have never
been added to the executor, this caused a second exception to be thrown when
the server shutdown from the first exception
Adds an check for existing entities before selecting the location allowing
for hanging entities to be spawned in blocks where there already is an
hanging entity at the default rotation.
Fixes the CraftHanging setRotation function to use the new 1.8 logic.
Related to SPIGOT-206.
Currently HangingEntities should be located next to the block they are
hanging on. With the direction set to the opposite of the block they
are hanging from.
This code is modified to find the correct direction.
calling CraftWorld.save() currently does not call WorldSaveEvent, and WorldSaveEvent could fire on worlds that have saving disabled.
New location will always fire during a world save and only during an actual save.
* commit '7371301edb1c44ab9153e1fba3722ba2f4e3c411':
Forgot that i work in Bukkit... Screw sun conventions
Implementation for the new rotation values. Fixes SPIGOT-93
Up until Minecraft version 1.5 it was not possible to teleport entities
within vehicles. With the 1.5 update came the change in the Minecraft
teleportation logic to dismount before teleporting the entity, if
applicable.
This commit ammends the existing CraftBukkit logic for rejecting
teleportation for entities in vehicles to permit the action. Due to this
change, CraftBukkit is now in-line with Minecraft 1.5 teleportation logic.
When a player dies their inventory is normally scattered over the the area
in which they died. Plugins should be able to modify this behaviour by
defining whether or not the player's inventory will be dropped on the ground or waiting for the player when they eventually respawn.
This commit implements the methods included in the Bukkit half for the new
behaviour by acting upon the boolean flag. The boolean flag is tested
prior to clearing the inventory as well as prior to dropping the items on
the ground. If the flag is true (indicating "keep inventory"), the items
are not removed from the player's inventory and are not dropped on the
ground.
When using a "vanilla" Minecraft server using the "pick block" key on a
command block yields the invoker with a command block within their
inventory while in creative mode. Implications of the invalid items set
containing the command block also include having a "ghost" item that
cannot be placed due to it not actually existing.
This commit resolves the problem and brings Craftbukkit closer to vanilla
behaviour by removing the command block item ID, 137, from the invalid
items set.
Prior to this commit cancelling the PlayerFishEvent would cause various
states of the fishing routine to be incorrectly or wrongly fired. This
incorrect behaviour was due to the miscommunication between the server and
client regarding the fishing state. When the event was cancelled, the
bobber entity was removed and caused the client to incorrectly determine
what the "next state" was to logically be.
This commit resolves the issue by ensuring the client is made aware of the
correct changes at the correct time regarding the bobber entity, therefore
keeping the logical steps of "fishing" proper and in-tact.
Up until this commit the PlayerDropItemEvent, if cancelled, would return
items to the first available slot in the inventory - which is clearly
undesirable as a player and plugin author to deal with.
This commit changes that by ensuring that the item is returned to where
it came from in the player's inventory. This still supports modifying the
drop from the player and will default to "first available slot" if the
item has changed since the event was fired. Other remaining behaviour of
the event is still in tact and has not been modified.
This change improves the quality of life for plugin developers using
iterator iteration with side-effects. In the specified Guava patch, the
internal iterator no longer relies on the AbstractList iterator which
iterates by index, and will instead wrap the provided iterator in a
transformer given the Function.
Many chunk sections contain parts of their data that are the same for
every block they contain. In these cases we can save memory by saving
a single value instead of an array of 4096 copies of that value. Block light
and block data are most likely to be uniform followed closely by sky light
data. Block ids are far less likely to be uniform but give the largest
saving when they are. Because of this we use a compact format for every
part of the chunk. Memory saved from this technique will vary based on the
world but seems to be about 50% on normal Minecraft generated chunks.
This commit centralizes event handling to where damage is actually applied
to the entity to avoid bugs that have resulted from nodamageticks,
modifications to damage after the event has been called, and similar
mishaps. This also implements new API for getting and setting of
modifications made to the damage amount actually applied to the entity.
This is done by storing the change in the damage amount as each modifier
is applied by vanilla code.
The method that actually damages the armor worn by an entity has been
relocated beneath the event called as to not apply durability loss when
the event has been cancelled.
When a chunk is loaded the server tries to ensure it has its initial light
calculations done before sending it to the player. When ticking entities
the server tries to ensure the entity does not walk into an unloaded chunk.
To accomplish these the server checks a one chunk radius around the chunk
to be lit or a two chunk radius around the chunk the entity is in. These
lookups happen every tick even though their result is unlikely to change
that often. To reduce the cost of these checks we replace them with a
system to keep track of what neighbor chunks a chunk has loaded and update
it when chunks load or unload which is a much less frequent action. On a
server with ten players this change removes about 100,000 calls a tick to
LongObjectHashMap's containsKey method.
In commits 71a238ee and c8591397 we added checks while ticking to ensure
we never ticked anything in a chunk meant to be unloaded. We did this to
prevent these chunks being removed from the unload queue and leaked.
However, this causes a ridiculously large number of lookups on the queue
for a somewhat rare occurance. We also now have the chunk GC which will
take care of these leaked chunks when they do happen. With this in mind
we now remove these checks which removes almost all uses of the
LongHashSet backing the unload queue.
After the changes in d611cff2 we started including a mob's equipment when
calling EntityDeathEvent so plugins can access this data. However, the
changes to enable this triggered a bug that makes skeletons and pig zombies
no longer drop equipment because they handle this differently than the rest.
On top of this we don't handle dropping equipment for mobs that cannot
pick up items in vanilla even though vanilla does drop equipment for them
if you summon them with it. We also do not include a horse's inventory
in the event so they drop their saddle, armor, chest, and chest contents
with no way for a plugin to control this.
To solve this issues we revert mob item dropping back to vanilla logic
and instead just capture all their drops in the method they all call to
spawn them into the world. We also move horse inventory dropping so it
happens at a time when we're capturing these drops. With these changes
all items mobs drop on death should now be included in the event and
we have less diff to worry about for future updates.
Waiting to log until after PlayerCommandPreprocessEvent makes the server
not log anything if the event is cancelled. It also makes the server log
what a plugin changed the command to instead of what the player actually
tried to run. As the point of the log is to have a record of every command
a player attempts to run these are both not desirable.
In 7e37cf96 we modified the container logic to handle custom max stack
sizes better and ensure the client stays in sync with this scenario. This
had the effect of sending an extra set slot packet for every inventory
click a player did which was not wanted. These extra packets also cause the
client to recalculate recipes which breaks the result slot for custom
recipes. To avoid the extra packets in general we now only send them if the
max stack is not the one we started with. In the case of a setting a custom
max stack size on a workbench this is still not enough so we also now send
another extra packet to make sure the result slot is always correct.
To handle changes in 1.7.9 we changed skull meta to use GameProfile
instances instead of strings of player names. This reflects what vanilla is
actually storing for skulls now. As skulls still require a name our API was
not changed and we instead look up the rest of the profile information from
the name. The way this was implemented made it so that deserializing a skull
or setting its name potentially involved a network request. As skull meta
itself does not actually require a complete profile we now simply create one
that only contains a name and leave populating it to the server when it is
actually needed.
With the current API it is possible to create an inventory with a specific
type, but it is not possible to give such an inventory a title other than
the default.
The commit changes that by adding a method to optionally supply the title
for the given inventory type and holder, creating the functionality to
display any supported inventory type with a 32 character length String.
If the inventory title supplied is larger than 32 characters then an
IllegalArgumentException is thrown stating so.
In commit 6efeddfe57, TALL_REDWOOD was used instead of the proper TreeType
of MEGA_REDWOOD. Additionally, this fixes an issue in CraftWorld with an
improper boolean flag related to the generation of MEGA_REDWOOD trees.
23 classes have been removed as they are no longer needed using the new
capture logic. This should help quite a bit with future MC updates.
BlockPlaceEvent Refactor
Before calling Item.interactWith, a recording flag is turned on for
setTypeAndData to capture a blockstate for each block that attempts to be set.
When a block place event is cancelled, the recorded blockstate, stack
size, and metadata will revert back to the captured state. If the event is
not cancelled, a notification will be sent to clients and block physics
will be updated.
BlockChangeDelegate Refactor
Now that we have the ability to capture blockstates through world, there
is no need to modify world gen classes with BlockChangeDelegate. Instead
we will simply capture blocks during world generation in order to "replay"
all of the captured blockstates to send back to delegates.
StructureGrowDelegate and BlockSapling.TreeGenerator have also been
removed as part of this change. BlockSapling and BlockMushroom will
capture blockstates the same as block placement and revert back any grow
events if needed.
After the changes in c549609d anvils started incorrectly limiting their
inputs to single item stacks. Vanilla allows for full size stacks here and
this is useful for using materials to repair items so now we do too.
Make sure we check the inventory's max stack size where appropriate and
don't assume the inventory slot is able to take our entire stack just
because it is empty. We also ensure the client is updated with the correct
slot contents and cursor contents in cases where the max stack changes
result in different behavior than the client expected.
The AnvilInventory reports its size as the sum of the ingredient and
result inventories, but when trying to access the slots, only the
ingredient inventory is used, leading to an ArrayIndexOutOfBounds exception.
This change overrides getItem(I) and setItem(I) to use both inventories,
with the slot number adjusted based on their size.
It's currently not possible for a plugin to allow enchanting of an
otherwise un-enchantable item using the enchanting table. This commit
causes EnchantItemEvent to be called with an empty list of enchantments,
allowing a plugin to provide it's own set of enchantments when vanilla
Minecraft would not allow any. It also bypasses the unsafe enchantment check
since a plugin should be permitted to apply any enchantments they like, and
vanilla should not generate unsafe enchantments of its own.
Setting the goal target overrides the entity's will to do something
else. This makes it so entities like wolves with attack another player
with .setTarget(), instead of hanging next to their owner.
Currently, whenever a player places a block in a protected area the
equipped itemstack size on client is never updated properly since the
client thinks the block was placed. The reason this happens is because
ItemStack.matches returns true since the server does not decrement stack
size if a BlockPlaceEvent is cancelled. To correct this on cancel we set
the flag to always update the client regardless of matching.
Currently if a plugin cancels an InventoryOpenEvent for vanilla chests,
the chest animation for clients is stuck in the open state since
IInventory's closeContainer method is never called. To fix the issue,
closeContainer is called before exiting the display GUI method.
If a conversation is abandoned due to a player disconnecting and an
exception is thrown in a ConversationAbandonedListener, the server will
crash. This commit prevents the exception from propagating further up
the stack and instead just logs the error.
Chunk caching in the World class does not know about outdated cache values.
This caused various problems when accessing previously unloaded chunks. The
caching also did not improve the performance so it is removed.
Synchronization is also not necessary, because all accesses to getChunkAt
may only come from the main thread.
Previously, Detector Rails were the only rails that properly called
BlockRedstoneEvent when they changed from powered to unpowered. This commit
adds BlockRedstoneEvent calls for both Powered Rails and Activator Rails.
Currently, plugins can set a player's display name to null, which could
cause issues for other calls to getDisplayName that aren't expecting a null
value. This changes setDisplayName to follow the same logic as
setPlayerListName, which sets the player's name back to their unmodified
"vanilla" name if it receives a null value as a parameter.
Previously, whenever BlockFadeEvent was called for ice melting, it returned
the new BlockState with a type of Material.STATIONARY_WATER. However, in
the Nether, ice melting does not form water, but is simply replaced by air
instead. This changes the event to use the proper BlockState based on
whether the block is located in the Nether or not.
CraftBukkit adds the ability to specify the maxStack size for most
inventories. However, some inventories were not overriding the getMaxStack
method properly, and so the functionality was unavailable. This fixes the
maxStack setting for Anvils, Minecarts, PlayerInventory, and Hoppers.
Previously, the SlotType for the last 4 slots in a player's inventory
returned QUICKBAR when it should have returned SlotType.CONTAINER. This
updates the code for determining slot type to return the proper value.
Previously, the SlotType for the 0 slot in a furnace returned CONTAINER,
when it should have returned SlotType.CRAFTING. This updates the code for
determining slot type to return the proper value.
Previously, when a skeleton was spawned via the spawn(...) function, the
resulting skeleton had no equipped bow and therefore could not properly
attack. This fix gives all skeletons the proper equipment and ensures that
they are able to attack.
Due to changes in how portals were created in Minecraft 1.7, the code that
was previously used to find the blocks involved in the PortalCreateEvent
no longer detected all blocks. Additionally, in the process of updating to
1.7.2, a missed diff resulted in some blocks that were found not being
properly added to the blocklist. This commit corrects that missed diff,
while also adding a check to ensure that the top and bottom of the portal
frame are included in the blocklist.
Adds BUKKIT-5370, BUKKIT-5377, BUKKIT-5378, BUKKIT-5379, BUKKIT-5380,
BUKKIT-5381, BUKKIT-5382. Adds reasons for zombies infecting villagers and
zombie villagers being cured. Readds reason for a skeleton being spawned as
a spider jockey. Adds reason to distinguish ocelot babies from the parent
they spawned with. Adds reasons for chunk generation causing the ender
dragon, villagers, and witches to spawn. And finally, adds a reason for
spawning a chicken mount for a baby zombie.
The old PaintingBreakByEntityEvent was deprecated and replaced by
HangingBreakByEntityEvent. However, in the case of being struck by
lightning, only the deprecated event was being called. This fixes that so
that both the new and old events are called appropriately.
Bans require a name and UUID but our API only allows for a single string
identifier for a ban entry. Until this is sorted out go back to the old
name based setup since we can always get a UUID given a name.
Any new API here needs more thought, skulls require a name but OfflinePlayer
is not guaranteed to have one. There is a Mojang approved way to get a
complete profile from a name but not from a UUID so for now just pretend
this still only uses names.
The getEntries methods on these return player names instead of UUIDs.
As we need the UUIDs for our API we add a getValues method to get at
the data we need. To further ensure we get the most data possible we
also add a way to get at the stored GameProfile to ensure we always
have both the UUID and the name from the list.
In the 1.7.5 update the diff that called book edit events when editing
books was accidentally dropped because of nms changes within the file.
This commit re-adds the craftbukkit call to restore event behavior.
The server's check is for whether or not a player can pass the whitelist
not just if the player is on it. That seems like more useful information
but the API has always just checked if they are on it so this commit
restores that.
When getting an OfflinePlayer by name we lookup their UUID and then
use that to fetch the OfflinePlayer. If the player has not played on
this server before the resulting OfflinePlayer will return null for
getName(). As this is unintuitive we now create the OfflinePlayer directly
using the profile we looked up and make OfflinePlayer prefer that data.
When working with inventories you regularly end up with different
Inventory objects that have the same underlying Minecraft inventory.
Currently, even those these point to the same thing, they are not
considered equal. With this commit comparing any Inventory object that
represents the same inventory will result in equals(Object) returning
true.
The method in EntityLiving to remove a potion effect was remapped during
the 1.7.5 update. The method invocation in CraftLivingEntity was not
updated to invoke the remapped method, which has led to a random method in
LivingEntity being called in its place.
This commit corrects the behavior of removePotionEffect by changing the
method to invoke the remapped method as opposed to EntityLiving#m(float).
Thanks to @gabizou for finding this issue.
Teleporting a player checks to see if the player is disconnected to
try to avoid creating ghost players. The check it uses, however, randomly
fails when the player is in the middle of joining the server. The check
that would work correctly here does not work correctly when the player
actually disconnects. To work around this we add a new flag which is
cleared on the first tick of the new player and assume they are connected
if the flag is set.
When VanillaCommandWrapper dispatches a command containing a
PlayerSelector wtih c>-1 (implicitly true for @a), it loops over the
selected players and exectures the command with each player. However, the
loop index is only incremented if the command fails. As a result, a
successful command is repeated on the same player indefinitely, locking up
the server. This commit fixes the issue by incrementing the loop index
regardless of whether the command succeeds, ensuring the command is only
executed once per player identified by the PlayerSelector.
If a plugin causes an entity to be removed from the world while the
world is ticking entities the ticking loop gets out of sync and fails due
to trying to go beyond the end of the entity array. To ensure this doesn't
happen we store the loop position as a field so we can fix it up in the
entity remove method just like the tick method does when it removes an
entity.
Previously the alias system would pass all arguments from the alias
to its command(s) implicitly. The new system requires arguments to be
explicitly passed so server owners can have more control over where and
how they are passed. To ensure this isn't a breaking change during the
migration from bukkit.yml to commands.yml we now add the $1- argument
to the alias commands to match the previous behavior.
Previously no implementation existed to access various additional
information fields regarding bans. This implementation expands on the
information outlined in the sister Bukkit commit to provide access to
the Minecraft implementation of the ban system.
This implementation of the banning API contains 2 new classes which
provide access to the internal workings of the built-in banning
system within Minecraft.
The CraftBanEntry class simply supports the representation of an internal
Minecraft BanEntry object. The data that may be modified within this new
object must be manually saved to the list contained within the
CraftBanEntry using it's save() method.
The CraftBanList class supports the representation of an internal
Minecraft BanList object through proxy methods. These methods do
validation on the passed objects where needed to ensure safe input to the
backed Minecraft objects.
These changes additionally re-route the existing banning API to the newer,
more detailed, system. Functionality prior to this change still behaves
as documented by the contract defined by the methods changed.
Books can now recieve more than one enchantment. As such, breaking out of
the loop after only 1 enchantment is applied is not the correct behavior.
This commit also reworks some of the logic surrounding the application of
enchantments to the item. By checking if the event doesn't add any
enchantments rather than if the original enchantments list is empty, the
application code is only reached if enchantments are applied, rendering
the "applied" boolean no longer necessary. The ItemStack's Item should only
be set once, so it is now set outside of the loop based upon whether or not
"flag" is true (with "flag" being whether or not the ItemStack's Item is a
book).
Hanging entities are placed into the entity tracker and updates are sent
out to clients for the initial placement. Thereafter data watchers are
configured to monitor the item inside the frame. However, if the
direction the ItemFrame facing changes the entity tracker will not send
out updates.
This commit removes and recreates the ItemFrame entity in the same way
that was already done for Painting entities. This causes clients to
be updated appropriately.
Previously any entities spawned through dispensers (monster eggs) or
by nether portals were given the incorrect SpawnReason of SPAWNER_EGG.
This made it impossible to distinguish what exactly happened in regards
to the creature being spawned.
A method in ItemMonsterEgg has been added to further fine tune reasons
for spawning creatures. This permits the DISPENSE_EGG reason to be used
correctly and accuratly as well as the NETHER_PORTAL reason due to how
BlockPortal spawns the mobs.
The redirected method, a(World, int, double, double, double), is still
called by the ItemMonsterEgg itself and therefore uses the default reason
of SPAWNER_EGG. This does not change previous behaviour.
Prior to this commit, a player disconnected during a respawn event would
remain in memory. This causes a ghosting issue of players in the slot
count and player list, as well as a reference leak.
This commit avoids re-adding the player to the player list (and world) if
they are disconnected. This ensures that the remainder of the respawn
logic is completed as well as ensuring a duplicate player is not left on
the server.
This commit also saves the player's file at the end of the method if they
have been disconnected to ensure that their next login is accurate to the
respawn event's actions. A player that was revived and disconnected will
reconnect as revived.
Currently we use the async chunk loading system only when players trigger
chunk loading. If a chunk is loaded for any other reason it goes through
a separate codepath. This means if a player has trigged a chunk load and
before the chunk loads something else wants the same chunk we will load it
twice and throw away the second result. With this change we instead use
the sync processing feature of the AsynchronousExecutor to load the chunk
which will pull it out of the queue if it was already queued to load. This
means we only ever load a chunk once. Because chunk generation is not
thread safe we still fallback to the vanilla chunk loading system if the
chunk does not currently exist.
Previously we attempted to call interact events in cases that were missing
by modifying the arm swing logic. This, however, was too broad and started
triggering events in cases we already covered leading to duplicates. Since
the only case we can handle cleanly and the primary point of the previous
fix was fluids we now instead simply treat fluids as air for this check.
This also ensures we do not get duplicate events when the player is in a
fluid and hits a normal block, unlike the previous change.
This reverts commit 68b702f7 and replaces it with a better fix.
The block obtained and stored within the block object higher up does not
reflect the block at the location being hit, rather it is the air block
the arrow was previously in. Thusly when the variable is used to check
if the arrow is still in the block, it fails.
Because EntityFireball.setDirection() adds a random offset to passed
parameters, it is not appropriate for use in an API method. As such,
the values need to be directly set to remain accurate.
Previously, trying to launch a ThrownExpBottle or Fish projectile would
result in an IllegalArgumentException. This commit adds support for both
ThrownExpBottle and Fish, which means that all current projectiles are
now properly supported by this method.
Previously, if an error occurred during CraftServer initialization before the
logger was instantiated, it would cause an NPE and the server would never
finish loading properly. By instantiating the logger before attempting to
load anything else in CraftServer, we ensure that a logger will always be
available in the case of any errors.
In 1.7, Minecraft changed Weighted Pressure Plates to allow players and
entities to interact with them, rather than simply changing redstone signal
based on the number of items on the pressure plate. This commit adds calls to
PlayerInteractEvent or EntityInteractEvent for every entity that steps on the
plate.
ItemStacks do not stack if one has null for a tag, while the other has an
empty tag. In CraftItemStack, if you set an item to an empty ItemMeta, it
will create an empty tag for the internal ItemStack.
This changes the setItemMeta function to check for empty meta, and then
use null for the tag instead of an empty NBTTagCompound.
The method being called was renamed during the 1.4.2 update process
but the function call was not replaced accordingly, leading to a
missed diff from 314051580a0a8e4745d3a539f232b552916eb302.
Damage caused by explosions will return null for the event as of
6588d6f72bbca74bf150de65593ac575b846111b. As such, a null check is
now necessary when handling non-living entity damage events.
When falling back to vanilla recipes in the iteration of recipes,
a check is necessary to ensure that vanilla recipes are present.
RecipeIterator has been modified to account for the multi-map setup.
In commit f94b7af8 I delay removing the block until after running the
block's cleanup code to avoid errors. However, this causes problems of
its own due to blocks not being written with this in mind. To avoid blocks
getting recursively removed we now only delay removing containers since
they are the only ones we had problems with to begin with.
When setting a block the server sets the new block ID, calls the cleanup
on the old block, then calls the placement logic for the new block. This
would normally work correctly but we have logic to prevent errors that is
causing one here. When trying to clean up the old block we notice the block
ID has changed and try to fix things, this causes the cleanup logic to
fail. To ensure cleanup happens correctly we now do all the cleanup before
changing the block which avoids triggering the fixup code.
Due to vanilla blanket comparing data values, and the unspecified
order of hashmap iterators, we need to run through custom recipes
first, and therefore separately, to ensure that they are actually
used. By not adding the custom results to the experience table, we do
not override the experience gains from vanilla smelting recipes.
Setting a horse's passenger to a non-living entity will cause a
server crash when the horse ticks, we need to check that it is
a living entity before casting, and skip otherwise.
With the update in 1.7 that improved the server ping, it was made to
include a long version string for CraftBukkit. This value is too long
for proper display so we now send a shortened string consisting of
the server implementation and the minecraft version.
When we first added the reach limiter in CraftBukkit there was no
difference between how far the client could reach in vanilla while in
Survival or Creative. At some point in Minecraft's cycle Creative was
given a block extra to work with and our protection was not updated to
account for this. We need to respect the possibility of different game
modes in Minecraft providing the client with varying reach distances.
Due to an incorrect mapping of this method to a friendly name, we're
unfortunately calling the wrong method within EntityPlayer.reset() to
reset attributes. Instead of what we've mapped as "removeAllEffects", we
should be calling EntityLiving.aP(). This mapping should be corrected in
the next naming version.
In the CraftBlockState implementation, updating the blockstate onto
a block will force the block state data value onto the block.
Unlike vanilla which relied on block data being set when the type
changed, we must instead explicitely set the data in the blockstate.
Minecraft now uses resource packs instead of texture packs, which broke
the setTexturePack method, as the client no longer listens on the MC|TPack
channel.
This commit fixes the issue by adding in a setResourcePack method, and by
deprecating setTexturePack and rewriting it to call the newly added
setResourcePack. In order to simplify the method and prevent this from
happening in the future, setResourcePack calls EntityPlayer.a(String) to use
the same logic as minecraft when sending resource packs.
In Minecraft 1.7, URL processing was removed from the client while the
server gained the ability to designate a URL to be launched in response to
clicking text. However, this functionality is not implemented in the
vanilla server. This commit adds that functionality to messages sent to
the client, processing URLs as clickable.
Additionally, char array iteration is replaced with regex.
When growing trees we use a BlockChangeDelegate which queues up the block
changes so plugins can modify/block/log tree growing. However, we always
check the actual world when checking for existing blocks. This means when
the tree growing code checks to see if putting a leaf in a block is valid
it may incorrectly overwrite a log block that should exist in that
location. To ensure trees grow correctly we now check the delegate itself
for blocks that match the queried location before checking the world.
Commit c576054539790bdeb35285f62863d74b48c0782d removed the chunklist
collection stored in ChunkProviderServer, however it has been partially
restored in some places by 7e1ac0a77129b169704c1e222ff2deb3ab6cd2d2. As
not all references to this were restored, this has caused the chunklist
and chunks collections to become out of sync, resulting in a memory leak.
This commit removes chunklist from ChunkProviderServer again.
When ItemDye is used to place a Cocoa Block, the postPlace() method
should not be called, as data is handled within the ItemDye class.
However, if Cocoa is placed via its block item, postPlace() should
still be called to mirror vanilla behavior.
Due to changes in the generation of trees, the name of the class responsible
for the generation of jungle trees has changed from WorldGenMegaTree to
WorldGenJungleTree. As such, references to WorldGenMegaTree need to be
updated to WorldGenJungleTree to generate the correct type of tree.
Pulled from PR #1277
Several sounds were renamed in Minecraft 1.7, and have been updated
accordingly. Additionally, two sounds, HURT and BREATH, were removed from
Minecraft.
For Cocoa Blocks, Block.getDropType() returns the item form of the Cocoa
block, rather than the Cocoa Bean item. Because of this, Cocoa blocks need
to have explicit handling in order to return the proper drop contents.
Previously, due to the way that death events were called, Blazes only
fired death events when they dropped loot. This change fixes that,
enabling death events for Blazes whenever they die, regardless of loot
drops.
EnderDragons did not call an EntityTargetEvent when they
were targeting random players in the End. This commit
adds that event call into the targeting code.
Explosions directly caused by LivingEntities, such as creepers and tnt lit
by players, have their EntityDamageEvent explicitely handled within
the Explosion class. In order to prevent double events when damage
is handled for other DamageSources, we need return null for explosion
based damage sources.
The EntityLiving dealDamage method will not call an event for the
entity damage caused by an explosion without an associated
entity cause, therefore, the explosion caused by EnderCrystals
needs to be explicitely handled within the EnderDragon class.
Bukkits Visibility API should prevent players from seeing fall particles
of players that they cannot see. This commit alters the handling to
provide an EntityPlayer argument that is later used to determine if they
are visible.
We do ray tracing on arm swings to filter out swings that hit blocks since
punching blocks has its own event handling. However, some blocks cannot
be punched so the air interact type is still valid for them. Luckily
these blocks all have a means to query them so add an additional check
for this and don't fail the check for them.
This changes the logic for furnace smelt event to consider a result of
null (read: air / invalid), which will still consume an item. It also
properly considers item meta in the result, instead of only checking the
item data value.
Log4j takes a long time to load on startup. Before it loads, the server
appears to have frozen as there is no output until after. We now print
a loading message before this happens to let the user know the server
is actually working.
When pistons push/pull blocks they call Entity.move(float, float) to move
entities out of their path. For hanging entities this code path makes them
simply die and drop as an item. We now call an event in this scenario so
plugins can control this behavior.
Some types of damage are handled specially so do not end up returning an
event in handleEntityDamageEvent. To ensure we don't have problems with
these we need to check for them and simply ignore them, as they've been
handled already.
Calling this event allows plugins to react to the situation by simply
handling a normal damage event, possibly using existing code to
handle other entity damage.
Pulled from PR #1279
A vanilla server does a series of checks for the client black-listing
certain chat types (commands or chat). This change changes a CB
whitelist to the vanilla blacklist behavior.
This implements the detonate method from bukkit by setting the fuse
timer to 0. This makes a firework explode using the normal codepath,
but without waiting for the fuse.
The validation check in CraftMapView.render(CraftPlayer) filters out any
values less than 0. As of Minecraft 1.7, -128 through -113 are valid colors,
so filtering them out prevents some of the new colors from being sent.
This commit fixes the issue by adjusting the validation check to include
any values less than or equal to -113. As the minimum value for a byte is
-128, no invalid colors are included.
WorldGenerator setType and setTypeAndData have their arguments changed to
add in support for CraftBlockChangeDelegate, which changes the method
signature. This change in the method signature breaks any WorldGenerators
that aren't modified to use CraftBlockChangeDelegate.
This commit fixes the issue by readding the old method and maintaining the
CraftBlockChangeDelegate method. This makes it so that there is a
compatible method for both CraftBlockChangeDelegate WorldGenerators and
unmodified WorldGenerators.
Additionally, this commit reduces and corrects the diffs in
WorldGenerator, moving the fix for layering violations to
CraftBlockChangeDelegate.
A Block object is now passed in place of the previous id value, so the
obfuscated name for all subsequent arguments was shifted. As such,
BlockCanBuildEvent was using the incorrect values for both the material
and the location of the event.
This is corrected by swapping the values into the correct order and
providing an id based upon the Block passed into the method.
CraftBukkit modifies the IRecipe interface, adding new methods, so all
classes that implement IRecipe need to be imported and modified to add the
new methods.
Extending ShapelessRecipes implements the added methods and allows
RecipeBookClone to work with the Recipes API in a way that is consistent
with similar recipes, even if the recipe information present in the API
isn't technically correct.
Adding or removing operators was mistakenly using a loose player lookup
method, which would cause a permission refreshes on an online player whos
name starts with the name of the (offline) opped player.
Add/Remove op operations are exact name match only and the permission
refresh will behave the same way.
Both log4j and our own jline/jansi initialization attempt to catch
errors caused by jansi's use of native libraries. However both of them use
the Exception type which does not catch all errors. On Windows Server 2008
R2 Enterprise without installing extra software the required C++ libraries
are not available which causes an error that does not extend Exception. To
ensure we catch all errors I've changed both of these to catch Throwable
instead which gets us a working console minus jansi functionality.
l previously was the block id, however Minecraft's refactoring means that
the method is now passed a Block reference rather than the id. l is now
the data value of the block, so the block retrieved with that value is not
the correct block to be testing.
Something the log4j ConsoleAppender does makes the console work correctly
on Windows. After trying to pull pieces of it out and run them manually
I decided to just put the appender back. We now once again start with the
ConsoleAppender then remove it immediately after starting.
WorldMapCollection stores scoreboard, map (item), structure, and
village information. Scoreboards are explicitly handled globally,
while villages and structures are erroneously shared.
This commit separates the WorldMapCollections to not be shared among
custom worlds. Maps are special-cased to maintain the previous shared
behavior.
This change will print a warning when a plugin induces a forced save. A
player or console forcing a save (via a command) is ignored for purposes
of printing a warning.
When Minecraft first introduced an auto-save feature, we
were taken by surprise by how much of an impact it actually had on the performance
of the server. After investigating the potential causes of the significant
slow-downs we saw at the time, we came to the conclusion that it was a
combination of the auto-save interval being incredibly frequent and
servers already having an auto-save solution that was conflicting with the
newly added built-in one.
Since we noticed that most servers already had their own auto-save
solution, we decided to completely disable the built in auto-save by
default. In hindsight, however, we were so happy that we discovered and
squashed the cause of the performance issues that we forgot to consider
the future and, as a result, some servers have unfortunately been caught
by surprise when they ran their servers without any auto-save plugins.
Without the auto-save plugin conflict, however, Minecraft's default save
interval of 45 seconds is not suitable for the types of servers that run
Bukkit, to the point where it was negatively impacting performance. As
such, we've decided to re-enable the built in auto-save at an interval of
5 minutes for newly created servers.
The WorldMapCollection object for SecondaryWorldServers(Nether, End) is
shared with the main world, so saving it again for each SecondaryWorldServer
is redundant.
This commit removes the redundant call by checking if the WorldServer is an
instanceof SecondaryWorldServer before invoking worldMaps.a().
The recent Minecraft update rendered the
e20e50f85083dc53cb5456254bcf5781ef750daa fix incorrect by adding a
compound name to the base tag in some code. This fix changes all uses
of tag changes to explicitly use a name.
When a "uid.dat" file is corrupt (empty or <16 bytes), WorldNBTStorage
will silently fail to read and return null. Non-null behavior is
expected everywhere that this value is used.
This change will force a random UUID when the previous UUID cannot be
read, and getUUID to no longer silently ignore read/write exceptions.
This change adds the location and a more specific message to the
IllegalArgumentException that gets thrown when a hanging entity is being
spawned in a location that it cannot survive.
Opening a hopper inventory created by Server.createInventory will
currently have no effect as proper handling code is missing in
CraftEntityHuman for hopper inventories that aren't associated with a tile
entity or minecart. Initialization logic for hoppers is also missing from
CraftContainer, which is necessary for the opening of custom hopper
inventories.
This commit fixes the two aforementioned by adding proper handling to
CraftHumanEntity for opening inventories not associated with a tile
entity, and by adding initialization logic for hoppers to CraftContainer.
Previously fires spawned by lightning strikes were in the wrong locations.
This introduced the possibility of having blocks replaced when they should
not be.
EntityLightning now uses the correct locations as defined to spawn the
fires when needed.
When an entity is being moved as the passenger of an entity from one
entity to another, a VehicleExitEvent is fired, but it is assumed that the
current entity is a Vehicle. However, entities can be passengers of more than
just Vehicles, which causes a ClassCastException to be thrown.
This commit fixes the issue by checking that the current entity's vehicle's
bukkitEntity is an instance of Vehicle before casting it to Vehicle.
Prior to this change when a plugin called Player.hasLineOfSite() the
method would always return false because EntityHuman does not extend
EntityInsentient. This commit changes that by explicitly checking for
line of sight between two entities and returning that value.
Maven paths that include spaces (and possible other characters) get
improperly translated when using a file handle from a URL. This changes
the unit test to open a stream directly from the URL, providing proper
file resolution on multiple platforms.
This commit removes chat wrapping. It is no longer needed, as clients
properly render lines with line breaks.
This commit also changes an outgoing chat message to use the vanilla
behavior for indicating a client cannot chat with commands-only setting.
If a plugin generates an exception when returning a world generator, the
server will crash. This change adds a try-catch block to keep the server
from crashing on plugin defined world generators.
Custom inventories currently do not validate the titles provided. Null values
cause NPEs when writing packets. Values longer than 32 characters
disconnect clients.
This change throws and IllegalArgumentException for null titles or titles
longer than 32 characters.
The unleash event is only called for animals that are sitting - ones that
receive no movement vector. This adds the missing event call for
non-sitting animals.
When only considering trackers from player perspective, attach entity
packet could be sent before a packet for a respective vehicle is in view
and will, in turn, be ignored.
This adds another notification when the vehicle comes into view to cover
all cases.
A method has been added to Player which allows the server to send a sound string to the client. Assuming the client has the specified sound, it will be played. This is needed by the implementation of the /playsound command.
Items that cause entities to change state, including tags, chest, and
leashes, do not update the client properly following the firing of
PlayerInteractEntityEvent. This change makes the item checks occur
before the event fires, to concur with the client's assumptions.
This commit implements the ability to set the scale of hearts that the
client renders. When the Packet44UpdateAttributes packet is sent, the
max health attribute is replaced with a scaled version, to preserve the
scaled health illusion clientside.
In order to accurately display the scaled health for players, a true
health is stored within CraftPlayer, and the datawatcher now stores the
scaled health. The getHealth() method for players still returns their
true health.
Changed setHealth() within EntityLiving to appropriately handle health
for instances of EntityPlayer. Inlined a call to
setHealth(getMaxHealth()) within the EntityLiving constructor to work
around CraftEntity instantiation.
Additionally fixes the health values sent when eating food within
FoodMetaData and ItemFood, which previously sent the unscaled health;
this commit alters them to send the properly scaled health.
Additionally fixes BUKKIT-4535, BUKKIT-4536, and BUKKIT-4127
This changes livingEntity.addPotionEffect(PotionEffect, boolean) to
construct the MobEffect using the constructor that includes the ambient
setting as supplied by the PotionEffect
This also changes livingEntity.getActivePotionEffects() to construct the
PotionEffects using the ambient setting supplied by the MobEffects.
This change makes it so that EntityHuman#setPassengerOf(Entity) invokes
its parent method when leaving vehicles so that VehicleExitEvent is fired
for players leaving vehicles.
This change also fixes BUKKIT-2110, making it so VehicleExitEvent
correctly handles cancellation. The implementation of VehicleExitEvent
completely ignored the cancellation state of the event, making it so that
cancelling the event had no effect. Cancelling a VehicleExitEvent now
causes the entity to remain inside of the vehicle, with no visual stutter.
API has been added to interface with Horses and to modify their inventories. Horse entities will now be recognized with the type EntityType.HORSE, and will no longer be UNKNOWN.
HorseJumpEvent, EntityDamageEvent, and EntityTameEvent are all correctly fired for horses.
This commit fixes BUKKIT-4393.
Cancelling InventoryDragEvent causes the placed items to be lost. This is
because the cursor is set to the result prior to the event taking place,
so the items are removed from the cursor. When the event is cancelled, the
items removed from the cursor aren't placed in the inventory, and are just
lost.
This change sets the cursor back to the original cursor when the event is
cancelled.
Cancelling an InventoryClickEvent for a single click causes the click not
to be processed by the clicked inventory. The server then doesn't
correctly identify their second click as being a double click, causing an
inconsistency between what the Player believes the inventory to be and
what the server believes the inventory to be.
This change forces an updateInventory call whenever an InventoryClickEvent
whose action is NOTHING is cancelled. Both clicks are considered
PICKUP_ALL, so updating the inventory after the second click fixes any
inconsistencies that could arise between the client and the server.
Currently, the method used for calculating the damage of zombies is scaled
to their health, but it uses the default max health rather than the real
max health value. If zombies have more health than the default max health
value, the amount of damage they deal becomes negative.
This is caused by EntityZombie.getMaxHealth() returning a hardcoded value of
20, which is the vanilla max health for zombies. Rather than using this value
when calculating zombie damage, the call is changed to instead use
((CraftLivingEntity) this.bukkitEntity).getMaxHealth(). This uses the true
maximum health of the Entity. "this.maxHealth" could be used instead of the
aforementioned method, however that creates a very unclear diff, and a
confusing change.
When a Player drops an ItemStack while in creative mode by placing it outside
of their inventory window, the slot number in the packet is -1. The check
that was added to avoid throwing InventoryCreativeEvent excessively didn't
take this into account, and would cause an ArrayIndexOutOfBoundsException to
be thrown when attempting to get the slot specified by the packet.
This change shorts the invocation of player.defaultContainer.getSlot(
packet107setcreativeslot.b) to only occur if the slot id is within the range
of the Inventory. This prevents attempting to get the slot from a location
that is actually outside of the Inventory.
This commit brings the InventoryClickEvent up to date with the new Minecraft
changes in 1.5.
InventoryDragEvent (thanks to @YLivay for his PR) is added to represent the
new "dragging" or "painting" functionality, where if you hold an itemstack and
click-drag over several slots, the items will be split evenly (left click) or
1 each (right click).
The ClickType enum is used to represent what the client did to trigger the
event.
The InventoryAction enum is reserved for future expansion, but will be used to
indicate the approximate result of the action.
Additionally, handling of creative inventory editing is improved with the new
InventoryCreativeEvent, and handling of numberkey presses is also improved
within InventoryClickEvent and CraftItemEvent.
Also, cancelling a creative click now displays properly on the client.
Adresses BUKKIT-3692, BUKKIT-4035, BUKKIT-3859 (new 1.5 events),
BUKKIT-2659, BUKKIT-3043, BUKKIT-2659, and BUKKIT-2897 (creative click events).
We only go through event creation and calling when dispensing filled buckets
if the bucket is able to place its liquid. However, the check for this is
incorrect so the event is not called when a block liquids can destroy is
in front of the dispenser. This commit fixes the check to match the checks
vanilla does when actually using the bucket.
The CraftBlock class is setting bit 0x4 of the update flag when bit 0x2
should in fact be set here. Bit 0x2 means "do updates"; bit 0x4 means
"don't do updates if the world is static, even when bit 0x2 is set".
Minecraft 1.5.2 changed mob spawning by ignoring persistent mobs from the
mob count. In CraftBukkit all mobs that previously used a separate hard
coded persistence system were ported to instead use this one. This causes
all animals to be persistent by default and thus never be counted. To
correct this issue we consider if the mob would be considered persistent
in the hard coded system as well when deciding if a mob should count.
Currently there are several cases where a player will have their inventory
screen closed client side but we will not call an event. To correct this
we call the event when the server is the cause of the inventory closing
instead of just when the client is the cause. We also ensure the server is
closing the inventory reliably so we get the events. Additionally this
commit also calls the event when a player disconnects which will handle
kicks, quits, and server shutdown.
As an optimization we don't do any movement processing on entities that
have not moved. However, players in minecarts trigger this condition when
the minecart is moving on its own. This causes issues with things that rely
on player collision like tripwires. To correct this and any future related
issues we always handle movement for passengers and their vehicles even
if one of the two hasn't moved since they are linked.
When converting things in Minecraft to use wall time instead of ticks I
realized we'd run into integer division rounding issues and could have
updates that end up counting as zero ticks. To compensate for this the
code ensures we always process at least one tick. However, every time we
end up with zero ticks the next time we have an extra tick due to rounding
the other way with the leftovers. This means we are going far too fast and
should not have this at least one tick logic at all.
On top of this some potions rely on the number of ticks they run and not
just the amount of time they last and so potions were put back to running
with ticks entirely.
If a chunk has somehow managed to save with arrays that are not 4096
entries long when reading them again we will get exceptions. Checking the
array length and resizing if needed is cheap so we should do this to help
avoid crashing servers due to this error.
When a chunk is being loaded the server checks to ensure the chunk's idea
of where it is located matches where it was located in the region file. If
these two values do not match the chunk's idea of its position is updated
and the chunk is reloaded. In vanilla minecraft this loading involves the
chunk's tile entities as well. With the change to loading player chunks
asynchronously we split loading tile entities to a separate step that takes
place after this check. Because of this tile entities are loaded with
invalid locations that result in trying to fetch block data from negative
or too large positions in the chunk's internal block storage arrays.
Because loading the tile entities is not thread safe we cannot return to
vanilla behavior here. Instead when we detect a misplaced chunk we just
edit the NBT data for the chunk to relocate the tile entities. This results
in them moving correctly with the chunk without having to actually load
them first.
If a hopper is unable to perform any action during a tick it attempts to do
so every tick from then on. Once it is able to do so it then sets a delay
before attempting to do something again. To avoid excessive CPU usage for
hoppers sitting idle we now apply this delay regardless of the success of
the action.
When using the new feature in 1.5 to drop the item in any highlighted slot,
the anvil result slot does not apply the full anvil calculation that picking
up the item does, including the experience calculation.
Currently furnace smelting and the item pickup delay timer use wall time
(aka actual time passed) to emulate a constant tick rate so run at the
same speed regardless of the server's actual tick rate. There are several
other places this makes sense so this commit converts them.
The item despawn timer is converted so now always takes 5 minutes. Users
know this 5 minute number well so keeping this constant helps to avoid
confusion. This also helps alleviate lag because if a large number of item
drops is the reason your server is running slowly having them stay around
longer just means your server is slow longer.
Potion brewing and the zombie villager conversion timer are now constant.
These match the furnace criteria of being useful for hiding lag and not
having a detrimental effect on gameplay.
Potion effects are now also using wall time. The client is told about effect
times in ticks and displays this information to the user as minutes and
seconds assuming a solid 20 ticks per second. The server does have
code for updating the client with the current time remaining to help
avoid skew due to differing tick rates but making this a constant makes
sense due to this display.
Add a check to avoid doing movement work if an entity doesn't move. This
usually will not ever happen in the current server but is useful when it
does and will be more useful in the future.
Only process mob on mob (non-player) collisions every other tick. Players
tend to pack a lot of mobs into a small space (sheep farm, mob grinder, etc)
so they do a lot of work processing collisions. To help alleviate some of
this we only run these calculations every other tick. This has no visible
effect on the client but can be a huge win on the server depending on
circumstances.
Use generic entity inWater checking for squids. Squids have their own logic
currently for determining if they are in water. This check is almost
identical to the generic entity checking which is run anyway. To avoid
doing duplicate work we just remove the squid version. This does not
have any noticeable effect on gameplay since the checks are so similar.
Use HashSet for tile entities instead of ArrayList. Using an ArrayList for
storing tile entities in a world means we have very expensive inserts and
removes that aren't at the end of the array due to the array copy this
causes. This is most noticeable during chunk unload when a large number of
tile entities are removed from the world at once. Using a HashSet here uses
a little more memory but is O(1) for all operations so removes this
bottleneck.
When a player comes into range of an entity in a vehicle they will often be
sent the spawn packet for the rider before receiving one for the vehicle.
This causes the attachment packet to fail client side because it attempts
to attach the rider to a vehicle that doesn't exist on the client. To
correct this we account for both possible orderings and send the
attachment packet appropriately.
Vanilla also sends an new attach packet every 60 ticks even if the vehicle
has not changed. As this packet is a toggle this resulting in players
teleporting around randomly. Since we handle attachments properly now we
simply revert this section to use the 1.4 logic.
When looking up tile entities for a chunk to send to a player we currently
loop through every tile entity in the world checking if it is within the
bounds of the relevant chunk. Instead of doing this we can just use the
tile entities list stored in the chunk to avoid this costly searching.
As a further optimization, we also modify the generic range-based lookup
to use chunks as well. For most lookups this will give a smaller search
pool which will result in faster lookups.
Thanks to @mikeprimm for the idea and most of the implementation.
In certain scenarios a boat can be killed multiple ways in a single tick.
Due to improper guards this can cause the death code to run multiple times
creating item drops. To correct this we insert the appropriate death check.
Two connection status checks were added to setting a scoreboard for a
player. The first checks to see if a player has logged in yet, which
implicates the ability to receive packets. The second checks to affirm
that the CraftPlayer reference is still to a logged in player; setting
it while not logged in would maintain a stale player reference in the
scoreboard manager.
The method's return value was being incorrectly calculated from the
perspective of this.canHurt(that), where it's actually used from the
this.canBeHurtBy(that) perspective.
The method getTeam gets the team from name of, as opposed to getting the
team a player belongs to.
This also addresses BUKKIT-4002 and partially BUKKIT-4044
When a world is created using our API, it does not use secondary world
server and will maintain a reference to its own scoreboard. In vanilla,
this is not an issue as there is only ever one world.
Similarly to maps, an overwrite to the scoreboard reference has been
added for when another world has been created.
This should also address BUKKIT-3982 and BUKKIT-3985
In commit 7710efc5f9 we corrected the handling of large chests as the
destination for hoppers moving items but did not apply the same fix for
large chests being the source or for droppers. This commit updates these
to have the same fix.
This implementation facilitates the correspondence of the Bukkit Scoreboard
API to the internal minecraft implementation.
When the first scoreboard is loaded, the scoreboard manager will be created.
It uses the newly added WeakCollection for handling plugin scoreboard
references to update the respective objectives. When a scoreboard contains no
more active references, it should be garbage collected.
An active reference can be held by a still registered objective, team, and
transitively a score for a still registered objective. An internal reference
will also be kept if a player's specific scoreboard has been set, and will
remain persistent until that player logs out.
A player's specific scoreboard becomes the scoreboard used when determining
team structure for the player's attacking damage and the player's vision.
This class is designed to be an invisible layer between a normal collection,
and one that silently loses entries because they are only weakly referencable.
Some operations have additional overhead to be semantically correct, but it
maintains the equals contract for all entries, as opposed to identity.
It does not support the equals or hash code method as it cannot easily have
the transitive and commutative properties.
This adds calls to BlockRedstoneEvent for the new daylight sensor and
trapped chest blocks. Note that the redstone level for trapped chests
cannot be modified, as it is based on the number of players currently
viewing the chest's inventory.
When an array of an inventory's contents is requested, we loop through the contents of the NMS inventory's ItemStacks in order to return Bukkit ItemStacks that can be used through the API. However, the NMS ItemStack can, in some cases, be larger than the physical size of the inventory. Using the size of the NMS array as a limit on the loop that follows can result in an ArrayIndexOutOfBoundsException because the Bukkit array's length is the actual size of the inventory, and thus will be smaller.
With this commit we use the smaller of the two arrays' length as the limit in the loop, thus eliminating the possibility that the smaller array will be asked for an index higher than its length.
When a block placement happens we currently update physics on the
attempted placement and update again if the placement is cancelled.
To correct the first one we simply set the block without applying
physics. To correct the second we have to add a new method to
BlockState that lets us update without applying physics and use
this method method when putting the block back.
Without this check, any non-null reference to a plugin is considered
'valid' for registering a task in the scheduler. This is obviously
unintentional behavior and has been changed to throw an
IllegalPluginAccessException. It is now consistent with the
SimplePluginManager event registration contract.
This in affect also addresses BUKKIT-3950 for uninitialized plugin
references (ones without a description).
Large chests work in a different fashion as they are a combination of
two other inventories. This causes their getOwner method to always return
null as their is no correct return. To compensate for this for the hopper
events we special case them to use their CraftBukkit counterpart that has
the information we need for the event.
When a splash potion has no applicable effects we currently do not call
PotionSplashEvent. This means plugins are unable to make custom
potions with reliable splash handling as they have to relicate the
functionality themselves.
With this commit we simply make the event fire regardless of the effects
on the potion.
When cloning an item, all references are copied to the new item. For
collections, this makes internal changes become visible in both the old and
new items.
In CraftMetaItem, clone was not making copies of the appropriate collections
and has been fixed for non-null values.
In CraftMetaEnchantedBook and CraftMetaPotion, clone was using possible empty
collection references and has been changed to explicitly null-check instead.
I should try to compile before I say "this change is okay".
I should try to compile before I say "this change is okay".
I should try to compile before I say "this change is okay".
I should try to compile before I say "this change is okay".
for i in range(100)
This causes the server to generate PrepareItemEnchantEvent even in the
case that an item is already enchanted or otherwise would normally not
be enchantable.
The client resets all formatting after a color code is received, but currently the ANSI codes do not, and so the console does not accurately reflect the appearance of the formatted text. Instead, the ANSI color codes are now set to reset all text attributes.
Currently when dealing with physical interactions with pressure plates
and tripwires we immediately block their activation as soon as a single
entity involved has their event cancelled. We also fire events whenever
an entity intersects the block a wooden button is in even if they aren't
actually pressing it. To correct this we move the button interaction to
the correct place and modify all three to only block the activation if
every entity is blocked from using them instead of just one of them.
CraftServer methods that implement the Server interface will throw an
IllegalArgumentException if a method cannot operate on a null input
and given a null pointer.
This causes methods to fail early and identify that a plugin is
responsible for passing in an invalid argument. This will only
change the exception thrown, if there originally was a thrown
exception. This helps with hunting down legitimate problems
with CraftBukkit.
If the server changes the weather it will set the per-player weather
variable and future changes will not apply. We should only set this
variable when a plugin is requesting per-player weather and not when
the server it doing it.
We used to fall Item.filterData() for this but that method is meant for
converting item data to block data during placement and does the wrong
thing for this case. Instead we just see if the item should have data and
if not set it to zero. We also have to filter wool data explicitly because
clients crash when given invalid wool data.
In Minecraft 1.5 saplings do not grow with a single use of bonemeal anymore.
Our code assumes they will and only takes away bonemeal from the player
when the tree grows successfully (not cancelled by a plugin). Instead we
now always remove a bonemeal even if a plugin is the reason a tree didn't
grow as this matches the vanilla logic more closely.
If a custom TravelAgent is used and returns null for findOrCreate method
a NullPointerException will occur.
Conflicts:
src/main/java/net/minecraft/server/PlayerList.java
Currently, CraftTravelAgent will call s() on the passed-in WorldServer in order to set DEFAULT. However, s() will always return null at this point, because WorldServer.P will still be null, as it is set after the constructor is called. Instead, we set CraftTravelAgent.DEFAULT to the instance that is being constructed.
Recent changes caused PlayerPortalEvent to suddenly return null
unexpectedly and could end up in NPEs resulting that did not before.
This commit addresses that situation by always ensuring a TravelAgent
instance is returned.
The TravelAgent for world 0 is returned arbitrarily in an effort to
compensate for plugins that are implementation dependent and expect some
form of a TravelAgent to be accessible in the event at all times.
Vanilla does not check for blocks in which the player could
suffocate when changing dimension, so portals will happily spawn
players in blocks when using a portal under certain
circumstances. However, we currently check for these instances
and move the player up until they will not suffocate. This means
that players can sometimes be taken to above the target portal,
making it seem as if a portal was not created. Instead, we now
disable this suffocation check when moveToWorld is called from
changeDimension, mirroring vanilla behavior more accurately.
Due to the having to generate new logic to avoid using the customized
PlayerConnection.moveToWorld, entities returning from The End were not
properly calculating their exit target. This commit corrects that
logic.
By having a single function to process BlockPlacement logic, we make
it so that there is consistent behavior throughout all BlockPlace
events. This should allow for easier troubleshooting and less diffs
in source.
This also fixes BUKKIT-3463 by including the correct coordinates that
were clicked to the event.
Also fixes: BUKKIT-3477 and BUKKIT-3488
Minecraft likes to double check that tile entities get set after they
are placed, however we didn't set tile entities until after our event
was called. This caused the world to have multiple tile entities in a
single block location; to fix this we now set tile entities before
the event.
When the skull BlockPlaceEvent was added it was made so the event
would be called after all the data has been set, however this is a
behavior change that is inconsistent with other BlockPlaceEvents.
Instead, if people wish to get the block data they should schedule
a task.
Relates to: BUKKIT-3438
When either of those settings are false, the worlds are not loaded and
therefore will not be targeted for portal exits. Existing worlds are
iterated directly to avoid defaulting to the first world if a direct
dimension match is not found.
Plugins must also specify exit from custom Bukkit worlds to comply with
original commit: https://github.com/Bukkit/CraftBukkit/commit/2dc2af0
This commit introduces a constant to clarify the dependency on the
CraftBukkit implementation of custom worlds having a dimension offset.
By returning the following value (7) we remove the need to special
case pistons in any way (other than the original purpose of this
check, which is to ensure pistons have valid data)
The previous logic was faulty since it lost the logic of "placing" the
block. It was also taking into account data that could have been
changed outside of the processing of this event, which is irrelevant
to the processing of this event.
The javadocs state that a null may be used to remove the currently
playing sound, however this causes a NullPointerException.
It also doesn't process registering the record correctly, along with
processing non-valid items.
By using return 0, we exit the loop prematurely preventing other
creature types from being spawned if one type is set to 0. By using
continue we move on to the other types and allow them to spawn
properly.
Fixes BUKKIT-3408, BUKKIT-3190, BUKKIT-3191, BUKKIT-3407
These changes relate mostly to semantical changes for serialization
contract, exception of changing the map scaling value from byte to boolean,
what it should have been in the first place. Appropriate unit tests were
added for CraftMapMeta, as they were missing.
This makes it so animals (tame or not) will sit properly and not move
around.
Wild animals that are sitting may override the sitting position if
they are attacking.
The 'tag' NBTTagCompound field of the ItemStack assumes that it is OK to
save a reference to an NBT supplied via load() and assumes it is OK to
supply a reference to the internal field during a save(). Neither is true,
as Chunk NBT structures are required to be read-only once created (due to
being written asynchronously off the server thread AND due to the potential
to be passed to a new Chunk if the same chunk is reloaded before the
writing of the NBT is completed by the File I/O thread). Keeping a live
reference to the NBT copy passed in, or to the NBT value passed back
during saving, creates serious thread safety issues which can result in
corrupted data being written to the world data files.
The specific issue here was uncovered by the recent change to use
setName("") on the ItemStack.tag object. When a chunk is being loaded
again before its save is completed, this results in name of the field
in the NBT being set to "". This causes it to be saved as "" instead
of "tag" resulting in it not being properly reloaded in the future which
results in the itemstack losing all of its metadata.
Teleportation should never be processed on dead entities. If you wish
to teleport an entity, do it on a living entity. If you wish to
teleport a player, set their respawn location in PlayerRespawnEvent.
This adds two settings to bukkit.yml, allowing activation and control of
two chunk garbage collection triggering conditions:
chunk-gc/period-in-ticks controls a periodic GC, run once every N ticks
(default is 600); chunk-gc/load-threshold causes the GC to run once
after every N calls to loadChunk() on a given world (this call is an API
call used by plugins, and is distinct from the path taken for routine
player movement-based loading). In both cases, setting to zero will
disable the given GC scheduling strategy.
In either case, the act of doing the GC is simply one of scanning the
loaded chunks, seeing which are NOT being used by one or more players
(due to view-distance) and which are not already queued for unload, and
queueing them for a normal unload. Ultimately, the unload is then
processed the same as if the chunk were unloaded due to leaving the
view-distance range of all players, so the impact on plugins should be
no different (and strategies such as handling the ChunkUnloadEvent in
order to prevent unload will still work).
The initial interval for the periodic GC is randomized on a per-world
basis, in order to avoid all world being GCed at the same time -
minimizing potential lag spikes.
With the persistence api introduced, pets did not have their
persistence flag updated to reflect their persistence. This caused
tame ocelots to not persist under specific conditions.
Slimes and wolves have health that can change based on certain
conditions. So we check if their max health should be updated, and if
it has been customized in any way.
We also scale the wolf's health for their tail
An ItemStack gains the tag name "tag" when the stack is serialized
to NBT, however items don't have a tag *until* they are serialized at
least once. So to solve this, we remove the tag name when loading the
NBT data.
Another problem with NBT are TagLists, when transferring tag lists
between the server and the client the names are lost, and so we
simply don't add a name to the tag.
If you cancel a BlockPlaceEvent for a sign the world is updated as if
the block was placed and then destroyed. To avoid this we set the block
without updating physics then apply the update after the event.
When unloading chunks we have a check to ensure we do not remove players
from the world due to the issues this would cause. However, our check
to see if the player is in this chunk is reversed and is in fact entirely
wrong. Even if the player isn't currently in this chunk we do not want
to remove them as that will still cause the same issues.
The key "direction" incorrectly mapped to variables that were already
set in the entity. In order to prevent loading incorrect data we
renamed "direction" to "power."
The player would have no permissions (other than their OP status)
when checked in the Quit event. This is because we removed permissions
before the event occurred. By calling it afterwards, we can persist
the data until the server finally removes the player.
In some situations, an async task could be cancelled with no tasks
pending. This means the finally {} block from run() never gets executed
properly on the last async task to have run, as it expected to be
executed again.
This fix takes the only spot that the task period is set to cancelled
and will check to see if the task should be purged from the runners
list.
Some meta functionality is refactored into common methods.
CraftItemStack uses the ItemMetaKey identifiers for enchantments.
Refactored unit test to include extra functionality; initially only
checking the presence of the DelegateDeserialization annotation.
The setTexturePack method causes the player's client to
download and switch to a texture pack specified by a URL.
Note: Players can disable server textures on their client, in which
case this API would not affect them.
With 1.4, entity sound tracking changed for the better.
Our previous method additions can now be removed.
All that's left is checking if the source can be seen
by the recipient of the sound packet. Thanks, Mojang!
The purpose of the isSimilar method was designed to consider all NBT
data, not solely enchantments, without the need to have exact stack
size matches. The respective methods in CraftInventory were still
comparing enchantments instead of the ItemMeta.
Changes some NPEs to IllegalArgumentExceptions for exception consistency.
Contains(ItemStack, int) correctly calculates number of ItemStacks.
Adds a containsAtLeast(ItemStack, int) for finding a combined amount of a
single similar ItemStack.
Makes some utility methods private to prevent ambiguity in use.
When a player triggers a chunk load via walking around or teleporting there
is no need to stop everything and get this chunk on the main thread. The
client is used to having to wait some time for this chunk and the server
doesn't immediately do anything with it except send it to the player. At
the same time chunk loading is the last major source of file IO that still
runs on the main thread.
These two facts make it possible to offload chunks loaded for this reason
to another thread. However, not all parts of chunk loading can happen off
the main thread. For this we use the new AsynchronousExecutor system to
split chunk loading in to three pieces. The first is loading data from
disk, decompressing it, and parsing it in to an NBT structure. The second
piece is creating entities and tile entities in the chunk and adding them
to the world, this is still done on the main thread. The third piece is
informing everyone who requested a chunk load that the load is finished.
For this we register callbacks and then run them on the main thread once
the previous two stages are finished.
There are still cases where a chunk is needed immediately and these will
still trigger chunk loading entirely on the main thread. The most obvious
case is plugins using the API to request a chunk load. We also must load
the chunk immediately when something in the world tries to access it. In
these cases we ignore any possibly pending or in progress chunk loading
that is happening asynchronously as we will have the chunk loaded by the
time they are finished.
The hope is that overall this system will result in less CPU time and
pauses due to blocking file IO on the main thread thus giving more
consistent performance. Testing so far has shown that this also speeds up
chunk loading client side although some of this is likely to be because
we are sending less chunks at once for the client to process.
Thanks for @ammaraskar for help with the implementation of this feature.
When a player has canPickUpLoot set to true the code for mob pickup is
triggerd which does not know how to deal with player inventory. Since
players have their own logic for picking up items we simply disable this
code for them.
The old flag for picking up loot was default to false, making existing players not able to pickup items. We now use this flag for Players, which gives us the problem we had in 48b46f83.
To fix this, we add an incremental flag that will be cross-examined to check if the data was saved before or after the flag level was introduced.
Addresses BUKKIT-3143
As an added feature, players defaulted to being able to not pick up items if the flag was false. However, since minecraft doesn't normally use the flag on players, the flag was always false.
Adds:
- Getting/Setting equipment
- getting/setting drop rates
- getting/setting ability to pick up items
-- As an added feature, players with this flag start off with a canceled PlayerPickupItemEvent
When a mob is marked with the persistent flag (animal or anything with
setRemoveWhenFarAway(false)) the entire block of code for checking if they
should be despawned is skipped. However, one part of this code updates the
mob state if a player is close enough to them. It turns out this state is
used by the AI system to decide if the mob should move around randomly or
not. To stop mobs from being frozen in place we now update this state if
the persistent flag is set as well.
Currently when a plugin wants to get the location of something it calls
getLocation() which returns a new Location object. In some scenarios this
can cause enough object creation/destruction churn to be a significant
overhead. For this cases we add a method that updates a provided Location
object so there is no object creation done. This allows well written code
to work on several locations with only a single Location object getting
created.
Providing a more efficient way to set a location was also looked at but
the current solution is the fastest we can provide. You are not required
to create a new Location object every time you want to set something's
location so, with proper design, you can set locations with only a single
Location object being created.
The old default for the persistent flag on mobs was false which was then
written out to their NBT data when they were saved. We now use this data
for all mobs, not just non-animal mobs. However, this means animals that
spawned before that change will now start despawning like monsters do.
To avoid this we add a new flag to the mob's saved data to mark if the
data was saved before or after we started using it and ignore it if it
was before.
As of 1.4 mobs have a flag to determine if they despawn when away from a
player or not. Unfortunately animals still use their own system to prevent
despawning instead of making use of this flag. This change modifies them
to use the new system (defaults to true) and to add API for plugins to adjust
this.
If the player is not in Creative (i.e. does not have the ability to
instantly build) we need to decrement the MonsterEgg item stack when used
on a breedable parent mob.
Stale player references will add a player back into the world when
teleporting them, causing a cascade of issues relating to ghost entities
and servers failing to stop.
On join we unconditionally add the player to the world they logged out in.
If a plugin teleports a player during PlayerJoinEvent in a way that adds
them to a world (cross-world teleport) we end up with one player in two
places. To avoid this we check to see if the player has changed worlds or
is already added to the world we have we skip adding them again.
This is a missed part of the original "[Bleeding] Use case from player data
for OfflinePlayer. Fixes BUKKIT-519" commit. It avoids doing (somewhat
expensive) lookups of player data to find the correct capitalization inside
getOfflinePlayers() as we're already loading their name from the player data
and thus have the correct capitalization.
When sending chunks to a player we use their writer thread to do chunk
compression to avoid blocking the main thread with this work. However,
after a teleport or respawn there are a large number of chunk packets to
process. This causes the thread to spend a long period handling compression
while we continue dumping more chunk packets on it to handle. The result of
this is a noticable delay in getting responses to commands and chat
immediately after teleporting.
Switching to a lower compression level reduces this load and makes our
behavior more like vanilla. We do, however, still give this thread more
work to do so there will likely still be some delay when comparing to
vanilla. The only way to avoid this would be to put chunk compression back
on the main thread and give everyone on the server a poorer experience
instead.
When an event changes the item to be dispensed we check to see if the new
item has special behavior for dispensing and if so pass it on to that
behavior handler. However, we are actually checking the old itemstack and
passing the new itemstack so this check fails.
If a plugin looks up a player that is offline they may not know the correct
capitalization for the name. In this case they're likely to get it wrong
and since we cache the result even after the player joins the server all
future request for an OfflinePlayer will return one with incorrect case.
When looking up a player who has played on the server before we can
get the correct case from the player data file saved by the server. If
the player has never played before this point we cannot do anything and
will still have the same issue but this is not a solvable problem.
If a player travels past 32,000,000 blocks on the X or Z coordinates they
will be kicked for having an illegal position. On kick their player data
is saved which includes their (illegal) position. This means on join they
are immediately kicked again for the same reason and are stuck. Instead of
kicking at all in this case just teleport the player back to their previous
position just like the moved wrongly check does.
In order to correctly handle disconnects for invalid chat we setup a
Waitable and pass it to the main thread then wait for it to be processed.
However, commands are also chat packets and they are already on the main
thread. In this case, waiting will deadlock the server so we should just
do a normal disconnect.
End portals can only be placed in the end during the dragon's death.
Attempts to place them outside of this window causes the block to remove
itself. However, we still create the tile entity for the portal which
leads to exceptions spamming the console about a tile entity existing
without the appropriate block. In these cases we should not place the tile
entity at all.
When invalid chat is detected we currently drop the connection with no
hint as to why as anything else is not allowed while we're off the main
thread. To give valid disconnect reasons and fire proper events instead
pass these off to the main thread and wait for it to process them.
If a plugin cancels a PlayerInteractEvent when left clicking a block the
client may have removed this block if they are in creative mode or if the
block breaks in a single hit. In this case, we need to update the client's
tile entity as well as telling it the block still exists.
Packet 51 is used to send updates about large changes to single chunks
and to remove chunks from the client when they get out of range. In the
first case a single packet object is created and queued for all relevant
players. With our current chunk compression scheme this means the first
player to have the packet processed will start the compression and get the
packet correctly but the rest will get garbage.
Since this packet never contains much data it is better to simply handle
compression of it on the main thread like vanilla does instead of putting in
locks and dealing with their overhead and complexity.
When a client tries to break a block it assumes it has done so unless told
otherwise by the server. This means the client also wipes out any tile
entity data it has for the block as well. We do not send this data when
updating the client so clients lose things like text on signs, skull type,
etc when they aren't allowed to break the block.
Skulls need their tile entity in order to create an item correctly when
broken unlike every other block. Instead of sprinkling special cases all
over the code just override dropNaturally for skulls to read from their
tile entity and make sure everything that wants to drop them calls this
method before removing the block. There is only one case where this wasn't
already true so we end up with much less special casing.
Sheep now use the crafting system when breeding to determine what color
their baby should be. This triggers an event but the event wants the
crafting inventory to have a result slot which sheep do not have. This
event could be useful for plugins to control the output of sheep breeding
so instead of disabling it we add a result slot so the event fires without
issue.
If a chunk gets a block added to it that requires the extended block id
nibble array (block id greater than 255) the array is created and saved
with the chunk. When the blocks are verified to make sure they exist these
entries are erased but the extended block id array is not. This causes the
server and client to disagree about how much data a chunk has which makes
the client crash while trying to load the chunk for rendering.
To resolve these issues we now clear the extended block id array on chunk
load if there is no valid data in it.
When a block creates a falling entity the block is not immediately removed
from the world. Instead, the falling entity is responsible for removing it
but only if the block still exists. Due to certain piston mechanics it is
possible to move the block before this check happens and thus the block is
not removed. This should be fine as the entity will kill itself in this
situation. However, the code does not stop here and continues running the
rest of the entity logic which includes either placing a block in the world
or placing a block item in the world depending on the circumstances.
If a block is air we return immediately so miss the cleanup work that would
normally happen in this case in vanilla. This causes us to get in to a
situation where, due to odd packet sending from the client, we never
properly stop an attempt by the client to break a block and thus it
eventually breaks.
We also use our own variable for block damage and never sync it up with the
vanilla one so damage reporting to other clients is not always correct.
The static assertions are not normally evaluated in the JVM, and failed
to fail when the enums went from size 25 to size 26. This meant missing
values would not be detected at runtime and instead return null,
compounding problems later. The switches should never evaluate to null
so will instead throw runtime assertion errors.
Additional unit tests were added to detect new paintings and assure they
have proper, unique mappings. The test checks both that a mapping
exists, is not null, and does not duplicate another mapping.
If a defensive copy is not used in the API, changes to the item are
reflected in memory, but never updated to the client. It also goes
against the general contract provided in Bukkit, where setItem should be
the only way to change the underlying item frame.
Skull blocks store their type in a tile entity and use their block data
as rotation. When breaking a block the block data is used for determining
what item to drop. Simply changing this to use the skull method for getting
their drop data is not enough because their tile entity is already gone.
Therefore we have to special case skulls to get the correct data _and_ get
that data before breaking the block.
On player death player PotionEffects need to be updated so that a player's
invisibility and other effects are removed, otherwise they will persist
after a respawn. This is a carry-over from our use of persistent player
entities.
Some features added in 1.4.2 use the difficulty value as an index to an
array so while before having it set to an invalid value would do nothing
or maybe cause an odd side effect somewhere it now crashes the server. This
patch ensures difficulty values are clamped between 0 and 3, inclusive.
Filtering item data is usually a good idea to make sure we don't have
invalid data or data on items that shouldn't have it. However, anvils
use item data in slightly different way and so running its code for
filtering here causes the data to be corrupted.