Java Code Examples for us.myles.ViaVersion.api.Via

The following examples show how to use us.myles.ViaVersion.api.Via. These examples are extracted from open source projects. 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 Project: ViaVersion   Author: ViaVersion   File: BlockEntityProvider.java    License: MIT License 6 votes vote down vote up
/**
 * Transforms the BlockEntities to blocks!
 *
 * @param user       UserConnection instance
 * @param position   Block Position - WARNING: Position is null when called from a chunk
 * @param tag        BlockEntity NBT
 * @param sendUpdate send a block change update
 * @return new block id
 * @throws Exception Gotta throw that exception
 */
public int transform(UserConnection user, Position position, CompoundTag tag, boolean sendUpdate) throws Exception {
    Tag idTag = tag.get("id");
    if (idTag == null) return -1;

    String id = (String) idTag.getValue();
    BlockEntityHandler handler = handlers.get(id);
    if (handler == null) {
        if (Via.getManager().isDebug()) {
            Via.getPlatform().getLogger().warning("Unhandled BlockEntity " + id + " full tag: " + tag);
        }
        return -1;
    }

    int newBlock = handler.transform(user, tag);

    if (sendUpdate && newBlock != -1) {
        sendBlockChange(user, position, newBlock);
    }

    return newBlock;
}
 
Example #2
Source Project: ViaVersion   Author: ViaVersion   File: MappingDataLoader.java    License: MIT License 6 votes vote down vote up
public static void mapIdentifiers(short[] output, JsonArray oldIdentifiers, JsonArray newIdentifiers, JsonObject diffIdentifiers, boolean warnOnMissing) {
    for (int i = 0; i < oldIdentifiers.size(); i++) {
        JsonElement value = oldIdentifiers.get(i);
        Integer index = findIndex(newIdentifiers, value.getAsString());
        if (index == null) {
            if (diffIdentifiers != null) {
                JsonElement diffElement = diffIdentifiers.get(value.getAsString());
                if (diffElement != null) {
                    index = findIndex(newIdentifiers, diffElement.getAsString());
                }
            }
            if (index == null) {
                if (warnOnMissing && !Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
                    Via.getPlatform().getLogger().warning("No key for " + value + " :( ");
                }
                continue;
            }
        }
        output[i] = index.shortValue();
    }
}
 
Example #3
Source Project: ViaVersion   Author: ViaVersion   File: BukkitViaInjector.java    License: MIT License 6 votes vote down vote up
public static void patchLists() throws Exception {
    Object connection = getServerConnection();
    if (connection == null) {
        Via.getPlatform().getLogger().warning("We failed to find the core component 'ServerConnection', please file an issue on our GitHub.");
        return;
    }

    for (Field field : connection.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Object value = field.get(connection);
        if (!(value instanceof List)) continue;
        if (value instanceof ConcurrentList) continue;

        ConcurrentList list = new ConcurrentList();
        list.addAll((Collection) value);
        field.set(connection, list);
    }
}
 
