us.myles.ViaVersion.api.protocol.ProtocolVersion Java Examples

The following examples show how to use us.myles.ViaVersion.api.protocol.ProtocolVersion. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProtocolDetectorService.java    From ViaVersion with MIT License 6 votes vote down vote up
public static Integer getProtocolId(String serverName) {
    // Step 1. Check Config
    Map<String, Integer> servers = ((VelocityViaConfig) Via.getConfig()).getVelocityServerProtocols();
    Integer protocol = servers.get(serverName);
    if (protocol != null) {
        return protocol;
    }
    // Step 2. Check Detected
    Integer detectedProtocol = detectedProtocolIds.get(serverName);
    if (detectedProtocol != null) {
        return detectedProtocol;
    }
    // Step 3. Use Default
    Integer defaultProtocol = servers.get("default");
    if (defaultProtocol != null) {
        return defaultProtocol;
    }
    // Step 4: Use bungee lowest supported... *cries*
    try {
        return Via.getManager().getInjector().getServerProtocolVersion();
    } catch (Exception e) {
        e.printStackTrace();
        return ProtocolVersion.v1_8.getId();
    }
}
 
Example #2
Source File: VelocityViaLoader.java    From ViaVersion with MIT License 6 votes vote down vote up
@Override
public void load() {
    Object plugin = VelocityPlugin.PROXY.getPluginManager()
            .getPlugin("viaversion").flatMap(PluginContainer::getInstance).get();

    if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_9.getId()) {
        Via.getManager().getProviders().use(MovementTransmitterProvider.class, new VelocityMovementTransmitter());
        Via.getManager().getProviders().use(BossBarProvider.class, new VelocityBossBarProvider());
        VelocityPlugin.PROXY.getEventManager().register(plugin, new ElytraPatch());
    }

    Via.getManager().getProviders().use(VersionProvider.class, new VelocityVersionProvider());
    // We probably don't need a EntityIdProvider because velocity sends a Join packet on server change
    // We don't need main hand patch because Join Game packet makes client send hand data again

    VelocityPlugin.PROXY.getEventManager().register(plugin, new UpdateListener());
    VelocityPlugin.PROXY.getEventManager().register(plugin, new VelocityServerHandler());

    int pingInterval = ((VelocityViaConfig) Via.getPlatform().getConf()).getVelocityPingInterval();
    if (pingInterval > 0) {
        Via.getPlatform().runRepeatingSync(
                new ProtocolDetectorService(),
                pingInterval * 20L);
    }
}
 
Example #3
Source File: MixinDebugHud.java    From ViaFabric with MIT License 5 votes vote down vote up
@Inject(at = @At("RETURN"), method = "getLeftText")
protected void getLeftText(CallbackInfoReturnable<List<String>> info) {
    info.getReturnValue().add("[ViaFabric] Injected: " + Via.getManager().getConnections().size() + " ("
            + Via.getManager().getConnectedClients().size() + " frontend)");
    ChannelHandler viaDecoder = ((MixinClientConnectionAccessor) MinecraftClient.getInstance().getNetworkHandler()
            .getConnection()).getChannel().pipeline().get(CommonTransformer.HANDLER_DECODER_NAME);
    if (viaDecoder instanceof VRDecodeHandler) {
        ProtocolInfo protocol = ((VRDecodeHandler) viaDecoder).getInfo().getProtocolInfo();
        if (protocol != null) {
            ProtocolVersion serverVer = ProtocolVersion.getProtocol(protocol.getServerProtocolVersion());
            String inactive = "";
            if (!protocol.getUser().isActive()) {
                inactive = " (inactive)";
            }
            info.getReturnValue().add("[ViaFabric] Client injected: "
                    + serverVer.getName() + " (" + serverVer.getId() + ") server" + inactive);
        }
    }
}
 
