Merge pull request #104 from LeoDog896/master

Microoptimization cleanup
This commit is contained in:
TheMode 2021-01-17 07:20:51 +01:00 committed by GitHub
commit b00824d053
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 76 additions and 107 deletions

3
.gitignore vendored
View File

@ -53,3 +53,6 @@ gradle-app.setting
# When running the demo we generate the extensions folder
/extensions/
# When compiling we get a docs folder
/docs

View File

@ -35,7 +35,7 @@ public class BlockEnumGenerator extends MinestomEnumGenerator<BlockContainer> {
private final String targetVersion;
private final File targetFolder;
private CodeBlock.Builder staticBlock = CodeBlock.builder();
private final CodeBlock.Builder staticBlock = CodeBlock.builder();
public static void main(String[] args) throws IOException {
@ -161,8 +161,6 @@ public class BlockEnumGenerator extends MinestomEnumGenerator<BlockContainer> {
}
return blocks;
} catch (IOException e) {
throw e;
}
}
@ -178,8 +176,6 @@ public class BlockEnumGenerator extends MinestomEnumGenerator<BlockContainer> {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(blockFile))) {
PrismarineJSBlock[] blocks = gson.fromJson(bufferedReader, PrismarineJSBlock[].class);
return Arrays.asList(blocks);
} catch (IOException e) {
throw e;
}
}

View File

@ -85,8 +85,6 @@ public class ItemEnumGenerator extends MinestomEnumGenerator<ItemContainer> {
items.add(item);
}
return items;
} catch (IOException e) {
throw e;
}
}

View File