Example #4
Source Project: ViaVersion   Author: ViaVersion   File: ViaVersionPlugin.java    License: MIT License 6 votes vote down vote up
public ViaVersionPlugin() {
    instance = this;

    // Command handler
    commandHandler = new BukkitCommandHandler();
    // Init platform
    Via.init(ViaManager.builder()
            .platform(this)
            .commandHandler(commandHandler)
            .injector(new BukkitViaInjector())
            .loader(new BukkitViaLoader(this))
            .build());
    // Config magic
    conf = new BukkitViaConfig();

    // Check if we're using protocol support too
    protocolSupport = Bukkit.getPluginManager().getPlugin("ProtocolSupport") != null;
    if (protocolSupport) {
        getLogger().info("Hooking into ProtocolSupport, to prevent issues!");
        try {
            BukkitViaInjector.patchLists();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example #5
Source Project: ViaVersion   Author: ViaVersion   File: MappingData.java    License: MIT License 6 votes vote down vote up
private BlockMappingsShortArray(JsonObject mapping1_12, JsonObject mapping1_13) {
    super(4084, mapping1_12, mapping1_13);

    // Map minecraft:snow[layers=1] of 1.12 to minecraft:snow[layers=2] in 1.13
    if (Via.getConfig().isSnowCollisionFix()) {
        oldToNew[1248] = 3416;
    }

    // Remap infested blocks, as they are instantly breakabale in 1.13+ and can't be broken by those clients on older servers
    if (Via.getConfig().isInfestedBlocksFix()) {
        oldToNew[1552] = 1; // stone
        oldToNew[1553] = 14; // cobblestone
        oldToNew[1554] = 3983; // stone bricks
        oldToNew[1555] = 3984; // mossy stone bricks
        oldToNew[1556] = 3985; // cracked stone bricks
        oldToNew[1557] = 3986; // chiseled stone bricks
    }
}
 
Example #6
Source Project: ViaBackwards   Author: ViaVersion   File: EntityPositionHandler.java    License: MIT License 6 votes vote down vote up
public void cacheEntityPosition(PacketWrapper wrapper, double x, double y, double z, boolean create, boolean relative) throws Exception {
    int entityId = wrapper.get(Type.VAR_INT, 0);
    EntityTracker.StoredEntity storedEntity = entityRewriter.getEntityTracker(wrapper.user()).getEntity(entityId);
    if (storedEntity == null) {
        if (Via.getManager().isDebug()) { // There is too many plugins violating this out there, and reading seems to be hard! :>
            ViaBackwards.getPlatform().getLogger().warning("Stored entity with id " + entityId + " missing at position: " + x + " - " + y + " - " + z + " in " + storageClass.getSimpleName());
            if (entityId == -1 && x == 0 && y == 0 && z == 0) {
                ViaBackwards.getPlatform().getLogger().warning("DO NOT REPORT THIS TO VIA, THIS IS A PLUGIN ISSUE");
            } else if (!warnedForMissingEntity) {
                warnedForMissingEntity = true;
                ViaBackwards.getPlatform().getLogger().warning("This is very likely caused by a plugin sending a teleport packet for an entity outside of the player's range.");
            }
        }
        return;
    }

    EntityPositionStorage positionStorage = create ? storageSupplier.get() : storedEntity.get(storageClass);
    if (positionStorage == null) {
        ViaBackwards.getPlatform().getLogger().warning("Stored entity with id " + entityId + " missing " + storageClass.getSimpleName());
        return;
    }

    positionStorage.setCoordinates(x, y, z, relative);
    storedEntity.put(positionStorage);
}
 
Example #7
Source Project: ViaVersion   Author: ViaVersion   File: BungeeServerHandler.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = 120)
public void onServerConnect(ServerConnectEvent e) {
    if (e.isCancelled()) {
        return;
    }

    UserConnection user = Via.getManager().getConnection(e.getPlayer().getUniqueId());
    if (user == null) return;
    if (!user.has(BungeeStorage.class)) {
        user.put(new BungeeStorage(user, e.getPlayer()));
    }

    int protocolId = ProtocolDetectorService.getProtocolId(e.getTarget().getName());
    List<Pair<Integer, Protocol>> protocols = ProtocolRegistry.getProtocolPath(user.getProtocolInfo().getProtocolVersion(), protocolId);

    // Check if ViaVersion can support that version
    try {
        //Object pendingConnection = getPendingConnection.invoke(e.getPlayer());
        Object handshake = getHandshake.invoke(e.getPlayer().getPendingConnection());
        setProtocol.invoke(handshake, protocols == null ? user.getProtocolInfo().getProtocolVersion() : protocolId);
    } catch (InvocationTargetException | IllegalAccessException e1) {
        e1.printStackTrace();
    }
}
 
Example #8
Source Project: ViaVersion   Author: ViaVersion   File: SpongeViaBulkChunkTranslator.java    License: MIT License 6 votes vote down vote up
@Override
public List<Object> transformMapChunkBulk(Object packet, ClientChunks clientChunks) {
    List<Object> list = Lists.newArrayList();
    try {
        int[] xcoords = mapChunkBulkRef.getFieldValue("field_149266_a", packet, int[].class);
        int[] zcoords = mapChunkBulkRef.getFieldValue("field_149264_b", packet, int[].class);
        Object[] chunkMaps = mapChunkBulkRef.getFieldValue("field_179755_c", packet, Object[].class);
        for (int i = 0; i < chunkMaps.length; i++) {
            int x = xcoords[i];
            int z = zcoords[i];
            Object chunkMap = chunkMaps[i];
            Object chunkPacket = mapChunkRef.newInstance();
            mapChunkRef.setFieldValue("field_149284_a", chunkPacket, x);
            mapChunkRef.setFieldValue("field_149282_b", chunkPacket, z);
            mapChunkRef.setFieldValue("field_179758_c", chunkPacket, chunkMap);
            mapChunkRef.setFieldValue("field_149279_g", chunkPacket, true); // Chunk bulk chunks are always ground-up
            clientChunks.getBulkChunks().add(ClientChunks.toLong(x, z)); // Store for later
            list.add(chunkPacket);
        }
    } catch (Exception e) {
        Via.getPlatform().getLogger().log(Level.WARNING, "Failed to transform chunks bulk", e);
    }
    return list;
}
 
Example #9
Source Project: ViaVersion   Author: ViaVersion   File: BedHandler.java    License: MIT License 6 votes vote down vote up
@Override
public int transform(UserConnection user, CompoundTag tag) {
    BlockStorage storage = user.get(BlockStorage.class);
    Position position = new Position((int) getLong(tag.get("x")), (short) getLong(tag.get("y")), (int) getLong(tag.get("z")));

    if (!storage.contains(position)) {
        Via.getPlatform().getLogger().warning("Received an bed color update packet, but there is no bed! O_o " + tag);
        return -1;
    }

    //                                              RED_BED + FIRST_BED
    int blockId = storage.get(position).getOriginal() - 972 + 748;

    Tag color = tag.get("color");
    if (color != null) {
        blockId += (((Number) color.getValue()).intValue() * 16);
    }

    return blockId;
}
 
Example #10
Source Project: ViaVersion   Author: ViaVersion   File: SpongePlugin.java    License: MIT License 6 votes vote down vote up
@Listener
public void onGameStart(GameInitializationEvent event) {
    // Setup Logger
    logger = new LoggerWrapper(container.getLogger());
    // Setup Plugin
    conf = new SpongeViaConfig(container, spongeConfig.getParentFile());
    SpongeCommandHandler commandHandler = new SpongeCommandHandler();
    game.getCommandManager().register(this, commandHandler, "viaversion", "viaver", "vvsponge");
    logger.info("ViaVersion " + getPluginVersion() + " is now loaded!");

    // Init platform
    Via.init(ViaManager.builder()
            .platform(this)
            .commandHandler(commandHandler)
            .injector(new SpongeViaInjector())
            .loader(new SpongeViaLoader(this))
            .build());
}
 
Example #11
Source Project: ViaVersion   Author: ViaVersion   File: VelocityViaLoader.java    License: 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 #12
Source Project: ViaBackwards   Author: ViaVersion   File: ViaBackwardsPlatform.java    License: MIT License 6 votes vote down vote up
default boolean isOutdated() {
    String vvVersion = Via.getPlatform().getPluginVersion();
    if (vvVersion != null && new Version(vvVersion).compareTo(new Version(MINIMUM_VV_VERSION + "--")) < 0) {
        getLogger().severe("================================");
        getLogger().severe("YOUR VIAVERSION IS OUTDATED");
        getLogger().severe("PLEASE USE VIAVERSION " + MINIMUM_VV_VERSION + " OR NEWER");
        getLogger().severe("LINK: https://viaversion.com");
        getLogger().severe("VIABACKWARDS WILL NOW DISABLE");
        getLogger().severe("================================");

        disable();
        return true;
    }

    return false;
}
 
Example #13
Source Project: ViaVersion   Author: ViaVersion   File: FlowerConnectionHandler.java    License: MIT License 6 votes vote down vote up
@Override
public int connect(UserConnection user, Position position, int blockState) {
    int blockBelowId = getBlockData(user, position.getRelative(BlockFace.BOTTOM));
    int connectBelow = flowers.get(blockBelowId);
    if (connectBelow != 0) {
        int blockAboveId = getBlockData(user, position.getRelative(BlockFace.TOP));
        if (Via.getConfig().isStemWhenBlockAbove()) {
            if (blockAboveId == 0) {
                return connectBelow;
            }
        } else if (!flowers.containsKey(blockAboveId)) {
            return connectBelow;
        }
    }
    return blockState;
}
 
Example #14
Source Project: ViaVersion   Author: ViaVersion   File: WorldPackets.java    License: MIT License 6 votes vote down vote up
public static int toNewId(int oldId) {
    if (oldId < 0) {
        oldId = 0; // Some plugins use negative numbers to clear blocks, remap them to air.
    }
    int newId = MappingData.blockMappings.getNewId(oldId);
    if (newId != -1) {
        return newId;
    }
    newId = MappingData.blockMappings.getNewId(oldId & ~0xF); // Remove data
    if (newId != -1) {
        if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
            Via.getPlatform().getLogger().warning("Missing block " + oldId);
        }
        return newId;
    }
    if (!Via.getConfig().isSuppressConversionWarnings() || Via.getManager().isDebug()) {
        Via.getPlatform().getLogger().warning("Missing block completely " + oldId);
    }
    // Default stone
    return 1;
}
 
Example #15
Source Project: ViaVersion   Author: ViaVersion   File: VelocityServerHandler.java    License: MIT License 6 votes vote down vote up
@Subscribe
public void preServerConnect(ServerPreConnectEvent e) {
    try {
        UserConnection user = Via.getManager().getConnection(e.getPlayer().getUniqueId());
        if (user == null) return;
        if (!user.has(VelocityStorage.class)) {
            user.put(new VelocityStorage(user, e.getPlayer()));
        }

        int protocolId = ProtocolDetectorService.getProtocolId(e.getOriginalServer().getServerInfo().getName());
        List<Pair<Integer, Protocol>> protocols = ProtocolRegistry.getProtocolPath(user.getProtocolInfo().getProtocolVersion(), protocolId);

        // Check if ViaVersion can support that version
        Object connection = getMinecraftConnection.invoke(e.getPlayer());
        setNextProtocolVersion.invoke(connection, ProtocolVersion.getProtocolVersion(protocols == null
                ? user.getProtocolInfo().getProtocolVersion()
                : protocolId));

    } catch (IllegalAccessException | InvocationTargetException e1) {
        e1.printStackTrace();
    }
}
 
Example #16
Source Project: PGM   Author: PGMDev   File: ViaUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see <a
 *     href="https://wiki.vg/Protocol_version_numbers">https://wiki.vg/Protocol_version_numbers</a>
 */
public static int getProtocolVersion(Player player) {
  if (enabled()) {
    return Via.getAPI().getPlayerVersion(player);
  } else {
    return NMSHacks.getProtocolVersion(player);
  }
}
 
Example #17
Source Project: ViaFabric   Author: ViaVersion   File: VRViaAPI.java    License: MIT License 5 votes vote down vote up
@Override
public int getPlayerVersion(UUID uuid) {
    UserConnection con = Via.getManager().getConnection(uuid);
    if (con != null) {
        return con.getProtocolInfo().getProtocolVersion();
    }
    try {
        return Via.getManager().getInjector().getServerProtocolVersion();
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}
 
Example #18
Source Project: ViaVersion   Author: ViaVersion   File: Sponge4ArmorListener.java    License: MIT License 5 votes vote down vote up
@Override
public void register() {
    if (isRegistered()) return;

    Sponge.getEventManager().registerListeners(Via.getPlatform(), this);
    setRegistered(true);
}
 
Example #19
Source Project: ViaVersion   Author: ViaVersion   File: Protocol.java    License: MIT License 5 votes vote down vote up
public void registerOutgoing(State state, int oldPacketID, int newPacketID, PacketRemapper packetRemapper, boolean override) {
    ProtocolPacket protocolPacket = new ProtocolPacket(state, oldPacketID, newPacketID, packetRemapper);
    Packet packet = new Packet(state, oldPacketID);
    if (!override && outgoing.containsKey(packet)) {
        Via.getPlatform().getLogger().log(Level.WARNING, packet + " already registered!" +
                " If override is intentional, set override to true. Stacktrace: ", new Exception());
    }
    outgoing.put(packet, protocolPacket);
}
 
Example #20
Source Project: ViaVersion   Author: ViaVersion   File: Entity1_14Types.java    License: MIT License 5 votes vote down vote up
public static EntityType getTypeFromId(int typeID) {
    Optional<EntityType> type = EntityType.findById(typeID);

    if (!type.isPresent()) {
        Via.getPlatform().getLogger().severe("Could not find 1.14 type id " + typeID);
        return EntityType.ENTITY; // Fall back to the basic ENTITY
    }

    return type.get();
}
 
Example #21
Source Project: ViaFabric   Author: ViaVersion   File: VRPlatform.java    License: MIT License 5 votes vote down vote up
@Override
public ViaCommandSender[] getOnlinePlayers() {
    MinecraftServer server = getServer();
    if (server != null && server.isOnThread()) {
        return getServerPlayers();
    }
    return Via.getManager().getConnectedClients().values().stream()
            .map(UserCommandSender::new)
            .toArray(ViaCommandSender[]::new);
}
 
Example #22
Source Project: ViaFabric   Author: ViaVersion   File: VRPlatform.java    License: MIT License 5 votes vote down vote up
@Override
public boolean kickPlayer(UUID uuid, String s) {
    UserConnection user = Via.getManager().getConnection(uuid);
    if (user instanceof VRClientSideUserConnection) {
        return kickClient(s);
    } else {
        return kickServer(uuid, s);
    }
}
 
Example #23
Source Project: ViaVersion   Author: ViaVersion   File: TabCompleteThread.java    License: MIT License 5 votes vote down vote up
@Override
public void run() {
    for (UserConnection info : Via.getManager().getConnections()) {
        if (info.getProtocolInfo() == null) continue;
        if (info.getProtocolInfo().getPipeline().contains(Protocol1_13To1_12_2.class)) {
            if (info.getChannel().isOpen()) {
                info.get(TabCompleteTracker.class).sendPacketToServer();
            }
        }
    }
}
 
Example #24
Source Project: ViaVersion   Author: ViaVersion   File: EntityTracker1_9.java    License: MIT License 5 votes vote down vote up
public int getProvidedEntityId() {
    try {
        return Via.getManager().getProviders().get(EntityIdProvider.class).getEntityId(getUser());
    } catch (Exception e) {
        return getClientEntityId();
    }
}
 
Example #25
Source Project: ViaFabric   Author: ViaVersion   File: MixinDebugHud.java    License: 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 #26
Source Project: ViaRewind   Author: ViaVersion   File: Ticker.java    License: MIT License 5 votes vote down vote up
public static void init() {
	if (init) return;
	synchronized (Ticker.class) {
		if (init) return;
		init = true;
	}
	Via.getPlatform().runRepeatingSync(() -> {
		Via.getManager().getPortedPlayers().values().forEach(user -> {
			user.getStoredObjects().values().stream().filter(Tickable.class::isInstance).map(Tickable.class::cast).forEach(Tickable::tick);
		});
	}, 1L);
}
 
Example #27
Source Project: ViaVersion   Author: ViaVersion   File: Entity1_12Types.java    License: MIT License 5 votes vote down vote up
public static EntityType getTypeFromId(int typeID, boolean isObject) {
    Optional<EntityType> type;

    if (isObject)
        type = ObjectType.getPCEntity(typeID);
    else
        type = EntityType.findById(typeID);

    if (!type.isPresent()) {
        Via.getPlatform().getLogger().severe("Could not find 1.12 type id " + typeID + " isObject=" + isObject);
        return EntityType.ENTITY; // Fall back to the basic ENTITY
    }

    return type.get();
}
 
Example #28
Source Project: ViaVersion   Author: ViaVersion   File: AutoTeamSubCmd.java    License: MIT License 5 votes vote down vote up
@Override
public boolean execute(ViaCommandSender sender, String[] args) {
    ConfigurationProvider provider = Via.getPlatform().getConfigurationProvider();
    boolean newValue = !Via.getConfig().isAutoTeam();

    provider.set("auto-team", newValue);
    provider.saveConfig();
    sendMessage(sender, "&6We will %s", (newValue ? "&aautomatically team players" : "&cno longer auto team players"));
    sendMessage(sender, "&6All players will need to re-login for the change to take place.");

    return true;
}
 
Example #29
Source Project: ViaVersion   Author: ViaVersion   File: InventoryPackets.java    License: MIT License 5 votes vote down vote up
public static int getNewItemId(int id) {
    int newId = MappingData.oldToNewItems.get(id);
    if (newId == -1) {
        Via.getPlatform().getLogger().warning("Missing 1.14 item for 1.13.2 item " + id);
        return 1;
    }
    return newId;
}
 
Example #30
Source Project: ViaVersion   Author: ViaVersion   File: UpdateListener.java    License: MIT License 5 votes vote down vote up
@EventHandler
public void onJoin(PlayerJoinEvent e) {
    if (e.getPlayer().hasPermission("viaversion.update")
            && Via.getConfig().isCheckForUpdates()) {
        UpdateUtil.sendUpdateMessage(e.getPlayer().getUniqueId());
    }
}