Example #4
Source File: AbstractFenceConnectionHandler.java    From ViaVersion with MIT License 5 votes vote down vote up
protected byte getStates(UserConnection user, Position position, int blockState) {
    byte states = 0;
    boolean pre1_12 = user.getProtocolInfo().getServerProtocolVersion() < ProtocolVersion.v1_12.getId();
    if (connects(BlockFace.EAST, getBlockData(user, position.getRelative(BlockFace.EAST)), pre1_12)) states |= 1;
    if (connects(BlockFace.NORTH, getBlockData(user, position.getRelative(BlockFace.NORTH)), pre1_12)) states |= 2;
    if (connects(BlockFace.SOUTH, getBlockData(user, position.getRelative(BlockFace.SOUTH)), pre1_12)) states |= 4;
    if (connects(BlockFace.WEST, getBlockData(user, position.getRelative(BlockFace.WEST)), pre1_12)) states |= 8;
    return states;
}
 
Example #5
Source File: ListSubCmd.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public boolean execute(ViaCommandSender sender, String[] args) {
    Map<ProtocolVersion, Set<String>> playerVersions = new TreeMap<>(new Comparator<ProtocolVersion>() {
        @Override
        public int compare(ProtocolVersion o1, ProtocolVersion o2) {
            return ProtocolVersion.getIndex(o2) - ProtocolVersion.getIndex(o1);
        }
    });

    for (ViaCommandSender p : Via.getPlatform().getOnlinePlayers()) {
        int playerVersion = Via.getAPI().getPlayerVersion(p.getUUID());
        ProtocolVersion key = ProtocolVersion.getProtocol(playerVersion);
        if (!playerVersions.containsKey(key))
            playerVersions.put(key, new HashSet<String>());
        playerVersions.get(key).add(p.getName());
    }

    for (Map.Entry<ProtocolVersion, Set<String>> entry : playerVersions.entrySet())
        sendMessage(sender, "&8[&6%s&8] (&7%d&8): &b%s", entry.getKey().getName(), entry.getValue().size(), entry.getValue());

    playerVersions.clear();
    return true;
}
 
Example #6
Source File: PPSSubCmd.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public boolean execute(ViaCommandSender sender, String[] args) {
    Map<Integer, Set<String>> playerVersions = new HashMap<>();
    int totalPackets = 0;
    int clients = 0;
    long max = 0;

    for (ViaCommandSender p : Via.getPlatform().getOnlinePlayers()) {
        int playerVersion = Via.getAPI().getPlayerVersion(p.getUUID());
        if (!playerVersions.containsKey(playerVersion))
            playerVersions.put(playerVersion, new HashSet<String>());
        UserConnection uc = Via.getManager().getConnection(p.getUUID());
        if (uc != null && uc.getPacketsPerSecond() > -1) {
            playerVersions.get(playerVersion).add(p.getName() + " (" + uc.getPacketsPerSecond() + " PPS)");
            totalPackets += uc.getPacketsPerSecond();
            if (uc.getPacketsPerSecond() > max) {
                max = uc.getPacketsPerSecond();
            }
            clients++;
        }
    }
    Map<Integer, Set<String>> sorted = new TreeMap<>(playerVersions);
    sendMessage(sender, "&4Live Packets Per Second");
    if (clients > 1) {
        sendMessage(sender, "&cAverage: &f" + (totalPackets / clients));
        sendMessage(sender, "&cHighest: &f" + max);
    }
    if (clients == 0) {
        sendMessage(sender, "&cNo clients to display.");
    }
    for (Map.Entry<Integer, Set<String>> entry : sorted.entrySet())
        sendMessage(sender, "&8[&6%s&8]: &b%s", ProtocolVersion.getProtocol(entry.getKey()).getName(), entry.getValue());
    sorted.clear();
    return true;
}
 
