Set the minimum Java version to 16; drop Bedrock 1.17.0 (#2477)

This commit is contained in:
Camotoy 2021-09-10 14:10:56 -04:00 committed by GitHub
parent 93f5298ee3
commit bc0cfde8f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
93 changed files with 668 additions and 10637 deletions

View File

@ -15,10 +15,10 @@ jobs:
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Set up JDK 1.8
- name: Set up JDK 16
uses: actions/setup-java@v1
with:
java-version: 1.8
java-version: 16
- name: submodules-init
uses: snickerbockers/submodules-init@v4
- name: Build with Maven

View File

@ -6,9 +6,9 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>geyser-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>ap</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</project>

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>bootstrap-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>bootstrap-bungeecord</artifactId>
@ -14,7 +14,7 @@
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>connector</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- Used for better working with internals without reflection -->
@ -49,7 +49,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<version>3.3.0-SNAPSHOT</version>
<executions>
<execution>
<phase>package</phase>

View File

@ -57,8 +57,7 @@ public class BungeeCommandSender implements CommandSender {
@Override
public String getLocale() {
if (handle instanceof ProxiedPlayer) {
ProxiedPlayer player = (ProxiedPlayer) handle;
if (handle instanceof ProxiedPlayer player) {
String locale = player.getLocale().getLanguage() + "_" + player.getLocale().getCountry();
return LanguageUtils.formatLocale(locale);
}

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>geyser-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>bootstrap-parent</artifactId>
<packaging>pom</packaging>
@ -34,7 +34,7 @@
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>ap</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>bootstrap-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>bootstrap-spigot</artifactId>
@ -21,7 +21,7 @@
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>connector</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
@ -66,7 +66,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<version>3.3.0-SNAPSHOT</version>
<executions>
<execution>
<phase>package</phase>

View File

@ -97,8 +97,7 @@ public class SpigotCommandSender implements CommandSender {
* @return the locale of the Spigot player
*/
private String getSpigotLocale() {
if (handle instanceof Player) {
Player player = (Player) handle;
if (handle instanceof Player player) {
if (USE_LEGACY_METHOD) {
try {
// sigh

View File

@ -109,8 +109,7 @@ public class GeyserSpigot1_11CraftingListener implements Listener {
if (output == null || output.getId() == 0) continue; // If items make air we don't want that
boolean isNotAllAir = false; // Check for all-air recipes
if (recipe instanceof ShapedRecipe) {
ShapedRecipe shapedRecipe = (ShapedRecipe) recipe;
if (recipe instanceof ShapedRecipe shapedRecipe) {
int size = shapedRecipe.getShape().length * shapedRecipe.getShape()[0].length();
Ingredient[] ingredients = new Ingredient[size];
ItemData[] input = new ItemData[size];
@ -134,8 +133,7 @@ public class GeyserSpigot1_11CraftingListener implements Listener {
craftingDataPacket.getCraftingData().add(CraftingData.fromShaped(uuid.toString(),
shapedRecipe.getShape()[0].length(), shapedRecipe.getShape().length, Arrays.asList(input),
Collections.singletonList(output), uuid, "crafting_table", 0, netId++));
} else if (recipe instanceof ShapelessRecipe) {
ShapelessRecipe shapelessRecipe = (ShapelessRecipe) recipe;
} else if (recipe instanceof ShapelessRecipe shapelessRecipe) {
Ingredient[] ingredients = new Ingredient[shapelessRecipe.getIngredientList().size()];
ItemData[] input = new ItemData[shapelessRecipe.getIngredientList().size()];

View File

@ -99,14 +99,13 @@ public class GeyserSpigotWorldManager extends GeyserWorldManager {
}
Block block = bukkitPlayer.getWorld().getBlockAt(x, y, z);
if (!(block.getState() instanceof Lectern)) {
if (!(block.getState() instanceof Lectern lectern)) {
session.getConnector().getLogger().error("Lectern expected at: " + Vector3i.from(x, y, z).toString() + " but was not! " + block.toString());
return;
}
Lectern lectern = (Lectern) block.getState();
ItemStack itemStack = lectern.getInventory().getItem(0);
if (itemStack == null || !(itemStack.getItemMeta() instanceof BookMeta)) {
if (itemStack == null || !(itemStack.getItemMeta() instanceof BookMeta bookMeta)) {
if (!isChunkLoad) {
// We need to update the lectern since it's not going to be updated otherwise
BlockEntityUtils.updateBlockEntity(session, LecternInventoryTranslator.getBaseLecternTag(x, y, z, 0).build(), Vector3i.from(x, y, z));
@ -115,7 +114,6 @@ public class GeyserSpigotWorldManager extends GeyserWorldManager {
return;
}
BookMeta bookMeta = (BookMeta) itemStack.getItemMeta();
// On the count: allow the book to show/open even there are no pages. We know there is a book here, after all, and this matches Java behavior
boolean hasBookPages = bookMeta.getPageCount() > 0;
NbtMapBuilder lecternTag = LecternInventoryTranslator.getBaseLecternTag(x, y, z, hasBookPages ? bookMeta.getPageCount() : 1);

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>bootstrap-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>bootstrap-sponge</artifactId>
@ -14,7 +14,7 @@
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>connector</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
@ -48,7 +48,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<version>3.3.0-SNAPSHOT</version>
<executions>
<execution>
<phase>package</phase>

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>bootstrap-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>bootstrap-standalone</artifactId>
@ -14,7 +14,7 @@
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>connector</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
@ -89,7 +89,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<version>3.3.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.github.edwgiz</groupId>

View File

@ -98,32 +98,26 @@ public class GeyserStandaloneBootstrap implements GeyserBootstrap {
// Allows gui and nogui without options, for backwards compatibility
String arg = args[i];
switch (arg) {
case "--gui":
case "gui":
useGuiOpts = true;
break;
case "--nogui":
case "nogui":
useGuiOpts = false;
break;
case "--config":
case "-c":
case "--gui", "gui" -> useGuiOpts = true;
case "--nogui", "nogui" -> useGuiOpts = false;
case "--config", "-c" -> {
if (i >= args.length - 1) {
System.err.println(MessageFormat.format(LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.config_not_specified"), "-c"));
return;
}
configFilenameOpt = args[i+1]; i++;
configFilenameOpt = args[i + 1];
i++;
System.out.println(MessageFormat.format(LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.config_specified"), configFilenameOpt));
break;
case "--help":
case "-h":
}
case "--help", "-h" -> {
System.out.println(MessageFormat.format(LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.usage"), "[java -jar] Geyser.jar [opts]"));
System.out.println(" " + LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.options"));
System.out.println(" -c, --config [file] " + LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.config"));
System.out.println(" -h, --help " + LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.help"));
System.out.println(" --gui, --nogui " + LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.gui"));
return;
default:
}
default -> {
// We have likely added a config option argument
if (arg.startsWith("--")) {
// Split the argument by an =
@ -159,9 +153,9 @@ public class GeyserStandaloneBootstrap implements GeyserBootstrap {
}
}
}
System.err.println(LanguageUtils.getLocaleStringLog("geyser.bootstrap.args.unrecognised", arg));
return;
}
}
}
bootstrap.onEnable(useGuiOpts, configFilenameOpt);

View File

@ -68,11 +68,10 @@ public final class GraphPanel extends JPanel {
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
if (!(graphics instanceof Graphics2D)) {
if (!(graphics instanceof final Graphics2D g)) {
graphics.drawString("Graphics is not Graphics2D, unable to render", 0, 0);
return;
}
final Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
final int length = values.size();

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>bootstrap-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>bootstrap-velocity</artifactId>
@ -14,7 +14,7 @@
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>connector</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
@ -48,7 +48,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<version>3.3.0-SNAPSHOT</version>
<executions>
<execution>
<phase>package</phase>

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>geyser-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>common</artifactId>

View File

@ -6,7 +6,7 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>geyser-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
</parent>
<artifactId>connector</artifactId>
@ -21,13 +21,13 @@
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>ap</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>common</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- Jackson JSON and YAML serialization -->

View File

@ -384,40 +384,9 @@ public class GeyserConnector {
logger.warning(LanguageUtils.getLocaleStringLog("geyser.core.movement_warn"));
}
checkForOutdatedJava();
newsHandler.handleNews(null, NewsItemAction.ON_SERVER_STARTED);
}
private void checkForOutdatedJava() {
final int supportedJavaVersion = 16;
// Taken from Paper
String javaVersion = System.getProperty("java.version");
Matcher matcher = Pattern.compile("(?:1\\.)?(\\d+)").matcher(javaVersion);
if (!matcher.find()) {
getLogger().debug("Could not parse Java version string " + javaVersion);
return;
}
String version = matcher.group(1);
int majorVersion;
try {
majorVersion = Integer.parseInt(version);
} catch (NumberFormatException e) {
getLogger().debug("Could not format as an int: " + version);
return;
}
if (majorVersion < supportedJavaVersion) {
getLogger().warning("*********************************************");
getLogger().warning("");
getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.bootstrap.unsupported_java.header"));
getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.bootstrap.unsupported_java.message", supportedJavaVersion, javaVersion));
getLogger().warning("");
getLogger().warning("*********************************************");
}
}
public void shutdown() {
bootstrap.getGeyserLogger().info(LanguageUtils.getLocaleStringLog("geyser.core.shutdown"));
shuttingDown = true;

View File

@ -69,15 +69,9 @@ public class DumpCommand extends GeyserCommand {
if (args.length >= 1) {
for (String arg : args) {
switch (arg) {
case "full":
showSensitive = true;
break;
case "offline":
offlineDump = true;
break;
case "logs":
addLog = true;
break;
case "full" -> showSensitive = true;
case "offline" -> offlineDump = true;
case "logs" -> addLog = true;
}
}
}

View File

@ -40,14 +40,11 @@ public enum EmoteOffhandWorkaroundOption {
@Override
public EmoteOffhandWorkaroundOption deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
switch (value) {
case "no-emotes":
return NO_EMOTES;
case "emotes-and-offhand":
return EMOTES_AND_OFFHAND;
default:
return DISABLED;
}
return switch (value) {
case "no-emotes" -> NO_EMOTES;
case "emotes-and-offhand" -> EMOTES_AND_OFFHAND;
default -> DISABLED;
};
}
}
}

View File

@ -48,8 +48,7 @@ public class EnderCrystalEntity extends Entity {
// Show beam
// Usually performed client-side on Bedrock except for Ender Dragon respawn event
if (entityMetadata.getId() == 8) {
if (entityMetadata.getValue() instanceof Position) {
Position pos = (Position) entityMetadata.getValue();
if (entityMetadata.getValue() instanceof Position pos) {
metadata.put(EntityData.BLOCK_TARGET, Vector3i.from(pos.getX(), pos.getY(), pos.getZ()));
} else {
metadata.put(EntityData.BLOCK_TARGET, Vector3i.ZERO);

View File

@ -256,11 +256,9 @@ public class Entity {
setAir((int) entityMetadata.getValue());
break;
case 2: // custom name
if (entityMetadata.getValue() instanceof Component) {
Component message = (Component) entityMetadata.getValue();
if (message != null)
// Always translate even if it's a TextMessage since there could be translatable parameters
metadata.put(EntityData.NAMETAG, MessageTranslator.convertMessage(message, session.getLocale()));
if (entityMetadata.getValue() instanceof Component message) {
// Always translate even if it's a TextMessage since there could be translatable parameters
metadata.put(EntityData.NAMETAG, MessageTranslator.convertMessage(message, session.getLocale()));
}
break;
case 3: // is custom name visible

View File

@ -84,21 +84,21 @@ public class LivingEntity extends Entity {
@Override
public void updateBedrockMetadata(EntityMetadata entityMetadata, GeyserSession session) {
switch (entityMetadata.getId()) {
case 8: // blocking
case 8 -> { // blocking
byte xd = (byte) entityMetadata.getValue();
//blocking gets triggered when using a bow, but if we set USING_ITEM for all items, it may look like
//you're "mining" with ex. a shield.
ItemMapping shield = session.getItemMappings().getStoredItems().shield();
boolean isUsingShield = (getHand().getId() == shield.getBedrockId() ||
getHand().equals(ItemData.AIR) && getOffHand().getId() == shield.getBedrockId());
getHand().equals(ItemData.AIR) && getOffHand().getId() == shield.getBedrockId());
metadata.getFlags().setFlag(EntityFlag.USING_ITEM, (xd & 0x01) == 0x01 && !isUsingShield);
metadata.getFlags().setFlag(EntityFlag.BLOCKING, (xd & 0x01) == 0x01);
// Riptide spin attack
metadata.getFlags().setFlag(EntityFlag.DAMAGE_NEARBY_MOBS, (xd & 0x04) == 0x04);
break;
case 9:
}
case 9 -> {
this.health = (float) entityMetadata.getValue();
AttributeData healthData = createHealthAttribute();
@ -106,14 +106,10 @@ public class LivingEntity extends Entity {
attributesPacket.setRuntimeEntityId(geyserId);
attributesPacket.setAttributes(Collections.singletonList(healthData));
session.sendUpstreamPacket(attributesPacket);
break;
case 10:
metadata.put(EntityData.EFFECT_COLOR, entityMetadata.getValue());
break;
case 11:
metadata.put(EntityData.EFFECT_AMBIENT, (byte) ((boolean) entityMetadata.getValue() ? 1 : 0));
break;
case 14: // Bed Position
}
case 10 -> metadata.put(EntityData.EFFECT_COLOR, entityMetadata.getValue());
case 11 -> metadata.put(EntityData.EFFECT_AMBIENT, (byte) ((boolean) entityMetadata.getValue() ? 1 : 0));
case 14 -> { // Bed Position
Position bedPosition = (Position) entityMetadata.getValue();
if (bedPosition != null) {
metadata.put(EntityData.BED_POSITION, Vector3i.from(bedPosition.getX(), bedPosition.getY(), bedPosition.getZ()));
@ -128,7 +124,7 @@ public class LivingEntity extends Entity {
// Player is no longer sleeping
metadata.put(EntityData.PLAYER_FLAGS, (byte) 0);
}
break;
}
}
super.updateBedrockMetadata(entityMetadata, session);
@ -249,28 +245,16 @@ public class LivingEntity extends Entity {
*/
protected void updateAttribute(Attribute javaAttribute, List<AttributeData> newAttributes) {
switch (javaAttribute.getType()) {
case GENERIC_MAX_HEALTH:
case GENERIC_MAX_HEALTH -> {
this.maxHealth = (float) AttributeUtils.calculateValue(javaAttribute);
newAttributes.add(createHealthAttribute());
break;
case GENERIC_ATTACK_DAMAGE:
newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.ATTACK_DAMAGE));
break;
case GENERIC_FLYING_SPEED:
newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.FLYING_SPEED));
break;
case GENERIC_MOVEMENT_SPEED:
newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.MOVEMENT_SPEED));
break;
case GENERIC_FOLLOW_RANGE:
newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.FOLLOW_RANGE));
break;
case GENERIC_KNOCKBACK_RESISTANCE:
newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.KNOCKBACK_RESISTANCE));
break;
case HORSE_JUMP_STRENGTH:
newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.HORSE_JUMP_STRENGTH));
break;
}
case GENERIC_ATTACK_DAMAGE -> newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.ATTACK_DAMAGE));
case GENERIC_FLYING_SPEED -> newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.FLYING_SPEED));
case GENERIC_MOVEMENT_SPEED -> newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.MOVEMENT_SPEED));
case GENERIC_FOLLOW_RANGE -> newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.FOLLOW_RANGE));
case GENERIC_KNOCKBACK_RESISTANCE -> newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.KNOCKBACK_RESISTANCE));
case HORSE_JUMP_STRENGTH -> newAttributes.add(calculateAttribute(javaAttribute, GeyserAttributeType.HORSE_JUMP_STRENGTH));
}
}

View File

@ -68,12 +68,12 @@ public class PaintingEntity extends Entity {
double widthOffset = paintingName.getWidth() > 1 ? 0.5 : 0;
double heightOffset = paintingName.getHeight() > 1 && paintingName.getHeight() != 3 ? 0.5 : 0;
switch (direction) {
case 0: return position.add(widthOffset, heightOffset, OFFSET);
case 1: return position.add(-OFFSET, heightOffset, widthOffset);
case 2: return position.add(-widthOffset, heightOffset, -OFFSET);
case 3: return position.add(OFFSET, heightOffset, -widthOffset);
}
return position;
return switch (direction) {
case 0 -> position.add(widthOffset, heightOffset, OFFSET);
case 1 -> position.add(-OFFSET, heightOffset, widthOffset);
case 2 -> position.add(-widthOffset, heightOffset, -OFFSET);
case 3 -> position.add(OFFSET, heightOffset, -widthOffset);
default -> position;
};
}
}

View File

@ -161,42 +161,42 @@ public class ArmorStandEntity extends LivingEntity {
EntityFlag negativeYToggle = null;
EntityFlag negativeZToggle = null;
switch (entityMetadata.getId()) {
case 16: // Head
case 16 -> { // Head
dataLeech = EntityData.MARK_VARIANT;
negativeXToggle = EntityFlag.INTERESTED;
negativeYToggle = EntityFlag.CHARGED;
negativeZToggle = EntityFlag.POWERED;
break;
case 17: // Body
}
case 17 -> { // Body
dataLeech = EntityData.VARIANT;
negativeXToggle = EntityFlag.IN_LOVE;
negativeYToggle = EntityFlag.CELEBRATING;
negativeZToggle = EntityFlag.CELEBRATING_SPECIAL;
break;
case 18: // Left arm
}
case 18 -> { // Left arm
dataLeech = EntityData.TRADE_TIER;
negativeXToggle = EntityFlag.CHARGING;
negativeYToggle = EntityFlag.CRITICAL;
negativeZToggle = EntityFlag.DANCING;
break;
case 19: // Right arm
}
case 19 -> { // Right arm
dataLeech = EntityData.MAX_TRADE_TIER;
negativeXToggle = EntityFlag.ELDER;
negativeYToggle = EntityFlag.EMOTING;
negativeZToggle = EntityFlag.IDLING;
break;
case 20: // Left leg
}
case 20 -> { // Left leg
dataLeech = EntityData.SKIN_ID;
negativeXToggle = EntityFlag.IS_ILLAGER_CAPTAIN;
negativeYToggle = EntityFlag.IS_IN_UI;
negativeZToggle = EntityFlag.LINGERING;
break;
case 21: // Right leg
}
case 21 -> { // Right leg
dataLeech = EntityData.HURT_DIRECTION;
negativeXToggle = EntityFlag.IS_PREGNANT;
negativeYToggle = EntityFlag.SHEARED;
negativeZToggle = EntityFlag.STALKING;
break;
}
}
if (dataLeech != null) {
// Indicate that rotation should be checked

View File

@ -44,12 +44,8 @@ public class AxolotlEntity extends AnimalEntity {
if (entityMetadata.getId() == 17) {
int variant = (int) entityMetadata.getValue();
switch (variant) {
case 1: // Java - "Wild" (brown)
variant = 3;
break;
case 3: // Java - cyan
variant = 1;
break;
case 1 -> variant = 3; // Java - "Wild" (brown)
case 3 -> variant = 1; // Java - cyan
}
metadata.put(EntityData.VARIANT, variant);
}

View File

@ -59,23 +59,14 @@ public class CatEntity extends TameableEntity {
}
if (entityMetadata.getId() == 19) {
// Different colors in Java and Bedrock for some reason
int variantColor;
switch ((int) entityMetadata.getValue()) {
case 0:
variantColor = 8;
break;
case 8:
variantColor = 0;
break;
case 9:
variantColor = 10;
break;
case 10:
variantColor = 9;
break;
default:
variantColor = (int) entityMetadata.getValue();
}
int metadataValue = (int) entityMetadata.getValue();
int variantColor = switch (metadataValue) {
case 0 -> 8;
case 8 -> 0;
case 9 -> 10;
case 10 -> 9;
default -> metadataValue;
};
metadata.put(EntityData.VARIANT, variantColor);
}
if (entityMetadata.getId() == 20) {

View File

@ -49,19 +49,13 @@ public class SpellcasterIllagerEntity extends AbstractIllagerEntity {
int spellType = (int) (byte) entityMetadata.getValue();
// Summon vex, attack, or wololo
metadata.getFlags().setFlag(EntityFlag.CASTING, spellType == 1 || spellType == 2 || spellType == 3);
int rgbData = 0;
// Set the spell color based on Java values
switch (spellType) {
case 1:
rgbData = SUMMON_VEX_PARTICLE_COLOR;
break;
case 2:
rgbData = ATTACK_PARTICLE_COLOR;
break;
case 3:
rgbData = WOLOLO_PARTICLE_COLOR;
break;
}
int rgbData = switch (spellType) {
// Set the spell color based on Java values
case 1 -> SUMMON_VEX_PARTICLE_COLOR;
case 2 -> ATTACK_PARTICLE_COLOR;
case 3 -> WOLOLO_PARTICLE_COLOR;
default -> 0;
};
metadata.put(EntityData.EVOKER_SPELL_COLOR, rgbData);
}
super.updateBedrockMetadata(entityMetadata, session);

View File

@ -316,17 +316,12 @@ public class PlayerEntity extends LivingEntity {
protected void setDimensions(Pose pose) {
float height;
switch (pose) {
case SNEAKING:
height = 1.5f;
break;
case FALL_FLYING:
case SPIN_ATTACK:
case SWIMMING:
height = 0.6f;
break;
default:
case SNEAKING -> height = 1.5f;
case FALL_FLYING, SPIN_ATTACK, SWIMMING -> height = 0.6f;
default -> {
super.setDimensions(pose);
return;
}
}
metadata.put(EntityData.BOUNDING_BOX_WIDTH, entityType.getWidth());
metadata.put(EntityData.BOUNDING_BOX_HEIGHT, height);

View File

@ -26,9 +26,7 @@
package org.geysermc.connector.network;
import com.nukkitx.protocol.bedrock.BedrockPacketCodec;
import com.nukkitx.protocol.bedrock.v440.Bedrock_v440;
import com.nukkitx.protocol.bedrock.v448.Bedrock_v448;
import org.geysermc.connector.GeyserConnector;
import java.util.ArrayList;
import java.util.List;
@ -49,11 +47,6 @@ public class BedrockProtocol {
public static final List<BedrockPacketCodec> SUPPORTED_BEDROCK_CODECS = new ArrayList<>();
static {
if (!GeyserConnector.getInstance().getConfig().isExtendedWorldHeight()) {
SUPPORTED_BEDROCK_CODECS.add(Bedrock_v440.V440_CODEC.toBuilder()
.minecraftVersion("1.17.0/1.17.1/1.17.2")
.build());
}
SUPPORTED_BEDROCK_CODECS.add(DEFAULT_BEDROCK_CODEC.toBuilder()
.minecraftVersion("1.17.10/1.17.11")
.build());

View File

@ -129,10 +129,10 @@ public class ConnectorServerEventHandler implements BedrockServerEventHandler {
}
// Fallbacks to prevent errors and allow Bedrock to see the server
if (pong.getMotd() == null || pong.getMotd().trim().isEmpty()) {
if (pong.getMotd() == null || pong.getMotd().isBlank()) {
pong.setMotd(GeyserConnector.NAME);
}
if (pong.getSubMotd() == null || pong.getSubMotd().trim().isEmpty()) {
if (pong.getSubMotd() == null || pong.getSubMotd().isBlank()) {
// Sub-MOTD cannot be empty as of 1.16.210.59
pong.setSubMotd(GeyserConnector.NAME);
}

View File

@ -48,30 +48,18 @@ public class EntityEffectCache {
public void setEffect(Effect effect, int effectAmplifier) {
switch (effect) {
case CONDUIT_POWER:
conduitPower = effectAmplifier + 1;
break;
case FASTER_DIG:
haste = effectAmplifier + 1;
break;
case SLOWER_DIG:
miningFatigue = effectAmplifier + 1;
break;
case CONDUIT_POWER -> conduitPower = effectAmplifier + 1;
case FASTER_DIG -> haste = effectAmplifier + 1;
case SLOWER_DIG -> miningFatigue = effectAmplifier + 1;
}
entityEffects.add(effect);
}
public void removeEffect(Effect effect) {
switch (effect) {
case CONDUIT_POWER:
conduitPower = 0;
break;
case FASTER_DIG:
haste = 0;
break;
case SLOWER_DIG:
miningFatigue = 0;
break;
case CONDUIT_POWER -> conduitPower = 0;
case FASTER_DIG -> haste = 0;
case SLOWER_DIG -> miningFatigue = 0;
}
entityEffects.remove(effect);
}

View File

@ -46,26 +46,25 @@ public class BedrockAnimateTranslator extends PacketTranslator<AnimatePacket> {
}
switch (packet.getAction()) {
case SWING_ARM:
case SWING_ARM ->
// Delay so entity damage can be processed first
session.scheduleInEventLoop(() ->
session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),
25,
TimeUnit.MILLISECONDS
);
break;
// These two might need to be flipped, but my recommendation is getting moving working first
case ROW_LEFT:
case ROW_LEFT -> {
// Packet value is a float of how long one has been rowing, so we convert that into a boolean
session.setSteeringLeft(packet.getRowingTime() > 0.0);
ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
session.sendDownstreamPacket(steerLeftPacket);
break;
case ROW_RIGHT:
}
case ROW_RIGHT -> {
session.setSteeringRight(packet.getRowingTime() > 0.0);
ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
session.sendDownstreamPacket(steerRightPacket);
break;
}
}
}
}

View File

@ -42,18 +42,14 @@ public class BedrockCommandBlockUpdateTranslator extends PacketTranslator<Comman
String command = packet.getCommand();
boolean outputTracked = packet.isOutputTracked();
if (packet.isBlock()) {
CommandBlockMode mode;
switch (packet.getMode()) {
case CHAIN: // The green one
mode = CommandBlockMode.SEQUENCE;
break;
case REPEATING: // The purple one
mode = CommandBlockMode.AUTO;
break;
default: // NORMAL, the orange one
mode = CommandBlockMode.REDSTONE;
break;
}
CommandBlockMode mode = switch (packet.getMode()) {
case CHAIN -> // The green one
CommandBlockMode.SEQUENCE;
case REPEATING -> // The purple one
CommandBlockMode.AUTO;
default -> // NORMAL, the orange one
CommandBlockMode.REDSTONE;
};
boolean isConditional = packet.isConditional();
boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java
ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket(

View File

@ -50,59 +50,30 @@ public class BedrockEntityPickRequestTranslator extends PacketTranslator<EntityP
// Get the corresponding item
String itemName;
switch (entity.getEntityType()) {
case BOAT:
case BOAT -> {
// Include type of boat in the name
int variant = entity.getMetadata().getInt(EntityData.VARIANT);
String typeOfBoat;
switch (variant) {
case 1:
typeOfBoat = "spruce";
break;
case 2:
typeOfBoat = "birch";
break;
case 3:
typeOfBoat = "jungle";
break;
case 4:
typeOfBoat = "acacia";
break;
case 5:
typeOfBoat = "dark_oak";
break;
default:
typeOfBoat = "oak";
break;
}
String typeOfBoat = switch (variant) {
case 1 -> "spruce";
case 2 -> "birch";
case 3 -> "jungle";
case 4 -> "acacia";
case 5 -> "dark_oak";
default -> "oak";
};
itemName = typeOfBoat + "_boat";
break;
case LEASH_KNOT:
itemName = "lead";
break;
case MINECART_CHEST:
case MINECART_COMMAND_BLOCK:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_TNT:
// Move MINECART to the end of the name
itemName = entity.getEntityType().toString().toLowerCase().replace("minecart_", "") + "_minecart";
break;
case MINECART_SPAWNER:
// Turns into a normal minecart
itemName = "minecart";
break;
case ARMOR_STAND:
case END_CRYSTAL:
//case ITEM_FRAME: Not an entity in Bedrock Edition
//case GLOW_ITEM_FRAME:
case MINECART:
case PAINTING:
// No spawn egg, just an item
itemName = entity.getEntityType().toString().toLowerCase();
break;
default:
itemName = entity.getEntityType().toString().toLowerCase() + "_spawn_egg";
break;
}
case LEASH_KNOT -> itemName = "lead";
case MINECART_CHEST, MINECART_COMMAND_BLOCK, MINECART_FURNACE, MINECART_HOPPER, MINECART_TNT ->
// Move MINECART to the end of the name
itemName = entity.getEntityType().toString().toLowerCase().replace("minecart_", "") + "_minecart";
case MINECART_SPAWNER -> itemName = "minecart"; // Turns into a normal minecart
//case ITEM_FRAME -> Not an entity in Bedrock Edition
//case GLOW_ITEM_FRAME ->
case ARMOR_STAND, END_CRYSTAL, MINECART, PAINTING ->
// No spawn egg, just an item
itemName = entity.getEntityType().toString().toLowerCase();
default -> itemName = entity.getEntityType().toString().toLowerCase() + "_spawn_egg";
}
String fullItemName = "minecraft:" + itemName;

View File

@ -108,7 +108,7 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve
break;
case ITEM_USE:
switch (packet.getActionType()) {
case 0:
case 0 -> {
// Check to make sure the client isn't spamming interaction
// Based on Nukkit 1.0, with changes to ensure holding down still works
boolean hasAlreadyClicked = System.currentTimeMillis() - session.getLastInteractionTime() < 110.0 &&
@ -155,17 +155,14 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve
// Adjust position for current eye height
switch (session.getPose()) {
case SNEAKING:
case SNEAKING ->
playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 1.27f), 0);
break;
case SWIMMING:
case FALL_FLYING: // Elytra
case SPIN_ATTACK: // Trident spin attack
case SWIMMING,
FALL_FLYING, // Elytra
SPIN_ATTACK -> // Trident spin attack
playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 0.4f), 0);
break;
case SLEEPING:
case SLEEPING ->
playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 0.2f), 0);
break;
} // else, we don't have to modify the position
float diffX = playerPosition.getX() - packet.getBlockPosition().getX();
@ -248,15 +245,14 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve
}
}
}
ItemMapping handItem = mappings.getMapping(packet.getItemInHand());
if (handItem.isBlock()) {
session.setLastBlockPlacePosition(blockPos);
session.setLastBlockPlacedId(handItem.getJavaIdentifier());
}
session.setInteracting(true);
break;
case 1:
}
case 1 -> {
if (packet.getActions().size() == 1 && packet.getLegacySlots().size() > 0) {
InventoryActionData actionData = packet.getActions().get(0);
LegacySetItemSlotData slotData = packet.getLegacySlots().get(0);
@ -286,8 +282,8 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve
ClientPlayerUseItemPacket useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND);
session.sendDownstreamPacket(useItemPacket);
break;
case 2:
}
case 2 -> {
int blockState = session.getGameMode() == GameMode.CREATIVE ?
session.getConnector().getWorldManager().getBlockAt(session, packet.getBlockPosition()) : session.getBreakingBlock();
@ -301,11 +297,11 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve
}
// This is working out the distance using 3d Pythagoras and the extra value added to the Y is the sneaking height of a java player.
playerPosition = session.getPlayerEntity().getPosition();
Vector3f playerPosition = session.getPlayerEntity().getPosition();
Vector3f floatBlockPosition = packet.getBlockPosition().toFloat();
diffX = playerPosition.getX() - (floatBlockPosition.getX() + 0.5f);
diffY = (playerPosition.getY() - EntityType.PLAYER.getOffset()) - (floatBlockPosition.getY() + 0.5f) + 1.5f;
diffZ = playerPosition.getZ() - (floatBlockPosition.getZ() + 0.5f);
float diffX = playerPosition.getX() - (floatBlockPosition.getX() + 0.5f);
float diffY = (playerPosition.getY() - EntityType.PLAYER.getOffset()) - (floatBlockPosition.getY() + 0.5f) + 1.5f;
float diffZ = playerPosition.getZ() - (floatBlockPosition.getZ() + 0.5f);
float distanceSquared = diffX * diffX + diffY * diffY + diffZ * diffZ;
if (distanceSquared > MAXIMUM_BLOCK_DESTROYING_DISTANCE) {
restoreCorrectBlock(session, packet.getBlockPosition(), packet);
@ -331,7 +327,7 @@ public class BedrockInventoryTransactionTranslator extends PacketTranslator<Inve
Position pos = new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ());
ClientPlayerActionPacket breakPacket = new ClientPlayerActionPacket(action, pos, BlockFace.values()[packet.getBlockFace()]);
session.sendDownstreamPacket(breakPacket);
break;
}
}
break;
case ITEM_RELEASE:

View File

@ -61,12 +61,11 @@ public class BedrockLecternUpdateTranslator extends PacketTranslator<LecternUpda
session.sendDownstreamPacket(blockPacket);
} else {
// Bedrock wants to either move a page or exit
if (!(session.getOpenInventory() instanceof LecternContainer)) {
if (!(session.getOpenInventory() instanceof LecternContainer lecternContainer)) {
session.getConnector().getLogger().debug("Expected lectern but it wasn't open!");
return;
}
LecternContainer lecternContainer = (LecternContainer) session.getOpenInventory();
if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) {
// The same page means Bedrock is closing the window
ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId());

View File

@ -45,19 +45,19 @@ public class BedrockEntityEventTranslator extends PacketTranslator<EntityEventPa
@Override
public void translate(GeyserSession session, EntityEventPacket packet) {
switch (packet.getType()) {
case EATING_ITEM:
case EATING_ITEM -> {
// Resend the packet so we get the eating sounds
session.sendUpstreamPacket(packet);
return;
case COMPLETE_TRADE:
}
case COMPLETE_TRADE -> {
ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData());
session.sendDownstreamPacket(selectTradePacket);
session.scheduleInEventLoop(() -> {
Entity villager = session.getPlayerEntity();
Inventory openInventory = session.getOpenInventory();
if (openInventory instanceof MerchantContainer) {
MerchantContainer merchantInventory = (MerchantContainer) openInventory;
if (openInventory instanceof MerchantContainer merchantInventory) {
VillagerTrade[] trades = merchantInventory.getVillagerTrades();
if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) {
VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()];
@ -68,6 +68,7 @@ public class BedrockEntityEventTranslator extends PacketTranslator<EntityEventPa
}
}, 100, TimeUnit.MILLISECONDS);
return;
}
}
session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString());
}

View File

@ -125,7 +125,7 @@ public class MessageTranslator {
* @return Bedrock formatted message
*/
public static String convertMessageLenient(String message, String locale) {
if (message.trim().isEmpty()) {
if (message.isBlank()) {
return message;
}

View File

@ -90,15 +90,11 @@ public class BoundingBox implements Cloneable {
}
private boolean checkOverlapInAxis(Vector3d offset, BoundingBox otherBox, Axis axis) {
switch (axis) {
case X:
return Math.abs((middleX + offset.getX()) - otherBox.getMiddleX()) * 2 < (sizeX + otherBox.getSizeX());
case Y:
return Math.abs((middleY + offset.getY()) - otherBox.getMiddleY()) * 2 < (sizeY + otherBox.getSizeY());
case Z:
return Math.abs((middleZ + offset.getZ()) - otherBox.getMiddleZ()) * 2 < (sizeZ + otherBox.getSizeZ());
}
return false;
return switch (axis) {
case X -> Math.abs((middleX + offset.getX()) - otherBox.getMiddleX()) * 2 < (sizeX + otherBox.getSizeX());
case Y -> Math.abs((middleY + offset.getY()) - otherBox.getMiddleY()) * 2 < (sizeY + otherBox.getSizeY());
case Z -> Math.abs((middleZ + offset.getZ()) - otherBox.getMiddleZ()) * 2 < (sizeZ + otherBox.getSizeZ());
};
}
/**
@ -141,21 +137,14 @@ public class BoundingBox implements Cloneable {
* @return The distance to move in the direction of {@code side}
*/
public double getIntersectionSize(BoundingBox otherBoundingBox, Direction side) {
switch (side) {
case DOWN:
return getMax().getY() - otherBoundingBox.getMin().getY();
case UP:
return otherBoundingBox.getMax().getY() - getMin().getY();
case NORTH:
return getMax().getZ() - otherBoundingBox.getMin().getZ();
case SOUTH:
return otherBoundingBox.getMax().getZ() - getMin().getZ();
case WEST:
return getMax().getX() - otherBoundingBox.getMin().getX();
case EAST:
return otherBoundingBox.getMax().getX() - getMin().getX();
}
return 0;
return switch (side) {
case DOWN -> getMax().getY() - otherBoundingBox.getMin().getY();
case UP -> otherBoundingBox.getMax().getY() - getMin().getY();
case NORTH -> getMax().getZ() - otherBoundingBox.getMin().getZ();
case SOUTH -> otherBoundingBox.getMax().getZ() - getMin().getZ();
case WEST -> getMax().getX() - otherBoundingBox.getMin().getX();
case EAST -> otherBoundingBox.getMax().getX() - getMin().getX();
};
}
@SneakyThrows(CloneNotSupportedException.class)

View File

@ -31,8 +31,8 @@ import com.nukkitx.math.vector.Vector3i;
import com.nukkitx.protocol.bedrock.data.entity.EntityData;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;
import com.nukkitx.protocol.bedrock.data.entity.EntityFlags;
import com.nukkitx.protocol.bedrock.packet.*;
import com.nukkitx.protocol.bedrock.v448.Bedrock_v448;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;
import lombok.Getter;
import lombok.Setter;
import org.geysermc.connector.entity.player.PlayerEntity;
@ -420,13 +420,8 @@ public class CollisionManager {
boolean flagsChanged;
boolean isSneakingWithScaffolding = (touchingScaffolding || onScaffolding) && session.isSneaking();
if (session.getUpstream().getProtocolVersion() < Bedrock_v448.V448_CODEC.getProtocolVersion()) {
// Now no longer sent with BDS as of 1.17.10
flagsChanged = flags.setFlag(EntityFlag.FALL_THROUGH_SCAFFOLDING, isSneakingWithScaffolding);
} else {
flagsChanged = flags.setFlag(EntityFlag.OVER_DESCENDABLE_BLOCK, onScaffolding);
flagsChanged |= flags.setFlag(EntityFlag.IN_ASCENDABLE_BLOCK, touchingScaffolding);
}
flagsChanged = flags.setFlag(EntityFlag.OVER_DESCENDABLE_BLOCK, onScaffolding);
flagsChanged |= flags.setFlag(EntityFlag.IN_ASCENDABLE_BLOCK, touchingScaffolding);
flagsChanged |= flags.setFlag(EntityFlag.OVER_SCAFFOLDING, isSneakingWithScaffolding);
flagsChanged |= flags.setFlag(EntityFlag.IN_SCAFFOLDING, touchingScaffolding);

View File

@ -75,18 +75,10 @@ public class DoorCollision extends BlockCollision {
int z = blockPos.getZ();
switch (facing) {
case 1: // North
playerCollision.setMiddleZ(z + 0.5125);
break;
case 2: // East
playerCollision.setMiddleX(x + 0.5125);
break;
case 3: // South
playerCollision.setMiddleZ(z + 0.4875);
break;
case 4: // West
playerCollision.setMiddleX(x + 0.4875);
break;
case 1 -> playerCollision.setMiddleZ(z + 0.5125); // North
case 2 -> playerCollision.setMiddleX(x + 0.5125); // East
case 3 -> playerCollision.setMiddleZ(z + 0.4875); // South
case 4 -> playerCollision.setMiddleX(x + 0.4875); // West
}
}

View File

@ -159,21 +159,14 @@ public abstract class InventoryTranslator {
// Some special request that shouldn't be processed normally
response = translateSpecialRequest(session, inventory, request);
} else {
switch (firstAction.getType()) {
case CRAFT_RECIPE:
response = translateCraftingRequest(session, inventory, request);
break;
case CRAFT_RECIPE_AUTO:
response = translateAutoCraftingRequest(session, inventory, request);
break;
case CRAFT_CREATIVE:
// This is also used for pulling items out of creative
response = translateCreativeRequest(session, inventory, request);
break;
default:
response = translateRequest(session, inventory, request);
break;
}
response = switch (firstAction.getType()) {
case CRAFT_RECIPE -> translateCraftingRequest(session, inventory, request);
case CRAFT_RECIPE_AUTO -> translateAutoCraftingRequest(session, inventory, request);
case CRAFT_CREATIVE ->
// This is also used for pulling items out of creative
translateCreativeRequest(session, inventory, request);
default -> translateRequest(session, inventory, request);
};
}
} else {
response = rejectRequest(request);
@ -572,7 +565,7 @@ public abstract class InventoryTranslator {
}
switch (recipe.getType()) {
case CRAFTING_SHAPED:
case CRAFTING_SHAPED -> {
ShapedRecipeData shapedData = (ShapedRecipeData) recipe.getData();
ingredients = shapedData.getIngredients();
recipeWidth = shapedData.getWidth();
@ -580,8 +573,8 @@ public abstract class InventoryTranslator {
if (shapedData.getWidth() > gridDimensions || shapedData.getHeight() > gridDimensions) {
return rejectRequest(request);
}
break;
case CRAFTING_SHAPELESS:
}
case CRAFTING_SHAPELESS -> {
ShapelessRecipeData shapelessData = (ShapelessRecipeData) recipe.getData();
ingredients = shapelessData.getIngredients();
recipeWidth = gridDimensions;
@ -589,7 +582,7 @@ public abstract class InventoryTranslator {
if (ingredients.length > gridSize) {
return rejectRequest(request);
}
break;
}
}
break;
}

View File

@ -179,31 +179,30 @@ public class ClickPlan {
private void simulateAction(ClickAction action) {
GeyserItemStack cursor = simulating ? getCursor() : session.getPlayerInventory().getCursor();
switch (action.click) {
case LEFT_OUTSIDE:
case LEFT_OUTSIDE -> {
setCursor(GeyserItemStack.EMPTY);
return;
case RIGHT_OUTSIDE:
}
case RIGHT_OUTSIDE -> {
if (!cursor.isEmpty()) {
cursor.sub(1);
}
return;
}
}
GeyserItemStack clicked = simulating ? getItem(action.slot) : inventory.getItem(action.slot);
if (translator.getSlotType(action.slot) == SlotType.OUTPUT) {
switch (action.click) {
case LEFT:
case RIGHT:
case LEFT, RIGHT -> {
if (cursor.isEmpty() && !clicked.isEmpty()) {
setCursor(clicked.copy());
} else if (InventoryUtils.canStack(cursor, clicked)) {
cursor.add(clicked.getAmount());
}
reduceCraftingGrid(false);
break;
case LEFT_SHIFT:
reduceCraftingGrid(true);
break;
}
case LEFT_SHIFT -> reduceCraftingGrid(true);
}
} else {
switch (action.click) {

View File

@ -43,42 +43,32 @@ public class AnvilInventoryTranslator extends AbstractBlockInventoryTranslator {
@Override
public int bedrockSlotToJava(StackRequestSlotInfoData slotInfoData) {
switch (slotInfoData.getContainer()) {
case ANVIL_INPUT:
return 0;
case ANVIL_MATERIAL:
return 1;
case ANVIL_RESULT:
case CREATIVE_OUTPUT:
return 2;
}
return super.bedrockSlotToJava(slotInfoData);
return switch (slotInfoData.getContainer()) {
case ANVIL_INPUT -> 0;
case ANVIL_MATERIAL -> 1;
case ANVIL_RESULT, CREATIVE_OUTPUT -> 2;
default -> super.bedrockSlotToJava(slotInfoData);
};
}
@Override
public BedrockContainerSlot javaSlotToBedrockContainer(int slot) {
switch (slot) {
case 0:
return new BedrockContainerSlot(ContainerSlotType.ANVIL_INPUT, 1);
case 1:
return new BedrockContainerSlot(ContainerSlotType.ANVIL_MATERIAL, 2);
case 2:
return new BedrockContainerSlot(ContainerSlotType.ANVIL_RESULT, 50);
}
return super.javaSlotToBedrockContainer(slot);
return switch (slot) {
case 0 -> new BedrockContainerSlot(ContainerSlotType.ANVIL_INPUT, 1);
case 1 -> new BedrockContainerSlot(ContainerSlotType.ANVIL_MATERIAL, 2);
case 2 -> new BedrockContainerSlot(ContainerSlotType.ANVIL_RESULT, 50);
default -> super.javaSlotToBedrockContainer(slot);
};
}
@Override
public int javaSlotToBedrock(int slot) {
switch (slot) {
case 0:
return 1;
case 1:
return 2;
case 2:
return 50;
}
return super.javaSlotToBedrock(slot);
return switch (slot) {
case 0 -> 1;
case 1 -> 2;
case 2 -> 50;
default -> super.javaSlotToBedrock(slot);
};
}
@Override

View File

@ -82,33 +82,23 @@ public class BrewingInventoryTranslator extends AbstractBlockInventoryTranslator
@Override
public int javaSlotToBedrock(int slot) {
switch (slot) {
case 0:
return 1;
case 1:
return 2;
case 2:
return 3;
case 3:
return 0;
case 4:
return 4;
}
return super.javaSlotToBedrock(slot);
return switch (slot) {
case 0 -> 1;
case 1 -> 2;
case 2 -> 3;
case 3 -> 0;
case 4 -> 4;
default -> super.javaSlotToBedrock(slot);
};
}
@Override
public BedrockContainerSlot javaSlotToBedrockContainer(int slot) {
switch (slot) {
case 0:
case 1:
case 2:
return new BedrockContainerSlot(ContainerSlotType.BREWING_RESULT, javaSlotToBedrock(slot));
case 3:
return new BedrockContainerSlot(ContainerSlotType.BREWING_INPUT, 0);
case 4:
return new BedrockContainerSlot(ContainerSlotType.BREWING_FUEL, 4);
}
return super.javaSlotToBedrockContainer(slot);
return switch (slot) {
case 0, 1, 2 -> new BedrockContainerSlot(ContainerSlotType.BREWING_RESULT, javaSlotToBedrock(slot));
case 3 -> new BedrockContainerSlot(ContainerSlotType.BREWING_INPUT, 0);
case 4 -> new BedrockContainerSlot(ContainerSlotType.BREWING_FUEL, 4);
default -> super.javaSlotToBedrockContainer(slot);
};
}
}

View File

@ -59,42 +59,32 @@ public class CartographyInventoryTranslator extends AbstractBlockInventoryTransl
@Override
public int bedrockSlotToJava(StackRequestSlotInfoData slotInfoData) {
switch (slotInfoData.getContainer()) {
case CARTOGRAPHY_INPUT:
return 0;
case CARTOGRAPHY_ADDITIONAL:
return 1;
case CARTOGRAPHY_RESULT:
case CREATIVE_OUTPUT:
return 2;
}
return super.bedrockSlotToJava(slotInfoData);
return switch (slotInfoData.getContainer()) {
case CARTOGRAPHY_INPUT -> 0;
case CARTOGRAPHY_ADDITIONAL -> 1;
case CARTOGRAPHY_RESULT, CREATIVE_OUTPUT -> 2;
default -> super.bedrockSlotToJava(slotInfoData);
};
}
@Override
public BedrockContainerSlot javaSlotToBedrockContainer(int slot) {
switch (slot) {
case 0:
return new BedrockContainerSlot(ContainerSlotType.CARTOGRAPHY_INPUT, 12);
case 1:
return new BedrockContainerSlot(ContainerSlotType.CARTOGRAPHY_ADDITIONAL, 13);
case 2:
return new BedrockContainerSlot(ContainerSlotType.CARTOGRAPHY_RESULT, 50);
}
return super.javaSlotToBedrockContainer(slot);
return switch (slot) {
case 0 -> new BedrockContainerSlot(ContainerSlotType.CARTOGRAPHY_INPUT, 12);
case 1 -> new BedrockContainerSlot(ContainerSlotType.CARTOGRAPHY_ADDITIONAL, 13);
case 2 -> new BedrockContainerSlot(ContainerSlotType.CARTOGRAPHY_RESULT, 50);
default -> super.javaSlotToBedrockContainer(slot);
};
}
@Override
public int javaSlotToBedrock(int slot) {
switch (slot) {
case 0:
return 12;
case 1:
return 13;
case 2:
return 50;
}
return super.javaSlotToBedrock(slot);
return switch (slot) {
case 0 -> 12;
case 1 -> 13;
case 2 -> 50;
default -> super.javaSlotToBedrock(slot);
};
}
@Override

View File

@ -38,41 +38,31 @@ public class GrindstoneInventoryTranslator extends AbstractBlockInventoryTransla
@Override
public int bedrockSlotToJava(StackRequestSlotInfoData slotInfoData) {
switch (slotInfoData.getContainer()) {
case GRINDSTONE_INPUT:
return 0;
case GRINDSTONE_ADDITIONAL:
return 1;
case GRINDSTONE_RESULT:
case CREATIVE_OUTPUT:
return 2;
}
return super.bedrockSlotToJava(slotInfoData);
return switch (slotInfoData.getContainer()) {
case GRINDSTONE_INPUT -> 0;
case GRINDSTONE_ADDITIONAL -> 1;
case GRINDSTONE_RESULT, CREATIVE_OUTPUT -> 2;
default -> super.bedrockSlotToJava(slotInfoData);
};
}
@Override
public BedrockContainerSlot javaSlotToBedrockContainer(int slot) {
switch (slot) {
case 0:
return new BedrockContainerSlot(ContainerSlotType.GRINDSTONE_INPUT, 16);
case 1:
return new BedrockContainerSlot(ContainerSlotType.GRINDSTONE_ADDITIONAL, 17);
case 2:
return new BedrockContainerSlot(ContainerSlotType.GRINDSTONE_RESULT, 50);
}
return super.javaSlotToBedrockContainer(slot);
return switch (slot) {
case 0 -> new BedrockContainerSlot(ContainerSlotType.GRINDSTONE_INPUT, 16);
case 1 -> new BedrockContainerSlot(ContainerSlotType.GRINDSTONE_ADDITIONAL, 17);
case 2 -> new BedrockContainerSlot(ContainerSlotType.GRINDSTONE_RESULT, 50);
default -> super.javaSlotToBedrockContainer(slot);
};
}
@Override
public int javaSlotToBedrock(int slot) {
switch (slot) {
case 0:
return 16;
case 1:
return 17;
case 2:
return 50;
}
return super.javaSlotToBedrock(slot);
return switch (slot) {
case 0 -> 16;
case 1 -> 17;
case 2 -> 50;
default -> super.javaSlotToBedrock(slot);
};
}
}

View File

@ -125,10 +125,9 @@ public class LoomInventoryTranslator extends AbstractBlockInventoryTranslator {
public ItemStackResponsePacket.Response translateSpecialRequest(GeyserSession session, Inventory inventory, ItemStackRequest request) {
// TODO: I anticipate this will be changed in the future to use something non-deprecated. Keep an eye out.
StackRequestActionData data = request.getActions()[1];
if (!(data instanceof CraftResultsDeprecatedStackRequestActionData)) {
if (!(data instanceof CraftResultsDeprecatedStackRequestActionData craftData)) {
return rejectRequest(request);
}
CraftResultsDeprecatedStackRequestActionData craftData = (CraftResultsDeprecatedStackRequestActionData) data;
// Get the patterns compound tag
List<NbtMap> newBlockEntityTag = craftData.getResultItems()[0].getTag().getList("Patterns", NbtType.COMPOUND);
@ -177,48 +176,35 @@ public class LoomInventoryTranslator extends AbstractBlockInventoryTranslator {
@Override
public int bedrockSlotToJava(StackRequestSlotInfoData slotInfoData) {
switch (slotInfoData.getContainer()) {
case LOOM_INPUT:
return 0;
case LOOM_DYE:
return 1;
case LOOM_MATERIAL:
return 2;
case LOOM_RESULT:
case CREATIVE_OUTPUT:
return 3;
}
return super.bedrockSlotToJava(slotInfoData);
return switch (slotInfoData.getContainer()) {
case LOOM_INPUT -> 0;
case LOOM_DYE -> 1;
case LOOM_MATERIAL -> 2;
case LOOM_RESULT, CREATIVE_OUTPUT -> 3;
default -> super.bedrockSlotToJava(slotInfoData);
};
}
@Override
public BedrockContainerSlot javaSlotToBedrockContainer(int slot) {
switch (slot) {
case 0:
return new BedrockContainerSlot(ContainerSlotType.LOOM_INPUT, 9);
case 1:
return new BedrockContainerSlot(ContainerSlotType.LOOM_DYE, 10);
case 2:
return new BedrockContainerSlot(ContainerSlotType.LOOM_MATERIAL, 11);
case 3:
return new BedrockContainerSlot(ContainerSlotType.LOOM_RESULT, 50);
}
return super.javaSlotToBedrockContainer(slot);
return switch (slot) {
case 0 -> new BedrockContainerSlot(ContainerSlotType.LOOM_INPUT, 9);
case 1 -> new BedrockContainerSlot(ContainerSlotType.LOOM_DYE, 10);
case 2 -> new BedrockContainerSlot(ContainerSlotType.LOOM_MATERIAL, 11);
case 3 -> new BedrockContainerSlot(ContainerSlotType.LOOM_RESULT, 50);
default -> super.javaSlotToBedrockContainer(slot);
};
}
@Override
public int javaSlotToBedrock(int slot) {
switch (slot) {
case 0:
return 9;
case 1:
return 10;
case 2:
return 11;
case 3:
return 50;
}
return super.javaSlotToBedrock(slot);
return switch (slot) {
case 0 -> 9;
case 1 -> 10;
case 2 -> 11;
case 3 -> 50;
default -> super.javaSlotToBedrock(slot);
};
}
@Override

View File

@ -56,42 +56,32 @@ public class MerchantInventoryTranslator extends BaseInventoryTranslator {
@Override
public int javaSlotToBedrock(int slot) {
switch (slot) {
case 0:
return 4;
case 1:
return 5;
case 2:
return 50;
}
return super.javaSlotToBedrock(slot);
return switch (slot) {
case 0 -> 4;
case 1 -> 5;
case 2 -> 50;
default -> super.javaSlotToBedrock(slot);
};
}
@Override
public BedrockContainerSlot javaSlotToBedrockContainer(int slot) {
switch (slot) {
case 0:
return new BedrockContainerSlot(ContainerSlotType.TRADE2_INGREDIENT1, 4);
case 1:
return new BedrockContainerSlot(ContainerSlotType.TRADE2_INGREDIENT2, 5);
case 2:
return new BedrockContainerSlot(ContainerSlotType.TRADE2_RESULT, 50);
}
return super.javaSlotToBedrockContainer(slot);
return switch (slot) {
case 0 -> new BedrockContainerSlot(ContainerSlotType.TRADE2_INGREDIENT1, 4);
case 1 -> new BedrockContainerSlot(ContainerSlotType.TRADE2_INGREDIENT2, 5);
case 2 -> new BedrockContainerSlot(ContainerSlotType.TRADE2_RESULT, 50);
default -> super.javaSlotToBedrockContainer(slot);
};
}
@Override
public int bedrockSlotToJava(StackRequestSlotInfoData slotInfoData) {
switch (slotInfoData.getContainer()) {
case TRADE2_INGREDIENT1:
return 0;
case TRADE2_INGREDIENT2:
return 1;
case TRADE2_RESULT:
case CREATIVE_OUTPUT:
return 2;
}
return super.bedrockSlotToJava(slotInfoData);
return switch (slotInfoData.getContainer()) {
case TRADE2_INGREDIENT1 -> 0;
case TRADE2_INGREDIENT2 -> 1;
case TRADE2_RESULT, CREATIVE_OUTPUT -> 2;
default -> super.bedrockSlotToJava(slotInfoData);
};
}
@Override

View File

@ -218,8 +218,7 @@ public class PlayerInventoryTranslator extends InventoryTranslator {
IntSet affectedSlots = new IntOpenHashSet();
for (StackRequestActionData action : request.getActions()) {
switch (action.getType()) {
case TAKE:
case PLACE: {
case TAKE, PLACE -> {
TransferStackRequestActionData transferAction = (TransferStackRequestActionData) action;
if (!(checkNetId(session, inventory, transferAction.getSource()) && checkNetId(session, inventory, transferAction.getDestination()))) {
return rejectRequest(request);
@ -265,9 +264,8 @@ public class PlayerInventoryTranslator extends InventoryTranslator {
affectedSlots.add(sourceSlot);
affectedSlots.add(destSlot);
}
break;
}
case SWAP: {
case SWAP -> {
SwapStackRequestActionData swapAction = (SwapStackRequestActionData) action;
if (!(checkNetId(session, inventory, swapAction.getSource()) && checkNetId(session, inventory, swapAction.getDestination()))) {
return rejectRequest(request);
@ -306,9 +304,8 @@ public class PlayerInventoryTranslator extends InventoryTranslator {
affectedSlots.add(sourceSlot);
affectedSlots.add(destSlot);
}
break;
}
case DROP: {
case DROP -> {
DropStackRequestActionData dropAction = (DropStackRequestActionData) action;
if (!checkNetId(session, inventory, dropAction.getSource())) {
return rejectRequest(request);
@ -334,9 +331,8 @@ public class PlayerInventoryTranslator extends InventoryTranslator {
session.sendDownstreamPacket(creativeDropPacket);
sourceItem.sub(dropAction.getCount());
break;
}
case DESTROY: {
case DESTROY -> {
// Only called when a creative client wants to destroy an item... I think - Camotoy
DestroyStackRequestActionData destroyAction = (DestroyStackRequestActionData) action;
if (!checkNetId(session, inventory, destroyAction.getSource())) {
@ -356,11 +352,11 @@ public class PlayerInventoryTranslator extends InventoryTranslator {
// Just sync up the item on our end, since the server doesn't care what's in our cursor
playerInv.getCursor().sub(destroyAction.getCount());
}
break;
}
default:
default -> {
session.getConnector().getLogger().error("Unknown crafting state induced by " + session.getName());
return rejectRequest(request);
}
}
}
for (int slot : affectedSlots) {

View File

@ -38,41 +38,31 @@ public class SmithingInventoryTranslator extends AbstractBlockInventoryTranslato
@Override
public int bedrockSlotToJava(StackRequestSlotInfoData slotInfoData) {
switch (slotInfoData.getContainer()) {
case SMITHING_TABLE_INPUT:
return 0;
case SMITHING_TABLE_MATERIAL:
return 1;
case SMITHING_TABLE_RESULT:
case CREATIVE_OUTPUT:
return 2;
}
return super.bedrockSlotToJava(slotInfoData);
return switch (slotInfoData.getContainer()) {
case SMITHING_TABLE_INPUT -> 0;
case SMITHING_TABLE_MATERIAL -> 1;
case SMITHING_TABLE_RESULT, CREATIVE_OUTPUT -> 2;
default -> super.bedrockSlotToJava(slotInfoData);
};
}
@Override
public BedrockContainerSlot javaSlotToBedrockContainer(int slot) {
switch (slot) {
case 0:
return new BedrockContainerSlot(ContainerSlotType.SMITHING_TABLE_INPUT, 51);
case 1:
return new BedrockContainerSlot(ContainerSlotType.SMITHING_TABLE_MATERIAL, 52);
case 2:
return new BedrockContainerSlot(ContainerSlotType.SMITHING_TABLE_RESULT, 50);
}
return super.javaSlotToBedrockContainer(slot);
return switch (slot) {
case 0 -> new BedrockContainerSlot(ContainerSlotType.SMITHING_TABLE_INPUT, 51);
case 1 -> new BedrockContainerSlot(ContainerSlotType.SMITHING_TABLE_MATERIAL, 52);
case 2 -> new BedrockContainerSlot(ContainerSlotType.SMITHING_TABLE_RESULT, 50);
default -> super.javaSlotToBedrockContainer(slot);
};
}
@Override
public int javaSlotToBedrock(int slot) {
switch (slot) {
case 0:
return 51;
case 1:
return 52;
case 2:
return 50;
}
return super.javaSlotToBedrock(slot);
return switch (slot) {
case 0 -> 51;
case 1 -> 52;
case 2 -> 50;
default -> super.javaSlotToBedrock(slot);
};
}
}

View File

@ -61,10 +61,9 @@ public class StonecutterInventoryTranslator extends AbstractBlockInventoryTransl
public ItemStackResponsePacket.Response translateSpecialRequest(GeyserSession session, Inventory inventory, ItemStackRequest request) {
// TODO: Also surely to change in the future
StackRequestActionData data = request.getActions()[1];
if (!(data instanceof CraftResultsDeprecatedStackRequestActionData)) {
if (!(data instanceof CraftResultsDeprecatedStackRequestActionData craftData)) {
return rejectRequest(request);
}
CraftResultsDeprecatedStackRequestActionData craftData = (CraftResultsDeprecatedStackRequestActionData) data;
StonecutterContainer container = (StonecutterContainer) inventory;
// Get the ID of the item we are cutting
@ -94,14 +93,11 @@ public class StonecutterInventoryTranslator extends AbstractBlockInventoryTransl
@Override
public int bedrockSlotToJava(StackRequestSlotInfoData slotInfoData) {
switch (slotInfoData.getContainer()) {
case STONECUTTER_INPUT:
return 0;
case STONECUTTER_RESULT:
case CREATIVE_OUTPUT:
return 1;
}
return super.bedrockSlotToJava(slotInfoData);
return switch (slotInfoData.getContainer()) {
case STONECUTTER_INPUT -> 0;
case STONECUTTER_RESULT, CREATIVE_OUTPUT -> 1;
default -> super.bedrockSlotToJava(slotInfoData);
};
}
@Override

View File

@ -299,8 +299,7 @@ public abstract class ItemTranslator {
return ((StringTag) tag).getValue();
}
if (tag instanceof ListTag) {
ListTag listTag = (ListTag) tag;
if (tag instanceof ListTag listTag) {
List<Object> tagList = new ArrayList<>();
for (Tag value : listTag) {
@ -313,8 +312,7 @@ public abstract class ItemTranslator {
return new NbtList(type, tagList);
}
if (tag instanceof CompoundTag) {
CompoundTag compoundTag = (CompoundTag) tag;
if (tag instanceof CompoundTag compoundTag) {
return translateNbtToBedrock(compoundTag);
}
@ -390,8 +388,7 @@ public abstract class ItemTranslator {
return new ListTag(name, tags);
}
if (object instanceof NbtMap) {
NbtMap map = (NbtMap) object;
if (object instanceof NbtMap map) {
return translateToJavaNBT(name, map);
}

View File

@ -49,11 +49,9 @@ public class BookPagesTranslator extends NbtItemStackTranslator {
List<Tag> pages = new ArrayList<>();
ListTag pagesTag = itemTag.get("pages");
for (Tag tag : pagesTag.getValue()) {
if (!(tag instanceof StringTag))
if (!(tag instanceof StringTag textTag))
continue;
StringTag textTag = (StringTag) tag;
CompoundTag pageTag = new CompoundTag("");
pageTag.put(new StringTag("photoname", ""));
pageTag.put(new StringTag("text", MessageTranslator.convertMessageLenient(textTag.getValue())));
@ -72,11 +70,9 @@ public class BookPagesTranslator extends NbtItemStackTranslator {
List<Tag> pages = new ArrayList<>();
ListTag pagesTag = itemTag.get("pages");
for (Tag tag : pagesTag.getValue()) {
if (!(tag instanceof CompoundTag))
if (!(tag instanceof CompoundTag pageTag))
continue;
CompoundTag pageTag = (CompoundTag) tag;
StringTag textTag = pageTag.get("text");
pages.add(new StringTag("", textTag.getValue()));
}

View File

@ -82,10 +82,9 @@ public class EnchantmentTranslator extends NbtItemStackTranslator {
List<Tag> enchantments = new ArrayList<>();
List<Tag> storedEnchantments = new ArrayList<>();
for (Tag value : enchantmentTag.getValue()) {
if (!(value instanceof CompoundTag))
if (!(value instanceof CompoundTag tagValue))
continue;
CompoundTag tagValue = (CompoundTag) value;
ShortTag bedrockId = tagValue.get("id");
if (bedrockId == null) continue;

View File

@ -41,20 +41,12 @@ public class JavaChatTranslator extends PacketTranslator<ServerChatPacket> {
textPacket.setPlatformChatId("");
textPacket.setSourceName("");
textPacket.setXuid(session.getAuthData().getXboxUUID());
switch (packet.getType()) {
case CHAT:
textPacket.setType(TextPacket.Type.CHAT);
break;
case SYSTEM:
textPacket.setType(TextPacket.Type.SYSTEM);
break;
case NOTIFICATION:
textPacket.setType(TextPacket.Type.TIP);
break;
default:
textPacket.setType(TextPacket.Type.RAW);
break;
}
textPacket.setType(switch (packet.getType()) {
case CHAT -> TextPacket.Type.CHAT;
case SYSTEM -> TextPacket.Type.SYSTEM;
case NOTIFICATION -> TextPacket.Type.TIP;
default -> TextPacket.Type.RAW;
});
textPacket.setNeedsTranslation(false);
textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale()));

View File

@ -204,67 +204,25 @@ public class JavaDeclareCommandsTranslator extends PacketTranslator<ServerDeclar
return CommandParam.STRING;
}
switch (parser) {
case FLOAT:
case ROTATION:
case DOUBLE:
return CommandParam.FLOAT;
case INTEGER:
case LONG:
return CommandParam.INT;
case ENTITY:
case GAME_PROFILE:
return CommandParam.TARGET;
case BLOCK_POS:
return CommandParam.BLOCK_POSITION;
case COLUMN_POS:
case VEC3:
return CommandParam.POSITION;
case MESSAGE:
return CommandParam.MESSAGE;
case NBT:
case NBT_COMPOUND_TAG:
case NBT_TAG:
case NBT_PATH:
return CommandParam.JSON;
case RESOURCE_LOCATION:
case FUNCTION:
return CommandParam.FILE_PATH;
case BOOL:
return ENUM_BOOLEAN;
case OPERATION: // ">=", "==", etc
return CommandParam.OPERATOR;
case BLOCK_STATE:
return BlockRegistries.JAVA_TO_BEDROCK_IDENTIFIERS.get().keySet().toArray(new String[0]);
case ITEM_STACK:
return session.getItemMappings().getItemNames();
case ITEM_ENCHANTMENT:
return Enchantment.JavaEnchantment.ALL_JAVA_IDENTIFIERS;
case ENTITY_SUMMON:
return EntityType.ALL_JAVA_IDENTIFIERS;
case COLOR:
return VALID_COLORS;
case SCOREBOARD_SLOT:
return VALID_SCOREBOARD_SLOTS;
default:
return CommandParam.STRING;
}
return switch (parser) {
case FLOAT, ROTATION, DOUBLE -> CommandParam.FLOAT;
case INTEGER, LONG -> CommandParam.INT;
case ENTITY, GAME_PROFILE -> CommandParam.TARGET;
case BLOCK_POS -> CommandParam.BLOCK_POSITION;
case COLUMN_POS, VEC3 -> CommandParam.POSITION;
case MESSAGE -> CommandParam.MESSAGE;
case NBT, NBT_COMPOUND_TAG, NBT_TAG, NBT_PATH -> CommandParam.JSON;
case RESOURCE_LOCATION, FUNCTION -> CommandParam.FILE_PATH;
case BOOL -> ENUM_BOOLEAN;
case OPERATION -> CommandParam.OPERATOR; // ">=", "==", etc
case BLOCK_STATE -> BlockRegistries.JAVA_TO_BEDROCK_IDENTIFIERS.get().keySet().toArray(new String[0]);
case ITEM_STACK -> session.getItemMappings().getItemNames();
case ITEM_ENCHANTMENT -> Enchantment.JavaEnchantment.ALL_JAVA_IDENTIFIERS;
case ENTITY_SUMMON -> EntityType.ALL_JAVA_IDENTIFIERS;
case COLOR -> VALID_COLORS;
case SCOREBOARD_SLOT -> VALID_SCOREBOARD_SLOTS;
default -> CommandParam.STRING;
};
}
@Getter

View File

@ -82,7 +82,7 @@ public class JavaDeclareRecipesTranslator extends PacketTranslator<ServerDeclare
craftingDataPacket.setCleanRecipes(true);
for (Recipe recipe : packet.getRecipes()) {
switch (recipe.getType()) {
case CRAFTING_SHAPELESS: {
case CRAFTING_SHAPELESS -> {
ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData();
ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult());
// Strip NBT - tools won't appear in the recipe book otherwise
@ -94,9 +94,8 @@ public class JavaDeclareRecipesTranslator extends PacketTranslator<ServerDeclare
Arrays.asList(inputs), Collections.singletonList(output), uuid, "crafting_table", 0, netId));
recipeMap.put(netId++, recipe);
}
break;
}
case CRAFTING_SHAPED: {
case CRAFTING_SHAPED -> {
ShapedRecipeData shapedRecipeData = (ShapedRecipeData) recipe.getData();
ItemData output = ItemTranslator.translateToBedrock(session, shapedRecipeData.getResult());
// See above
@ -106,12 +105,11 @@ public class JavaDeclareRecipesTranslator extends PacketTranslator<ServerDeclare
UUID uuid = UUID.randomUUID();
craftingDataPacket.getCraftingData().add(CraftingData.fromShaped(uuid.toString(),
shapedRecipeData.getWidth(), shapedRecipeData.getHeight(), Arrays.asList(inputs),
Collections.singletonList(output), uuid, "crafting_table", 0, netId));
Collections.singletonList(output), uuid, "crafting_table", 0, netId));
recipeMap.put(netId++, recipe);
}
break;
}
case STONECUTTING: {
case STONECUTTING -> {
StoneCuttingRecipeData stoneCuttingData = (StoneCuttingRecipeData) recipe.getData();
ItemStack ingredient = stoneCuttingData.getIngredient().getOptions()[0];
List<StoneCuttingRecipeData> data = unsortedStonecutterData.get(ingredient.getId());
@ -121,14 +119,12 @@ public class JavaDeclareRecipesTranslator extends PacketTranslator<ServerDeclare
}
data.add(stoneCuttingData);
// Save for processing after all recipes have been received
break;
}
default: {
default -> {
List<CraftingData> craftingData = recipeTypes.get(recipe.getType());
if (craftingData != null) {
craftingDataPacket.getCraftingData().addAll(craftingData);
}
break;
}
}
}

View File

@ -50,7 +50,7 @@ public class JavaEntityEquipmentTranslator extends PacketTranslator<ServerEntity
if (entity == null)
return;
if (!(entity instanceof LivingEntity)) {
if (!(entity instanceof LivingEntity livingEntity)) {
session.getConnector().getLogger().debug("Attempted to add armor to a non-living entity type (" +
entity.getEntityType().name() + ").");
return;
@ -59,34 +59,33 @@ public class JavaEntityEquipmentTranslator extends PacketTranslator<ServerEntity
boolean armorUpdated = false;
boolean mainHandUpdated = false;
boolean offHandUpdated = false;
LivingEntity livingEntity = (LivingEntity) entity;
for (Equipment equipment : packet.getEquipment()) {
ItemData item = ItemTranslator.translateToBedrock(session, equipment.getItem());
switch (equipment.getSlot()) {
case HELMET:
case HELMET -> {
livingEntity.setHelmet(item);
armorUpdated = true;
break;
case CHESTPLATE:
}
case CHESTPLATE -> {
livingEntity.setChestplate(item);
armorUpdated = true;
break;
case LEGGINGS:
}
case LEGGINGS -> {
livingEntity.setLeggings(item);
armorUpdated = true;
break;
case BOOTS:
}
case BOOTS -> {
livingEntity.setBoots(item);
armorUpdated = true;
break;
case MAIN_HAND:
}
case MAIN_HAND -> {
livingEntity.setHand(item);
mainHandUpdated = true;
break;
case OFF_HAND:
}
case OFF_HAND -> {
livingEntity.setOffHand(item);
offHandUpdated = true;
break;
}
}
}

View File

@ -124,14 +124,10 @@ public class JavaEntitySetPassengersTranslator extends PacketTranslator<ServerEn
}
switch (entity.getEntityType()) {
case HORSE:
case SKELETON_HORSE:
case DONKEY:
case MULE:
case RAVAGER:
case HORSE, SKELETON_HORSE, DONKEY, MULE, RAVAGER -> {
entity.getMetadata().put(EntityData.RIDER_MAX_ROTATION, 181.0f);
entity.updateBedrockMetadata(session);
break;
}
}
}
}

View File

@ -211,8 +211,7 @@ public class JavaEntityStatusTranslator extends PacketTranslator<ServerEntitySta
session.sendUpstreamPacket(equipmentBreakPacket);
return;
case PLAYER_SWAP_SAME_ITEM: // Not just used for players
if (entity instanceof LivingEntity) {
LivingEntity livingEntity = (LivingEntity) entity;
if (entity instanceof LivingEntity livingEntity) {
ItemData newMainHand = livingEntity.getOffHand();
livingEntity.setOffHand(livingEntity.getHand());
livingEntity.setHand(newMainHand);

View File

@ -49,7 +49,7 @@ public class JavaPlayerListEntryTranslator extends PacketTranslator<ServerPlayer
for (PlayerListEntry entry : packet.getEntries()) {
switch (packet.getAction()) {
case ADD_PLAYER:
case ADD_PLAYER -> {
PlayerEntity playerEntity;
boolean self = entry.getProfile().getId().equals(session.getPlayerEntity().getUuid());
@ -90,8 +90,8 @@ public class JavaPlayerListEntryTranslator extends PacketTranslator<ServerPlayer
translate.getEntries().add(playerListEntry);
}
break;
case REMOVE_PLAYER:
}
case REMOVE_PLAYER -> {
// As the player entity is no longer present, we can remove the entry
PlayerEntity entity = session.getEntityCache().removePlayerEntity(entry.getProfile().getId());
if (entity != null) {
@ -105,7 +105,7 @@ public class JavaPlayerListEntryTranslator extends PacketTranslator<ServerPlayer
} else {
translate.getEntries().add(new PlayerListPacket.Entry(entry.getProfile().getId()));
}
break;
}
}
}

View File

@ -52,14 +52,9 @@ public class JavaScoreboardObjectiveTranslator extends PacketTranslator<ServerSc
}
switch (packet.getAction()) {
case ADD:
case UPDATE:
objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName()))
.setType(packet.getType().ordinal());
break;
case REMOVE:
scoreboard.unregisterObjective(packet.getName());
break;
case ADD, UPDATE -> objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName()))
.setType(packet.getType().ordinal());
case REMOVE -> scoreboard.unregisterObjective(packet.getName());
}
if (objective == null || !objective.isActive()) {

View File

@ -57,15 +57,13 @@ public class JavaTeamTranslator extends PacketTranslator<ServerTeamPacket> {
Scoreboard scoreboard = session.getWorldCache().getScoreboard();
Team team = scoreboard.getTeam(packet.getTeamName());
switch (packet.getAction()) {
case CREATE:
scoreboard.registerNewTeam(packet.getTeamName(), toPlayerSet(packet.getPlayers()))
.setName(MessageTranslator.convertMessage(packet.getDisplayName()))
.setColor(packet.getColor())
.setNameTagVisibility(packet.getNameTagVisibility())
.setPrefix(MessageTranslator.convertMessage(packet.getPrefix(), session.getLocale()))
.setSuffix(MessageTranslator.convertMessage(packet.getSuffix(), session.getLocale()));
break;
case UPDATE:
case CREATE -> scoreboard.registerNewTeam(packet.getTeamName(), toPlayerSet(packet.getPlayers()))
.setName(MessageTranslator.convertMessage(packet.getDisplayName()))
.setColor(packet.getColor())
.setNameTagVisibility(packet.getNameTagVisibility())
.setPrefix(MessageTranslator.convertMessage(packet.getPrefix(), session.getLocale()))
.setSuffix(MessageTranslator.convertMessage(packet.getSuffix(), session.getLocale()));
case UPDATE -> {
if (team == null) {
LOGGER.debug(LanguageUtils.getLocaleStringLog(
"geyser.network.translator.team.failed_not_registered",
@ -80,8 +78,8 @@ public class JavaTeamTranslator extends PacketTranslator<ServerTeamPacket> {
.setPrefix(MessageTranslator.convertMessage(packet.getPrefix(), session.getLocale()))
.setSuffix(MessageTranslator.convertMessage(packet.getSuffix(), session.getLocale()))
.setUpdateType(UpdateType.UPDATE);
break;
case ADD_PLAYER:
}
case ADD_PLAYER -> {
if (team == null) {
LOGGER.debug(LanguageUtils.getLocaleStringLog(
"geyser.network.translator.team.failed_not_registered",
@ -90,8 +88,8 @@ public class JavaTeamTranslator extends PacketTranslator<ServerTeamPacket> {
return;
}
team.addEntities(packet.getPlayers());
break;
case REMOVE_PLAYER:
}
case REMOVE_PLAYER -> {
if (team == null) {
LOGGER.debug(LanguageUtils.getLocaleStringLog(
"geyser.network.translator.team.failed_not_registered",
@ -100,10 +98,8 @@ public class JavaTeamTranslator extends PacketTranslator<ServerTeamPacket> {
return;
}
team.removeEntities(packet.getPlayers());
break;
case REMOVE:
scoreboard.removeTeam(packet.getTeamName());
break;
}
case REMOVE -> scoreboard.removeTeam(packet.getTeamName());
}
// ScoreboardUpdater will handle it for us if the packets per second

View File

@ -53,40 +53,20 @@ public class JavaBlockBreakAnimTranslator extends PacketTranslator<ServerBlockBr
levelEventPacket.setType(LevelEventType.BLOCK_START_BREAK);
switch (packet.getStage()) {
case STAGE_1:
levelEventPacket.setData(breakTime);
break;
case STAGE_2:
levelEventPacket.setData(breakTime * 2);
break;
case STAGE_3:
levelEventPacket.setData(breakTime * 3);
break;
case STAGE_4:
levelEventPacket.setData(breakTime * 4);
break;
case STAGE_5:
levelEventPacket.setData(breakTime * 5);
break;
case STAGE_6:
levelEventPacket.setData(breakTime * 6);
break;
case STAGE_7:
levelEventPacket.setData(breakTime * 7);
break;
case STAGE_8:
levelEventPacket.setData(breakTime * 8);
break;
case STAGE_9:
levelEventPacket.setData(breakTime * 9);
break;
case STAGE_10:
levelEventPacket.setData(breakTime * 10);
break;
case RESET:
case STAGE_1 -> levelEventPacket.setData(breakTime);
case STAGE_2 -> levelEventPacket.setData(breakTime * 2);
case STAGE_3 -> levelEventPacket.setData(breakTime * 3);
case STAGE_4 -> levelEventPacket.setData(breakTime * 4);
case STAGE_5 -> levelEventPacket.setData(breakTime * 5);
case STAGE_6 -> levelEventPacket.setData(breakTime * 6);
case STAGE_7 -> levelEventPacket.setData(breakTime * 7);
case STAGE_8 -> levelEventPacket.setData(breakTime * 8);
case STAGE_9 -> levelEventPacket.setData(breakTime * 9);
case STAGE_10 -> levelEventPacket.setData(breakTime * 10);
case RESET -> {
levelEventPacket.setType(LevelEventType.BLOCK_STOP_BREAK);
levelEventPacket.setData(0);
break;
}
}
session.sendUpstreamPacket(levelEventPacket);
}

View File

@ -52,8 +52,7 @@ public class JavaBlockValueTranslator extends PacketTranslator<ServerBlockValueP
BlockEventPacket blockEventPacket = new BlockEventPacket();
blockEventPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(),
packet.getPosition().getY(), packet.getPosition().getZ()));
if (packet.getValue() instanceof ChestValue) {
ChestValue value = (ChestValue) packet.getValue() ;
if (packet.getValue() instanceof ChestValue value) {
blockEventPacket.setEventType(1);
blockEventPacket.setEventData(value.getViewers() > 0 ? 1 : 0);
session.sendUpstreamPacket(blockEventPacket);
@ -62,9 +61,9 @@ public class JavaBlockValueTranslator extends PacketTranslator<ServerBlockValueP
session.sendUpstreamPacket(blockEventPacket);
} else if (packet.getValue() instanceof NoteBlockValue) {
NoteblockBlockEntityTranslator.translate(session, packet.getPosition());
} else if (packet.getValue() instanceof PistonValue) {
} else if (packet.getValue() instanceof PistonValue pistonValue) {
PistonValueType action = (PistonValueType) packet.getType();
Direction direction = Direction.fromPistonValue((PistonValue) packet.getValue());
Direction direction = Direction.fromPistonValue(pistonValue);
Vector3i position = Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());
PistonCache pistonCache = session.getPistonCache();
@ -105,9 +104,8 @@ public class JavaBlockValueTranslator extends PacketTranslator<ServerBlockValueP
} else if (packet.getValue() instanceof EndGatewayValue) {
blockEventPacket.setEventType(1);
session.sendUpstreamPacket(blockEventPacket);
} else if (packet.getValue() instanceof GenericBlockValue && packet.getBlockId() == BlockStateValues.JAVA_BELL_ID) {
} else if (packet.getValue() instanceof GenericBlockValue bellValue && packet.getBlockId() == BlockStateValues.JAVA_BELL_ID) {
// Bells - needed to show ring from other players
GenericBlockValue bellValue = (GenericBlockValue) packet.getValue();
Position position = packet.getPosition();
BlockEntityDataPacket blockEntityPacket = new BlockEntityDataPacket();
@ -118,20 +116,12 @@ public class JavaBlockValueTranslator extends PacketTranslator<ServerBlockValueP
builder.putInt("y", position.getY());
builder.putInt("z", position.getZ());
builder.putString("id", "Bell");
int bedrockRingDirection;
switch (bellValue.getValue()) {
case 3: // north
bedrockRingDirection = 0;
break;
case 4: // east
bedrockRingDirection = 1;
break;
case 5: // west
bedrockRingDirection = 3;
break;
default: // south (2) is identical
bedrockRingDirection = bellValue.getValue();
}
int bedrockRingDirection = switch (bellValue.getValue()) {
case 3 -> 0; // north
case 4 -> 1; // east
case 5 -> 3;// west
default -> bellValue.getValue(); // south (2) is identical
};
builder.putInt("Direction", bedrockRingDirection);
builder.putByte("Ringing", (byte) 1);
builder.putInt("Ticks", 0);

View File

@ -125,16 +125,16 @@ public class JavaNotifyClientTranslator extends PacketTranslator<ServerNotifyCli
break;
case ENTER_CREDITS:
switch ((EnterCreditsValue) packet.getValue()) {
case SEEN_BEFORE:
case SEEN_BEFORE -> {
ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
session.sendDownstreamPacket(javaRespawnPacket);
break;
case FIRST_TIME:
}
case FIRST_TIME -> {
ShowCreditsPacket showCreditsPacket = new ShowCreditsPacket();
showCreditsPacket.setStatus(ShowCreditsPacket.Status.START_CREDITS);
showCreditsPacket.setRuntimeEntityId(entity.getGeyserId());
session.sendUpstreamPacket(showCreditsPacket);
break;
}
}
break;
case AFFECTED_BY_ELDER_GUARDIAN:

View File

@ -80,34 +80,28 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
return;
}
if (packet.getEffect() instanceof SoundEffect) {
SoundEffect soundEffect = (SoundEffect) packet.getEffect();
if (packet.getEffect() instanceof SoundEffect soundEffect) {
Effect geyserEffect = Registries.SOUND_EFFECTS.get(soundEffect);
if (geyserEffect != null) {
geyserEffect.handleEffectPacket(session, packet);
return;
}
GeyserConnector.getInstance().getLogger().debug("Unhandled sound effect: " + soundEffect.name());
} else if (packet.getEffect() instanceof ParticleEffect) {
ParticleEffect particleEffect = (ParticleEffect) packet.getEffect();
} else if (packet.getEffect() instanceof ParticleEffect particleEffect) {
Vector3f pos = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()).add(0.5f, 0.5f, 0.5f);
LevelEventPacket effectPacket = new LevelEventPacket();
effectPacket.setPosition(pos);
effectPacket.setData(0);
switch (particleEffect) {
case COMPOSTER: {
case COMPOSTER -> {
effectPacket.setType(LevelEventType.PARTICLE_CROP_GROWTH);
ComposterEffectData composterEffectData = (ComposterEffectData) packet.getData();
LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket();
switch (composterEffectData) {
case FILL:
soundEventPacket.setSound(SoundEvent.COMPOSTER_FILL);
break;
case FILL_SUCCESS:
soundEventPacket.setSound(SoundEvent.COMPOSTER_FILL_LAYER);
break;
case FILL -> soundEventPacket.setSound(SoundEvent.COMPOSTER_FILL);
case FILL_SUCCESS -> soundEventPacket.setSound(SoundEvent.COMPOSTER_FILL_LAYER);
}
soundEventPacket.setPosition(pos);
soundEventPacket.setIdentifier("");
@ -115,9 +109,8 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
soundEventPacket.setBabySound(false);
soundEventPacket.setRelativeVolumeDisabled(false);
session.sendUpstreamPacket(soundEventPacket);
break;
}
case BLOCK_LAVA_EXTINGUISH: {
case BLOCK_LAVA_EXTINGUISH -> {
effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE);
effectPacket.setPosition(pos.add(-0.5f, 0.7f, -0.5f));
@ -129,9 +122,8 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
soundEventPacket.setBabySound(false);
soundEventPacket.setRelativeVolumeDisabled(false);
session.sendUpstreamPacket(soundEventPacket);
break;
}
case BLOCK_REDSTONE_TORCH_BURNOUT: {
case BLOCK_REDSTONE_TORCH_BURNOUT -> {
effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE);
effectPacket.setPosition(pos.add(-0.5f, 0, -0.5f));
@ -143,9 +135,8 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
soundEventPacket.setBabySound(false);
soundEventPacket.setRelativeVolumeDisabled(false);
session.sendUpstreamPacket(soundEventPacket);
break;
}
case BLOCK_END_PORTAL_FRAME_FILL: {
case BLOCK_END_PORTAL_FRAME_FILL -> {
effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE);
effectPacket.setPosition(pos.add(-0.5f, 0.3125f, -0.5f));
@ -157,53 +148,50 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
soundEventPacket.setBabySound(false);
soundEventPacket.setRelativeVolumeDisabled(false);
session.sendUpstreamPacket(soundEventPacket);
break;
}
case SMOKE: {
case SMOKE -> {
effectPacket.setType(LevelEventType.PARTICLE_SHOOT);
SmokeEffectData smokeEffectData = (SmokeEffectData) packet.getData();
int data = 0;
switch (smokeEffectData) {
case DOWN:
case DOWN -> {
data = 4;
pos = pos.add(0, -0.9f, 0);
break;
case UP:
}
case UP -> {
data = 4;
pos = pos.add(0, 0.5f, 0);
break;
case NORTH:
}
case NORTH -> {
data = 1;
pos = pos.add(0, -0.2f, -0.7f);
break;
case SOUTH:
}
case SOUTH -> {
data = 7;
pos = pos.add(0, -0.2f, 0.7f);
break;
case WEST:
}
case WEST -> {
data = 3;
pos = pos.add(-0.7f, -0.2f, 0);
break;
case EAST:
}
case EAST -> {
data = 5;
pos = pos.add(0.7f, -0.2f, 0);
break;
}
}
effectPacket.setPosition(pos);
effectPacket.setData(data);
break;
}
//TODO: Block break particles when under fire
case BREAK_BLOCK: {
case BREAK_BLOCK -> {
effectPacket.setType(LevelEventType.PARTICLE_DESTROY_BLOCK);
BreakBlockEffectData breakBlockEffectData = (BreakBlockEffectData) packet.getData();
effectPacket.setData(session.getBlockMappings().getBedrockBlockId(breakBlockEffectData.getBlockState()));
break;
}
case BREAK_SPLASH_POTION: {
case BREAK_SPLASH_POTION -> {
effectPacket.setType(LevelEventType.PARTICLE_POTION_SPLASH);
effectPacket.setPosition(pos.add(0, -0.5f, 0));
@ -218,25 +206,21 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
soundEventPacket.setBabySound(false);
soundEventPacket.setRelativeVolumeDisabled(false);
session.sendUpstreamPacket(soundEventPacket);
break;
}
case BREAK_EYE_OF_ENDER: {
case BREAK_EYE_OF_ENDER -> {
effectPacket.setType(LevelEventType.PARTICLE_EYE_OF_ENDER_DEATH);
break;
}
case MOB_SPAWN: {
case MOB_SPAWN -> {
effectPacket.setType(LevelEventType.PARTICLE_MOB_BLOCK_SPAWN); // TODO: Check, but I don't think I really verified this ever went into effect on Java
break;
}
case BONEMEAL_GROW_WITH_SOUND: // Note that there is no particle without sound in Bedrock. If you wanted to implement the sound, send a PlaySoundPacket with "item.bone_meal.use" and volume and pitch at 1.0F
case BONEMEAL_GROW: {
// Note that there is no particle without sound in Bedrock. If you wanted to implement the sound, send a PlaySoundPacket with "item.bone_meal.use" and volume and pitch at 1.0F
case BONEMEAL_GROW_WITH_SOUND, BONEMEAL_GROW -> {
effectPacket.setType(LevelEventType.PARTICLE_CROP_GROWTH);
BonemealGrowEffectData growEffectData = (BonemealGrowEffectData) packet.getData();
effectPacket.setData(growEffectData.getParticleCount());
break;
}
case ENDERDRAGON_FIREBALL_EXPLODE: {
case ENDERDRAGON_FIREBALL_EXPLODE -> {
effectPacket.setType(LevelEventType.PARTICLE_EYE_OF_ENDER_DEATH); // TODO
DragonFireballEffectData fireballEffectData = (DragonFireballEffectData) packet.getData();
@ -250,19 +234,16 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
soundEventPacket.setRelativeVolumeDisabled(false);
session.sendUpstreamPacket(soundEventPacket);
}
break;
}
case EXPLOSION: {
case EXPLOSION -> {
effectPacket.setType(LevelEventType.PARTICLE_GENERIC_SPAWN);
effectPacket.setData(61);
break;
}
case EVAPORATE: {
case EVAPORATE -> {
effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE_WATER);
effectPacket.setPosition(pos.add(-0.5f, 0.5f, -0.5f));
break;
}
case END_GATEWAY_SPAWN: {
case END_GATEWAY_SPAWN -> {
effectPacket.setType(LevelEventType.PARTICLE_EXPLOSION);
LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket();
@ -273,30 +254,24 @@ public class JavaPlayEffectTranslator extends PacketTranslator<ServerPlayEffectP
soundEventPacket.setBabySound(false);
soundEventPacket.setRelativeVolumeDisabled(false);
session.sendUpstreamPacket(soundEventPacket);
break;
}
case DRIPSTONE_DRIP: {
case DRIPSTONE_DRIP -> {
effectPacket.setType(LevelEventType.PARTICLE_DRIPSTONE_DRIP);
break;
}
case ELECTRIC_SPARK: {
case ELECTRIC_SPARK -> {
// Matches with a Bedrock server but doesn't seem to match up with Java
effectPacket.setType(LevelEventType.PARTICLE_ELECTRIC_SPARK);
break;
}
case WAX_ON: {
case WAX_ON -> {
effectPacket.setType(LevelEventType.PARTICLE_WAX_ON);
break;
}
case WAX_OFF: {
case WAX_OFF -> {
effectPacket.setType(LevelEventType.PARTICLE_WAX_OFF);
break;
}
case SCRAPE: {
case SCRAPE -> {
effectPacket.setType(LevelEventType.PARTICLE_SCRAPE);
break;
}
default: {
default -> {
GeyserConnector.getInstance().getLogger().debug("Unhandled particle effect: " + particleEffect.name());
return;
}

View File

@ -82,7 +82,7 @@ public class JavaSpawnParticleTranslator extends PacketTranslator<ServerSpawnPar
*/
private Function<Vector3f, BedrockPacket> createParticle(GeyserSession session, Particle particle) {
switch (particle.getType()) {
case BLOCK: {
case BLOCK -> {
int blockState = session.getBlockMappings().getBedrockBlockId(((BlockParticleData) particle.getData()).getBlockState());
return (position) -> {
LevelEventPacket packet = new LevelEventPacket();
@ -92,7 +92,7 @@ public class JavaSpawnParticleTranslator extends PacketTranslator<ServerSpawnPar
return packet;
};
}
case FALLING_DUST: {
case FALLING_DUST -> {
int blockState = session.getBlockMappings().getBedrockBlockId(((FallingDustParticleData) particle.getData()).getBlockState());
return (position) -> {
LevelEventPacket packet = new LevelEventPacket();
@ -104,7 +104,7 @@ public class JavaSpawnParticleTranslator extends PacketTranslator<ServerSpawnPar
return packet;
};
}
case ITEM: {
case ITEM -> {
ItemStack javaItem = ((ItemParticleData) particle.getData()).getItemStack();
ItemData bedrockItem = ItemTranslator.translateToBedrock(session, javaItem);
int data = bedrockItem.getId() << 16 | bedrockItem.getDamage();
@ -116,8 +116,7 @@ public class JavaSpawnParticleTranslator extends PacketTranslator<ServerSpawnPar
return packet;
};
}
case DUST:
case DUST_COLOR_TRANSITION: { //TODO
case DUST, DUST_COLOR_TRANSITION -> { //TODO
DustParticleData data = (DustParticleData) particle.getData();
int r = (int) (data.getRed() * 255);
int g = (int) (data.getGreen() * 255);
@ -131,7 +130,7 @@ public class JavaSpawnParticleTranslator extends PacketTranslator<ServerSpawnPar
return packet;
};
}
default: {
default -> {
ParticleMapping particleMapping = Registries.PARTICLES.get(particle.getType());
if (particleMapping == null) { //TODO ensure no particle can be null
return null;

View File

@ -53,12 +53,11 @@ public class JavaTradeListTranslator extends PacketTranslator<ServerTradeListPac
@Override
public void translate(GeyserSession session, ServerTradeListPacket packet) {
Inventory openInventory = session.getOpenInventory();
if (!(openInventory instanceof MerchantContainer && openInventory.getId() == packet.getWindowId())) {
if (!(openInventory instanceof MerchantContainer merchantInventory && openInventory.getId() == packet.getWindowId())) {
return;
}
// Retrieve the fake villager involved in the trade, and update its metadata to match with the window information
MerchantContainer merchantInventory = (MerchantContainer) openInventory;
merchantInventory.setVillagerTrades(packet.getTrades());
Entity villager = merchantInventory.getVillager();
villager.getMetadata().put(EntityData.TRADE_TIER, packet.getVillagerLevel() - 1);

View File

@ -56,39 +56,15 @@ public class BiomeTranslator {
if (bedrockId == -1) {
// There is no matching Bedrock variation for this biome; let's set the closest match based on biome category
String category = ((StringTag) ((CompoundTag) biomeTag.get("element")).get("category")).getValue();
String replacementBiome;
switch (category) {
case "extreme_hills":
replacementBiome = "minecraft:mountains";
break;
case "icy":
replacementBiome = "minecraft:ice_spikes";
break;
case "mesa":
replacementBiome = "minecraft:badlands";
break;
case "mushroom":
replacementBiome = "minecraft:mushroom_fields";
break;
case "nether":
replacementBiome = "minecraft:nether_wastes";
break;
default:
replacementBiome = "minecraft:ocean"; // Typically ID 0 so a good default
break;
case "taiga":
case "jungle":
case "plains":
case "savanna":
case "the_end":
case "beach":
case "ocean":
case "desert":
case "river":
case "swamp":
replacementBiome = "minecraft:" + category;
break;
}
String replacementBiome = switch (category) {
case "extreme_hills" -> "minecraft:mountains";
case "icy" -> "minecraft:ice_spikes";
case "mesa" -> "minecraft:badlands";
case "mushroom" -> "minecraft:mushroom_fields";
case "nether" -> "minecraft:nether_wastes";
default -> "minecraft:ocean"; // Typically ID 0 so a good default
case "taiga", "jungle", "plains", "savanna", "the_end", "beach", "ocean", "desert", "river", "swamp" -> "minecraft:" + category;
};
bedrockId = Registries.BIOME_IDENTIFIERS.get().getInt(replacementBiome);
}

View File

@ -155,21 +155,12 @@ public class BlockStateValues {
if (javaId.contains("wall_skull") || javaId.contains("wall_head")) {
String direction = javaId.substring(javaId.lastIndexOf("facing=") + 7);
int rotation = 0;
switch (direction.substring(0, direction.length() - 1)) {
case "north":
rotation = 180;
break;
case "south":
rotation = 0;
break;
case "west":
rotation = 90;
break;
case "east":
rotation = 270;
break;
}
int rotation = switch (direction.substring(0, direction.length() - 1)) {
case "north" -> 180;
case "west" -> 90;
case "east" -> 270;
default -> 0; // Also south
};
SKULL_WALL_DIRECTIONS.put(javaBlockState, rotation);
}
@ -405,16 +396,12 @@ public class BlockStateValues {
*/
public static float getSlipperiness(int state) {
String blockIdentifier = BlockRegistries.JAVA_BLOCKS.getOrDefault(state, BlockMapping.AIR).getJavaIdentifier();
switch (blockIdentifier) {
case "minecraft:slime_block":
return 0.8f;
case "minecraft:ice":
case "minecraft:packed_ice":
return 0.98f;
case "minecraft:blue_ice":
return 0.989f;
}
return 0.6f;
return switch (blockIdentifier) {
case "minecraft:slime_block" -> 0.8f;
case "minecraft:ice", "minecraft:packed_ice" -> 0.98f;
case "minecraft:blue_ice" -> 0.989f;
default -> 0.6f;
};
}
private static Direction getBlockDirection(String javaId) {

View File

@ -147,13 +147,8 @@ public class PistonBlockEntity {
// Set progress and lastProgress to allow 0 tick pistons to animate
switch (action) {
case PUSHING:
progress = 0;
break;
case PULLING:
case CANCELLED_MID_PUSH:
progress = 1;
break;
case PUSHING -> progress = 0;
case PULLING, CANCELLED_MID_PUSH -> progress = 1;
}
lastProgress = progress;
@ -182,13 +177,8 @@ public class PistonBlockEntity {
// Set progress and lastProgress to allow 0 tick pistons to animate
switch (action) {
case PUSHING:
progress = 0;
break;
case PULLING:
case CANCELLED_MID_PUSH:
progress = 1;
break;
case PUSHING -> progress = 0;
case PULLING, CANCELLED_MID_PUSH -> progress = 1;
}
lastProgress = progress;
@ -326,15 +316,11 @@ public class PistonBlockEntity {
if (block.getHardness() == -1.0d) {
return false;
}
switch (block.getPistonBehavior()) {
case BLOCK:
case DESTROY:
return false;
case PUSH_ONLY: // Glazed terracotta can only be pushed
return isPushing;
}
// Pistons can't move block entities
return !block.isBlockEntity();
return switch (block.getPistonBehavior()) {
case BLOCK, DESTROY -> false;
case PUSH_ONLY -> isPushing; // Glazed terracotta can only be pushed
default -> !block.isBlockEntity(); // Pistons can't move block entities
};
}
/**
@ -723,21 +709,20 @@ public class PistonBlockEntity {
*/
private void updateProgress() {
switch (action) {
case PUSHING:
case PUSHING -> {
lastProgress = progress;
progress += 0.5f;
if (progress >= 1.0f) {
progress = 1.0f;
}
break;
case CANCELLED_MID_PUSH:
case PULLING:
}
case CANCELLED_MID_PUSH, PULLING -> {
lastProgress = progress;
progress -= 0.5f;
if (progress <= 0.0f) {
progress = 0.0f;
}
break;
}
}
}
@ -745,14 +730,10 @@ public class PistonBlockEntity {
* @return True if the piston has finished its movement, otherwise false
*/
public boolean isDone() {
switch (action) {
case PUSHING:
return progress == 1.0f && lastProgress == 1.0f;
case PULLING:
case CANCELLED_MID_PUSH:
return progress == 0.0f && lastProgress == 0.0f;
}
return true;
return switch (action) {
case PUSHING -> progress == 1.0f && lastProgress == 1.0f;
case PULLING, CANCELLED_MID_PUSH -> progress == 0.0f && lastProgress == 0.0f;
};
}
public boolean canBeRemoved() {

View File

@ -41,59 +41,24 @@ public class SignBlockEntityTranslator extends BlockEntityTranslator {
*/
private int getBedrockSignColor(String javaColor) {
//TODO create a DyeColor class and combine with FireworkColor???
int dyeColor;
switch (javaColor) {
case "white":
dyeColor = 16383998;
break;
case "orange":
dyeColor = 16351261;
break;
case "magenta":
dyeColor = 13061821;
break;
case "light_blue":
dyeColor = 3847130;
break;
case "yellow":
dyeColor = 16701501;
break;
case "lime":
dyeColor = 8439583;
break;
case "pink":
dyeColor = 15961002;
break;
case "gray":
dyeColor = 4673362;
break;
case "light_gray":
dyeColor = 10329495;
break;
case "cyan":
dyeColor = 1481884;
break;
case "purple":
dyeColor = 8991416;
break;
case "blue":
dyeColor = 3949738;
break;
case "brown":
dyeColor = 8606770;
break;
case "green":
dyeColor = 6192150;
break;
case "red":
dyeColor = 11546150;
break;
case "black":
default:
// The proper Java color is 1908001, but this does not render well with glow text.
dyeColor = 0;
break;
}
int dyeColor = switch (javaColor) {
case "white" -> 16383998;
case "orange" -> 16351261;
case "magenta" -> 13061821;
case "light_blue" -> 3847130;
case "yellow" -> 16701501;
case "lime" -> 8439583;
case "pink" -> 15961002;
case "gray" -> 4673362;
case "light_gray" -> 10329495;
case "cyan" -> 1481884;
case "purple" -> 8991416;
case "blue" -> 3949738;
case "brown" -> 8606770;
case "green" -> 6192150;
case "red" -> 11546150;
default -> 0; // The proper Java color is 1908001, but this does not render well with glow text.
};
// Add the transparency of the color, too.
return dyeColor | (255 << 24);
}

View File

@ -99,22 +99,10 @@ public class SkullBlockEntityTranslator extends BlockEntityTranslator implements
y += 0.25f;
rotation = BlockStateValues.getSkullWallDirections().get(blockState);
switch ((int) rotation) {
case 180:
// North
z += 0.24f;
break;
case 0:
// South
z -= 0.24f;
break;
case 90:
// West
x += 0.24f;
break;
case 270:
// East
x -= 0.24f;
break;
case 180 -> z += 0.24f; // North
case 0 -> z -= 0.24f; // South
case 90 -> x += 0.24f; // West
case 270 -> x -= 0.24f; // East
}
} else {
rotation = (180f + (floorRotation * 22.5f)) % 360;

View File

@ -58,22 +58,20 @@ public class SoundEffectsRegistryLoader extends EffectRegistryLoader<Map<SoundEf
SoundEffect javaEffect = null;
Effect effect = null;
switch (type) {
case "soundLevel": {
case "soundLevel" -> {
javaEffect = SoundEffect.valueOf(entry.getKey());
LevelEventType levelEventType = LevelEventType.valueOf(node.get("name").asText());
int data = node.has("data") ? node.get("data").intValue() : 0;
effect = new SoundLevelEffect(levelEventType, data);
break;
}
case "soundEvent": {
case "soundEvent" -> {
javaEffect = SoundEffect.valueOf(entry.getKey());
SoundEvent soundEvent = SoundEvent.valueOf(node.get("name").asText());
String identifier = node.has("identifier") ? node.get("identifier").asText() : "";
int extraData = node.has("extraData") ? node.get("extraData").intValue() : -1;
effect = new SoundEventEffect(soundEvent, identifier, extraData);
break;
}
case "playSound": {
case "playSound" -> {
javaEffect = SoundEffect.valueOf(entry.getKey());
String name = node.get("name").asText();
float volume = node.has("volume") ? node.get("volume").floatValue() : 1.0f;
@ -82,7 +80,6 @@ public class SoundEffectsRegistryLoader extends EffectRegistryLoader<Map<SoundEf
float pitchAdd = node.has("pitch_add") ? node.get("pitch_add").floatValue() : 0.0f;
boolean relative = !node.has("relative") || node.get("relative").booleanValue();
effect = new PlaySoundEffect(name, volume, pitchSub, pitchMul, pitchAdd, relative);
break;
}
}
if (javaEffect != null) {

View File

@ -28,7 +28,6 @@ package org.geysermc.connector.registry.populator;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableMap;
import com.nukkitx.nbt.*;
import com.nukkitx.protocol.bedrock.v440.Bedrock_v440;
import com.nukkitx.protocol.bedrock.v448.Bedrock_v448;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
@ -66,29 +65,9 @@ public class BlockRegistryPopulator {
static {
ImmutableMap.Builder<String, BiFunction<String, NbtMapBuilder, String>> stateMapperBuilder = ImmutableMap.<String, BiFunction<String, NbtMapBuilder, String>>builder()
.put("1_17_10", (bedrockIdentifier, statesBuilder) -> null);
if (!GeyserConnector.getInstance().getConfig().isExtendedWorldHeight()) {
stateMapperBuilder.put("1_17_0", (bedrockIdentifier, statesBuilder) -> {
if (bedrockIdentifier.contains("candle")) {
// Replace candles with sea pickles or cake
if (bedrockIdentifier.contains("cake")) {
statesBuilder.remove("lit");
statesBuilder.putInt("bite_counter", 0);
return "minecraft:cake";
} else {
statesBuilder.put("cluster_count", statesBuilder.remove("candles"));
statesBuilder.putBoolean("dead_bit", ((byte) (statesBuilder.remove("lit"))) != 0);
return "minecraft:sea_pickle";
}
}
return null;
});
}
STATE_MAPPER = stateMapperBuilder.build();
PALETTE_VERSIONS = new Object2IntOpenHashMap<>();
if (!GeyserConnector.getInstance().getConfig().isExtendedWorldHeight()) {
PALETTE_VERSIONS.put("1_17_0", Bedrock_v440.V440_CODEC.getProtocolVersion());
}
PALETTE_VERSIONS.put("1_17_10", Bedrock_v448.V448_CODEC.getProtocolVersion());
}
@ -159,17 +138,10 @@ public class BlockRegistryPopulator {
}
switch (javaId) {
case "minecraft:air":
airRuntimeId = bedrockRuntimeId;
break;
case "minecraft:water[level=0]":
waterRuntimeId = bedrockRuntimeId;
break;
case "minecraft:command_block[conditional=false,facing=north]":
commandBlockRuntimeId = bedrockRuntimeId;
break;
case "minecraft:moving_piston[facing=north,type=normal]":
movingBlockRuntimeId = bedrockRuntimeId;
case "minecraft:air" -> airRuntimeId = bedrockRuntimeId;
case "minecraft:water[level=0]" -> waterRuntimeId = bedrockRuntimeId;
case "minecraft:command_block[conditional=false,facing=north]" -> commandBlockRuntimeId = bedrockRuntimeId;
case "minecraft:moving_piston[facing=north,type=normal]" -> movingBlockRuntimeId = bedrockRuntimeId;
}
if (javaId.contains("jigsaw")) {
@ -414,14 +386,9 @@ public class BlockRegistryPopulator {
Map.Entry<String, JsonNode> stateEntry = statesIterator.next();
JsonNode stateValue = stateEntry.getValue();
switch (stateValue.getNodeType()) {
case BOOLEAN:
statesBuilder.putBoolean(stateEntry.getKey(), stateValue.booleanValue());
continue;
case STRING:
statesBuilder.putString(stateEntry.getKey(), stateValue.textValue());
continue;
case NUMBER:
statesBuilder.putInt(stateEntry.getKey(), stateValue.intValue());
case BOOLEAN -> statesBuilder.putBoolean(stateEntry.getKey(), stateValue.booleanValue());
case STRING -> statesBuilder.putString(stateEntry.getKey(), stateValue.textValue());
case NUMBER -> statesBuilder.putInt(stateEntry.getKey(), stateValue.intValue());
}
}
}

View File

@ -35,7 +35,6 @@ import com.nukkitx.protocol.bedrock.data.SoundEvent;
import com.nukkitx.protocol.bedrock.data.inventory.ComponentItemData;
import com.nukkitx.protocol.bedrock.data.inventory.ItemData;
import com.nukkitx.protocol.bedrock.packet.StartGamePacket;
import com.nukkitx.protocol.bedrock.v440.Bedrock_v440;
import com.nukkitx.protocol.bedrock.v448.Bedrock_v448;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
@ -67,27 +66,6 @@ public class ItemRegistryPopulator {
if (GeyserConnector.getInstance().getConfig().isExtendedWorldHeight()) {
PALETTE_VERSIONS.put("1_17_10.caves_and_cliffs", new PaletteVersion(Bedrock_v448.V448_CODEC.getProtocolVersion(), Collections.emptyMap()));
} else {
PALETTE_VERSIONS.put("1_17_0", new PaletteVersion(Bedrock_v440.V440_CODEC.getProtocolVersion(), new Object2ObjectOpenHashMap<String, String>() {
{
put("minecraft:candle", "minecraft:sea_pickle");
put("minecraft:white_candle", "minecraft:sea_pickle");
put("minecraft:orange_candle", "minecraft:sea_pickle");
put("minecraft:magenta_candle", "minecraft:sea_pickle");
put("minecraft:light_blue_candle", "minecraft:sea_pickle");
put("minecraft:yellow_candle", "minecraft:sea_pickle");
put("minecraft:lime_candle", "minecraft:sea_pickle");
put("minecraft:pink_candle", "minecraft:sea_pickle");
put("minecraft:gray_candle", "minecraft:sea_pickle");
put("minecraft:light_gray_candle", "minecraft:sea_pickle");
put("minecraft:cyan_candle", "minecraft:sea_pickle");
put("minecraft:purple_candle", "minecraft:sea_pickle");
put("minecraft:blue_candle", "minecraft:sea_pickle");
put("minecraft:brown_candle", "minecraft:sea_pickle");
put("minecraft:green_candle", "minecraft:sea_pickle");
put("minecraft:red_candle", "minecraft:sea_pickle");
put("minecraft:black_candle", "minecraft:sea_pickle");
}
}));
PALETTE_VERSIONS.put("1_17_10", new PaletteVersion(Bedrock_v448.V448_CODEC.getProtocolVersion(), Collections.emptyMap()));
}
}

View File

@ -76,25 +76,19 @@ public final class Objective {
}
private static String translateDisplaySlot(ScoreboardPosition displaySlot) {
switch (displaySlot) {
case BELOW_NAME:
return "belowname";
case PLAYER_LIST:
return "list";
default:
return "sidebar";
}
return switch (displaySlot) {
case BELOW_NAME -> "belowname";
case PLAYER_LIST -> "list";
default -> "sidebar";
};
}
private static ScoreboardPosition correctDisplaySlot(ScoreboardPosition displaySlot) {
switch (displaySlot) {
case BELOW_NAME:
return ScoreboardPosition.BELOW_NAME;
case PLAYER_LIST:
return ScoreboardPosition.PLAYER_LIST;
default:
return ScoreboardPosition.SIDEBAR;
}
return switch (displaySlot) {
case BELOW_NAME -> ScoreboardPosition.BELOW_NAME;
case PLAYER_LIST -> ScoreboardPosition.PLAYER_LIST;
default -> ScoreboardPosition.SIDEBAR;
};
}
public void registerScore(String id, int score) {

View File

@ -240,12 +240,8 @@ public final class Scoreboard {
Team current = teamIterator.next();
switch (current.getUpdateType()) {
case ADD:
case UPDATE:
current.markUpdated();
break;
case REMOVE:
teamIterator.remove();
case ADD, UPDATE -> current.markUpdated();
case REMOVE -> teamIterator.remove();
}
}

View File

@ -181,17 +181,12 @@ public final class Team {
}
public boolean isVisibleFor(String entity) {
switch (nameTagVisibility) {
case HIDE_FOR_OTHER_TEAMS:
return hasEntity(entity);
case HIDE_FOR_OWN_TEAM:
return !hasEntity(entity);
case ALWAYS:
return true;
case NEVER:
return false;
}
return true;
return switch (nameTagVisibility) {
case HIDE_FOR_OTHER_TEAMS -> hasEntity(entity);
case HIDE_FOR_OWN_TEAM -> !hasEntity(entity);
case ALWAYS -> true;
case NEVER -> false;
};
}
@Override

View File

@ -132,18 +132,10 @@ public final class FloodgateSkinUploader {
case LOG_MESSAGE:
String logMessage = node.get("message").asText();
switch (node.get("priority").asInt()) {
case -1:
logger.debug("Got a message from skin uploader: " + logMessage);
break;
case 0:
logger.info("Got a message from skin uploader: " +logMessage);
break;
case 1:
logger.error("Got a message from skin uploader: " + logMessage);
break;
default:
logger.info(logMessage);
break;
case -1 -> logger.debug("Got a message from skin uploader: " + logMessage);
case 0 -> logger.info("Got a message from skin uploader: " + logMessage);
case 1 -> logger.error("Got a message from skin uploader: " + logMessage);
default -> logger.info(logMessage);
}
break;
case NEWS_ADDED:

View File

@ -679,11 +679,11 @@ public class SkinProvider {
}
public static String toRequestedType(CapeUrlType type, UUID uuid, String username) {
switch (type) {
case UUID: return uuid.toString().replace("-", "");
case UUID_DASHED: return uuid.toString();
default: return username;
}
return switch (type) {
case UUID -> uuid.toString().replace("-", "");
case UUID_DASHED -> uuid.toString();
default -> username;
};
}
}
@ -715,11 +715,11 @@ public class SkinProvider {
}
public static String toRequestedType(CapeUrlType type, UUID uuid, String username) {
switch (type) {
case UUID: return uuid.toString().replace("-", "");
case UUID_DASHED: return uuid.toString();
default: return username;
}
return switch (type) {
case UUID -> uuid.toString().replace("-", "");
case UUID_DASHED -> uuid.toString();
default -> username;
};
}
}
}

View File

@ -37,14 +37,10 @@ public enum Axis {
* @return The component of the vector in this axis
*/
public double choose(Vector3d vector) {
switch (this) {
case X:
return vector.getX();
case Y:
return vector.getY();
case Z:
return vector.getZ();
}
return -1;
return switch (this) {
case X -> vector.getX();
case Y -> vector.getY();
case Z -> vector.getZ();
};
}
}

View File

@ -67,23 +67,16 @@ public class BlockUtils {
private static double toolBreakTimeBonus(String toolType, String toolTier, boolean isShearsEffective) {
if (toolType.equals("shears")) return isShearsEffective ? 5.0 : 15.0;
if (toolType.equals("")) return 1.0;
switch (toolTier) {
return switch (toolTier) {
// https://minecraft.gamepedia.com/Breaking#Speed
case "wooden":
return 2.0;
case "stone":
return 4.0;
case "iron":
return 6.0;
case "diamond":
return 8.0;
case "netherite":
return 9.0;
case "golden":
return 12.0;
default:
return 1.0;
}
case "wooden" -> 2.0;
case "stone" -> 4.0;
case "iron" -> 6.0;
case "diamond" -> 8.0;
case "netherite" -> 9.0;
case "golden" -> 12.0;
default -> 1.0;
};
}
private static boolean canToolTierBreakBlock(GeyserSession session, BlockMapping blockMapping, String toolTier) {
@ -208,21 +201,15 @@ public class BlockUtils {
* @return the block position with the block face accounted for
*/
public static Vector3i getBlockPosition(Vector3i blockPos, int face) {
switch (face) {
case 0:
return blockPos.sub(0, 1, 0);
case 1:
return blockPos.add(0, 1, 0);
case 2:
return blockPos.sub(0, 0, 1);
case 3:
return blockPos.add(0, 0, 1);
case 4:
return blockPos.sub(1, 0, 0);
case 5:
return blockPos.add(1, 0, 0);
}
return blockPos;
return switch (face) {
case 0 -> blockPos.sub(0, 1, 0);
case 1 -> blockPos.add(0, 1, 0);
case 2 -> blockPos.sub(0, 0, 1);
case 3 -> blockPos.add(0, 0, 1);
case 4 -> blockPos.sub(1, 0, 0);
case 5 -> blockPos.add(1, 0, 0);
default -> blockPos;
};
}
/**

View File

@ -263,8 +263,7 @@ public class ChunkUtils {
tagName = "Empty";
// Sometimes legacy tags have their ID be a StringTag with empty value
for (Tag subTag : tag) {
if (subTag instanceof StringTag) {
StringTag stringTag = (StringTag) subTag;
if (subTag instanceof StringTag stringTag) {
if (stringTag.getValue().isEmpty()) {
tagName = stringTag.getName();
break;

View File

@ -111,14 +111,11 @@ public class DimensionUtils {
* @return Converted Bedrock edition dimension ID
*/
public static int javaToBedrock(String javaDimension) {
switch (javaDimension) {
case NETHER:
return BEDROCK_NETHER_ID;
case THE_END:
return 2;
default:
return 0;
}
return switch (javaDimension) {
case NETHER -> BEDROCK_NETHER_ID;
case THE_END -> 2;
default -> 0;
};
}
/**

View File

@ -44,26 +44,15 @@ public final class EntityUtils {
* @return The numeric ID for the Bedrock edition effect
*/
public static int toBedrockEffectId(Effect effect) {
switch (effect) {
case GLOWING:
case LUCK:
case UNLUCK:
case DOLPHINS_GRACE:
// All Java-exclusive effects as of 1.16.2
return 0;
case LEVITATION:
return 24;
case CONDUIT_POWER:
return 26;
case SLOW_FALLING:
return 27;
case BAD_OMEN:
return 28;
case HERO_OF_THE_VILLAGE:
return 29;
default:
return effect.ordinal() + 1;
}
return switch (effect) {
case GLOWING, LUCK, UNLUCK, DOLPHINS_GRACE -> 0; // All Java-exclusive effects as of 1.16.2
case LEVITATION -> 24;
case CONDUIT_POWER -> 26;
case SLOW_FALLING -> 27;
case BAD_OMEN -> 28;
case HERO_OF_THE_VILLAGE -> 29;
default -> effect.ordinal() + 1;
};
}
/**
@ -84,46 +73,20 @@ public final class EntityUtils {
float height = mount.getMetadata().getFloat(EntityData.BOUNDING_BOX_HEIGHT);
float mountedHeightOffset = height * 0.75f;
switch (mount.getEntityType()) {
case CHICKEN:
case SPIDER:
mountedHeightOffset = height * 0.5f;
break;
case DONKEY:
case MULE:
mountedHeightOffset -= 0.25f;
break;
case LLAMA:
mountedHeightOffset = height * 0.67f;
break;
case MINECART:
case MINECART_HOPPER:
case MINECART_TNT:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_SPAWNER:
case MINECART_COMMAND_BLOCK:
mountedHeightOffset = 0;
break;
case BOAT:
mountedHeightOffset = -0.1f;
break;
case HOGLIN:
case ZOGLIN:
case CHICKEN, SPIDER -> mountedHeightOffset = height * 0.5f;
case DONKEY, MULE -> mountedHeightOffset -= 0.25f;
case LLAMA -> mountedHeightOffset = height * 0.67f;
case MINECART, MINECART_HOPPER, MINECART_TNT, MINECART_CHEST, MINECART_FURNACE, MINECART_SPAWNER,
MINECART_COMMAND_BLOCK -> mountedHeightOffset = 0;
case BOAT -> mountedHeightOffset = -0.1f;
case HOGLIN, ZOGLIN -> {
boolean isBaby = mount.getMetadata().getFlags().getFlag(EntityFlag.BABY);
mountedHeightOffset = height - (isBaby ? 0.2f : 0.15f);
break;
case PIGLIN:
mountedHeightOffset = height * 0.92f;
break;
case RAVAGER:
mountedHeightOffset = 2.1f;
break;
case SKELETON_HORSE:
mountedHeightOffset -= 0.1875f;
break;
case STRIDER:
mountedHeightOffset = height - 0.19f;
break;
}
case PIGLIN -> mountedHeightOffset = height * 0.92f;
case RAVAGER -> mountedHeightOffset = 2.1f;
case SKELETON_HORSE -> mountedHeightOffset -= 0.1875f;
case STRIDER -> mountedHeightOffset = height - 0.19f;
}
return mountedHeightOffset;
}
@ -207,15 +170,8 @@ public final class EntityUtils {
yOffset += EntityType.PLAYER.getOffset();
}
switch (mount.getEntityType()) {
case MINECART:
case MINECART_HOPPER:
case MINECART_TNT:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_SPAWNER:
case MINECART_COMMAND_BLOCK:
case BOAT:
yOffset -= mount.getEntityType().getHeight() * 0.5f;
case MINECART, MINECART_HOPPER, MINECART_TNT, MINECART_CHEST, MINECART_FURNACE, MINECART_SPAWNER,
MINECART_COMMAND_BLOCK, BOAT -> yOffset -= mount.getEntityType().getHeight() * 0.5f;
}
Vector3f offset = Vector3f.from(xOffset, yOffset, zOffset);
passenger.getMetadata().put(EntityData.RIDER_SEAT_POSITION, offset);

View File

@ -48,52 +48,14 @@ public class SignUtils {
* @return width of the character
*/
public static int getCharacterWidth(char c) {
switch (c) {
case '!':
case ',':
case '.':
case ':':
case ';':
case 'i':
case '|':
case '¡':
return 2;
case '\'':
case 'l':
case 'ì':
case 'í':
return 3;
case ' ':
case 'I':
case '[':
case ']':
case 't':
case '×':
case 'ï':
return 4;
case '"':
case '(':
case ')':
case '*':
case '<':
case '>':
case 'f':
case 'k':
case '{':
case '}':
return 5;
case '@':
case '~':
case '®':
return 7;
default:
return 6;
}
return switch (c) {
case '!', ',', '.', ':', ';', 'i', '|', '¡' -> 2;
case '\'', 'l', 'ì', 'í' -> 3;
case ' ', 'I', '[', ']', 't', '×', 'ï' -> 4;
case '"', '(', ')', '*', '<', '>', 'f', 'k', '{', '}' -> 5;
case '@', '~', '®' -> 7;
default -> 6;
};
}
}

File diff suppressed because it is too large Load Diff

14
pom.xml
View File

@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.geysermc</groupId>
<artifactId>geyser-parent</artifactId>
<version>1.4.2-SNAPSHOT</version>
<version>1.4.3-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Geyser</name>
<description>Allows for players from Minecraft Bedrock Edition to join Minecraft Java Edition servers.</description>
@ -15,8 +15,8 @@
<outputName>Geyser</outputName>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
</properties>
<organization>
@ -37,6 +37,14 @@
<module>connector</module>
</modules>
<pluginRepositories>
<!-- Remove once maven-shade-plugin gets a stable release that supports Java 16 -->
<pluginRepository>
<id>apache.snapshots</id>
<url>https://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>jitpack.io</id>