@ -1,5 +1,8 @@
package net.minestom.server.map;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
@ -10,7 +13,7 @@ import java.util.Map;
public class PaletteGenerator {
public static void main(String[] args) {
Map<Integer, Integer> colors = new HashMap<>();
Int2IntMap colors = new Int2IntOpenHashMap();
int highestIndex = 0;
for(MapColors c : MapColors.values()) {
if (c == MapColors.NONE)

View File

@ -217,7 +217,6 @@ public final class MinecraftServer {
* @throws NullPointerException if {@code brandName} is null
*/
public static void setBrandName(@NotNull String brandName) {
Check.notNull(brandName, "The brand name cannot be null");
MinecraftServer.brandName = brandName;
PacketUtils.sendGroupedPacket(connectionManager.getOnlinePlayers(), PluginMessagePacket.getBrandPacket());
@ -275,7 +274,6 @@ public final class MinecraftServer {
* @param difficulty the new server difficulty
*/
public static void setDifficulty(@NotNull Difficulty difficulty) {
Check.notNull(difficulty, "The server difficulty cannot be null.");
MinecraftServer.difficulty = difficulty;
// Send the packet to all online players
@ -478,9 +476,7 @@ public final class MinecraftServer {
MinecraftServer.chunkViewDistance = chunkViewDistance;
if (started) {
final Collection<Player> players = connectionManager.getOnlinePlayers();
players.forEach(player -> {
for (final Player player : connectionManager.getOnlinePlayers()) {
final Chunk playerChunk = player.getChunk();
if (playerChunk != null) {
@ -490,7 +486,7 @@ public final class MinecraftServer {
player.refreshVisibleChunks(playerChunk);
}
});
}
}
}
@ -514,12 +510,12 @@ public final class MinecraftServer {
"The entity view distance must be between 0 and 32");
MinecraftServer.entityViewDistance = entityViewDistance;
if (started) {
connectionManager.getOnlinePlayers().forEach(player -> {
for (final Player player : connectionManager.getOnlinePlayers()) {
final Chunk playerChunk = player.getChunk();
if (playerChunk != null) {
player.refreshVisibleEntities(playerChunk);
}
});
}
}
}

View File

@ -140,7 +140,6 @@ public final class UpdateManager {
* @throws NullPointerException if <code>threadProvider</code> is null
*/
public synchronized void setThreadProvider(ThreadProvider threadProvider) {
Check.notNull(threadProvider, "The thread provider cannot be null");
this.threadProvider = threadProvider;
}

View File

@ -73,7 +73,6 @@ public class AdvancementTab implements Viewable {
* @param parent the parent of this advancement, it cannot be null
*/
public void createAdvancement(@NotNull String identifier, @NotNull Advancement advancement, @NotNull Advancement parent) {
Check.argCondition(identifier == null, "the advancement identifier cannot be null");
Check.stateCondition(!advancementMap.containsKey(parent),
"You tried to set a parent which doesn't exist or isn't registered");
cacheAdvancement(identifier, advancement, parent);

View File

@ -19,8 +19,11 @@ import java.util.regex.Pattern;
*/
public class ColoredText extends JsonMessage {
// the raw text
private String message;
/**
* The raw text StringBuilder
* Its a single StringBuilder instance for easier and faster concenation
*/
private final StringBuilder message = new StringBuilder();
/**
* Creates a colored text.
@ -31,7 +34,7 @@ public class ColoredText extends JsonMessage {
* @see #of(String) to create a colored text
*/
private ColoredText(@NotNull String message) {
this.message = message;
this.message.append(message);
refreshUpdate();
}
@ -79,7 +82,7 @@ public class ColoredText extends JsonMessage {
*/
@NotNull
public ColoredText append(@NotNull ChatColor color, @NotNull String message) {
this.message += color + message;
this.message.append(color).append(message);
refreshUpdate();
return this;
}
@ -116,7 +119,7 @@ public class ColoredText extends JsonMessage {
*/
@NotNull
public String getMessage() {
return message;
return message.toString();
}
/**
@ -160,7 +163,7 @@ public class ColoredText extends JsonMessage {
protected List<JsonObject> getComponents() {
final List<JsonObject> objects = new ArrayList<>();
// No message, return empty list
if (message.isEmpty())
if (getMessage().isEmpty())
return objects;
boolean inFormat = false;

View File

@ -37,7 +37,6 @@ public class RichMessage extends JsonMessage {
* @return the created rich message object
*/
public static RichMessage of(@NotNull ColoredText coloredText) {
Check.notNull(coloredText, "ColoredText cannot be null");
RichMessage richMessage = new RichMessage();
appendText(richMessage, coloredText);
@ -58,7 +57,6 @@ public class RichMessage extends JsonMessage {
* @return the rich message
*/
public RichMessage append(@NotNull ColoredText coloredText) {
Check.notNull(coloredText, "ColoredText cannot be null");
appendText(this, coloredText);
return this;

View File

@ -185,8 +185,6 @@ public final class CommandManager {
* @return true if the command hadn't been cancelled and has been successful
*/
public boolean execute(@NotNull CommandSender sender, @NotNull String command) {
Check.notNull(sender, "Source cannot be null");
Check.notNull(command, "Command string cannot be null");
// Command event
if (sender instanceof Player) {

View File

@ -39,7 +39,7 @@ public interface CommandSender extends PermissionHandler {
* */
default void sendMessage(@NotNull JsonMessage text) {
if (this instanceof Player) {
((Player) this).sendMessage((JsonMessage) text);
this.sendMessage(text);
} else {
sendMessage(text.getRawMessage());
}

View File

@ -1,5 +1,6 @@
package net.minestom.server.command.builder;
import it.unimi.dsi.fastutil.ints.Int2ObjectRBTreeMap;
import net.minestom.server.command.CommandSender;
import net.minestom.server.command.builder.arguments.Argument;
import net.minestom.server.command.builder.condition.CommandCondition;
@ -58,6 +59,7 @@ public class CommandDispatcher {
* @param commandString the command (containing the command name and the args if any)
* @return the result of the parsing, null if the command doesn't exist
*/
@Nullable
public CommandResult parse(@NotNull String commandString) {
commandString = commandString.trim();
@ -131,7 +133,7 @@ public class CommandDispatcher {
// Contains all the syntaxes that are not fully correct, used to later, retrieve the "most correct syntax"
// Number of correct argument - The data about the failing argument
TreeMap<Integer, CommandSuggestionHolder> syntaxesSuggestions = new TreeMap<>(Collections.reverseOrder());
Int2ObjectRBTreeMap<CommandSuggestionHolder> syntaxesSuggestions = new Int2ObjectRBTreeMap<>(Collections.reverseOrder());
for (CommandSyntax syntax : syntaxes) {
final Argument<?>[] arguments = syntax.getArguments();
@ -257,7 +259,7 @@ public class CommandDispatcher {
{
// Get closest valid syntax
if (!syntaxesSuggestions.isEmpty()) {
final int max = syntaxesSuggestions.firstKey(); // number of correct arguments in the most correct syntax
final int max = syntaxesSuggestions.firstIntKey(); // number of correct arguments in the most correct syntax
final CommandSuggestionHolder suggestionHolder = syntaxesSuggestions.get(max);
final CommandSyntax syntax = suggestionHolder.syntax;
final ArgumentSyntaxException argumentSyntaxException = suggestionHolder.argumentSyntaxException;

View File

@ -242,7 +242,6 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer, P
* @throws IllegalStateException if you try to teleport an entity before settings its instance
*/
public void teleport(@NotNull Position position, @Nullable long[] chunks, @Nullable Runnable callback) {
Check.notNull(position, "Teleport position cannot be null");
Check.stateCondition(instance == null, "You need to use Entity#setInstance before teleporting an entity!");
final ChunkCallback endCallback = (chunk) -> {
@ -329,7 +328,6 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer, P
@Override
public boolean addViewer(@NotNull Player player) {
Check.notNull(player, "Viewer cannot be null");
boolean result = this.viewers.add(player);
if (!result)
return false;
@ -339,7 +337,6 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer, P
@Override
public boolean removeViewer(@NotNull Player player) {
Check.notNull(player, "Viewer cannot be null");
if (!viewers.remove(player))
return false;
@ -757,7 +754,6 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer, P
* @throws IllegalStateException if {@code instance} has not been registered in {@link InstanceManager}
*/
public void setInstance(@NotNull Instance instance) {
Check.notNull(instance, "instance cannot be null!");
Check.stateCondition(!instance.isRegistered(),
"Instances need to be registered, please use InstanceManager#registerInstance or InstanceManager#registerSharedInstance");
@ -866,7 +862,6 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer, P
* @return the distance between this and {@code entity}
*/
public float getDistance(@NotNull Entity entity) {
Check.notNull(entity, "Entity cannot be null");
return getPosition().getDistance(entity.getPosition());
}
@ -888,7 +883,6 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer, P
* @throws IllegalStateException if {@link #getInstance()} returns null
*/
public void addPassenger(@NotNull Entity entity) {
Check.notNull(entity, "Passenger cannot be null");
Check.stateCondition(instance == null, "You need to set an instance using Entity#setInstance");
if (entity.getVehicle() != null) {
@ -909,7 +903,6 @@ public abstract class Entity implements Viewable, EventHandler, DataContainer, P
* @throws IllegalStateException if {@link #getInstance()} returns null
*/
public void removePassenger(@NotNull Entity entity) {
Check.notNull(entity, "Passenger cannot be null");
Check.stateCondition(instance == null, "You need to set an instance using Entity#setInstance");
if (!passengers.remove(entity))

View File

@ -272,7 +272,6 @@ public abstract class LivingEntity extends Entity implements EquipmentHandler {
* @return true if damage has been applied, false if it didn't
*/
public boolean damage(@NotNull DamageType type, float value) {
Check.notNull(type, "The damage type cannot be null!");
if (isDead())
return false;
if (isInvulnerable() || isImmune(type)) {

View File

@ -536,7 +536,7 @@ public class Player extends LivingEntity implements CommandSender {
// #buildDeathScreenText can return null, check here
if (deathText != null) {
CombatEventPacket deathPacket = CombatEventPacket.death(this, Optional.empty(), deathText);
CombatEventPacket deathPacket = CombatEventPacket.death(this, null, deathText);
playerConnection.sendPacket(deathPacket);
}
@ -670,7 +670,6 @@ public class Player extends LivingEntity implements CommandSender {
* @param spawnPosition the new position of the player
*/
public void setInstance(@NotNull Instance instance, @NotNull Position spawnPosition) {
Check.notNull(instance, "instance cannot be null!");
Check.argCondition(this.instance == instance, "Instance should be different than the current one");
// true if the chunks need to be sent to the client, can be false if the instances share the same chunks (eg SharedInstance)
@ -1364,7 +1363,6 @@ public class Player extends LivingEntity implements CommandSender {
* @param resourcePack the resource pack
*/
public void setResourcePack(@NotNull ResourcePack resourcePack) {
Check.notNull(resourcePack, "The resource pack cannot be null");
final String url = resourcePack.getUrl();
final String hash = resourcePack.getHash();
@ -1737,7 +1735,6 @@ public class Player extends LivingEntity implements CommandSender {
* @param gameMode the new player GameMode
*/
public void setGameMode(@NotNull GameMode gameMode) {
Check.notNull(gameMode, "GameMode cannot be null");
this.gameMode = gameMode;
// Condition to prevent sending the packets before spawning the player
@ -1766,7 +1763,6 @@ public class Player extends LivingEntity implements CommandSender {
* @param dimensionType the new player dimension
*/
protected void sendDimension(@NotNull DimensionType dimensionType) {
Check.notNull(dimensionType, "Dimension cannot be null!");
Check.argCondition(dimensionType.equals(getDimensionType()), "The dimension needs to be different than the current one!");
this.dimensionType = dimensionType;
@ -1900,7 +1896,6 @@ public class Player extends LivingEntity implements CommandSender {
* @return true if the inventory has been opened/sent to the player, false otherwise (cancelled by event)
*/
public boolean openInventory(@NotNull Inventory inventory) {
Check.notNull(inventory, "Inventory cannot be null, use Player#closeInventory() to close current");
InventoryOpenEvent inventoryOpenEvent = new InventoryOpenEvent(inventory, this);

View File

@ -7,7 +7,6 @@ import net.minestom.server.instance.Instance;
import net.minestom.server.utils.BlockPosition;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Random;
public class EatBlockGoal extends GoalSelector {

View File

@ -30,7 +30,6 @@ public interface NavigableEntity {
* @param speed define how far the entity will move
*/
default void moveTowards(@NotNull Position direction, float speed) {
Check.notNull(direction, "The direction cannot be null");
final Position position = getNavigableEntity().getPosition();

View File

@ -37,8 +37,6 @@ public interface EventHandler {
* @return true if the callback collection changed as a result of the call
*/
default <E extends Event> boolean addEventCallback(@NotNull Class<E> eventClass, @NotNull EventCallback<E> eventCallback) {
Check.notNull(eventClass, "Event class cannot be null");
Check.notNull(eventCallback, "Event callback cannot be null");
Collection<EventCallback> callbacks = getEventCallbacks(eventClass);
return callbacks.add(eventCallback);
}
@ -52,8 +50,6 @@ public interface EventHandler {
* @return true if the callback was removed as a result of this call
*/
default <E extends Event> boolean removeEventCallback(@NotNull Class<E> eventClass, @NotNull EventCallback<E> eventCallback) {
Check.notNull(eventClass, "Event class cannot be null");
Check.notNull(eventCallback, "Event callback cannot be null");
Collection<EventCallback> callbacks = getEventCallbacks(eventClass);
return callbacks.remove(eventCallback);
}
@ -67,7 +63,6 @@ public interface EventHandler {
*/
@NotNull
default <E extends Event> Collection<EventCallback> getEventCallbacks(@NotNull Class<E> eventClass) {
Check.notNull(eventClass, "Event class cannot be null");
return getEventCallbacksMap().computeIfAbsent(eventClass, clazz -> new CopyOnWriteArraySet<>());
}

View File

@ -58,8 +58,7 @@ public class MinestomExtensionClassLoader extends HierarchyClassLoader {
} catch (ClassNotFoundException e) {
for(MinestomExtensionClassLoader child : children) {
try {
Class<?> loaded = child.loadClassAsChild(name, resolve);
return loaded;
return child.loadClassAsChild(name, resolve);
} catch (ClassNotFoundException e1) {
// move on to next child
}

View File

@ -71,13 +71,10 @@ public interface BlockModifier {
}
default void setBlock(@NotNull BlockPosition blockPosition, @NotNull Block block) {
Check.notNull(blockPosition, "The block position cannot be null");
Check.notNull(block, "The block cannot be null");
setBlock(blockPosition.getX(), blockPosition.getY(), blockPosition.getZ(), block);
}
default void setBlockStateId(@NotNull BlockPosition blockPosition, short blockStateId) {
Check.notNull(blockPosition, "The block position cannot be null");
setBlockStateId(blockPosition.getX(), blockPosition.getY(), blockPosition.getZ(), blockStateId);
}
@ -97,7 +94,6 @@ public interface BlockModifier {
}
default void setCustomBlock(@NotNull BlockPosition blockPosition, @NotNull String customBlockId) {
Check.notNull(blockPosition, "The block position cannot be null");
setCustomBlock(blockPosition.getX(), blockPosition.getY(), blockPosition.getZ(), customBlockId);
}
@ -106,7 +102,6 @@ public interface BlockModifier {
}
default void setSeparateBlocks(@NotNull BlockPosition blockPosition, short blockStateId, short customBlockId) {
Check.notNull(blockPosition, "The block position cannot be null");
setSeparateBlocks(blockPosition.getX(), blockPosition.getY(), blockPosition.getZ(), blockStateId, customBlockId, null);
}

View File

@ -1,5 +1,6 @@
package net.minestom.server.instance;
import it.unimi.dsi.fastutil.ints.IntSet;
import net.minestom.server.MinecraftServer;
import net.minestom.server.Viewable;
import net.minestom.server.data.Data;

View File

@ -508,7 +508,6 @@ public class InstanceContainer extends Instance {
@Override
public ChunkBatch createChunkBatch(@NotNull Chunk chunk) {
Check.notNull(chunk, "The chunk of a ChunkBatch cannot be null");
return new ChunkBatch(this, chunk, false);
}
@ -587,7 +586,6 @@ public class InstanceContainer extends Instance {
* @throws NullPointerException if {@code chunkSupplier} is null
*/
public void setChunkSupplier(@NotNull ChunkSupplier chunkSupplier) {
Check.notNull(chunkSupplier, "The chunk supplier cannot be null!");
this.chunkSupplier = chunkSupplier;
}

View File

@ -19,7 +19,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
public class InventoryClickProcessor {
@ -161,12 +160,12 @@ public class InventoryClickProcessor {
if (cursor.isAir()) {
// if held item [key] is air then set clicked to held
resultClicked = ItemStack.getAirItem();
resultHeld = clicked;
} else {
// Otherwise replace held item and held
resultClicked = cursor;
resultHeld = clicked;
}
resultHeld = clicked;
}
clickResult.setClicked(resultClicked);
@ -278,7 +277,7 @@ public class InventoryClickProcessor {
// End left
if (!leftDraggingMap.containsKey(player))
return null;
final Set<Integer> slots = leftDraggingMap.get(player);
final IntSet slots = leftDraggingMap.get(player);
final int slotCount = slots.size();
final int cursorAmount = stackingRule.getAmount(cursor);
if (slotCount > cursorAmount)
@ -287,7 +286,7 @@ public class InventoryClickProcessor {
final int slotSize = (int) ((float) cursorAmount / (float) slotCount);
int finalCursorAmount = cursorAmount;
for (Integer s : slots) {
for (int s : slots) {
final ItemStack draggedItem = cursor.clone();
ItemStack slotItem = itemGetter.apply(s);
@ -322,12 +321,12 @@ public class InventoryClickProcessor {
// End right
if (!rightDraggingMap.containsKey(player))
return null;
final Set<Integer> slots = rightDraggingMap.get(player);
final IntSet slots = rightDraggingMap.get(player);
final int size = slots.size();
int cursorAmount = stackingRule.getAmount(cursor);
if (size > cursorAmount)
return null;
for (Integer s : slots) {
for (int s : slots) {
ItemStack draggedItem = cursor.clone();
ItemStack slotItem = itemGetter.apply(s);

View File

@ -1,6 +1,5 @@
package net.minestom.server.item;
import net.minestom.server.chat.ColoredText;
import net.minestom.server.chat.JsonMessage;
public class ItemDisplay {

View File

@ -1,5 +1,7 @@
package net.minestom.server.item;
import it.unimi.dsi.fastutil.objects.Object2ShortMap;
import it.unimi.dsi.fastutil.objects.Object2ShortOpenHashMap;
import net.minestom.server.chat.JsonMessage;
import net.minestom.server.data.Data;
import net.minestom.server.data.DataContainer;
@ -18,7 +20,6 @@ import net.minestom.server.utils.Direction;
import net.minestom.server.utils.NBTUtils;
import net.minestom.server.utils.clone.PublicCloneable;
import net.minestom.server.utils.ownership.OwnershipHandler;
import net.minestom.server.utils.validate.Check;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jglrxavpok.hephaistos.nbt.NBTCompound;
@ -38,11 +39,11 @@ import java.util.*;
*/
public class ItemStack implements DataContainer, PublicCloneable<ItemStack> {
public static final OwnershipHandler<Data> DATA_OWNERSHIP = new OwnershipHandler();
public static final OwnershipHandler<Data> DATA_OWNERSHIP = new OwnershipHandler<>();
public static final String OWNERSHIP_DATA_KEY = "ownership_identifier";
private static final StackingRule VANILLA_STACKING_RULE = new VanillaStackingRule(64);
private UUID identifier;
private final UUID identifier;
private Material material;
@ -56,7 +57,7 @@ public class ItemStack implements DataContainer, PublicCloneable<ItemStack> {
private boolean unbreakable;
private List<JsonMessage> lore;
private Map<Enchantment, Short> enchantmentMap;
private Object2ShortMap<Enchantment> enchantmentMap;
private List<ItemAttribute> attributes;
private int hideFlag;
@ -78,7 +79,7 @@ public class ItemStack implements DataContainer, PublicCloneable<ItemStack> {
this.damage = damage;
this.lore = new ArrayList<>();
this.enchantmentMap = new HashMap<>();
this.enchantmentMap = new Object2ShortOpenHashMap<>();
this.attributes = new ArrayList<>();
this.itemMeta = findMeta();
@ -117,7 +118,6 @@ public class ItemStack implements DataContainer, PublicCloneable<ItemStack> {
* @throws NullPointerException if {@code defaultStackingRule} is null
*/
public static void setDefaultStackingRule(@NotNull StackingRule defaultStackingRule) {
Check.notNull(defaultStackingRule, "StackingRule cannot be null!");
ItemStack.defaultStackingRule = defaultStackingRule;
}
@ -341,7 +341,7 @@ public class ItemStack implements DataContainer, PublicCloneable<ItemStack> {
* @param enchantment the enchantment type
*/
public void removeEnchantment(@NotNull Enchantment enchantment) {
this.enchantmentMap.remove(enchantment);
this.enchantmentMap.removeShort(enchantment);
}
/**
@ -581,7 +581,7 @@ public class ItemStack implements DataContainer, PublicCloneable<ItemStack> {
itemStack.setStackingRule(stackingRule);
}
itemStack.enchantmentMap = new HashMap<>(enchantmentMap);
itemStack.enchantmentMap = new Object2ShortOpenHashMap<>(enchantmentMap);
itemStack.attributes = new ArrayList<>(attributes);
itemStack.hideFlag = hideFlag;
@ -635,7 +635,6 @@ public class ItemStack implements DataContainer, PublicCloneable<ItemStack> {
* @throws NullPointerException if {@code stackingRule} is null
*/
public void setStackingRule(@NotNull StackingRule stackingRule) {
Check.notNull(stackingRule, "The stacking rule cannot be null!");
this.stackingRule = stackingRule;
}

View File

@ -1,7 +1,7 @@
package net.minestom.server.item.firework;
import java.util.HashMap;
import java.util.Map;
import it.unimi.dsi.fastutil.bytes.Byte2ObjectMap;
import it.unimi.dsi.fastutil.bytes.Byte2ObjectOpenHashMap;
/**
* An enumeration that representing all available firework types.
@ -15,7 +15,7 @@ public enum FireworkEffectType {
BURST((byte) 4),
;
private static final Map<Byte, FireworkEffectType> BY_ID = new HashMap<>();
private static final Byte2ObjectMap<FireworkEffectType> BY_ID = new Byte2ObjectOpenHashMap<>();
static {
for (FireworkEffectType value : values()) {

View File

@ -1,17 +1,18 @@
package net.minestom.server.item.metadata;
import it.unimi.dsi.fastutil.objects.Object2ShortMap;
import it.unimi.dsi.fastutil.objects.Object2ShortOpenHashMap;
import net.minestom.server.item.Enchantment;
import net.minestom.server.utils.NBTUtils;
import org.jetbrains.annotations.NotNull;
import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class EnchantedBookMeta extends ItemMeta {
private final Map<Enchantment, Short> storedEnchantmentMap = new HashMap<>();
private final Object2ShortMap<Enchantment> storedEnchantmentMap = new Object2ShortOpenHashMap<>();
/**
* Gets the stored enchantment map.
@ -45,7 +46,7 @@ public class EnchantedBookMeta extends ItemMeta {
* @param enchantment the enchantment type
*/
public void removeStoredEnchantment(@NotNull Enchantment enchantment) {
this.storedEnchantmentMap.remove(enchantment);
this.storedEnchantmentMap.removeShort(enchantment);
}
/**

View File

@ -31,19 +31,19 @@ public class CombatEventPacket implements ServerPacket {
return packet;
}
public static CombatEventPacket end(int durationInTicks, Optional<Entity> opponent) {
public static CombatEventPacket end(int durationInTicks, Entity opponent) {
CombatEventPacket packet = new CombatEventPacket();
packet.type = EventType.END_COMBAT;
packet.duration = durationInTicks;
packet.opponent = opponent.map(Entity::getEntityId).orElse(-1);
packet.opponent = opponent != null ? opponent.getEntityId() : -1;
return packet;
}
public static CombatEventPacket death(Player player, Optional<Entity> killer, JsonMessage message) {
public static CombatEventPacket death(Player player, Entity killer, JsonMessage message) {
CombatEventPacket packet = new CombatEventPacket();
packet.type = EventType.DEATH;
packet.playerID = player.getEntityId();
packet.opponent = killer.map(Entity::getEntityId).orElse(-1);
packet.opponent = killer != null ? killer.getEntityId() : -1;
packet.deathMessage = message;
return packet;
}

View File

@ -4,6 +4,7 @@ import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import it.unimi.dsi.fastutil.io.FastBufferedInputStream;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
@ -169,7 +170,7 @@ public class ResourceGatherer {
private static File download(@NotNull String version, @NotNull String url, @NotNull String sha1Source) throws IOException {
File target = new File(TMP_FOLDER, "server_" + version + ".jar");
// Download
try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream())) {
try (FastBufferedInputStream in = new FastBufferedInputStream(new URL(url).openStream())) {
Files.copy(in, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IOException("Failed to download Minecraft server jar.", e);

View File

@ -14,7 +14,6 @@ public class ResourcePack {
private final String hash;
public ResourcePack(@NotNull String url, @Nullable String hash) {
Check.notNull(url, "The resource pack url cannot be null");
this.url = url;
// Optional, set to empty if null
this.hash = hash == null ? "" : hash;

View File

@ -36,7 +36,6 @@ public final class StorageManager {
* @return the specified {@link StorageLocation}
*/
public StorageLocation getLocation(@NotNull String location, @NotNull StorageOptions storageOptions, @NotNull StorageSystem storageSystem) {
Check.notNull(storageOptions, "The storage option cannot be null");
return locationMap.computeIfAbsent(location,
s -> new StorageLocation(storageSystem, location, storageOptions));
}

View File

@ -281,20 +281,20 @@ public class EntityFinder {
closestDistance = distance;
}
}
return Arrays.asList(entity);
return Collections.singletonList(entity);
} else if (targetSelector == TargetSelector.RANDOM_PLAYER) {
Collection<Player> instancePlayers = instance != null ?
instance.getPlayers() : MinecraftServer.getConnectionManager().getOnlinePlayers();
final int index = ThreadLocalRandom.current().nextInt(instancePlayers.size());
final Player player = instancePlayers.stream().skip(index).findFirst().orElseThrow();
return Arrays.asList(player);
return Collections.singletonList(player);
} else if (targetSelector == TargetSelector.ALL_PLAYERS) {
return new ArrayList<>(instance != null ?
instance.getPlayers() : MinecraftServer.getConnectionManager().getOnlinePlayers());
} else if (targetSelector == TargetSelector.ALL_ENTITIES) {
return new ArrayList<>(instance.getEntities());
} else if (targetSelector == TargetSelector.SELF) {
return Arrays.asList(self);
return Collections.singletonList(self);
}
throw new IllegalStateException("Weird thing happened");
}

View File

@ -2,10 +2,10 @@ package net.minestom.server.world;
import net.minestom.server.utils.NamespaceID;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
/**
@ -24,7 +24,7 @@ public class DimensionType {
.raidCapable(true)
.skylightEnabled(true)
.ceilingEnabled(false)
.fixedTime(Optional.empty())
.fixedTime(null)
.ambientLight(0.0f)
.logicalHeight(256)
.infiniburn(NamespaceID.from("minecraft:infiniburn_overworld"))
@ -39,7 +39,10 @@ public class DimensionType {
private final float ambientLight;
private final boolean ceilingEnabled;
private final boolean skylightEnabled;
private final Optional<Long> fixedTime;
@Nullable
private final Long fixedTime;
private final boolean raidCapable;
private final boolean respawnAnchorSafe;
private final boolean ultrawarm;
@ -51,7 +54,7 @@ public class DimensionType {
private final NamespaceID infiniburn;
DimensionType(NamespaceID name, boolean natural, float ambientLight, boolean ceilingEnabled,
boolean skylightEnabled, Optional<Long> fixedTime, boolean raidCapable,
boolean skylightEnabled, @Nullable Long fixedTime, boolean raidCapable,
boolean respawnAnchorSafe, boolean ultrawarm, boolean bedSafe, String effects, boolean piglinSafe,
int logicalHeight, int coordinateScale, NamespaceID infiniburn) {
this.name = name;
@ -106,7 +109,7 @@ public class DimensionType {
.setInt("logical_height", logicalHeight)
.setInt("coordinate_scale", coordinateScale)
.setString("name", name.toString());
fixedTime.ifPresent(time -> nbt.setLong("fixed_time", time));
if (fixedTime != null) nbt.setLong("fixed_time", fixedTime);
return nbt;
}
@ -143,7 +146,8 @@ public class DimensionType {
return this.skylightEnabled;
}
public Optional<Long> getFixedTime() {
@Nullable
public Long getFixedTime() {
return this.fixedTime;
}
@ -203,7 +207,9 @@ public class DimensionType {
private float ambientLight;
private boolean ceilingEnabled;
private boolean skylightEnabled;
private Optional<Long> fixedTime = Optional.empty();
@Nullable
private Long fixedTime = null;
private boolean raidCapable;
private boolean respawnAnchorSafe;
private boolean ultrawarm;
@ -242,7 +248,7 @@ public class DimensionType {
return this;
}
public DimensionType.DimensionTypeBuilder fixedTime(Optional<Long> fixedTime) {
public DimensionType.DimensionTypeBuilder fixedTime(Long fixedTime) {
this.fixedTime = fixedTime;
return this;
}

View File

@ -36,8 +36,7 @@ public class DimensionCommand implements CommandProcessor {
// targetDimensionType = DimensionType.OVERWORLD;
//}
DimensionType finalTargetDimensionType = targetDimensionType;
Optional<Instance> targetInstance = MinecraftServer.getInstanceManager().getInstances().stream().filter(in -> in.getDimensionType() == finalTargetDimensionType).findFirst();
Optional<Instance> targetInstance = MinecraftServer.getInstanceManager().getInstances().stream().filter(in -> in.getDimensionType() == targetDimensionType).findFirst();
if (targetInstance.isPresent()) {
player.sendMessage("You were in " + instance.getDimensionType());
player.setInstance(targetInstance.get());

View File

@ -25,11 +25,10 @@ public class ReloadExtensionCommand extends Command {
private static String[] extensionsName;
static {
List<String> extensionsName = MinecraftServer.getExtensionManager().getExtensions()
ReloadExtensionCommand.extensionsName = MinecraftServer.getExtensionManager().getExtensions()
.stream()
.map(extension -> extension.getDescription().getName())
.collect(Collectors.toList());
ReloadExtensionCommand.extensionsName = extensionsName.toArray(new String[0]);
.toArray(String[]::new);
}
public ReloadExtensionCommand() {