Example #7
Source File: VelocityVersionProvider.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public int getServerProtocol(UserConnection user) throws Exception {
    int playerVersion = user.getProtocolInfo().getProtocolVersion();

    IntStream versions = com.velocitypowered.api.network.ProtocolVersion.SUPPORTED_VERSIONS.stream()
            .mapToInt(com.velocitypowered.api.network.ProtocolVersion::getProtocol);

    // Modern forwarding mode needs 1.13 Login plugin message
    if (VelocityViaInjector.getPlayerInfoForwardingMode != null
            && ((Enum<?>) VelocityViaInjector.getPlayerInfoForwardingMode.invoke(VelocityPlugin.PROXY.getConfiguration()))
            .name().equals("MODERN")) {
        versions = versions.filter(ver -> ver >= ProtocolVersion.v1_13.getId());
    }
    int[] compatibleProtocols = versions.toArray();

    // Bungee supports it
    if (Arrays.binarySearch(compatibleProtocols, playerVersion) >= 0)
        return playerVersion;

    // Older than bungee supports, get the lowest version
    if (playerVersion < compatibleProtocols[0]) {
        return compatibleProtocols[0];
    }

    // Loop through all protocols to get the closest protocol id that bungee supports (and that viaversion does too)

    // TODO: This needs a better fix, i.e checking ProtocolRegistry to see if it would work.
    // This is more of a workaround for snapshot support by bungee.
    for (int i = compatibleProtocols.length - 1; i >= 0; i--) {
        int protocol = compatibleProtocols[i];
        if (playerVersion > protocol && ProtocolVersion.isRegistered(protocol))
            return protocol;
    }

    Via.getPlatform().getLogger().severe("Panic, no protocol id found for " + playerVersion);
    return playerVersion;
}
 
Example #8
Source File: VelocityViaInjector.java    From ViaVersion with MIT License 5 votes vote down vote up
public static int getLowestSupportedProtocolVersion() {
    try {
        if (getPlayerInfoForwardingMode != null
                && ((Enum<?>) getPlayerInfoForwardingMode.invoke(VelocityPlugin.PROXY.getConfiguration()))
                .name().equals("MODERN")) return ProtocolVersion.v1_13.getId();
    } catch (IllegalAccessException | InvocationTargetException ignored) {
    }
    return com.velocitypowered.api.network.ProtocolVersion.MINIMUM_VERSION.getProtocol();
}
 
Example #9
Source File: VelocityViaConfig.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
protected void handleConfig(Map<String, Object> config) {
    // Parse servers
    Map<String, Object> servers;
    if (!(config.get("velocity-servers") instanceof Map)) {
        servers = new HashMap<>();
    } else {
        servers = (Map) config.get("velocity-servers");
    }
    // Convert any bad Protocol Ids
    for (Map.Entry<String, Object> entry : new HashSet<>(servers.entrySet())) {
        if (!(entry.getValue() instanceof Integer)) {
            if (entry.getValue() instanceof String) {
                ProtocolVersion found = ProtocolVersion.getClosest((String) entry.getValue());
                if (found != null) {
                    servers.put(entry.getKey(), found.getId());
                } else {
                    servers.remove(entry.getKey()); // Remove!
                }
            } else {
                servers.remove(entry.getKey()); // Remove!
            }
        }
    }
    // Ensure default exists
    if (!servers.containsKey("default")) {
        // Side note: This doesn't use ProtocolRegistry as it doesn't know the protocol version at boot.
        try {
            servers.put("default", VelocityViaInjector.getLowestSupportedProtocolVersion());
        } catch (Exception e) {
            // Something went very wrong
            e.printStackTrace();
        }
    }
    // Put back
    config.put("velocity-servers", servers);
}
 
Example #10
Source File: SpongeViaLoader.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public void load() {
    // Update Listener
    registerListener(new UpdateListener());

    /* 1.9 client to 1.8 server */
    if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_9.getId()) {
        try {
            Class.forName("org.spongepowered.api.event.entity.DisplaceEntityEvent");
            storeListener(new Sponge4ArmorListener()).register();
        } catch (ClassNotFoundException e) {
            storeListener(new Sponge5ArmorListener(plugin)).register();
        }
        storeListener(new DeathListener(plugin)).register();
        storeListener(new BlockListener(plugin)).register();

        if (plugin.getConf().isItemCache()) {
            tasks.add(Via.getPlatform().runRepeatingSync(new HandItemCache(), 2L)); // Updates players items :)
            HandItemCache.CACHE = true;
        }
    }

    /* Providers */
    if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_9.getId()) {
        Via.getManager().getProviders().use(BulkChunkTranslatorProvider.class, new SpongeViaBulkChunkTranslator());
        Via.getManager().getProviders().use(MovementTransmitterProvider.class, new SpongeViaMovementTransmitter());

        Via.getManager().getProviders().use(HandItemProvider.class, new HandItemProvider() {
            @Override
            public Item getHandItem(final UserConnection info) {
                if (HandItemCache.CACHE) {
                    return HandItemCache.getHandItem(info.getProtocolInfo().getUuid());
                } else {
                    return super.getHandItem(info);
                }
            }
        });
    }
}
 
Example #11
Source File: BungeeVersionProvider.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public int getServerProtocol(UserConnection user) throws Exception {
    if (ref == null)
        return super.getServerProtocol(user);
    // TODO Have one constant list forever until restart? (Might limit plugins if they change this)
    List<Integer> list = ReflectionUtil.getStatic(ref, "SUPPORTED_VERSION_IDS", List.class);
    List<Integer> sorted = new ArrayList<>(list);
    Collections.sort(sorted);

    ProtocolInfo info = user.getProtocolInfo();

    // Bungee supports it
    if (sorted.contains(info.getProtocolVersion()))
        return info.getProtocolVersion();

    // Older than bungee supports, get the lowest version
    if (info.getProtocolVersion() < sorted.get(0)) {
        return getLowestSupportedVersion();
    }

    // Loop through all protocols to get the closest protocol id that bungee supports (and that viaversion does too)

    // TODO: This needs a better fix, i.e checking ProtocolRegistry to see if it would work.
    // This is more of a workaround for snapshot support by bungee.
    for (Integer protocol : Lists.reverse(sorted)) {
        if (info.getProtocolVersion() > protocol && ProtocolVersion.isRegistered(protocol))
            return protocol;
    }

    Via.getPlatform().getLogger().severe("Panic, no protocol id found for " + info.getProtocolVersion());
    return info.getProtocolVersion();
}
 
Example #12
Source File: BungeeViaLoader.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public void load() {
    // Listeners
    registerListener(plugin);
    registerListener(new UpdateListener());
    registerListener(new BungeeServerHandler());

    if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_9.getId()) {
        registerListener(new ElytraPatch());
    }

    // Providers
    Via.getManager().getProviders().use(VersionProvider.class, new BungeeVersionProvider());
    Via.getManager().getProviders().use(EntityIdProvider.class, new BungeeEntityIdProvider());

    if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_9.getId()) {
        Via.getManager().getProviders().use(MovementTransmitterProvider.class, new BungeeMovementTransmitter());
        Via.getManager().getProviders().use(BossBarProvider.class, new BungeeBossBarProvider());
        Via.getManager().getProviders().use(MainHandProvider.class, new BungeeMainHandProvider());
    }

    if (plugin.getConf().getBungeePingInterval() > 0) {
        tasks.add(plugin.getProxy().getScheduler().schedule(
                plugin,
                new ProtocolDetectorService(plugin),
                0, plugin.getConf().getBungeePingInterval(),
                TimeUnit.SECONDS
        ));
    }
}
 
Example #13
Source File: BungeeViaConfig.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
protected void handleConfig(Map<String, Object> config) {
    // Parse servers
    Map<String, Object> servers;
    if (!(config.get("bungee-servers") instanceof Map)) {
        servers = new HashMap<>();
    } else {
        servers = (Map) config.get("bungee-servers");
    }
    // Convert any bad Protocol Ids
    for (Map.Entry<String, Object> entry : new HashSet<>(servers.entrySet())) {
        if (!(entry.getValue() instanceof Integer)) {
            if (entry.getValue() instanceof String) {
                ProtocolVersion found = ProtocolVersion.getClosest((String) entry.getValue());
                if (found != null) {
                    servers.put(entry.getKey(), found.getId());
                } else {
                    servers.remove(entry.getKey()); // Remove!
                }
            } else {
                servers.remove(entry.getKey()); // Remove!
            }
        }
    }
    // Ensure default exists
    if (!servers.containsKey("default")) {
        servers.put("default", BungeeVersionProvider.getLowestSupportedVersion());
    }
    // Put back
    config.put("bungee-servers", servers);
}
 
Example #14
Source File: PlayerSneakListener.java    From ViaVersion with MIT License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void playerToggleSneak(PlayerToggleSneakEvent event) {
    Player player = event.getPlayer();
    UserConnection userConnection = getUserConnection(player);
    if (userConnection == null) return;
    ProtocolInfo info = userConnection.getProtocolInfo();
    if (info == null) return;

    int protocolVersion = info.getProtocolVersion();
    if (is1_14Fix && protocolVersion >= ProtocolVersion.v1_14.getId()) {
        setHeight(player, event.isSneaking() ? HEIGHT_1_14 : STANDING_HEIGHT);
        if (event.isSneaking())
            sneakingUuids.add(player.getUniqueId());
        else
            sneakingUuids.remove(player.getUniqueId());

        if (!useCache) return;
        if (event.isSneaking())
            sneaking.put(player, true);
        else
            sneaking.remove(player);
    } else if (is1_9Fix && protocolVersion >= ProtocolVersion.v1_9.getId()) {
        setHeight(player, event.isSneaking() ? HEIGHT_1_9 : STANDING_HEIGHT);
        if (!useCache) return;
        if (event.isSneaking())
            sneaking.put(player, false);
        else
            sneaking.remove(player);
    }
}
 
Example #15
Source File: PlayerSneakListener.java    From ViaVersion with MIT License 5 votes vote down vote up
public PlayerSneakListener(ViaVersionPlugin plugin, boolean is1_9Fix, boolean is1_14Fix) throws ReflectiveOperationException {
    super(plugin, null);
    this.is1_9Fix = is1_9Fix;
    this.is1_14Fix = is1_14Fix;

    final String packageName = plugin.getServer().getClass().getPackage().getName();
    getHandle = Class.forName(packageName + ".entity.CraftPlayer").getMethod("getHandle");

    final Class<?> entityPlayerClass = Class.forName(packageName
            .replace("org.bukkit.craftbukkit", "net.minecraft.server") + ".EntityPlayer");
    try {
        setSize = entityPlayerClass.getMethod("setSize", Float.TYPE, Float.TYPE);
    } catch (NoSuchMethodException e) {
        // Don't catch this one
        setSize = entityPlayerClass.getMethod("a", Float.TYPE, Float.TYPE);
    }


    // From 1.9 upwards the server hitbox is set in every entity tick, so we have to reset it everytime
    if (ProtocolRegistry.SERVER_PROTOCOL >= ProtocolVersion.v1_9.getId()) {
        sneaking = new WeakHashMap<>();
        useCache = true;
        plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() {
            @Override
            public void run() {
                for (Map.Entry<Player, Boolean> entry : sneaking.entrySet()) {
                    setHeight(entry.getKey(), entry.getValue() ? HEIGHT_1_14 : HEIGHT_1_9);
                }
            }
        }, 1, 1);
    }

    // Suffocation removal only required for 1.14+ clients.
    if (is1_14Fix) {
        sneakingUuids = new HashSet<>();
    }
}
 
Example #16
Source File: BukkitInventoryQuickMoveProvider.java    From ViaVersion with MIT License 5 votes vote down vote up
private boolean isSupported() {
    int protocolId = ProtocolRegistry.SERVER_PROTOCOL;
    if (protocolId >= ProtocolVersion.v1_8.getId() && protocolId <= ProtocolVersion.v1_11_1.getId()) {
        return true; // 1.8-1.11.2
    }
    // this is not needed on 1.12+ servers
    return false;
}
 
Example #17
Source File: BukkitInventoryQuickMoveProvider.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public boolean registerQuickMoveAction(short windowId, short slotId, short actionId, UserConnection userConnection) {
    if (!supported) {
        return false;
    }
    if (slotId < 0) { // clicked out of inv slot
        return false;
    }
    if (windowId == 0) {
        /**
         * windowId is always 0 for player inventory.
         * This has almost definitely something to do with the offhand slot.
         */
        if (slotId >= 36 && slotId <= 44) {
            int protocolId = ProtocolRegistry.SERVER_PROTOCOL;
            // this seems to be working just fine.
            if (protocolId == ProtocolVersion.v1_8.getId()) {
                return false;
            }
        }
    }
    ProtocolInfo info = userConnection.getProtocolInfo();
    UUID uuid = info.getUuid();
    BukkitInventoryUpdateTask updateTask = updateTasks.get(uuid);
    final boolean registered = updateTask != null;
    if (!registered) {
        updateTask = new BukkitInventoryUpdateTask(this, uuid);
        updateTasks.put(uuid, updateTask);
    }
    // http://wiki.vg/index.php?title=Protocol&oldid=13223#Click_Window
    updateTask.addItem(windowId, slotId, actionId);
    if (!registered) {
        Via.getPlatform().runSync(updateTask, 5L);
    }
    return true;
}
 
Example #18
Source File: ViaRewindPlatform.java    From ViaRewind with MIT License 5 votes vote down vote up
default void init(ViaRewindConfig config) {
	ViaRewind.init(this, config);

	String version = ViaRewind.class.getPackage().getImplementationVersion();
	Via.getManager().getSubPlatforms().add(version != null ? version : "UNKNOWN");

	ProtocolRegistry.registerProtocol(new Protocol1_8TO1_9(), Collections.singletonList(ProtocolVersion.v1_8.getId()), ProtocolVersion.v1_9.getId());
	ProtocolRegistry.registerProtocol(new Protocol1_7_6_10TO1_8(), Collections.singletonList(ProtocolVersion.v1_7_6.getId()), ProtocolVersion.v1_8.getId());
	ProtocolRegistry.registerProtocol(new Protocol1_7_0_5to1_7_6_10(), Collections.singletonList(ProtocolVersion.v1_7_1.getId()), ProtocolVersion.v1_7_6.getId());
}
 
Example #19
Source File: MixinMultiplayerScreen.java    From ViaFabric with MIT License 4 votes vote down vote up
@Inject(method = "init", at = @At("TAIL"))
private void onInit(CallbackInfo ci) {
    protocolVersion = new TextFieldWidget(this.textRenderer, this.width / 2 + 88, 13, 65, 15, new TranslatableText("gui.protocol_version_field.name"));
    protocolVersion.setTextPredicate(new VersionFormatFilter());
    protocolVersion.setChangedListener((text) -> {
        protocolVersion.setSuggestion(null);
        int newVersion = ViaFabric.config.getClientSideVersion();
        validProtocol = true;
        try {
            newVersion = Integer.parseInt(text);
        } catch (NumberFormatException e) {
            ProtocolVersion closest = ProtocolVersion.getClosest(text);
            if (closest != null) {
                newVersion = closest.getId();
            } else {
                validProtocol = false;
                List<String> completions = ProtocolVersion.getProtocols().stream()
                        .map(ProtocolVersion::getName)
                        .flatMap(str -> Stream.concat(
                                Arrays.stream(str.split("-")),
                                Arrays.stream(new String[]{str})
                        ))
                        .distinct()
                        .filter(ver -> ver.startsWith(text))
                        .collect(Collectors.toList());
                if (completions.size() == 1) {
                    protocolVersion.setSuggestion(completions.get(0).substring(text.length()));
                }
            }
        }
        supportedProtocol = isSupported(newVersion);
        protocolVersion.setEditableColor(getTextColor());
        int finalNewVersion = newVersion;
        if (latestProtocolSave == null) latestProtocolSave = CompletableFuture.completedFuture(null);
        latestProtocolSave = latestProtocolSave.thenRunAsync(() -> {
            ViaFabric.config.setClientSideVersion(finalNewVersion);
            ViaFabric.config.saveConfig();
        }, ViaFabric.ASYNC_EXECUTOR);
    });
    int clientSideVersion = ViaFabric.config.getClientSideVersion();

    protocolVersion.setVisible(ViaFabric.config.isClientSideEnabled());

    protocolVersion.setText(ProtocolVersion.isRegistered(clientSideVersion)
            ? ProtocolVersion.getProtocol(clientSideVersion).getName()
            : Integer.toString(clientSideVersion));
    this.children.add(protocolVersion);

    enableClientSideViaVersion = new TexturedButtonWidget(this.width / 2 + 113, 10,
            40, 20, // Size
            0, 0, // Start pos of texture
            20, // v Hover offset
            new Identifier("viafabric:textures/gui/via_button.png"),
            64, 64, // Texture size
            button -> MinecraftClient.getInstance().openScreen(new ConfirmScreen(
                    answer -> {
                        MinecraftClient.getInstance().openScreen(this);
                        if (answer) {
                            ViaFabric.config.setClientSideEnabled(true);
                            ViaFabric.config.saveConfig();
                            protocolVersion.setVisible(true);
                            enableClientSideViaVersion.visible = false;
                        }
                    },
                    new TranslatableText("gui.enable_client_side.question"),
                    new TranslatableText("gui.enable_client_side.warning"),
                    new TranslatableText("gui.enable_client_side.enable"),
                    new TranslatableText("gui.cancel")
            )),
            new TranslatableText("gui.enable_client_side_button"));
    enableClientSideViaVersion.visible = !protocolVersion.isVisible();
    addButton(enableClientSideViaVersion);
}
 
Example #20
Source File: VersionFormatFilter.java    From ViaFabric with MIT License 4 votes vote down vote up
@Override
public boolean test(String s) {
    try {
        Integer.parseInt(s);
        return true;
    } catch (NumberFormatException e) {
        try {
            Integer.parseInt(s + '0');
            return true;
        } catch (NumberFormatException e2) {
            return ProtocolVersion.getProtocols().stream()
                    .map(ProtocolVersion::getName)
                    .flatMap(str -> Stream.concat(
                            Arrays.stream(str.split("-")),
                            Arrays.stream(new String[]{str})
                    ))
                    .anyMatch(ver -> ver.startsWith(s));
        }
    }
}
 
Example #21
Source File: ViaManager.java    From ViaVersion with MIT License 4 votes vote down vote up
public void onServerLoaded() {
    // Load Server Protocol
    try {
        ProtocolRegistry.SERVER_PROTOCOL = injector.getServerProtocolVersion();
    } catch (Exception e) {
        platform.getLogger().severe("ViaVersion failed to get the server protocol!");
        e.printStackTrace();
    }
    // Check if there are any pipes to this version
    if (ProtocolRegistry.SERVER_PROTOCOL != -1) {
        platform.getLogger().info("ViaVersion detected server version: " + ProtocolVersion.getProtocol(ProtocolRegistry.SERVER_PROTOCOL));
        if (!ProtocolRegistry.isWorkingPipe()) {
            platform.getLogger().warning("ViaVersion does not have any compatible versions for this server version!");
            platform.getLogger().warning("Please remember that ViaVersion only adds support for versions newer than the server version.");
            platform.getLogger().warning("If you need support for older versions you may need to use one or more ViaVersion addons too.");
            platform.getLogger().warning("In that case please read the ViaVersion resource page carefully, and if you're");
            platform.getLogger().warning("still unsure, feel free to join our Discord-Server for further assistance.");
        }
    }
    // Load Listeners / Tasks
    ProtocolRegistry.onServerLoaded();

    // Load Platform
    loader.load();
    // Common tasks
    mappingLoadingTask = Via.getPlatform().runRepeatingSync(() -> {
        if (ProtocolRegistry.checkForMappingCompletion()) {
            platform.cancelTask(mappingLoadingTask);
            mappingLoadingTask = null;
        }
    }, 10L);
    if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_9.getId()) {
        if (Via.getConfig().isSimulatePlayerTick()) {
            Via.getPlatform().runRepeatingSync(new ViaIdleThread(), 1L);
        }
    }
    if (ProtocolRegistry.SERVER_PROTOCOL < ProtocolVersion.v1_13.getId()) {
        if (Via.getConfig().get1_13TabCompleteDelay() > 0) {
            Via.getPlatform().runRepeatingSync(new TabCompleteThread(), 1L);
        }
    }

    // Refresh Versions
    ProtocolRegistry.refreshVersions();
}
 
Example #22
Source File: BukkitPlugin.java    From ViaBackwards with MIT License 4 votes vote down vote up
private void onServerLoaded() {
    if (ProtocolRegistry.SERVER_PROTOCOL >= ProtocolVersion.v1_14.getId()) {
        BukkitViaLoader loader = (BukkitViaLoader) Via.getManager().getLoader();
        loader.storeListener(new LecternInteractListener(this)).register();
    }
}
 
Example #23
Source File: ViaBackwardsPlatform.java    From ViaBackwards with MIT License 4 votes vote down vote up
/**
 * Initialize ViaBackwards.
 */
default void init(File dataFolder) {
    ViaBackwardsConfig config = new ViaBackwardsConfig(new File(dataFolder, "config.yml"));
    config.reloadConfig();

    ViaBackwards.init(this, config);

    if (isOutdated()) return;

    String version = ViaBackwards.class.getPackage().getImplementationVersion();
    Via.getManager().getSubPlatforms().add(version != null ? version : "UNKNOWN");

    getLogger().info("Loading translations...");
    TranslatableRewriter.loadTranslatables();

    getLogger().info("Registering protocols...");
    registerProtocol(new Protocol1_9_4To1_10(), ProtocolVersion.v1_9_3, ProtocolVersion.v1_10);

    registerProtocol(new Protocol1_10To1_11(), ProtocolVersion.v1_10, ProtocolVersion.v1_11);
    registerProtocol(new Protocol1_11To1_11_1(), ProtocolVersion.v1_11, ProtocolVersion.v1_11_1);

    registerProtocol(new Protocol1_11_1To1_12(), ProtocolVersion.v1_11_1, ProtocolVersion.v1_12);
    registerProtocol(new Protocol1_12To1_12_1(), ProtocolVersion.v1_12, ProtocolVersion.v1_12_1);
    registerProtocol(new Protocol1_12_1To1_12_2(), ProtocolVersion.v1_12_1, ProtocolVersion.v1_12_2);

    registerProtocol(new Protocol1_12_2To1_13(), ProtocolVersion.v1_12_2, ProtocolVersion.v1_13);
    registerProtocol(new Protocol1_13To1_13_1(), ProtocolVersion.v1_13, ProtocolVersion.v1_13_1);
    registerProtocol(new Protocol1_13_1To1_13_2(), ProtocolVersion.v1_13_1, ProtocolVersion.v1_13_2);

    registerProtocol(new Protocol1_13_2To1_14(), ProtocolVersion.v1_13_2, ProtocolVersion.v1_14);
    registerProtocol(new Protocol1_14To1_14_1(), ProtocolVersion.v1_14, ProtocolVersion.v1_14_1);
    registerProtocol(new Protocol1_14_1To1_14_2(), ProtocolVersion.v1_14_1, ProtocolVersion.v1_14_2);
    registerProtocol(new Protocol1_14_2To1_14_3(), ProtocolVersion.v1_14_2, ProtocolVersion.v1_14_3);
    registerProtocol(new Protocol1_14_3To1_14_4(), ProtocolVersion.v1_14_3, ProtocolVersion.v1_14_4);

    registerProtocol(new Protocol1_14_4To1_15(), ProtocolVersion.v1_14_4, ProtocolVersion.v1_15);
    registerProtocol(new Protocol1_15To1_15_1(), ProtocolVersion.v1_15, ProtocolVersion.v1_15_1);
    registerProtocol(new Protocol1_15_1To1_15_2(), ProtocolVersion.v1_15_1, ProtocolVersion.v1_15_2);

    registerProtocol(new Protocol1_15_2To1_16(), ProtocolVersion.v1_15_2, ProtocolVersion.v1_16);
    registerProtocol(new Protocol1_16To1_16_1(), ProtocolVersion.v1_16, ProtocolVersion.v1_16_1);
}
 
Example #24
Source File: ViaVersionProtocolVersionProvider.java    From BungeeTabListPlus with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean has18OrLater(ProxiedPlayer player) {
    int version = Via.getAPI().getPlayerVersion(player);
    return ProtocolVersion.getIndex(ProtocolVersion.getProtocol(version)) >= ProtocolVersion.getIndex(ProtocolVersion.v1_8);
}
 
Example #25
Source File: ViaVersionProtocolVersionProvider.java    From BungeeTabListPlus with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String getVersion(ProxiedPlayer player) {
    return ProtocolVersion.getProtocol(Via.getAPI().getPlayerVersion(player)).getName();
}