内置api

This commit is contained in:
Color_yr committed 2026-03-04 16:59:27 +08:00
1 parent 5b197a0c70
commit ded84f0ef8
84 files changed
+5291 -111

No files matched your search

+15 -14
View File
@@ -1,7 +1,6 @@
plugins {
id 'fabric-loom' version '1.10-SNAPSHOT'
id 'net.fabricmc.fabric-loom-remap' version "${loom_version}"
id 'maven-publish'
// id "org.jetbrains.kotlin.jvm" version "1.9.23"
}
def getVersionFromFile() {
@@ -27,19 +26,24 @@ repositories {
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
mavenCentral()
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
mappings loom.officialMojangMappings()
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
modImplementation "net.fabricmc:fabric-language-kotlin:${project.fabric_kotlin_version}"
// modImplementation include('net.kyori:adventure-platform-fabric:5.3.0') // for Minecraft 1.21.11
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}"
include modImplementation("net.kyori:examination-api:1.3.0")
include modImplementation("net.kyori:examination-string:1.3.0")
include modImplementation("net.kyori:adventure-platform-api:4.0.0")
include modImplementation("net.kyori:adventure-text-serializer-gson:4.9.3")
include modImplementation("net.kyori:adventure-text-serializer-plain:4.9.3")
include modImplementation('net.kyori:adventure-text-minimessage:4.26.1')
include modImplementation('net.kyori:adventure-api:4.26.1')
include modImplementation('net.kyori:adventure-key:4.26.1')
@@ -47,6 +51,7 @@ dependencies {
include modImplementation('org.apache.httpcomponents.core5:httpcore5:5.4')
include modImplementation('org.apache.httpcomponents.core5:httpcore5-h2:5.4')
include modImplementation('org.xerial:sqlite-jdbc:3.51.1.0')
include modImplementation('org.slf4j:slf4j-api:1.7.36')
// Uncomment the following line to enable the deprecated Fabric API modules.
// These are included in the Fabric API production distribution and allow you to update your mod to the latest modules at a later more convenient time.
@@ -58,7 +63,7 @@ processResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
expand "version": inputs.properties.version
}
}
@@ -66,12 +71,6 @@ tasks.withType(JavaCompile).configureEach {
it.options.release = 8
}
//tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
// kotlinOptions {
// jvmTarget = 1.8
// }
//}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
@@ -83,8 +82,10 @@ java {
}
jar {
inputs.property "archivesName", project.base.archivesName
from("LICENSE") {
rename { "${it}_${project.base.archivesName.get()}"}
rename { "${it}_${inputs.properties.archivesName}"}
}
}
+7 -4
View File
@@ -2,16 +2,19 @@
org.gradle.jvmargs=-Xmx1G
org.gradle.parallel=true
# IntelliJ IDEA is not yet fully compatible with configuration cache, see: https://github.com/FabricMC/fabric-loom/issues/1349
org.gradle.configuration-cache=false
# Fabric Properties
# check these on https://fabricmc.net/develop
minecraft_version=1.16.5
yarn_mappings=1.16.5+build.10
loader_version=0.15.11
fabric_kotlin_version=1.10.19+kotlin.1.9.23
loader_version=0.18.4
loom_version=1.15-SNAPSHOT
# Mod Properties
mod_version=1.0.0
maven_group = com.coloryr.allmusic.server
archives_base_name =[fabric-1.16.5]AllMusic_Server
# Dependencies
fabric_version=0.42.0+1.16
fabric_api_version=0.42.0+1.16
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
@@ -5,8 +5,8 @@ import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.Identifier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -14,9 +14,9 @@ import java.io.File;
public class AllMusicServer implements DedicatedServerModInitializer {
public static final Logger LOGGER = LogManager.getLogger("AllMusic Server");
public static final Identifier ID = new Identifier("allmusic", "channel");
public static final ResourceLocation ID = new ResourceLocation("allmusic", "channel");
public static MinecraftServer server;
public static FabricServerAudiences adventure;
public static FabricServerAudiences audiences;
public static final String dir = "allmusic_server/";
@@ -26,18 +26,18 @@ public class AllMusicServer implements DedicatedServerModInitializer {
AllMusic.log = new LogFabric();
AllMusic.side = new SideFabric();
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> CommandFabric.instance.register(dispatcher));
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) ->
CommandFabric.instance.register(dispatcher));
ServerLifecycleEvents.SERVER_STARTED.register((a) -> {
adventure = FabricServerAudiences.of(a);
new AllMusic().init(new File(dir));
server = a;
audiences = FabricServerAudiences.of(server);
AllMusic.init(new File(dir));
AllMusic.start();
Tasks.init();
});
ServerLifecycleEvents.SERVER_STOPPING.register((a) -> {
adventure = null;
AllMusic.stop();
});
}
@@ -8,44 +8,44 @@ import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
public class CommandFabric implements Command<ServerCommandSource>, Predicate<ServerCommandSource>, SuggestionProvider<ServerCommandSource> {
public class CommandFabric implements Command<CommandSourceStack>, Predicate<CommandSourceStack>, SuggestionProvider<CommandSourceStack> {
public static CommandFabric instance = new CommandFabric();
public void register(CommandDispatcher<ServerCommandSource> dispatcher) {
dispatcher.register(((CommandManager.literal("music").requires(this)).executes(this))
.then(CommandManager.argument("args", StringArgumentType.greedyString())
public void register(CommandDispatcher<CommandSourceStack> dispatcher) {
dispatcher.register(((Commands.literal("music").requires(this)).executes(this))
.then(Commands.argument("args", StringArgumentType.greedyString())
.suggests(this).executes(this)));
}
@Override
public int run(CommandContext<ServerCommandSource> context) {
ServerCommandSource item = context.getSource();
public int run(CommandContext<CommandSourceStack> context) {
CommandSourceStack item = context.getSource();
String input = context.getInput();
String[] temp = input.split(" ");
String[] arg = new String[temp.length - 1];
System.arraycopy(temp, 1, arg, 0, arg.length);
CommandEX.execute(item, context.getSource().getName(), arg);
CommandEX.execute(item, context.getSource().getTextName(), arg);
return 0;
}
@Override
public boolean test(ServerCommandSource stack) {
public boolean test(CommandSourceStack stack) {
return true;
}
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> context, SuggestionsBuilder builder) {
ServerCommandSource item = context.getSource();
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSourceStack> context, SuggestionsBuilder builder) {
CommandSourceStack item = context.getSource();
String input = context.getInput();
String[] temp = input.split(" ");
@@ -54,7 +54,7 @@ public class CommandFabric implements Command<ServerCommandSource>, Predicate<Se
builder = builder.createOffset(builder.getInput().lastIndexOf(32) + 1);
List<String> results = CommandEX.getTabList(item, item.getName(), arg);
List<String> results = CommandEX.getTabList(item, item.getTextName(), arg);
String remaining = builder.getRemaining().trim();
@@ -1,16 +1,11 @@
package com.coloryr.allmusic.server;
import com.coloryr.allmusic.server.core.AllMusic;
import com.coloryr.allmusic.server.core.side.IAllMusicLogger;
import net.kyori.adventure.text.Component;
public class LogFabric implements IAllMusicLogger {
@Override
public void warning(String data) {
AllMusicServer.adventure.console().sendMessage(AllMusic.miniMessage(data));
}
@Override
public void info(String data) {
AllMusicServer.adventure.console().sendMessage(AllMusic.miniMessage(data));
public void data(Component data) {
AllMusicServer.audiences.console().sendMessage(data);
}
}
@@ -11,10 +11,9 @@ import com.coloryr.allmusic.server.event.MusicPlayEvent;
import io.netty.buffer.ByteBuf;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.kyori.adventure.text.Component;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import java.io.File;
import java.util.Collection;
@@ -36,14 +35,14 @@ public class SideFabric extends BaseSide {
@Override
public boolean checkPermission(Object player) {
ServerCommandSource source = (ServerCommandSource) player;
return source.hasPermissionLevel(2);
CommandSourceStack source = (CommandSourceStack) player;
return source.hasPermission(2);
}
@Override
public boolean isPlayer(Object player) {
ServerCommandSource source = (ServerCommandSource) player;
return source.getEntity() instanceof ServerPlayerEntity;
CommandSourceStack source = (CommandSourceStack) player;
return source.getEntity() instanceof ServerPlayer;
}
@Override
@@ -53,13 +52,13 @@ public class SideFabric extends BaseSide {
@Override
public Collection<?> getPlayers() {
return AllMusicServer.server.getPlayerManager().getPlayerList();
return AllMusicServer.server.getPlayerList().getPlayers();
}
@Override
public String getPlayerName(Object player) {
if (player instanceof ServerPlayerEntity) {
ServerPlayerEntity player1 = (ServerPlayerEntity) player;
if (player instanceof ServerPlayer) {
ServerPlayer player1 = (ServerPlayer) player;
return player1.getName().getString();
}
@@ -73,8 +72,8 @@ public class SideFabric extends BaseSide {
@Override
public void send(Object player, CommandType type, String data, int data1) {
if (player instanceof ServerPlayerEntity) {
ServerPlayerEntity player1 = (ServerPlayerEntity) player;
if (player instanceof ServerPlayer) {
ServerPlayer player1 = (ServerPlayer) player;
send(player1, MusicPacketCodec.pack(type, data, data1));
}
}
@@ -86,9 +85,9 @@ public class SideFabric extends BaseSide {
@Override
public void sendBar(Object player, Component data) {
if (player instanceof ServerPlayerEntity) {
ServerPlayerEntity player1 = (ServerPlayerEntity) player;
AllMusicServer.adventure.audience(player1).sendActionBar(data);
if (player instanceof ServerPlayer) {
ServerPlayer player1 = (ServerPlayer) player;
AllMusicServer.audiences.audience(player1).sendActionBar(data);
}
}
@@ -99,7 +98,7 @@ public class SideFabric extends BaseSide {
@Override
public boolean needPlay(boolean islist) {
for (ServerPlayerEntity player : AllMusicServer.server.getPlayerManager().getPlayerList()) {
for (ServerPlayer player : AllMusicServer.server.getPlayerList().getPlayers()) {
if (!AllMusic.isSkip(player.getName().getString(), null, false, islist)) {
return true;
}
@@ -109,42 +108,37 @@ public class SideFabric extends BaseSide {
@Override
public void broadcast(Component message) {
for (ServerPlayerEntity player : AllMusicServer.server.getPlayerManager().getPlayerList()) {
AllMusicServer.adventure.audience(player).sendMessage(message);
for (ServerPlayer player : AllMusicServer.server.getPlayerList().getPlayers()) {
AllMusicServer.audiences.audience(player).sendMessage(message);
}
}
@Override
public void sendMessage(Object obj, Component message) {
if (obj instanceof ServerCommandSource) {
ServerCommandSource sender = (ServerCommandSource) obj;
AllMusicServer.adventure.audience(sender).sendMessage(message);
public void sendMessage(Object obj, Component message1) {
if (obj instanceof CommandSourceStack) {
CommandSourceStack sender = (CommandSourceStack) obj;
AllMusicServer.audiences.audience(sender).sendMessage(message1);
}
}
@Override
public boolean onMusicPlay(SongInfoObj obj) {
return MusicPlayEvent.EVENT.invoker().interact(obj) != ActionResult.PASS;
return MusicPlayEvent.EVENT.invoker().interact(obj);
}
@Override
public boolean onMusicAdd(Object obj, PlayerAddMusicObj music) {
ServerCommandSource sender = (ServerCommandSource) obj;
ServerPlayerEntity entity = null;
if (sender.getEntity() instanceof ServerPlayerEntity) {
entity = (ServerPlayerEntity) sender.getEntity();
CommandSourceStack sender = (CommandSourceStack) obj;
ServerPlayer entity = null;
if (sender.getEntity() instanceof ServerPlayer) {
entity = (ServerPlayer) sender.getEntity();
}
return MusicAddEvent.EVENT.invoker().interact(entity, music) != ActionResult.PASS;
return MusicAddEvent.EVENT.invoker().interact(entity, music);
}
private void send(ServerPlayerEntity players, ByteBuf data) {
private void send(ServerPlayer players, ByteBuf data) {
if (players == null)
return;
try {
runTask(() -> ServerPlayNetworking.send(players, AllMusicServer.ID, new PacketByteBuf(data)));
} catch (Exception e) {
AllMusic.log.warning("§c数据发送发生错误");
e.printStackTrace();
}
runTask(() -> ServerPlayNetworking.send(players, AllMusicServer.ID, new FriendlyByteBuf(data)));
}
}
@@ -8,7 +8,7 @@ public class Tasks {
private static final List<TaskItem> taskItems = new CopyOnWriteArrayList<>();
public static void init() {
AllMusicServer.server.addServerGuiTickable(Tasks::tick);
AllMusicServer.server.addTickable(Tasks::tick);
}
public static void tick() {
@@ -3,22 +3,21 @@ package com.coloryr.allmusic.server.event;
import com.coloryr.allmusic.server.core.objs.music.PlayerAddMusicObj;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.server.level.ServerPlayer;
public interface MusicAddEvent {
Event<MusicAddEvent> EVENT = EventFactory.createArrayBacked(MusicAddEvent.class,
(listeners) -> (player, music) -> {
for (MusicAddEvent listener : listeners) {
ActionResult result = listener.interact(player, music);
boolean result = listener.interact(player, music);
if (result != ActionResult.PASS) {
return result;
if (result) {
return true;
}
}
return ActionResult.PASS;
return false;
});
ActionResult interact(ServerPlayerEntity player, PlayerAddMusicObj music);
boolean interact(ServerPlayer player, PlayerAddMusicObj music);
}
@@ -3,21 +3,18 @@ package com.coloryr.allmusic.server.event;
import com.coloryr.allmusic.server.core.objs.music.SongInfoObj;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.util.ActionResult;
public interface MusicPlayEvent {
Event<MusicPlayEvent> EVENT = EventFactory.createArrayBacked(MusicPlayEvent.class,
(listeners) -> (music) -> {
for (MusicPlayEvent listener : listeners) {
ActionResult result = listener.interact(music);
if (result != ActionResult.PASS) {
return result;
if (listener.interact(music)) {
return true;
}
}
return ActionResult.PASS;
return false;
});
ActionResult interact(SongInfoObj music);
boolean interact(SongInfoObj music);
}
@@ -1,14 +1,14 @@
package com.coloryr.allmusic.server.mixin;
import net.minecraft.server.command.CommandOutput;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ServerCommandSource.class)
@Mixin(CommandSourceStack.class)
public interface IGetCommandOutput {
@Accessor(value = "output")
CommandOutput getOutput();
@Accessor(value = "source")
CommandSource getSource();
@Accessor(value = "silent")
boolean getSilent();
@@ -1,23 +1,23 @@
package com.coloryr.allmusic.server.mixin;
import com.coloryr.allmusic.server.core.AllMusic;
import net.minecraft.network.ClientConnection;
import net.minecraft.server.PlayerManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.network.Connection;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerManager.class)
@Mixin(PlayerList.class)
public class ServerPlayerMixin {
@Inject(at = @At("HEAD"), method = "remove")
private void remove(ServerPlayerEntity entity, CallbackInfo info) {
private void remove(ServerPlayer entity, CallbackInfo info) {
AllMusic.removeNowPlayPlayer(entity.getName().getString());
}
@Inject(at = @At("TAIL"), method = "onPlayerConnect")
private void add(ClientConnection connection, ServerPlayerEntity player, CallbackInfo info) {
@Inject(at = @At("TAIL"), method = "placeNewPlayer")
private void add(Connection connection, ServerPlayer player, CallbackInfo info) {
AllMusic.joinPlay(player.getName().getString());
}
}
@@ -0,0 +1,53 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
/**
* An interface applied to {@link net.minecraft.commands.CommandSourceStack} to allow sending {@link Component Components}.
*
* @since 4.0.0
*/
public interface AdventureCommandSourceStack extends ForwardingAudience.Single, Identified {
/**
* Send a result message to the command source.
*
* @param text The text to send
* @param sendToOps If this message should be sent to all ops listening
* @since 4.0.0
*/
void sendSuccess(final @NotNull Component text, final boolean sendToOps);
/**
* Send an error message to the command source.
*
* @param text The error
* @since 4.0.0
*/
void sendFailure(final @NotNull Component text);
}
@@ -0,0 +1,100 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric;
import com.google.common.collect.ImmutableSet;
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonReader;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import net.kyori.adventure.platform.fabric.impl.accessor.ComponentSerializerAccess;
import net.kyori.adventure.text.Component;
import net.minecraft.commands.arguments.ComponentArgument;
import org.jetbrains.annotations.NotNull;
/**
* An argument that takes JSON-format text.
*
* <p>At the moment, using this argument type will require this mod
* <strong>both server- and clientside</strong>, unless the
* <a href="https://gitlab.com/stellardrift/colonel">Colonel</a> mod is present on the server.</p>
*
* @since 4.0.0
*/
public final class ComponentArgumentType implements ArgumentType<Component> {
private static final ComponentArgumentType INSTANCE = new ComponentArgumentType();
private static final Set<String> EXAMPLES = ImmutableSet.of(
"\"Hello world!\"",
"[\"Message\", {\"text\": \"example\", \"color\": \"#aabbcc\"}]"
);
/**
* Get the argument type for component arguments.
*
* @return argument type instance
* @since 4.0.0
*/
public static @NotNull ComponentArgumentType component() {
return INSTANCE;
}
/**
* Get the component from the provided context.
*
* @param ctx Context to get from
* @param key argument key
* @return parsed component
* @since 4.0.0
*/
public static @NotNull Component component(final @NotNull CommandContext<?> ctx, final @NotNull String key) {
return ctx.getArgument(key, Component.class);
}
private ComponentArgumentType() {
}
@Override
public @NotNull Component parse(final @NotNull StringReader reader) throws CommandSyntaxException {
try (final JsonReader json = new JsonReader(new java.io.StringReader(reader.getRemaining()))) {
final Component ret = ComponentSerializerAccess.getGSON().fromJson(json, Component.class);
reader.setCursor(reader.getCursor() + ComponentSerializerAccess.getPos(json));
return ret;
} catch (final JsonParseException | IOException ex) {
final String message = ex.getCause() == null ? ex.getMessage() : ex.getCause().getMessage();
throw ComponentArgument.ERROR_INVALID_JSON.createWithContext(reader, message);
}
}
@Override
public @NotNull Collection<String> getExamples() {
return EXAMPLES;
}
}
@@ -0,0 +1,224 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric;
import com.mojang.authlib.GameProfile;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.platform.fabric.impl.NonWrappingComponentSerializer;
import net.kyori.adventure.platform.fabric.impl.WrappedComponent;
import net.kyori.adventure.platform.fabric.impl.accessor.ComponentSerializerAccess;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.flattener.ComponentFlattener;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.kyori.adventure.text.serializer.ComponentSerializer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static java.util.Objects.requireNonNull;
/**
* Common operations in both the client and server environments.
*
* <p>See {@link FabricServerAudiences} for logical server-specific operations,
* and {@link FabricClientAudiences} for logical client-specific operations</p>
*
* @since 4.0.0
*/
public interface FabricAudiences {
/**
* Given an existing native component, convert it into an Adventure component for working with.
*
* @param input source component
* @param modifier operator to transform the component
* @return new component
* @since 4.0.0
*/
static net.minecraft.network.chat.@NotNull Component update(final net.minecraft.network.chat.@NotNull Component input, final UnaryOperator<Component> modifier) {
final Component modified;
final @Nullable Function<Pointered, ?> partition;
final @Nullable ComponentRenderer<Pointered> renderer;
if (input instanceof WrappedComponent) {
modified = requireNonNull(modifier).apply(((WrappedComponent) input).wrapped());
partition = ((WrappedComponent) input).partition();
renderer = ((WrappedComponent) input).renderer();
} else {
final Component original = ComponentSerializerAccess.getGSON().fromJson(net.minecraft.network.chat.Component.Serializer.toJsonTree(input), Component.class);
modified = modifier.apply(original);
partition = null;
renderer = null;
}
return new WrappedComponent(modified, partition, renderer);
}
/**
* Convert a MC {@link ResourceLocation} instance to a text Key.
*
* @param loc The Identifier to convert
* @return The equivalent data as a Key
* @since 4.0.0
*/
@Contract("null -> null; !null -> !null")
static Key toAdventure(final ResourceLocation loc) {
if (loc == null) {
return null;
}
return Key.key(loc.getNamespace(), loc.getPath());
}
/**
* Convert a Kyori {@link Key} instance to a MC ResourceLocation.
*
* @param key The Key to convert
* @return The equivalent data as an Identifier
* @since 4.0.0
*/
@Contract("null -> null; !null -> !null")
static ResourceLocation toNative(final Key key) {
if (key == null) {
return null;
}
return new ResourceLocation(key.namespace(), key.value());
}
/**
* Get an {@link Entity}'s representation as an {@link Sound.Emitter} of sounds.
*
* @param entity the entity to convert
* @return the entity as a sound emitter
* @since 4.0.0
*/
static Sound.@NotNull Emitter asEmitter(final @NotNull Entity entity) {
return (Sound.Emitter) entity;
}
/**
* Return a TextSerializer instance that will do deep conversions between
* Adventure {@link Component Components} and Minecraft {@link net.minecraft.network.chat.Component Components}.
*
* <p>This serializer will never wrap text, and can provide {@link net.minecraft.network.chat.MutableComponent}
* instances suitable for passing around the game.</p>
*
* @return a serializer instance
* @since 4.0.0
*/
static @NotNull ComponentSerializer<Component, Component, net.minecraft.network.chat.Component> nonWrappingSerializer() {
return NonWrappingComponentSerializer.INSTANCE;
}
/**
* Get the appropriate Gson component serializer for the running game version.
*
* <p>This can be used to convert components to their JSON representation.</p>
*
* @return the appropriate serializer
* @since 4.0.0
* @deprecated for removal, use {@link GsonComponentSerializer#gson()} instead.
*/
@Deprecated
static @NotNull GsonComponentSerializer gsonSerializer() {
return GsonComponentSerializer.gson();
}
/**
* Get a {@link Player} identified by their profile's {@link java.util.UUID}.
*
* @param player the player to identify
* @return an identified representation of the player
* @since 4.0.0
*/
static @NotNull Identified identified(final @NotNull Player player) {
return (Identified) player;
}
/**
* Get an {@link Identity} representation of a {@link GameProfile}.
*
* @param profile the profile to represent
* @return an identity of the game profile
* @since 4.0.0
*/
static @NotNull Identity identity(final @NotNull GameProfile profile) {
return (Identity) profile;
}
/**
* Return a component flattener that can use game data to resolve extra information about components.
*
* @return the flattener
* @since 4.0.0
*/
@NotNull ComponentFlattener flattener();
/**
* Return a {@link PlainComponentSerializer} instance that can resolve key bindings and translations using the game's data.
*
* @return the plain serializer instance
* @since 4.0.0
* @deprecated for removal since 4.0.0, use {@link PlainTextComponentSerializer#plainText()} instead. Will be removed in 1.18 snapshots.
*/
@Deprecated
@NotNull PlainComponentSerializer plainSerializer();
/**
* Active renderer to render components.
*
* @return Shared renderer
* @since 4.0.0
*/
@NotNull ComponentRenderer<Pointered> renderer();
/**
* Get a native {@link net.minecraft.network.chat.Component} from an adventure {@link Component}.
*
* <p>The specific type of the returned component is undefined. For example, it may be a wrapper object.</p>
*
* @param adventure adventure input
* @return native representation
* @since 4.0.0
*/
net.minecraft.network.chat.@NotNull Component toNative(final @NotNull Component adventure);
/**
* Get an adventure {@link Component} from a native {@link net.minecraft.network.chat.Component}.
*
* @param vanilla the native component
* @return adventure component
* @since 4.0.0
*/
@NotNull Component toAdventure(final net.minecraft.network.chat.@NotNull Component vanilla);
}
@@ -0,0 +1,149 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric;
import java.util.Locale;
import java.util.function.Function;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.fabric.impl.AdventureCommon;
import net.kyori.adventure.platform.fabric.impl.client.FabricClientAudiencesImpl;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import org.jetbrains.annotations.NotNull;
/**
* Access the client's player as an {@link Audience}.
*
* @since 4.0.0
*/
public interface FabricClientAudiences extends FabricAudiences {
/**
* Get the common instance, that will render using the global translation registry.
*
* @return the audience provider
* @since 4.0.0
*/
static @NotNull FabricClientAudiences of() {
return FabricClientAudiencesImpl.INSTANCE;
}
/**
* Create a builder for an audience provider that might use custom locales.
*
* @return the builder
* @since 4.0.0
*/
static @NotNull FabricClientAudiences.Builder builder() {
return new FabricClientAudiencesImpl.Builder();
}
/**
* Get an audience provider that will render using the provided renderer.
*
* @param renderer Renderer to use
* @return new audience provider
* @since 4.0.0
* @deprecated for removal, use {@link #builder()} instead
*/
@Deprecated
static @NotNull FabricClientAudiences of(final @NotNull ComponentRenderer<Locale> renderer) {
return FabricClientAudiences.builder()
.componentRenderer(AdventureCommon.localePartition(), renderer)
.build();
}
/**
* Get an audience for the client's player.
*
* <p>When not in-game, most operations will no-op</p>
*
* @return player audience
* @since 4.0.0
*/
@NotNull Audience audience();
/**
* Build a {@link FabricClientAudiences} instance.
*
* @since 4.0.0
*/
interface Builder {
/**
* Sets the component renderer for the provider.
*
* @param componentRenderer a component renderer
* @return this builder
* @see #componentRenderer(Function, ComponentRenderer)
* @since 4.0.0
*/
@NotNull Builder componentRenderer(final @NotNull ComponentRenderer<Pointered> componentRenderer);
/**
* Set the partition function for the provider.
*
* <p>The output of the function must have {@link Object#equals(Object)} and {@link Object#hashCode()}
* methods overridden to ensure efficient operation.</p>
*
* <p>The output of the partition function must also be something suitable for use as a map key and
* as such, for long-term storage. This excludes objects that may hold live game state
* like {@code Entity} or {@code Level}.</p>
*
* <p>The configured {@link #componentRenderer(ComponentRenderer) component renderer} must produce
* the same result for two {@link Pointered} instances where this partition function provides the
* same output. If this condition is violated, caching issues are likely to occur, producing
* incorrect output for at least one of the inputs.</p>
*
* <p>A local {@code record} is a good way to produce a compound output value for this function.</p>
*
* @param partitionFunction the partition function to apply
* @return this builder
* @see #componentRenderer(Function, ComponentRenderer)
* @since 4.0.0
*/
@NotNull Builder partition(final @NotNull Function<Pointered, ?> partitionFunction);
/**
* Sets the component renderer and partition function for the provider.
*
* <p>This variant validates that the component renderer only depends on information included in the partition.</p>
*
* @param componentRenderer a component renderer
* @return this builder
* @since 4.0.0
*/
default <T> @NotNull Builder componentRenderer(final @NotNull Function<Pointered, T> partition, final @NotNull ComponentRenderer<T> componentRenderer) {
return this.partition(partition)
.componentRenderer(componentRenderer.mapContext(partition));
}
/**
* Builds the provider.
*
* @return the built provider
* @since 4.0.0
*/
@NotNull FabricClientAudiences build();
}
}
@@ -0,0 +1,129 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric;
import java.util.Locale;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.AudienceProvider;
import net.kyori.adventure.platform.fabric.impl.AdventureCommon;
import net.kyori.adventure.platform.fabric.impl.server.FabricServerAudiencesImpl;
import net.kyori.adventure.platform.fabric.impl.server.MinecraftServerBridge;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import org.jetbrains.annotations.NotNull;
import static java.util.Objects.requireNonNull;
/**
* Provides {@link Audience} instances for a specific server instance.
*
* @since 4.0.0
*/
public interface FabricServerAudiences extends AudienceProvider, FabricAudiences {
/**
* Get the shared audience provider for the server.
*
* <p>This provider will render messages using the global translation registry.</p>
*
* @param server server instance to work with
* @return common audience provider
* @since 4.0.0
*/
static @NotNull FabricServerAudiences of(final @NotNull MinecraftServer server) {
return ((MinecraftServerBridge) server).adventure$globalProvider();
}
/**
* Create an audience provider for this server with customized settings.
*
* @param server the server
* @return audience provider builder
* @since 4.0.0
*/
static @NotNull Builder builder(final @NotNull MinecraftServer server) {
return new FabricServerAudiencesImpl.Builder(requireNonNull(server, "server"));
}
/**
* Get a customized audience provider for the server.
*
* <p>This provider will render messages using the global translation registry.</p>
*
* @param server server to work in
* @param renderer renderer for messages.
* @return new audience provider
* @since 4.0.0
* @deprecated for removal, use {@link #builder(MinecraftServer)} instead
*/
@Deprecated
static @NotNull FabricServerAudiences of(final @NotNull MinecraftServer server, final @NotNull ComponentRenderer<Locale> renderer) {
return FabricServerAudiences.builder(server)
.componentRenderer(AdventureCommon.localePartition(), renderer)
.build();
}
/**
* Get an audience to send to a {@link CommandSourceStack}.
*
* <p>This will delegate to the native implementation by the command source, or
* otherwise use a wrapping implementation.</p>
*
* @param source source to send to.
* @return the audience
* @since 4.0.0
*/
@NotNull AdventureCommandSourceStack audience(@NotNull CommandSourceStack source);
/**
* Get an audience that will send to the provided {@link CommandSource}.
*
* <p>Depending on the specific source, the returned audience may only support
* a subset of abilities.</p>
*
* @param source source to send to
* @return an audience for the source
* @since 4.0.0
*/
@NotNull Audience audience(@NotNull CommandSource source);
/**
* Create an audience that will send to every listed player.
*
* @param players Players to send to.
* @return a new audience
* @since 4.0.0
*/
@NotNull Audience audience(@NotNull Iterable<ServerPlayer> players);
/**
* Builder for {@link FabricServerAudiences} with custom attributes.
*
* @since 4.0.0
*/
interface Builder extends AudienceProvider.Builder<FabricServerAudiences, Builder> {
}
}
@@ -0,0 +1,72 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.kyori.adventure.key.Key;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
/**
* An argument that will be decoded as a Key.
*
* @since 4.0.0
*/
public final class KeyArgumentType implements ArgumentType<Key> {
private static final KeyArgumentType INSTANCE = new KeyArgumentType();
/**
* Get an argument type instance for {@link Key}s.
*
* @return key argument type
* @since 4.0.0
*/
public static @NotNull KeyArgumentType key() {
return INSTANCE;
}
/**
* Get a {@link Key}-typed value from a parsed {@link CommandContext}.
*
* @param ctx context to get the value from
* @param id id the argument was taken from
* @return provided argument
* @since 4.0.0
*/
public static @NotNull Key key(final @NotNull CommandContext<?> ctx, final @NotNull String id) {
return ctx.getArgument(id, Key.class);
}
private KeyArgumentType() {
}
@Override
public @NotNull Key parse(final @NotNull StringReader reader) throws CommandSyntaxException {
// TODO: do this without creating a ResourceLocation instance
return FabricAudiences.toAdventure(ResourceLocation.read(reader));
}
}
@@ -0,0 +1,83 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric;
import java.util.Locale;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.kyori.adventure.platform.fabric.impl.LocaleHolderBridge;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* API for working with player locales.
*
* @since 4.0.0
*/
public interface PlayerLocales {
/**
* Registration for {@link Changed}.
*
* @since 4.0.0
*/
@NotNull Event<Changed> CHANGED_EVENT = EventFactory.createArrayBacked(Changed.class, listeners -> (player, locale) -> {
for (final Changed event : listeners) {
event.onLocaleChanged(player, locale);
}
});
/**
* An event called when a player locale update is received.
*
* <p>This event is only called if the player locale has actually changed from its previous value.</p>
*
* @since 4.0.0
*/
interface Changed {
/**
* Handle the locale change.
*
* @param player the player whose locale changed
* @param newLocale the new locale
* @since 4.0.0
*/
void onLocaleChanged(final @NotNull ServerPlayer player, final @Nullable Locale newLocale);
}
/**
* Get the active locale for a player, either on the server or client sides.
*
* <p>Will return the system-wide default value if the player has no locale set.</p>
*
* @param player the source of the locale
* @return player locale
* @since 4.0.0
*/
static @NotNull Locale locale(final @NotNull Player player) {
return player instanceof LocaleHolderBridge ? ((LocaleHolderBridge) player).adventure$locale() : Locale.getDefault();
}
}
@@ -0,0 +1,108 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.text.Component;
import net.minecraft.world.BossEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class AbstractBossBarListener<T extends BossEvent> implements BossBar.Listener {
private final FabricAudiences controller;
protected final Map<BossBar, T> bars = new IdentityHashMap<>();
protected AbstractBossBarListener(final FabricAudiences controller) {
this.controller = controller;
}
@Override
public void bossBarNameChanged(final @NotNull BossBar bar, final @NotNull Component oldName, final @NotNull Component newName) {
if (!oldName.equals(newName)) {
this.minecraft(bar).setName(this.controller.toNative(newName));
}
}
@Override
public void bossBarProgressChanged(final @NotNull BossBar bar, final float oldPercent, final float newPercent) {
if (oldPercent != newPercent) {
this.minecraft(bar).setPercent(newPercent);
}
}
@Override
public void bossBarColorChanged(final @NotNull BossBar bar, final BossBar.@NotNull Color oldColor, final BossBar.@NotNull Color newColor) {
if (oldColor != newColor) {
this.minecraft(bar).setColor(GameEnums.BOSS_BAR_COLOR.toMinecraft(newColor));
}
}
@Override
public void bossBarOverlayChanged(final @NotNull BossBar bar, final BossBar.@NotNull Overlay oldOverlay, final BossBar.@NotNull Overlay newOverlay) {
if (oldOverlay != newOverlay) {
this.minecraft(bar).setOverlay(GameEnums.BOSS_BAR_OVERLAY.toMinecraft(newOverlay));
}
}
@Override
public void bossBarFlagsChanged(final @NotNull BossBar bar, final @NotNull Set<BossBar.Flag> flagsRemoved, final @NotNull Set<BossBar.Flag> flagsAdded) {
updateFlags(this.minecraft(bar), bar.flags());
}
private static void updateFlags(final @NotNull BossEvent bar, final @NotNull Set<BossBar.Flag> flags) {
bar.setCreateWorldFog(flags.contains(BossBar.Flag.CREATE_WORLD_FOG));
bar.setDarkenScreen(flags.contains(BossBar.Flag.DARKEN_SCREEN));
bar.setPlayBossMusic(flags.contains(BossBar.Flag.PLAY_BOSS_MUSIC));
}
private T minecraft(final @NotNull BossBar bar) {
final @Nullable T mc = this.bars.get(bar);
if (mc == null) {
throw new IllegalArgumentException("Unknown boss bar instance " + bar);
}
return mc;
}
protected abstract T newBar(final net.minecraft.network.chat.@NotNull Component title,
final BossEvent.@NotNull BossBarColor color,
final BossEvent.@NotNull BossBarOverlay style,
final float progress);
protected T minecraftCreating(final @NotNull BossBar bar) {
return this.bars.computeIfAbsent(bar, key -> {
final T ret = this.newBar(this.controller.toNative(key.name()),
GameEnums.BOSS_BAR_COLOR.toMinecraft(key.color()),
GameEnums.BOSS_BAR_OVERLAY.toMinecraft(key.overlay()),
key.progress());
updateFlags(ret, key.flags());
key.addListener(this);
return ret;
});
}
}
@@ -0,0 +1,47 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.fabric.AdventureCommandSourceStack;
import net.kyori.adventure.platform.fabric.impl.server.FabricServerAudiencesImpl;
import net.minecraft.commands.CommandSource;
public interface AdventureCommandSourceStackInternal extends AdventureCommandSourceStack {
/**
* Set the audience to be delegated to.
*
* @param wrapped wrapped audience
* @param controller controller to render with
* @return the wrapped audience
*/
AdventureCommandSourceStack adventure$audience(final Audience wrapped, final FabricServerAudiencesImpl controller);
/**
* The backing source for the command.
*
* @return backing source
*/
CommandSource adventure$source();
}
@@ -0,0 +1,145 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.fabric.ComponentArgumentType;
import net.kyori.adventure.platform.fabric.KeyArgumentType;
import net.kyori.adventure.platform.fabric.PlayerLocales;
import net.kyori.adventure.platform.fabric.impl.server.FabricServerAudiencesImpl;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.KeybindComponent;
import net.kyori.adventure.text.TranslatableComponent;
import net.kyori.adventure.text.flattener.ComponentFlattener;
import net.kyori.adventure.translation.GlobalTranslator;
import net.kyori.adventure.translation.TranslationRegistry;
import net.kyori.adventure.translation.Translator;
import net.minecraft.client.KeyMapping;
import net.minecraft.commands.synchronization.ArgumentTypes;
import net.minecraft.commands.synchronization.EmptyArgumentSerializer;
import net.minecraft.locale.Language;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class AdventureCommon implements ModInitializer {
public static final ComponentFlattener FLATTENER;
private static final Pattern LOCALIZATION_PATTERN = Pattern.compile("%(?:(\\d+)\\$)?s");
static {
final ComponentFlattener.Builder flattenerBuilder = ComponentFlattener.basic().toBuilder();
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
flattenerBuilder.mapper(KeybindComponent.class, keybind -> KeyMapping.createNameSupplier(keybind.keybind()).get().getContents());
}
flattenerBuilder.complexMapper(TranslatableComponent.class, (translatable, consumer) -> {
final String key = translatable.key();
for (final Translator registry : GlobalTranslator.translator().sources()) {
if (registry instanceof TranslationRegistry && ((TranslationRegistry) registry).contains(key)) {
consumer.accept(GlobalTranslator.render(translatable, Locale.getDefault()));
return;
}
}
final @NotNull String translated = Language.getInstance().getOrDefault(key);
final Matcher matcher = LOCALIZATION_PATTERN.matcher(translated);
final List<Component> args = translatable.args();
int argPosition = 0;
int lastIdx = 0;
while (matcher.find()) {
// append prior
if (lastIdx < matcher.start()) consumer.accept(Component.text(translated.substring(lastIdx, matcher.start())));
lastIdx = matcher.end();
final @Nullable String argIdx = matcher.group(1);
// calculate argument position
if (argIdx != null) {
try {
final int idx = Integer.parseInt(argIdx) - 1;
if (idx < args.size()) {
consumer.accept(args.get(idx));
}
} catch (final NumberFormatException ex) {
// ignore, drop the format placeholder
}
} else {
final int idx = argPosition++;
if (idx < args.size()) {
consumer.accept(args.get(idx));
}
}
}
// append tail
if (lastIdx < translated.length()) {
consumer.accept(Component.text(translated.substring(lastIdx)));
}
});
FLATTENER = flattenerBuilder.build();
}
static ResourceLocation res(final @NotNull String value) {
return new ResourceLocation("adventure", value);
}
@Override
public void onInitialize() {
// Register custom argument types
ArgumentTypes.register("adventure:component", ComponentArgumentType.class, new ComponentArgumentTypeSerializer());
ArgumentTypes.register("adventure:key", KeyArgumentType.class, new EmptyArgumentSerializer<>(KeyArgumentType::key));
PlayerLocales.CHANGED_EVENT.register((player, locale) -> {
FabricServerAudiencesImpl.forEachInstance(instance -> {
instance.bossBars().refreshTitles(player);
});
});
}
public static Function<Pointered, Locale> localePartition() {
return ptr -> ptr.getOrDefault(Identity.LOCALE, Locale.US);
}
public static Pointered pointered(final FPointered pointers) {
return pointers;
}
@FunctionalInterface
interface FPointered extends Pointered {
@Override
@NotNull Pointers pointers();
}
}
@@ -0,0 +1,92 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import java.lang.reflect.Method;
import java.net.URL;
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
/**
* Via i509VCB, a trick to get Brig onto the Knot classpath in order to properly mix in.
*
* <p>YOU SHOULD ONLY USE THIS CLASS DURING "preLaunch" and ONLY TARGET A CLASS WHICH IS NOT ANY CLASS YOU MIXIN TO.
* This will likely not work on Gson because FabricLoader has some special logic related to Gson.</p>
*
* <p>Original on GitHub at <a href="https://github.com/i509VCB/Fabric-Junkkyard/blob/ce278daa93804697c745a51af06ec812896ec2ad/src/main/java/me/i509/junkkyard/hacks/PreLaunchHacks.java">i509VCB/Fabric-Junkkyard</a></p>
*/
public class AdventurePrelaunch implements PreLaunchEntrypoint {
@Override
public void onPreLaunch() {
// 在 Fabric 环境中,不需要特殊处理
if (isFabricEnvironment()) {
System.out.println("Adventure platform running in Fabric environment");
return;
}
// 非 Fabric 环境,执行原来的逻辑
try {
hackilyLoadForMixin("com.mojang.authlib.UserAuthentication");
} catch (final Exception e) {
throw new RuntimeException("Failed to setup Adventure platform", e);
}
}
private static boolean isFabricEnvironment() {
try {
Class.forName("net.fabricmc.loader.api.FabricLoader");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
static void hackilyLoadForMixin(final String pathOfAClass) throws Exception {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final URL url = Class.forName(pathOfAClass).getProtectionDomain().getCodeSource().getLocation();
// 尝试添加 URL
try {
Method addURLMethod = findAddURLMethod(classLoader);
if (addURLMethod != null) {
addURLMethod.invoke(classLoader, url);
}
} catch (Exception e) {
System.err.println("Failed to add URL, but continuing: " + e.getMessage());
}
}
private static Method findAddURLMethod(ClassLoader classLoader) {
Class<?> clazz = classLoader.getClass();
while (clazz != null) {
try {
Method method = clazz.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
return null;
}
}
@@ -0,0 +1,52 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import com.google.gson.JsonObject;
import net.kyori.adventure.platform.fabric.ComponentArgumentType;
import net.kyori.adventure.platform.fabric.impl.accessor.ComponentSerializerAccess;
import net.minecraft.commands.synchronization.ArgumentSerializer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ComponentArgumentTypeSerializer implements ArgumentSerializer<ComponentArgumentType> {
private static final ResourceLocation SERIALIZER_GSON = new ResourceLocation("adventure", "gson");
@Override
public void serializeToNetwork(final ComponentArgumentType type, final FriendlyByteBuf buffer) {
buffer.writeResourceLocation(SERIALIZER_GSON);
}
@Override
public ComponentArgumentType deserializeFromNetwork(final FriendlyByteBuf buffer) {
buffer.readResourceLocation(); // TODO: Serializer type
return ComponentArgumentType.component();
}
@Override
public void serializeToJson(final ComponentArgumentType type, final JsonObject json) {
json.add("serializer", ComponentSerializerAccess.getGSON().toJsonTree(SERIALIZER_GSON));
}
}
@@ -0,0 +1,48 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.bossbar.BossBar.Overlay;
import net.kyori.adventure.platform.fabric.impl.accessor.SoundSourceAccess;
import net.kyori.adventure.sound.Sound;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.BossEvent;
public final class GameEnums {
public static final MappedRegistry<BossEvent.BossBarColor, BossBar.Color> BOSS_BAR_COLOR
= MappedRegistry.named(BossEvent.BossBarColor.class, BossEvent.BossBarColor::byName,
BossBar.Color.class, BossBar.Color.NAMES);
public static final MappedRegistry<BossEvent.BossBarOverlay, Overlay> BOSS_BAR_OVERLAY
= MappedRegistry.named(BossEvent.BossBarOverlay.class, BossEvent.BossBarOverlay::byName,
Overlay.class, Overlay.NAMES);
public static final MappedRegistry<SoundSource, Sound.Source> SOUND_SOURCE
= MappedRegistry.named(SoundSource.class, key -> SoundSourceAccess.getNameMap().get(key),
Sound.Source.class, Sound.Source.NAMES);
private GameEnums() {
}
}
@@ -0,0 +1,56 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import java.util.Locale;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface LocaleHolderBridge {
/**
* Take a locale string provided from a minecraft client and attempt to parse it as a locale.
* These are not strictly compliant with the iso standard, so we try to make things a bit more normalized.
*
* @param mcLocale The locale string, in the format provided by the Minecraft client
* @return A Locale object matching the provided locale string
*/
static @Nullable Locale toLocale(final @Nullable String mcLocale) {
if (mcLocale == null) return null;
final String[] parts = mcLocale.split("_", 3);
switch (parts.length) {
case 1:
return parts[0].isEmpty() ? null : new Locale(parts[0]);
case 2:
return new Locale(parts[0], parts[1]);
case 3:
return new Locale(parts[0], parts[1], parts[2]);
case 0:
default:
return null;
}
}
@NotNull Locale adventure$locale();
}
@@ -0,0 +1,124 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import net.kyori.adventure.util.Index;
import org.jetbrains.annotations.Nullable;
import static java.util.Objects.requireNonNull;
/**
* Represents a mapping between an enum-like set of values controlled by Minecraft, and an enum-like set of values controlled by
* Adventure.
*
* <p>Because these enums both refer to known constants, it is relatively easy to generate an automated
* mapping between the two of them. As the two enums represent the same set of values, it is
* required that any element that appears in one is present in the other, so mappings will never
* return null.</p>
*
* @param <Mc> The Minecraft type
* @param <Adv> The Adventure type
*/
public class MappedRegistry<Mc, Adv> {
private final Map<Mc, Adv> mcToAdventure;
private final Map<Adv, Mc> adventureToMc;
static <Mc extends Enum<Mc>, Adv extends Enum<Adv>> MappedRegistry<Mc, Adv> named(final Class<Mc> mcType, final Function<String, @Nullable Mc> mcByName, final Class<Adv> advType, final Index<String, Adv> names) {
return new OfEnum<>(mcType, mcByName, advType, names::key);
}
static <Mc, Adv> MappedRegistry<Mc, Adv> named(final Function<String, @Nullable Mc> mcByName, final Supplier<Iterable<Mc>> mcValues, final Index<String, Adv> names, final Supplier<Iterable<Adv>> adventureValues) {
return new MappedRegistry<>(new HashMap<>(), new HashMap<>(), mcByName, mcValues, names::key, adventureValues);
}
MappedRegistry(final Map<Mc, Adv> mcMap, final Map<Adv, Mc> adventureMap, final Function<String, @Nullable Mc> mcByName, final Supplier<Iterable<Mc>> mcValues, final Function<Adv, @Nullable String> advToName, final Supplier<Iterable<Adv>> adventureValues) {
this.mcToAdventure = mcMap;
this.adventureToMc = adventureMap;
for (final Adv advElement : adventureValues.get()) {
final @Nullable String mcName = advToName.apply(advElement);
if (mcName == null) {
throw new ExceptionInInitializerError("Unable to get name for enum-like element " + advElement);
}
final @Nullable Mc mcElement = mcByName.apply(mcName);
if (mcElement == null) {
throw new ExceptionInInitializerError("Unknown MC element for Adventure " + mcName);
}
this.mcToAdventure.put(mcElement, advElement);
this.adventureToMc.put(advElement, mcElement);
}
checkCoverage(this.mcToAdventure, mcValues.get());
}
/**
* Validates that all members of an enum are present in the given map Throws {@link
* IllegalStateException} if there is a missing value.
*
* @param toCheck The map to check
* @param values The values to verify are keys of the provided map
* @param <T> The type of enum
* @throws IllegalStateException if a value is missing
*/
private static <T> void checkCoverage(final Map<T, ?> toCheck, final Iterable<T> values) throws IllegalStateException {
for (final T value : values) {
if (!toCheck.containsKey(value)) {
throw new IllegalStateException("Unmapped " + value.getClass().getSimpleName() + " element '" + value + '!');
}
}
}
/**
* Given a Minecraft enum element, return the equivalent Adventure element.
*
* @param mcItem The Minecraft element
* @return The adventure equivalent.
*/
public Adv toAdventure(final Mc mcItem) {
return requireNonNull(this.mcToAdventure.get(mcItem), "Invalid enum value presented: " + mcItem);
}
/**
* Given an Adventure enum element, return the equivalent Minecraft element.
*
* @param advItem The Minecraft element
* @return The adventure equivalent.
*/
public Mc toMinecraft(final Adv advItem) {
return this.adventureToMc.get(advItem);
}
static class OfEnum<Mc extends Enum<Mc>, Adv extends Enum<Adv>> extends MappedRegistry<Mc, Adv> {
OfEnum(final Class<Mc> mcType, final Function<String, @Nullable Mc> mcByName, final Class<Adv> advType, final Function<Adv, @Nullable String> advToName) {
super(new EnumMap<>(mcType), new EnumMap<>(advType), mcByName, () -> Arrays.asList(mcType.getEnumConstants()), advToName, () -> Arrays.asList(advType.getEnumConstants()));
}
}
}
@@ -0,0 +1,113 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.io.IOException;
import java.util.UUID;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.nbt.api.BinaryTagHolder;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.serializer.gson.LegacyHoverEventSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.kyori.adventure.util.Codec;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.TagParser;
import org.jetbrains.annotations.NotNull;
public final class NBTLegacyHoverEventSerializer implements LegacyHoverEventSerializer {
public static final NBTLegacyHoverEventSerializer INSTANCE = new NBTLegacyHoverEventSerializer();
private static final Codec<CompoundTag, String, CommandSyntaxException, RuntimeException> SNBT_CODEC = Codec.of(TagParser::parseTag, Tag::toString);
static final String ITEM_TYPE = "id";
static final String ITEM_COUNT = "Count";
static final String ITEM_TAG = "tag";
static final String ENTITY_NAME = "name";
static final String ENTITY_TYPE = "type";
static final String ENTITY_ID = "id";
private NBTLegacyHoverEventSerializer() {
}
@Override
public HoverEvent.@NotNull ShowItem deserializeShowItem(final @NotNull Component input) throws IOException {
final String raw = PlainTextComponentSerializer.plainText().serialize(input);
try {
final CompoundTag contents = SNBT_CODEC.decode(raw);
final CompoundTag tag = contents.getCompound(ITEM_TAG);
return HoverEvent.ShowItem.of(
Key.key(contents.getString(ITEM_TYPE)),
contents.contains(ITEM_COUNT) ? contents.getByte(ITEM_COUNT) : 1,
tag.isEmpty() ? null : BinaryTagHolder.encode(tag, SNBT_CODEC)
);
} catch (final CommandSyntaxException ex) {
throw new IOException(ex);
}
}
@Override
public HoverEvent.@NotNull ShowEntity deserializeShowEntity(final @NotNull Component input, final Codec.Decoder<Component, String, ? extends RuntimeException> componentCodec) throws IOException {
final String raw = PlainTextComponentSerializer.plainText().serialize(input);
try {
final CompoundTag contents = SNBT_CODEC.decode(raw);
return HoverEvent.ShowEntity.of(
Key.key(contents.getString(ENTITY_TYPE)),
UUID.fromString(contents.getString(ENTITY_ID)),
componentCodec.decode(contents.getString(ENTITY_NAME))
);
} catch (final CommandSyntaxException ex) {
throw new IOException(ex);
}
}
@Override
public @NotNull Component serializeShowItem(final HoverEvent.@NotNull ShowItem input) throws IOException {
final CompoundTag tag = new CompoundTag();
tag.putString(ITEM_TYPE, input.item().asString());
tag.putByte(ITEM_COUNT, (byte) input.count());
if (input.nbt() != null) {
try {
tag.put(ITEM_TAG, input.nbt().get(SNBT_CODEC));
} catch (final CommandSyntaxException ex) {
throw new IOException(ex);
}
}
return Component.text(SNBT_CODEC.encode(tag));
}
@Override
public @NotNull Component serializeShowEntity(final HoverEvent.@NotNull ShowEntity input, final Codec.Encoder<Component, String, ? extends RuntimeException> componentCodec) throws IOException {
final CompoundTag tag = new CompoundTag();
tag.putString(ENTITY_ID, input.id().toString());
tag.putString(ENTITY_TYPE, input.type().asString());
if (input.name() != null) {
tag.putString(ENTITY_NAME, componentCodec.encode(input.name()));
}
return Component.text(SNBT_CODEC.encode(tag));
}
}
@@ -0,0 +1,63 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import net.kyori.adventure.platform.fabric.impl.accessor.ComponentSerializerAccess;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.ComponentSerializer;
import net.minecraft.network.chat.MutableComponent;
public final class NonWrappingComponentSerializer implements ComponentSerializer<Component, Component, net.minecraft.network.chat.Component> {
public static final NonWrappingComponentSerializer INSTANCE = new NonWrappingComponentSerializer();
private final ThreadLocal<Boolean> bypassIsAllowedFromServer = ThreadLocal.withInitial(() -> false);
private NonWrappingComponentSerializer() {
}
public boolean bypassIsAllowedFromServer() {
return this.bypassIsAllowedFromServer.get();
}
@Override
public Component deserialize(final net.minecraft.network.chat.Component input) {
if (input instanceof WrappedComponent) {
return ((WrappedComponent) input).wrapped();
}
return ComponentSerializerAccess.getGSON().fromJson(net.minecraft.network.chat.Component.Serializer.toJsonTree(input), Component.class);
}
@Override
public MutableComponent serialize(final Component component) {
this.bypassIsAllowedFromServer.set(true);
final MutableComponent mutableComponent;
try {
mutableComponent = net.minecraft.network.chat.Component.Serializer.fromJson(ComponentSerializerAccess.getGSON().toJsonTree(component));
} finally {
this.bypassIsAllowedFromServer.set(false);
}
return mutableComponent;
}
}
@@ -0,0 +1,37 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import net.kyori.adventure.pointer.Pointers;
import org.jetbrains.annotations.NotNull;
public interface PointerProviderBridge {
/**
* Get a shared instance of pointers.
*
* @return the pointers
*/
@NotNull Pointers adventure$pointers();
}
@@ -0,0 +1,171 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.util.FormattedCharSequence;
import org.jetbrains.annotations.Nullable;
public final class WrappedComponent implements Component {
private Component converted;
private @Nullable Object deepConvertedLocalized = null;
private final net.kyori.adventure.text.Component wrapped;
private final @Nullable Function<Pointered, ?> partition;
private final @Nullable ComponentRenderer<Pointered> renderer;
private @Nullable Object lastData;
private @Nullable WrappedComponent lastRendered;
public WrappedComponent(final net.kyori.adventure.text.Component wrapped, final @Nullable Function<Pointered, ?> partition, final @Nullable ComponentRenderer<Pointered> renderer) {
this.wrapped = wrapped;
this.partition = partition;
this.renderer = renderer;
}
/**
* Renderer to use to translate messages.
*
* @return the renderer, if any
*/
public @Nullable ComponentRenderer<Pointered> renderer() {
return this.renderer;
}
/**
* Partition to use to generate cache keys.
*
* @return the partition, if any
*/
public @Nullable Function<Pointered, ?> partition() {
return this.partition;
}
public net.kyori.adventure.text.Component wrapped() {
return this.wrapped;
}
public synchronized WrappedComponent rendered(final Pointered ptr) {
final Object data = this.partition == null ? null : this.partition.apply(ptr);
if (this.lastData != null && Objects.equals(data, this.lastData)) {
return this.lastRendered;
}
this.lastData = data;
return this.lastRendered = this.renderer == null ? this : new WrappedComponent(this.renderer.render(this.wrapped, ptr), null, null);
}
Component deepConverted() {
Component converted = this.converted;
if (converted == null || this.deepConvertedLocalized != null) {
converted = this.converted = FabricAudiences.nonWrappingSerializer().serialize(this.wrapped);
this.deepConvertedLocalized = null;
}
return converted;
}
@Environment(EnvType.CLIENT)
Component deepConvertedLocalized() {
Component converted = this.converted;
final Pointered target = (Pointered) Minecraft.getInstance().player;
final Object data = this.partition == null ? null : this.partition.apply(target);
if (converted == null || this.deepConvertedLocalized != data) {
converted = this.converted = this.rendered(target).deepConverted();
this.deepConvertedLocalized = data;
}
return converted;
}
public @Nullable Component deepConvertedIfPresent() {
return this.converted;
}
@Override
public Style getStyle() {
return this.deepConverted().getStyle();
}
@Override
public String getString() {
return PlainTextComponentSerializer.plainText().serialize(this.rendered(AdventureCommon.pointered(Pointers::empty)).wrapped);
}
@Override
public String getString(final int length) {
return this.deepConverted().getString(length);
}
@Override
public String getContents() {
if (this.wrapped instanceof TextComponent) {
return ((TextComponent) this.wrapped).content();
} else {
return this.deepConverted().getContents();
}
}
@Override
public List<Component> getSiblings() {
return this.deepConverted().getSiblings();
}
@Override
public MutableComponent plainCopy() {
return this.deepConverted().plainCopy();
}
@Override
public MutableComponent copy() {
return this.deepConverted().copy();
}
@Override
@Environment(EnvType.CLIENT)
public FormattedCharSequence getVisualOrderText() {
return this.deepConvertedLocalized().getVisualOrderText();
}
@Override
@Environment(EnvType.CLIENT)
public <T> Optional<T> visit(final StyledContentConsumer<T> visitor, final Style style) {
return this.deepConvertedLocalized().visit(visitor, style);
}
@Override
public <T> Optional<T> visit(final ContentConsumer<T> visitor) {
return this.deepConverted().visit(visitor);
}
}
@@ -0,0 +1,42 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.accessor;
import java.util.UUID;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundBossEventPacket;
import net.minecraft.world.BossEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ClientboundBossEventPacket.class)
public interface ClientboundBossEventPacketAccess {
// @formatter:off
@Accessor void setId(final UUID id);
@Accessor void setName(final Component name);
@Accessor void setColor(final BossEvent.BossBarColor color);
@Accessor void setOverlay(final BossEvent.BossBarOverlay overlay);
@Accessor void setPct(final float percent);
// @formatter:on
}
@@ -0,0 +1,37 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.accessor;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundTabListPacket;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ClientboundTabListPacket.class)
public interface ClientboundTabListPacketAccess {
// @formatter:off
@Accessor void setHeader(final Component header);
@Accessor void setFooter(final Component footer);
// @formatter:on
}
@@ -0,0 +1,43 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.accessor;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import net.minecraft.network.chat.Component;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(Component.Serializer.class)
public interface ComponentSerializerAccess {
// @formatter:off
@Accessor static Gson getGSON() {
throw new AssertionError();
}
@Invoker("getPos") static int getPos(final JsonReader reader) {
throw new AssertionError();
}
// @formatter:on
}
@@ -0,0 +1,36 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.accessor;
import io.netty.channel.Channel;
import net.minecraft.network.Connection;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(Connection.class)
public interface ConnectionAccess {
// @formatter:off
@Accessor Channel getChannel();
// @formatter:on
}
@@ -0,0 +1,35 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.accessor;
import net.minecraft.network.protocol.game.ServerboundClientInformationPacket;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ServerboundClientInformationPacket.class)
public interface ServerboundClientInformationPacketAccess {
// @formatter:off
@Accessor String getLanguage();
// @formatter:on
}
@@ -0,0 +1,38 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.accessor;
import java.util.Map;
import net.minecraft.sounds.SoundSource;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(SoundSource.class)
public interface SoundSourceAccess {
// @formatter:off
@Accessor("BY_NAME") static Map<String, SoundSource> getNameMap() {
throw new AssertionError();
}
// @formatter:on
}
@@ -0,0 +1,36 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.accessor.client;
import net.minecraft.client.resources.sounds.AbstractSoundInstance;
import net.minecraft.resources.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(AbstractSoundInstance.class)
public interface AbstractSoundInstanceAccess {
// @formatter:off
@Accessor void setLocation(final ResourceLocation loc);
// @formatter:on
}
@@ -0,0 +1,30 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Mixin accessors for internal use only.
*/
@ApiStatus.Internal
package net.kyori.adventure.platform.fabric.impl.accessor;
import org.jetbrains.annotations.ApiStatus;
@@ -0,0 +1,65 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.client;
import java.util.function.Function;
import net.kyori.adventure.inventory.Book;
import net.kyori.adventure.platform.fabric.impl.WrappedComponent;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.minecraft.client.gui.screens.inventory.BookViewScreen;
import net.minecraft.network.chat.FormattedText;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static java.util.Objects.requireNonNull;
/**
* An implementation of the book GUI's contents.
*
* <p>This implementation gets its data directly from an
* Adventure {@link Book}, without needing
* an {@link net.minecraft.world.item.ItemStack}.</p>
*/
public class AdventureBookAccess implements BookViewScreen.BookAccess {
private final Book book;
private final @Nullable Function<Pointered, ?> partition;
private final @Nullable ComponentRenderer<Pointered> renderer;
public AdventureBookAccess(final @NotNull Book book, final @Nullable Function<Pointered, ?> partition, final @Nullable ComponentRenderer<Pointered> renderer) {
this.book = requireNonNull(book, "book");
this.partition = partition;
this.renderer = renderer;
}
@Override
public int getPageCount() {
return this.book.pages().size();
}
@Override
public FormattedText getPageRaw(final int index) {
return new WrappedComponent(this.book.pages().get(index), this.partition, this.renderer);
}
}
@@ -0,0 +1,40 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.client;
import net.minecraft.client.gui.components.BossHealthOverlay;
import org.jetbrains.annotations.NotNull;
import static java.util.Objects.requireNonNull;
/**
* Accessor for our listener stored in the client HUD.
*/
public interface BossHealthOverlayBridge {
@NotNull ClientBossBarListener adventure$listener(final @NotNull FabricClientAudiencesImpl controller);
static @NotNull ClientBossBarListener listener(final @NotNull BossHealthOverlay hud, final @NotNull FabricClientAudiencesImpl controller) {
return ((BossHealthOverlayBridge) requireNonNull(hud, "hud")).adventure$listener(controller);
}
}
@@ -0,0 +1,222 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.client;
import java.time.Duration;
import java.util.Objects;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.inventory.Book;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.platform.fabric.impl.GameEnums;
import net.kyori.adventure.platform.fabric.impl.PointerProviderBridge;
import net.kyori.adventure.platform.fabric.impl.accessor.client.AbstractSoundInstanceAccess;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.sound.SoundStop;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.title.Title;
import net.kyori.adventure.title.TitlePart;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.inventory.BookViewScreen;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.resources.sounds.EntityBoundSoundInstance;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.ChatVisiblity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ClientAudience implements Audience {
private final Minecraft client;
private final FabricClientAudiencesImpl controller;
public ClientAudience(final Minecraft client, final FabricClientAudiencesImpl renderer) {
this.client = client;
this.controller = renderer;
}
@Override
public void sendMessage(final Identity source, final @NotNull Component message, final @NotNull MessageType type) {
if (this.client.isBlocked(source.uuid())) return;
final ChatVisiblity visibility = this.client.options.chatVisibility;
if (type == MessageType.CHAT) {
// Add to chat queue (following delay and such)
if (visibility == ChatVisiblity.FULL) {
this.client.gui.getChat().enqueueMessage(this.controller.toNative(message));
}
} else {
// Add immediately as a system message
if (visibility == ChatVisiblity.FULL || visibility == ChatVisiblity.SYSTEM) {
this.client.gui.getChat().addMessage(this.controller.toNative(message));
}
}
}
@Override
public void sendActionBar(final @NotNull Component message) {
this.client.gui.setOverlayMessage(this.controller.toNative(message), false);
}
@Override
public void showTitle(final @NotNull Title title) {
final net.minecraft.network.chat.@Nullable Component titleText = title.title() == Component.empty() ? null : this.controller.toNative(title.title());
final net.minecraft.network.chat.@Nullable Component subtitleText = title.subtitle() == Component.empty() ? null : this.controller.toNative(title.subtitle());
final Title.@Nullable Times times = title.times();
this.client.gui.setTitles(titleText, subtitleText,
this.adventure$ticks(times == null ? null : times.fadeIn()),
this.adventure$ticks(times == null ? null : times.stay()),
this.adventure$ticks(times == null ? null : times.fadeOut()));
}
@Override
public <T> void sendTitlePart(final @NotNull TitlePart<T> part, @NotNull final T value) {
Objects.requireNonNull(value, "value");
if (part == TitlePart.TITLE) {
this.client.gui.setTitles(this.controller.toNative((Component) value), null, -1, -1, -1);
} else if (part == TitlePart.SUBTITLE) {
this.client.gui.setTitles(null, this.controller.toNative((Component) value), -1, -1, -1);
} else if (part == TitlePart.TIMES) {
final Title.Times times = (Title.Times) value;
this.client.gui.setTitles(
null,
null,
this.adventure$ticks(times.fadeIn()),
this.adventure$ticks(times.stay()),
this.adventure$ticks(times.fadeOut())
);
} else {
throw new IllegalArgumentException("Unknown TitlePart '" + part + "'");
}
}
private int adventure$ticks(final @Nullable Duration duration) {
return duration == null || duration.getSeconds() == -1 ? -1 : (int) (duration.toMillis() / 50);
}
@Override
public void clearTitle() {
this.client.gui.setTitles(null, null, -1, -1, -1);
}
@Override
public void resetTitle() {
this.client.gui.resetTitleTimes();
}
@Override
public void showBossBar(final @NotNull BossBar bar) {
BossHealthOverlayBridge.listener(this.client.gui.getBossOverlay(), this.controller).add(bar);
}
@Override
public void hideBossBar(final @NotNull BossBar bar) {
BossHealthOverlayBridge.listener(this.client.gui.getBossOverlay(), this.controller).remove(bar);
}
@Override
public void playSound(final @NotNull Sound sound) {
final LocalPlayer player = this.client.player;
if (player != null) {
this.playSound(sound, player.getX(), player.getY(), player.getZ());
} else {
// not in-game
this.client.getSoundManager().play(new SimpleSoundInstance(FabricAudiences.toNative(sound.name()), GameEnums.SOUND_SOURCE.toMinecraft(sound.source()),
sound.volume(), sound.pitch(), false, 0, SoundInstance.Attenuation.NONE, 0, 0, 0, true));
}
}
@Override
public void playSound(final @NotNull Sound sound, final Sound.@NotNull Emitter emitter) {
final Entity targetEntity;
if (emitter == Sound.Emitter.self()) {
targetEntity = this.client.player;
} else if (emitter instanceof Entity) {
targetEntity = (Entity) emitter;
} else {
throw new IllegalArgumentException("Provided emitter '" + emitter + "' was not Sound.Emitter.self() or an Entity");
}
// Initialize with a placeholder event
final EntityBoundSoundInstance mcSound = new EntityBoundSoundInstance(SoundEvents.ITEM_PICKUP, GameEnums.SOUND_SOURCE.toMinecraft(sound.source()), sound.volume(), sound.pitch(), targetEntity);
// Then apply the ResourceLocation of our real sound event
((AbstractSoundInstanceAccess) mcSound).setLocation(FabricAudiences.toNative(sound.name()));
this.client.getSoundManager().play(mcSound);
}
@Override
public void playSound(final @NotNull Sound sound, final double x, final double y, final double z) {
this.client.getSoundManager().play(new SimpleSoundInstance(FabricAudiences.toNative(sound.name()), GameEnums.SOUND_SOURCE.toMinecraft(sound.source()),
sound.volume(), sound.pitch(), false, 0, SoundInstance.Attenuation.LINEAR, x, y, z, false));
}
@Override
public void stopSound(final @NotNull SoundStop stop) {
final @Nullable Key sound = stop.sound();
final @Nullable ResourceLocation soundIdent = sound == null ? null : FabricAudiences.toNative(sound);
final Sound.@Nullable Source source = stop.source();
final @Nullable SoundSource category = source == null ? null : GameEnums.SOUND_SOURCE.toMinecraft(source);
this.client.getSoundManager().stop(soundIdent, category);
}
@Override
public void openBook(final @NotNull Book book) {
this.client.setScreen(new BookViewScreen(new AdventureBookAccess(book, this.controller.partition(), this.controller.renderer())));
}
@Override
public void sendPlayerListHeader(final @NotNull Component header) {
this.client.gui.getTabList().setHeader(header == Component.empty() ? null : this.controller.toNative(header));
}
@Override
public void sendPlayerListFooter(final @NotNull Component footer) {
this.client.gui.getTabList().setHeader(footer == Component.empty() ? null : this.controller.toNative(footer));
}
@Override
public void sendPlayerListHeaderAndFooter(final @NotNull Component header, final @NotNull Component footer) {
this.sendPlayerListHeader(header);
this.sendPlayerListFooter(footer);
}
@Override
public @NotNull Pointers pointers() {
final @Nullable LocalPlayer clientPlayer = this.client.player;
if (clientPlayer != null) {
return ((PointerProviderBridge) clientPlayer).adventure$pointers();
} else {
return Audience.super.pointers();
}
}
}
@@ -0,0 +1,80 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.client;
import java.util.Map;
import java.util.UUID;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.platform.fabric.impl.AbstractBossBarListener;
import net.kyori.adventure.platform.fabric.impl.accessor.ClientboundBossEventPacketAccess;
import net.minecraft.client.gui.components.LerpingBossEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundBossEventPacket;
import net.minecraft.world.BossEvent;
import org.jetbrains.annotations.NotNull;
public class ClientBossBarListener extends AbstractBossBarListener<LerpingBossEvent> {
private final Map<UUID, LerpingBossEvent> hudBars;
public ClientBossBarListener(final FabricClientAudiencesImpl controller, final Map<UUID, LerpingBossEvent> hudBars) {
super(controller);
this.hudBars = hudBars;
}
@Override
protected LerpingBossEvent newBar(final @NotNull Component title,
final BossEvent.@NotNull BossBarColor color,
final BossEvent.@NotNull BossBarOverlay style,
final float progress) {
final ClientboundBossEventPacket pkt = new ClientboundBossEventPacket();
final ClientboundBossEventPacketAccess access = (ClientboundBossEventPacketAccess) pkt;
access.setId(UUID.randomUUID());
access.setName(title);
access.setColor(color);
access.setOverlay(style);
access.setPct(progress);
return new LerpingBossEvent(pkt); // the only constructor uses a packet, so we use that
}
public void add(final BossBar bar) {
final LerpingBossEvent mc = this.minecraftCreating(bar);
this.hudBars.put(mc.getId(), mc);
}
public void remove(final BossBar bar) {
final LerpingBossEvent mc = this.bars.remove(bar);
if (mc != null) {
bar.removeListener(this);
this.hudBars.remove(mc.getId());
}
}
public void clear() {
for (final Map.Entry<BossBar, LerpingBossEvent> entry : this.bars.entrySet()) {
entry.getKey().removeListener(this);
this.hudBars.remove(entry.getValue().getId());
}
this.bars.clear();
}
}
@@ -0,0 +1,119 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.client;
import java.util.function.Function;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.platform.fabric.FabricClientAudiences;
import net.kyori.adventure.platform.fabric.impl.AdventureCommon;
import net.kyori.adventure.platform.fabric.impl.WrappedComponent;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.text.flattener.ComponentFlattener;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import net.kyori.adventure.translation.GlobalTranslator;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.NotNull;
import static java.util.Objects.requireNonNull;
public class FabricClientAudiencesImpl implements FabricClientAudiences {
public static final FabricClientAudiences INSTANCE = new Builder().build();
private final Function<Pointered, ?> partition;
private final ComponentRenderer<Pointered> renderer;
private final ClientAudience audience;
public FabricClientAudiencesImpl(final Function<Pointered, ?> partition, final ComponentRenderer<Pointered> renderer) {
this.partition = partition;
this.renderer = renderer;
this.audience = new ClientAudience(Minecraft.getInstance(), this);
}
@Override
public @NotNull Audience audience() {
return this.audience;
}
@Override
public @NotNull ComponentFlattener flattener() {
return AdventureCommon.FLATTENER;
}
@Override
@Deprecated
public @NotNull PlainComponentSerializer plainSerializer() {
return PlainComponentSerializer.plain();
}
@Override
public @NotNull ComponentRenderer<Pointered> renderer() {
return this.renderer;
}
@Override
public @NotNull Component toNative(final net.kyori.adventure.text.@NotNull Component adventure) {
return new WrappedComponent(requireNonNull(adventure, "adventure"), this.partition, this.renderer);
}
@Override
public net.kyori.adventure.text.@NotNull Component toAdventure(final @NotNull Component vanilla) {
if (vanilla instanceof WrappedComponent) {
return ((WrappedComponent) vanilla).wrapped();
} else {
return FabricAudiences.nonWrappingSerializer().deserialize(vanilla);
}
}
public Function<Pointered, ?> partition() {
return this.partition;
}
public static final class Builder implements FabricClientAudiences.Builder {
private Function<Pointered, ?> partition;
private ComponentRenderer<Pointered> renderer;
public Builder() {
this.componentRenderer(AdventureCommon.localePartition(), GlobalTranslator.renderer());
}
@Override
public FabricClientAudiences.@NotNull Builder componentRenderer(final @NotNull ComponentRenderer<Pointered> componentRenderer) {
this.renderer = requireNonNull(componentRenderer, "componentRenderer");
return this;
}
@Override
public FabricClientAudiences.@NotNull Builder partition(final @NotNull Function<Pointered, ?> partitionFunction) {
this.partition = requireNonNull(partitionFunction, "partitionFunction");
return this;
}
@Override
public @NotNull FabricClientAudiences build() {
return new FabricClientAudiencesImpl(this.partition, this.renderer);
}
}
}
@@ -0,0 +1,27 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@ApiStatus.Internal
package net.kyori.adventure.platform.fabric.impl.client;
import org.jetbrains.annotations.ApiStatus;
@@ -0,0 +1,40 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Type;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.network.protocol.status.ClientboundStatusResponsePacket;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(ClientboundStatusResponsePacket.class)
public class ClientboundStatusResponsePacketMixin {
@Redirect(method = "<clinit>", at = @At(value = "INVOKE", target = "Lcom/google/gson/GsonBuilder;registerTypeAdapter(Ljava/lang/reflect/Type;Ljava/lang/Object;)Lcom/google/gson/GsonBuilder;", ordinal = 0), remap = false)
private static GsonBuilder adventure$injectSerializers(final GsonBuilder instance, final Type type, final Object adapter) {
return GsonComponentSerializer.gson().populator().apply(instance.registerTypeAdapter(type, adapter));
}
}
@@ -0,0 +1,116 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import java.util.Objects;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.fabric.AdventureCommandSourceStack;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.platform.fabric.impl.AdventureCommandSourceStackInternal;
import net.kyori.adventure.platform.fabric.impl.server.FabricServerAudiencesImpl;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.MinecraftServer;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
/**
* The methods in this class should match the implementations of their Text-using counterparts in {@link CommandSourceStack}.
*/
@Mixin(CommandSourceStack.class)
public abstract class CommandSourceStackMixin implements AdventureCommandSourceStackInternal {
// @formatter:off
@Shadow @Final private CommandSource source;
@Shadow @Final private boolean silent;
@Shadow @Final private MinecraftServer server;
@Shadow protected abstract void shadow$broadcastToAdmins(net.minecraft.network.chat.Component text);
// @formatter:on
private boolean adventure$assigned = false;
private Audience adventure$out;
private FabricServerAudiences adventure$controller;
@Override
public void sendSuccess(final @NotNull Component text, final boolean sendToOps) {
if (this.source.acceptsSuccess() && !this.silent) {
this.sendMessage(Identity.nil(), text);
}
if (sendToOps && this.source.shouldInformAdmins() && !this.silent) {
this.shadow$broadcastToAdmins(this.adventure$controller.toNative(text));
}
}
@Override
public void sendFailure(final @NotNull Component text) {
if (this.source.acceptsFailure()) {
this.sendMessage(Identity.nil(), text.color(NamedTextColor.RED));
}
}
@Override
public @NotNull Audience audience() {
if (this.adventure$out == null) {
if (this.server == null) {
throw new IllegalStateException("Cannot use adventure operations without an available server!");
}
this.adventure$controller = FabricServerAudiences.of(this.server);
this.adventure$out = this.adventure$controller.audience(this.source);
}
return this.adventure$out;
}
@Override
public @NotNull Identity identity() {
if (this.source instanceof Identified) {
return ((Identified) this.source).identity();
} else {
return Identity.nil();
}
}
@Override
public AdventureCommandSourceStack adventure$audience(final Audience wrapped, final FabricServerAudiencesImpl controller) {
if (this.adventure$assigned && !Objects.equals(controller, this.adventure$controller)) {
throw new IllegalStateException("This command source has been attached to a specific renderer already!");
// TODO: return a new instance
}
this.adventure$assigned = true;
this.adventure$out = wrapped;
this.adventure$controller = controller;
return this;
}
@Override
public CommandSource adventure$source() {
return this.source;
}
}
@@ -0,0 +1,66 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import java.lang.reflect.Type;
import net.kyori.adventure.platform.fabric.impl.WrappedComponent;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Mixin(net.minecraft.network.chat.Component.Serializer.class)
public abstract class ComponentSerializerMixin {
// @formatter:off
@Shadow public abstract JsonElement shadow$serialize(final Component text, final Type type, final JsonSerializationContext jsonSerializationContext);
// @formatter:on
@Inject(method = "serialize", at = @At("HEAD"), cancellable = true)
public void adventure$writeComponentText(final Component text, final Type type, final JsonSerializationContext ctx, final CallbackInfoReturnable<JsonElement> cir) {
if (text instanceof WrappedComponent) {
final @Nullable Component converted = ((WrappedComponent) text).deepConvertedIfPresent();
if (converted != null) {
cir.setReturnValue(this.shadow$serialize(text, type, ctx));
} else {
cir.setReturnValue(ctx.serialize(((WrappedComponent) text).wrapped(), net.kyori.adventure.text.Component.class));
}
}
}
// inject into the anonymous function to build a gson instance
@Inject(method = "*()Lcom/google/gson/Gson;", at = @At(value = "INVOKE_ASSIGN", target = "com/google/gson/GsonBuilder.disableHtmlEscaping()Lcom/google/gson/GsonBuilder;", remap = false),
locals = LocalCapture.CAPTURE_FAILEXCEPTION, remap = false)
private static void adventure$injectGson(final CallbackInfoReturnable<Gson> cir, final GsonBuilder gson) {
GsonComponentSerializer.gson().populator().apply(gson);
}
}
@@ -0,0 +1,32 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import net.kyori.adventure.sound.Sound;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(Entity.class)
public class EntityMixin implements Sound.Emitter {
}
@@ -0,0 +1,52 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import net.kyori.adventure.platform.fabric.impl.WrappedComponent;
import net.kyori.adventure.platform.fabric.impl.server.FriendlyByteBufBridge;
import net.kyori.adventure.pointer.Pointered;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
@Mixin(FriendlyByteBuf.class)
public class FriendlyByteBufMixin implements FriendlyByteBufBridge {
private @Nullable Pointered adventure$data;
@ModifyVariable(method = "writeComponent", at = @At("HEAD"), argsOnly = true)
private Component adventure$localizeComponent(final Component input) {
if (this.adventure$data != null && input instanceof WrappedComponent) {
return ((WrappedComponent) input).rendered(this.adventure$data);
}
return input;
}
@Override
public void adventure$data(final @Nullable Pointered data) {
this.adventure$data = data;
}
}
@@ -0,0 +1,43 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import com.mojang.authlib.GameProfile;
import java.util.UUID;
import net.kyori.adventure.identity.Identity;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(value = GameProfile.class, remap = false)
public abstract class GameProfileMixin implements Identity {
// @formatter:off
@Shadow public abstract UUID shadow$getId();
// @formatter:on
@Override
public @NotNull UUID uuid() {
return this.shadow$getId();
}
}
@@ -0,0 +1,95 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import com.google.common.collect.MapMaker;
import java.util.Map;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.permission.PermissionChecker;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.platform.fabric.impl.server.FabricServerAudiencesImpl;
import net.kyori.adventure.platform.fabric.impl.server.MinecraftServerBridge;
import net.kyori.adventure.platform.fabric.impl.server.PlainAudience;
import net.kyori.adventure.platform.fabric.impl.server.RenderableAudience;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.util.TriState;
import net.minecraft.server.MinecraftServer;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
/**
* Implement ComponentCommandOutput for output to the server console.
*/
@Mixin(value = MinecraftServer.class)
public abstract class MinecraftServerMixin implements MinecraftServerBridge, RenderableAudience, ForwardingAudience.Single {
// @formatter:off
@Shadow @Final private static Logger LOGGER;
// @formatter:on
private final FabricServerAudiencesImpl adventure$globalProvider = new FabricServerAudiencesImpl.Builder((MinecraftServer) (Object) this).build();
private final Map<FabricAudiences, Audience> adventure$renderers = new MapMaker().weakKeys().makeMap();
private final Audience adventure$backing = this.renderUsing(this.adventure$globalProvider);
private volatile Pointers adventure$pointers;
@Override
public FabricServerAudiences adventure$globalProvider() {
return this.adventure$globalProvider;
}
@Override
public @NotNull Audience audience() {
return this.adventure$backing;
}
@Override
public Audience renderUsing(final FabricServerAudiencesImpl controller) {
return this.adventure$renderers.computeIfAbsent(controller, ctrl -> new PlainAudience(ctrl, this, LOGGER::info));
}
@Override
public @NotNull Pointers pointers() {
if (this.adventure$pointers == null) {
synchronized (this) {
if (this.adventure$pointers == null) {
return this.adventure$pointers = Pointers.builder()
.withStatic(Identity.NAME, "Server")
.withStatic(PermissionChecker.POINTER, perm -> TriState.TRUE)
.build();
}
}
}
return this.adventure$pointers;
}
@Override
public void refresh() {
// nothing to refresh
}
}
@@ -0,0 +1,45 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.kyori.adventure.platform.fabric.impl.server.FriendlyByteBufBridge;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.PacketEncoder;
import net.minecraft.network.protocol.Packet;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Mixin(PacketEncoder.class)
public class PacketEncoderMixin {
@Inject(method = "encode", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/FriendlyByteBuf;writeVarInt(I)Lnet/minecraft/network/FriendlyByteBuf;"), locals = LocalCapture.CAPTURE_FAILHARD)
private void adventure$applyLocaleToBuffer(final ChannelHandlerContext ctx, final Packet<?> pkt, final ByteBuf orig, final CallbackInfo ci, final ConnectionProtocol unused$proto, final Integer unused$id, final FriendlyByteBuf buffer) {
((FriendlyByteBufBridge) buffer).adventure$data(ctx.channel().attr(FriendlyByteBufBridge.CHANNEL_RENDER_DATA).get());
}
}
@@ -0,0 +1,61 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import net.minecraft.core.RegistryAccess;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import net.minecraft.world.level.storage.PlayerDataStorage;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Replace the player list fields so we can safely access and iterate them off the server thread.
*/
@Mixin(PlayerList.class)
public class PlayerListMixin {
// @formatter:off
@Shadow @Final @Mutable private List<ServerPlayer> players;
@Shadow @Final @Mutable private Map<UUID, ServerPlayer> playersByUUID;
// @formatter:on
@Inject(method = "<init>", at = @At("RETURN"), require = 0)
private void adventure$replacePlayerLists(final MinecraftServer server, final RegistryAccess.RegistryHolder tracker, final PlayerDataStorage handler, final int i,
final CallbackInfo ci) {
this.players = new CopyOnWriteArrayList<>();
this.playersByUUID = new ConcurrentHashMap<>();
}
}
@@ -0,0 +1,88 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import com.mojang.authlib.GameProfile;
import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.fabric.impl.NonWrappingComponentSerializer;
import net.kyori.adventure.platform.fabric.impl.PointerProviderBridge;
import net.kyori.adventure.pointer.Pointers;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(Player.class)
public abstract class PlayerMixin extends LivingEntity implements Identified, PointerProviderBridge {
// @formatter:off
@Shadow @Final private GameProfile gameProfile;
@Shadow public abstract GameProfile shadow$getGameProfile();
// @formatter:on
private Pointers adventure$pointers;
protected PlayerMixin(final EntityType<? extends LivingEntity> entityType, final Level level) {
super(entityType, level);
}
@Override
public @NotNull Identity identity() {
return (Identity) this.gameProfile;
}
@Override
public @NotNull Pointers adventure$pointers() {
Pointers pointers = this.adventure$pointers;
if (pointers == null) {
synchronized (this) {
if (this.adventure$pointers != null) {
return this.adventure$pointers;
}
final Pointers.Builder builder = Pointers.builder()
.withDynamic(Identity.NAME, () -> this.shadow$getGameProfile().getName())
.withDynamic(Identity.UUID, this::getUUID)
.withDynamic(Identity.DISPLAY_NAME, () -> NonWrappingComponentSerializer.INSTANCE.deserialize(this.getDisplayName()));
// add any extra data
this.adventure$populateExtraPointers(builder);
this.adventure$pointers = pointers = builder.build();
}
}
return pointers;
}
protected void adventure$populateExtraPointers(final Pointers.Builder builder) {
// for overriding by implementations
// todo: support permissions here if Luck's permissions API is available
}
}
@@ -0,0 +1,80 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import com.google.common.collect.MapMaker;
import java.util.Map;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.permission.PermissionChecker;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.platform.fabric.impl.server.FabricServerAudiencesImpl;
import net.kyori.adventure.platform.fabric.impl.server.PlainAudience;
import net.kyori.adventure.platform.fabric.impl.server.RenderableAudience;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.util.TriState;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.rcon.RconConsoleSource;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(RconConsoleSource.class)
public abstract class RconConsoleSourceMixin implements RenderableAudience, ForwardingAudience.Single {
// @formatter:off
@Shadow @Final private StringBuffer buffer;
@Shadow @Final private MinecraftServer server;
// @formatter:off
private volatile Pointers adventure$pointers;
private final Map<FabricAudiences, Audience> adventure$renderers = new MapMaker().weakKeys().makeMap();
@Override
public Audience renderUsing(final FabricServerAudiencesImpl controller) {
return this.adventure$renderers.computeIfAbsent(controller, ctrl -> new PlainAudience(ctrl, this, this.buffer::append));
}
@Override
public @NotNull Audience audience() {
return FabricServerAudiences.of(this.server).audience((RconConsoleSource) (Object) this);
}
@Override
public @NotNull Pointers pointers() {
if (this.adventure$pointers == null) {
synchronized (this) {
if (this.adventure$pointers == null) {
return this.adventure$pointers = Pointers.builder()
.withStatic(Identity.NAME, "Server")
.withStatic(PermissionChecker.POINTER, perm -> TriState.TRUE)
.build();
}
}
}
return this.adventure$pointers;
}
}
@@ -0,0 +1,121 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import net.kyori.adventure.platform.fabric.impl.server.ServerBossEventBridge;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundBossEventPacket;
import net.minecraft.server.level.ServerBossEvent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.BossEvent;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerBossEvent.class)
public abstract class ServerBossEventMixin extends BossEvent implements ServerBossEventBridge {
private static final float MINIMUM_PERCENT_CHANGE = 5e-4f;
// @formatter:off
@Shadow @Final private Set<ServerPlayer> players;
@Shadow public abstract boolean shadow$isVisible();
// @formatter:on
private float adventure$lastSentPercent;
public ServerBossEventMixin(final UUID uuid, final Component name, final BossBarColor color, final BossBarOverlay style) {
super(uuid, name, color, style);
this.adventure$lastSentPercent = this.percent;
}
// If a player has respawned, we still want to be able to remove the player using old references to their entity
@Redirect(method = "removePlayer", at = @At(value = "INVOKE", target = "Ljava/util/Set;remove(Ljava/lang/Object;)Z"))
private boolean adventure$removeByUuid(final Set<?> instance, final Object player) {
if (instance.remove(player)) {
return true;
}
if (!(player instanceof ServerPlayer)) {
return false;
}
final UUID testId = ((ServerPlayer) player).getUUID();
for (final Iterator<?> it = instance.iterator(); it.hasNext();) {
if (((ServerPlayer) it.next()).getUUID().equals(testId)) {
it.remove();
return true;
}
}
return false;
}
@Override
public void adventure$addAll(final Collection<ServerPlayer> players) {
final ClientboundBossEventPacket pkt = new ClientboundBossEventPacket(ClientboundBossEventPacket.Operation.ADD, this);
for (final ServerPlayer player : players) {
if (this.players.add(player) && this.shadow$isVisible()) {
player.connection.send(pkt);
}
}
}
@Override
public void adventure$removeAll(final Collection<ServerPlayer> players) {
final ClientboundBossEventPacket pkt = new ClientboundBossEventPacket(ClientboundBossEventPacket.Operation.REMOVE, this);
for (final ServerPlayer player : players) {
if (this.players.remove(player) && this.shadow$isVisible()) {
player.connection.send(pkt);
}
}
}
@Override
public void adventure$replaceSubscriber(final ServerPlayer oldSub, final ServerPlayer newSub) {
if (this.players.remove(oldSub)) {
this.players.add(newSub);
}
}
// Optimization -- don't send a packet for tiny changes
@Inject(method = "setPercent", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/BossEvent;setPercent(F)V"), cancellable = true, require = 0)
private void adventure$onlySetPercentIfBigEnough(final float newPercent, final CallbackInfo ci) {
if (Math.abs(newPercent - this.adventure$lastSentPercent) < MINIMUM_PERCENT_CHANGE) {
this.percent = newPercent;
ci.cancel();
} else {
this.adventure$lastSentPercent = newPercent;
// continue as normal
}
}
}
@@ -0,0 +1,48 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import net.kyori.adventure.platform.fabric.impl.accessor.ConnectionAccess;
import net.kyori.adventure.platform.fabric.impl.server.FriendlyByteBufBridge;
import net.kyori.adventure.pointer.Pointered;
import net.minecraft.network.Connection;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import org.objectweb.asm.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerGamePacketListenerImpl.class)
public class ServerGamePacketListenerImplMixin {
// Initialize attribute tracking the player for component rendering
@Inject(method = "<init>", at = @At(value = "FIELD", target = "Lnet/minecraft/server/level/ServerPlayer;connection:Lnet/minecraft/server/network/ServerGamePacketListenerImpl;", opcode = Opcodes.PUTFIELD))
private void adventure$initTracking(final MinecraftServer server, final Connection conn, final ServerPlayer player, final CallbackInfo ci) {
((ConnectionAccess) conn).getChannel().attr(FriendlyByteBufBridge.CHANNEL_RENDER_DATA)
.set((Pointered) player);
}
}
@@ -0,0 +1,148 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import com.google.common.collect.MapMaker;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.platform.fabric.PlayerLocales;
import net.kyori.adventure.platform.fabric.impl.LocaleHolderBridge;
import net.kyori.adventure.platform.fabric.impl.accessor.ClientboundTabListPacketAccess;
import net.kyori.adventure.platform.fabric.impl.accessor.ConnectionAccess;
import net.kyori.adventure.platform.fabric.impl.accessor.ServerboundClientInformationPacketAccess;
import net.kyori.adventure.platform.fabric.impl.server.FabricServerAudiencesImpl;
import net.kyori.adventure.platform.fabric.impl.server.FriendlyByteBufBridge;
import net.kyori.adventure.platform.fabric.impl.server.RenderableAudience;
import net.kyori.adventure.platform.fabric.impl.server.ServerPlayerAudience;
import net.kyori.adventure.platform.fabric.impl.server.ServerPlayerBridge;
import net.kyori.adventure.pointer.Pointers;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.protocol.game.ClientboundTabListPacket;
import net.minecraft.network.protocol.game.ServerboundClientInformationPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerPlayer.class)
public abstract class ServerPlayerMixin extends PlayerMixin implements ForwardingAudience.Single, LocaleHolderBridge, RenderableAudience, ServerPlayerBridge {
// @formatter:off
@Shadow @Final public MinecraftServer server;
@Shadow public ServerGamePacketListenerImpl connection;
// @formatter:on
private Audience adventure$backing;
private Locale adventure$locale;
private final Map<FabricServerAudiencesImpl, Audience> adventure$renderers = new MapMaker().weakKeys().makeMap();
private Component adventure$tabListHeader = TextComponent.EMPTY;
private Component adventure$tabListFooter = TextComponent.EMPTY;
protected ServerPlayerMixin(final EntityType<? extends LivingEntity> entityType, final Level level) {
super(entityType, level);
}
@Inject(method = "<init>", at = @At("TAIL"))
private void adventure$init(final CallbackInfo ci) {
this.adventure$backing = FabricServerAudiences.of(this.server).audience(this);
}
@Override
public @NotNull Audience audience() {
return this.adventure$backing;
}
@Override
public Audience renderUsing(final FabricServerAudiencesImpl controller) {
return this.adventure$renderers.computeIfAbsent(controller, ctrl -> new ServerPlayerAudience((ServerPlayer) (Object) this, ctrl));
}
@Override
public @NotNull Locale adventure$locale() {
return this.adventure$locale;
}
@Override
protected void adventure$populateExtraPointers(final Pointers.Builder builder) {
builder.withDynamic(Identity.LOCALE, this::adventure$locale);
}
// Tab list
@Override
public void bridge$updateTabList(final @Nullable Component header, final @Nullable Component footer) {
if (header != null) {
this.adventure$tabListHeader = header;
}
if (footer != null) {
this.adventure$tabListFooter = footer;
}
final ClientboundTabListPacket packet = new ClientboundTabListPacket();
((ClientboundTabListPacketAccess) packet).setHeader(this.adventure$tabListHeader);
((ClientboundTabListPacketAccess) packet).setFooter(this.adventure$tabListFooter);
this.connection.send(packet);
}
// Locale tracking
@Inject(method = "updateOptions", at = @At("HEAD"))
private void adventure$handleLocaleUpdate(final ServerboundClientInformationPacket information, final CallbackInfo ci) {
final String language = ((ServerboundClientInformationPacketAccess) information).getLanguage();
final @Nullable Locale locale = LocaleHolderBridge.toLocale(language);
if (!Objects.equals(this.adventure$locale, locale)) {
this.adventure$locale = locale;
PlayerLocales.CHANGED_EVENT.invoker().onLocaleChanged((ServerPlayer) (Object) this, locale);
}
}
// Player tracking for boss bars and rendering
@Inject(method = "restoreFrom", at = @At("RETURN"))
private void copyData(final ServerPlayer old, final boolean alive, final CallbackInfo ci) {
FabricServerAudiencesImpl.forEachInstance(controller -> controller.bossBars().replacePlayer(old, (ServerPlayer) (Object) this));
((ConnectionAccess) this.connection.connection).getChannel().attr(FriendlyByteBufBridge.CHANNEL_RENDER_DATA).set(this);
}
@Inject(method = "disconnect", at = @At("RETURN"))
private void adventure$removeBossBarsOnDisconnect(final CallbackInfo ci) {
FabricServerAudiencesImpl.forEachInstance(controller -> controller.bossBars().unsubscribeFromAll((ServerPlayer) (Object) this));
}
}
@@ -0,0 +1,43 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin;
import net.kyori.adventure.platform.fabric.impl.NonWrappingComponentSerializer;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Style;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(Style.Serializer.class)
abstract class StyleSerializerMixin {
@Redirect(method = "getClickEvent", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/chat/ClickEvent$Action;isAllowedFromServer()Z"))
private static boolean adventure$redirectIsAllowedFromServer(final ClickEvent.@NotNull Action action) {
if (NonWrappingComponentSerializer.INSTANCE.bypassIsAllowedFromServer()) {
return true;
}
return action.isAllowedFromServer();
}
}
@@ -0,0 +1,61 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin.client;
import com.google.common.collect.MapMaker;
import java.util.Map;
import java.util.UUID;
import net.kyori.adventure.platform.fabric.impl.client.BossHealthOverlayBridge;
import net.kyori.adventure.platform.fabric.impl.client.ClientBossBarListener;
import net.kyori.adventure.platform.fabric.impl.client.FabricClientAudiencesImpl;
import net.minecraft.client.gui.components.BossHealthOverlay;
import net.minecraft.client.gui.components.LerpingBossEvent;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(BossHealthOverlay.class)
public class BossHealthOverlayMixin implements BossHealthOverlayBridge {
// @formatter:off
@Shadow @Final private Map<UUID, LerpingBossEvent> events;
// @formatter:on
private final Map<FabricClientAudiencesImpl, ClientBossBarListener> adventure$listener = new MapMaker().weakKeys().makeMap();
@Override
public @NotNull ClientBossBarListener adventure$listener(final @NotNull FabricClientAudiencesImpl controller) {
return this.adventure$listener.computeIfAbsent(controller, ctrl -> new ClientBossBarListener(ctrl, this.events));
}
@Inject(method = "reset", at = @At("HEAD"))
private void adventure$resetListener(final CallbackInfo ci) {
if (this.adventure$listener != null) {
this.adventure$listener.clear();
}
}
}
@@ -0,0 +1,82 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin.client;
import java.util.Locale;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.fabric.FabricClientAudiences;
import net.kyori.adventure.platform.fabric.impl.LocaleHolderBridge;
import net.kyori.adventure.platform.fabric.impl.mixin.PlayerMixin;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.sound.Sound;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(LocalPlayer.class)
public abstract class LocalPlayerMixin extends PlayerMixin implements ForwardingAudience.Single, LocaleHolderBridge {
// @formatter:off
@Shadow @Final protected Minecraft minecraft;
// @formatter:on
// TODO: Do we want to enforce synchronization with the client thread?
private LocalPlayerMixin(final EntityType<? extends LivingEntity> type, final Level level) { // mixin will strip
super(type, level);
}
private final Audience adventure$default = FabricClientAudiences.of().audience();
@Override
public @NotNull Audience audience() {
return this.adventure$default;
}
@Override
public @NotNull Pointers pointers() {
return this.audience().pointers();
}
@Override
public void playSound(final @NotNull Sound sound) {
this.audience().playSound(sound, this.getX(), this.getY(), this.getZ());
}
@Override
public @NotNull Locale adventure$locale() {
return ((LocaleHolderBridge) this.minecraft.options).adventure$locale();
}
@Override
protected void adventure$populateExtraPointers(final Pointers.Builder builder) {
builder.withDynamic(Identity.LOCALE, this::adventure$locale);
}
}
@@ -0,0 +1,52 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.mixin.client;
import java.util.Locale;
import java.util.Objects;
import net.kyori.adventure.platform.fabric.impl.LocaleHolderBridge;
import net.minecraft.client.Options;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(Options.class)
public class OptionsMixin implements LocaleHolderBridge {
// @formatter:off
@Shadow public String languageCode;
// @formatter:on
private String adventure$cachedLanguage;
private Locale adventure$cachedLocale;
@Override
public Locale adventure$locale() {
final String language = this.languageCode;
if (Objects.equals(this.adventure$cachedLanguage, language)) {
return this.adventure$cachedLocale;
} else {
this.adventure$cachedLanguage = language;
return this.adventure$cachedLocale = LocaleHolderBridge.toLocale(language);
}
}
}
@@ -0,0 +1,31 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Mixin accessors for internal use only.
*/
@ApiStatus.Internal
package net.kyori.adventure.platform.fabric.impl.mixin;
import org.jetbrains.annotations.ApiStatus;
@@ -0,0 +1,33 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Internal implementation of the adventure platform.
*
* <p>Direct access to classes in this package is
* unsupported, and changes may occur at any time.</p>
*/
@ApiStatus.Internal
package net.kyori.adventure.platform.fabric.impl;
import org.jetbrains.annotations.ApiStatus;
@@ -0,0 +1,55 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.text.Component;
import net.minecraft.commands.CommandSource;
import org.jetbrains.annotations.NotNull;
/**
* Audience implementation that can wrap a {@link CommandSource}.
*/
final class CommandSourceAudience implements Audience {
private final CommandSource output;
private final FabricAudiences serializer;
CommandSourceAudience(final CommandSource output, final FabricAudiences serializer) {
this.output = output;
this.serializer = serializer;
}
@Override
public void sendMessage(final Identity source, final Component text, final MessageType type) {
this.output.sendMessage(this.serializer.toNative(text), source.uuid());
}
@Override
public void sendActionBar(final @NotNull Component message) {
this.sendMessage(Identity.nil(), message);
}
}
@@ -0,0 +1,234 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import com.google.common.collect.Iterables;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.platform.fabric.AdventureCommandSourceStack;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.platform.fabric.impl.AdventureCommandSourceStackInternal;
import net.kyori.adventure.platform.fabric.impl.AdventureCommon;
import net.kyori.adventure.platform.fabric.impl.WrappedComponent;
import net.kyori.adventure.platform.fabric.impl.accessor.ComponentSerializerAccess;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.flattener.ComponentFlattener;
import net.kyori.adventure.text.renderer.ComponentRenderer;
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import net.kyori.adventure.translation.GlobalTranslator;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.Registry;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static java.util.Objects.requireNonNull;
/**
* The entry point for accessing Adventure.
*/
public final class FabricServerAudiencesImpl implements FabricServerAudiences {
private static final Set<FabricServerAudiencesImpl> INSTANCES = Collections.newSetFromMap(new WeakHashMap<>());
/**
* Perform an action on every audience provider instance.
*
* @param actor a consumer that will be called for every provider
*/
public static void forEachInstance(final Consumer<FabricServerAudiencesImpl> actor) {
synchronized (INSTANCES) {
for (final FabricServerAudiencesImpl instance : INSTANCES) {
actor.accept(instance);
}
}
}
private final MinecraftServer server;
private final Function<Pointered, ?> partition;
private final ComponentRenderer<Pointered> renderer;
final ServerBossBarListener bossBars;
public FabricServerAudiencesImpl(final MinecraftServer server, final Function<Pointered, ?> partition, final ComponentRenderer<Pointered> renderer) {
this.server = server;
this.partition = partition;
this.renderer = renderer;
this.bossBars = new ServerBossBarListener(this);
synchronized (INSTANCES) {
INSTANCES.add(this);
}
}
@Override
public @NotNull Audience all() {
return Audience.audience(this.console(), this.players());
}
@Override
public @NotNull Audience console() {
return this.audience(this.server);
}
@Override
public @NotNull Audience players() {
return Audience.audience(this.audiences(this.server.getPlayerList().getPlayers()));
}
@Override
public @NotNull Audience player(final @NotNull UUID playerId) {
final @Nullable ServerPlayer player = this.server.getPlayerList().getPlayer(playerId);
return player != null ? this.audience(player) : Audience.empty();
}
private Iterable<Audience> audiences(final Iterable<? extends ServerPlayer> players) {
return Iterables.transform(players, this::audience);
}
@Override
public @NotNull Audience permission(final @NotNull String permission) {
return Audience.empty(); // TODO: permissions api
}
@Override
public @NotNull AdventureCommandSourceStack audience(final @NotNull CommandSourceStack source) {
if (!(source instanceof AdventureCommandSourceStackInternal)) {
throw new IllegalArgumentException("The AdventureCommandSource mixin failed!");
}
final AdventureCommandSourceStackInternal internal = (AdventureCommandSourceStackInternal) source;
return internal.adventure$audience(this.audience(internal.adventure$source()), this);
}
@Override
public @NotNull Audience audience(final @NotNull CommandSource source) {
if (source instanceof RenderableAudience) {
return ((RenderableAudience) source).renderUsing(this);
} else if (source instanceof Audience) {
// TODO: How to pass component renderer through
return (Audience) source;
} else {
return new CommandSourceAudience(source, this);
}
}
@Override
public @NotNull Audience audience(final @NotNull Iterable<ServerPlayer> players) {
return Audience.audience(this.audiences(players));
}
@Override
public @NotNull Audience world(final @NotNull Key worldId) {
final @Nullable ServerLevel level = this.server.getLevel(ResourceKey.create(Registry.DIMENSION_REGISTRY,
FabricAudiences.toNative(requireNonNull(worldId, "worldId"))));
if (level != null) {
return this.audience(level.players());
}
return Audience.empty();
}
@Override
public @NotNull Audience server(final @NotNull String serverName) {
return Audience.empty();
}
@Override
public @NotNull ComponentFlattener flattener() {
return AdventureCommon.FLATTENER;
}
@Override
@Deprecated
public @NotNull PlainComponentSerializer plainSerializer() {
return PlainComponentSerializer.plain();
}
@Override
public @NotNull ComponentRenderer<Pointered> renderer() {
return this.renderer;
}
@Override
public net.minecraft.network.chat.@NotNull Component toNative(final @NotNull Component adventure) {
if (adventure == Component.empty()) return TextComponent.EMPTY;
return new WrappedComponent(requireNonNull(adventure, "adventure"), this.partition, this.renderer);
}
@Override
public @NotNull Component toAdventure(final net.minecraft.network.chat.@NotNull Component vanilla) {
if (vanilla instanceof WrappedComponent) {
return ((WrappedComponent) vanilla).wrapped();
} else {
return ComponentSerializerAccess.getGSON().fromJson(net.minecraft.network.chat.Component.Serializer.toJsonTree(vanilla), Component.class);
}
}
public ServerBossBarListener bossBars() {
return this.bossBars;
}
@Override
public void close() {
}
public static final class Builder implements FabricServerAudiences.Builder {
private final MinecraftServer server;
private Function<Pointered, ?> partition;
private ComponentRenderer<Pointered> renderer;
public Builder(final MinecraftServer server) {
this.server = server;
this.componentRenderer(AdventureCommon.localePartition(), GlobalTranslator.renderer());
}
@Override
public @NotNull FabricServerAudiences.Builder componentRenderer(final @NotNull ComponentRenderer<Pointered> componentRenderer) {
this.renderer = requireNonNull(componentRenderer, "componentRenderer");
return this;
}
@Override
public @NotNull FabricServerAudiences.Builder partition(final @NotNull Function<Pointered, ?> partitionFunction) {
this.partition = requireNonNull(partitionFunction, "partitionFunction");
return this;
}
@Override
public @NotNull FabricServerAudiencesImpl build() {
return new FabricServerAudiencesImpl(this.server, this.partition, this.renderer);
}
}
}
@@ -0,0 +1,34 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import io.netty.util.AttributeKey;
import net.kyori.adventure.pointer.Pointered;
import org.jetbrains.annotations.Nullable;
public interface FriendlyByteBufBridge {
AttributeKey<Pointered> CHANNEL_RENDER_DATA = AttributeKey.newInstance("adventure:render_data");
void adventure$data(final @Nullable Pointered data);
}
@@ -0,0 +1,30 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
public interface MinecraftServerBridge {
FabricServerAudiences adventure$globalProvider();
}
@@ -0,0 +1,62 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import java.util.function.Consumer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.pointer.Pointered;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.jetbrains.annotations.NotNull;
public final class PlainAudience implements Audience {
private final FabricAudiences controller;
private final Pointered source;
private final Consumer<String> plainOutput;
public PlainAudience(final FabricAudiences controller, final Pointered source, final Consumer<String> plainOutput) {
this.controller = controller;
this.source = source;
this.plainOutput = plainOutput;
}
@Override
public void sendMessage(final @NotNull Identity source, final @NotNull Component message, final @NotNull MessageType type) {
this.plainOutput.accept(PlainTextComponentSerializer.plainText().serialize(this.controller.renderer().render(message, this.source)));
}
@Override
public void sendActionBar(final @NotNull Component message) {
this.sendMessage(Identity.nil(), message);
}
@Override
public @NotNull Pointers pointers() {
return this.source.pointers();
}
}
@@ -0,0 +1,37 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import net.kyori.adventure.audience.Audience;
public interface RenderableAudience extends Audience {
Audience renderUsing(final FabricServerAudiencesImpl controller);
/**
* Refresh this audience, to update any actively displayed rendered content.
*
* @since 4.0.0
*/
void refresh();
}
@@ -0,0 +1,133 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.platform.fabric.impl.AbstractBossBarListener;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundBossEventPacket;
import net.minecraft.server.level.ServerBossEvent;
import net.minecraft.server.level.ServerPlayer;
import org.jetbrains.annotations.NotNull;
import static java.util.Objects.requireNonNull;
public class ServerBossBarListener extends AbstractBossBarListener<ServerBossEvent> {
public ServerBossBarListener(final FabricAudiences controller) {
super(controller);
}
public void subscribe(final ServerPlayer player, final BossBar bar) {
this.minecraftCreating(requireNonNull(bar, "bar")).addPlayer(requireNonNull(player, "player"));
}
public void subscribeAll(final Collection<ServerPlayer> players, final BossBar bar) {
((ServerBossEventBridge) this.minecraftCreating(requireNonNull(bar, "bar"))).adventure$addAll(players);
}
public void unsubscribe(final ServerPlayer player, final BossBar bar) {
this.bars.computeIfPresent(bar, (key, old) -> {
old.removePlayer(player);
if (old.getPlayers().isEmpty()) {
key.removeListener(this);
return null;
} else {
return old;
}
});
}
public void unsubscribeAll(final Collection<ServerPlayer> players, final BossBar bar) {
this.bars.computeIfPresent(bar, (key, old) -> {
((ServerBossEventBridge) old).adventure$removeAll(players);
if (old.getPlayers().isEmpty()) {
key.removeListener(this);
return null;
} else {
return old;
}
});
}
/**
* Replace a player entity without sending any packets.
*
* <p>This should be triggered when the entity representing a player changes
* (such as during a respawn)</p>
*
* @param old old player
* @param newPlayer new one
*/
public void replacePlayer(final ServerPlayer old, final ServerPlayer newPlayer) {
for (final ServerBossEvent bar : this.bars.values()) {
((ServerBossEventBridge) bar).adventure$replaceSubscriber(old, newPlayer);
}
}
/**
* Refresh titles when a player's locale has changed.
*
* @param player player to refresh titles fro
*/
public void refreshTitles(final ServerPlayer player) {
for (final ServerBossEvent bar : this.bars.values()) {
if (bar.getPlayers().contains(player)) {
player.connection.send(new ClientboundBossEventPacket(ClientboundBossEventPacket.Operation.UPDATE_NAME, bar));
}
}
}
/**
* Remove the player from all associated boss bars.
*
* @param player The player to remove
*/
public void unsubscribeFromAll(final ServerPlayer player) {
for (final Iterator<Map.Entry<BossBar, ServerBossEvent>> it = this.bars.entrySet().iterator(); it.hasNext();) {
final ServerBossEvent bar = it.next().getValue();
if (bar.getPlayers().contains(player)) {
bar.removePlayer(player);
if (bar.getPlayers().isEmpty()) {
it.remove();
}
}
}
}
@Override
protected ServerBossEvent newBar(
final @NotNull Component title,
final net.minecraft.world.BossEvent.@NotNull BossBarColor color,
final net.minecraft.world.BossEvent.@NotNull BossBarOverlay style,
final float progress
) {
final ServerBossEvent event = new ServerBossEvent(title, color, style);
event.setPercent(progress);
return event;
}
}
@@ -0,0 +1,38 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import java.util.Collection;
import net.minecraft.server.level.ServerPlayer;
/**
* An interface for performing bulk adds and removes on a {@link net.minecraft.server.level.ServerBossEvent}.
*/
public interface ServerBossEventBridge {
void adventure$addAll(Collection<ServerPlayer> players);
void adventure$removeAll(Collection<ServerPlayer> players);
void adventure$replaceSubscriber(ServerPlayer oldSub, ServerPlayer newSub);
}
@@ -0,0 +1,264 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import java.time.Duration;
import java.util.Objects;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.inventory.Book;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.platform.fabric.FabricAudiences;
import net.kyori.adventure.platform.fabric.impl.GameEnums;
import net.kyori.adventure.platform.fabric.impl.PointerProviderBridge;
import net.kyori.adventure.pointer.Pointers;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.sound.SoundStop;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.kyori.adventure.title.Title;
import net.kyori.adventure.title.TitlePart;
import net.minecraft.core.Registry;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.StringTag;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientboundChatPacket;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.network.protocol.game.ClientboundCustomSoundPacket;
import net.minecraft.network.protocol.game.ClientboundSetTitlesPacket;
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
import net.minecraft.network.protocol.game.ClientboundStopSoundPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static java.util.Objects.requireNonNull;
public final class ServerPlayerAudience implements Audience {
private final ServerPlayer player;
private final FabricServerAudiencesImpl controller;
public ServerPlayerAudience(final ServerPlayer player, final FabricServerAudiencesImpl controller) {
this.player = player;
this.controller = controller;
}
void sendPacket(final Packet<?> packet) {
this.player.connection.send(packet);
}
@Override
public void sendMessage(final Identity source, final Component text, final net.kyori.adventure.audience.MessageType type) {
final ChatType mcType;
if (type == net.kyori.adventure.audience.MessageType.CHAT) {
mcType = ChatType.CHAT;
} else {
mcType = ChatType.SYSTEM;
}
this.sendPacket(new ClientboundChatPacket(this.controller.toNative(text), mcType, source.uuid()));
}
@Override
public void sendActionBar(final @NotNull Component message) {
this.sendPacket(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.ACTIONBAR, this.controller.toNative(message)));
}
@Override
public void showBossBar(final @NotNull BossBar bar) {
FabricServerAudiencesImpl.forEachInstance(controller -> {
if (controller != this.controller) {
controller.bossBars.unsubscribe(this.player, bar);
}
});
this.controller.bossBars.subscribe(this.player, bar);
}
@Override
public void hideBossBar(final @NotNull BossBar bar) {
FabricServerAudiencesImpl.forEachInstance(controller -> controller.bossBars.unsubscribe(this.player, bar));
}
@Override
public void playSound(final @NotNull Sound sound) {
this.sendPacket(new ClientboundCustomSoundPacket(FabricAudiences.toNative(sound.name()),
GameEnums.SOUND_SOURCE.toMinecraft(sound.source()), this.player.position(), sound.volume(), sound.pitch()));
}
@Override
public void playSound(final @NotNull Sound sound, final double x, final double y, final double z) {
this.sendPacket(new ClientboundCustomSoundPacket(FabricAudiences.toNative(sound.name()),
GameEnums.SOUND_SOURCE.toMinecraft(sound.source()), new Vec3(x, y, z), sound.volume(), sound.pitch()));
}
@Override
public void playSound(final @NotNull Sound sound, final Sound.@NotNull Emitter emitter) {
final Entity targetEntity;
if (emitter == Sound.Emitter.self()) {
targetEntity = this.player;
} else if (emitter instanceof Entity) {
targetEntity = (Entity) emitter;
} else {
throw new IllegalArgumentException("Provided emitter '" + emitter + "' was not Sound.Emitter.self() or an Entity");
}
if (!this.player.level.equals(targetEntity.level)) {
// don't send unless entities are in the same dimension
return;
}
final SoundEvent event = Registry.SOUND_EVENT.getOptional(FabricAudiences.toNative(sound.name())).orElse(null);
if (event == null) {
return;
}
this.sendPacket(new ClientboundSoundEntityPacket(event, GameEnums.SOUND_SOURCE.toMinecraft(sound.source()), targetEntity, sound.volume(), sound.pitch()));
}
@Override
public void stopSound(final @NotNull SoundStop stop) {
final @Nullable Key sound = stop.sound();
final Sound.@Nullable Source src = stop.source();
final @Nullable SoundSource cat = src == null ? null : GameEnums.SOUND_SOURCE.toMinecraft(src);
this.sendPacket(new ClientboundStopSoundPacket(sound == null ? null : FabricAudiences.toNative(sound), cat));
}
static final String BOOK_TITLE = "title";
static final String BOOK_AUTHOR = "author";
static final String BOOK_PAGES = "pages";
static final String BOOK_RESOLVED = "resolved";
@Override
public void openBook(final @NotNull Book book) {
final ItemStack bookStack = new ItemStack(Items.WRITTEN_BOOK, 1);
final CompoundTag bookTag = bookStack.getOrCreateTag();
bookTag.putString(BOOK_TITLE, this.adventure$plain(book.title()));
bookTag.putString(BOOK_AUTHOR, this.adventure$plain(book.author()));
final ListTag pages = new ListTag();
for (final Component page : book.pages()) {
pages.add(StringTag.valueOf(this.adventure$serialize(page)));
}
bookTag.put(BOOK_PAGES, pages);
bookTag.putBoolean(BOOK_RESOLVED, true); // todo: any parseable texts?
final ItemStack previous = this.player.inventory.getSelected();
this.sendPacket(new ClientboundContainerSetSlotPacket(-2, this.player.inventory.selected, bookStack));
this.player.openItemGui(bookStack, InteractionHand.MAIN_HAND);
this.sendPacket(new ClientboundContainerSetSlotPacket(-2, this.player.inventory.selected, previous));
}
private String adventure$plain(final @NotNull Component component) {
return PlainTextComponentSerializer.plainText().serialize(this.controller.renderer().render(component, this));
}
private String adventure$serialize(final @NotNull Component component) {
return GsonComponentSerializer.gson().serialize(this.controller.renderer().render(component, this));
}
@Override
public void showTitle(final @NotNull Title title) {
if (title.subtitle() != Component.empty()) {
this.sendPacket(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.SUBTITLE, this.controller.toNative(title.subtitle())));
}
final Title.@Nullable Times times = title.times();
if (times != null) {
final int fadeIn = ticks(times.fadeIn());
final int fadeOut = ticks(times.fadeOut());
final int dwell = ticks(times.stay());
if (fadeIn != -1 || fadeOut != -1 || dwell != -1) {
this.sendPacket(new ClientboundSetTitlesPacket(fadeIn, dwell, fadeOut));
}
}
if (title.title() != Component.empty()) {
this.sendPacket(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.TITLE, this.controller.toNative(title.title())));
}
}
@Override
public <T> void sendTitlePart(final @NotNull TitlePart<T> part, @NotNull final T value) {
Objects.requireNonNull(value, "value");
if (part == TitlePart.TITLE) {
this.sendPacket(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.TITLE, this.controller.toNative((Component) value)));
} else if (part == TitlePart.SUBTITLE) {
this.sendPacket(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.SUBTITLE, this.controller.toNative((Component) value)));
} else if (part == TitlePart.TIMES) {
final Title.Times times = (Title.Times) value;
this.sendPacket(new ClientboundSetTitlesPacket(ticks(times.fadeIn()), ticks(times.stay()), ticks(times.fadeOut())));
} else {
throw new IllegalArgumentException("Unknown TitlePart '" + part + "'");
}
}
static int ticks(final @NotNull Duration duration) {
return duration.getSeconds() == -1 ? -1 : (int) (duration.toMillis() / 50);
}
@Override
public void clearTitle() {
this.sendPacket(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.CLEAR, null));
}
@Override
public void resetTitle() {
this.sendPacket(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.RESET, null));
}
@Override
public void sendPlayerListHeader(final @NotNull Component header) {
requireNonNull(header, "header");
((ServerPlayerBridge) this.player).bridge$updateTabList(this.controller.toNative(header), null);
}
@Override
public void sendPlayerListFooter(final @NotNull Component footer) {
requireNonNull(footer, "footer");
((ServerPlayerBridge) this.player).bridge$updateTabList(null, this.controller.toNative(footer));
}
@Override
public void sendPlayerListHeaderAndFooter(final @NotNull Component header, final @NotNull Component footer) {
((ServerPlayerBridge) this.player).bridge$updateTabList(
this.controller.toNative(requireNonNull(header, "header")),
this.controller.toNative(requireNonNull(footer, "footer")));
}
@Override
public @NotNull Pointers pointers() {
return ((PointerProviderBridge) this.player).adventure$pointers();
}
}
@@ -0,0 +1,38 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.server;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.Nullable;
public interface ServerPlayerBridge {
/**
* Update the tab list header and footer.
*
* @param header header, null to leave unchanged
* @param footer footer, null to leave unchanged
* @since 4.0.0
*/
void bridge$updateTabList(final @Nullable Component header, final @Nullable Component footer);
}
@@ -0,0 +1,27 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@ApiStatus.Internal
package net.kyori.adventure.platform.fabric.impl.server;
import org.jetbrains.annotations.ApiStatus;
@@ -0,0 +1,52 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.service;
import java.util.function.Consumer;
import net.kyori.adventure.platform.fabric.impl.NBTLegacyHoverEventSerializer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.jetbrains.annotations.NotNull;
public class GsonComponentSerializerProviderImpl implements GsonComponentSerializer.Provider {
@Override
public @NotNull GsonComponentSerializer gson() {
return GsonComponentSerializer.builder()
.legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE)
.build();
}
@Override
public @NotNull GsonComponentSerializer gsonLegacy() {
return GsonComponentSerializer.builder()
.legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE)
.downsampleColors()
.emitLegacyHoverEvent()
.build();
}
@Override
public @NotNull Consumer<GsonComponentSerializer.Builder> builder() {
return builder -> builder.legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE);
}
}
@@ -0,0 +1,41 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.adventure.platform.fabric.impl.service;
import java.util.function.Consumer;
import net.kyori.adventure.platform.fabric.impl.AdventureCommon;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.jetbrains.annotations.NotNull;
public class PlainTextComponentSerializerProviderImpl implements PlainTextComponentSerializer.Provider {
@Override
public @NotNull PlainTextComponentSerializer plainTextSimple() {
return PlainTextComponentSerializer.builder().flattener(AdventureCommon.FLATTENER).build();
}
@Override
public @NotNull Consumer<PlainTextComponentSerializer.Builder> plainText() {
return builder -> builder.flattener(AdventureCommon.FLATTENER);
}
}
@@ -0,0 +1,33 @@
/*
* This file is part of adventure-platform-fabric, licensed under the MIT License.
*
* Copyright (c) 2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Implementation of <a href="https://docs.adventure.kyori.net">Adventure</a>
* on Minecraft using the Fabric mod loader.
*
* <p>There are both server- and clientside entry points for Adventure.</p>
*
* @see net.kyori.adventure.platform.fabric.FabricServerAudiences
* @see net.kyori.adventure.platform.fabric.FabricClientAudiences
*/
package net.kyori.adventure.platform.fabric;
@@ -0,0 +1 @@
net.kyori.adventure.platform.fabric.impl.service.GsonComponentSerializerProviderImpl
@@ -0,0 +1 @@
net.kyori.adventure.platform.fabric.impl.service.PlainTextComponentSerializerProviderImpl
@@ -0,0 +1,20 @@
{
"required": true,
"package": "net.kyori.adventure.platform.fabric.impl.accessor",
"refmap": "adventure-platform-fabric-accessor-refmap.json",
"compatibilityLevel": "JAVA_8",
"mixins": [
"ClientboundBossEventPacketAccess",
"ClientboundTabListPacketAccess",
"ComponentSerializerAccess",
"ConnectionAccess",
"ServerboundClientInformationPacketAccess",
"SoundSourceAccess",
],
"client": [
"client.AbstractSoundInstanceAccess"
],
"injectors": {
"defaultRequire": 1
}
}
@@ -0,0 +1,30 @@
{
"required": true,
"package": "net.kyori.adventure.platform.fabric.impl.mixin",
"compatibilityLevel": "JAVA_8",
"mixins": [
"ClientboundStatusResponsePacketMixin",
"CommandSourceStackMixin",
"ComponentSerializerMixin",
"EntityMixin",
"FriendlyByteBufMixin",
"GameProfileMixin",
"MinecraftServerMixin",
"PacketEncoderMixin",
"PlayerListMixin",
"PlayerMixin",
"RconConsoleSourceMixin",
"ServerBossEventMixin",
"ServerGamePacketListenerImplMixin",
"ServerPlayerMixin",
"StyleSerializerMixin"
],
"client": [
"client.BossHealthOverlayMixin",
"client.LocalPlayerMixin",
"client.OptionsMixin"
],
"injectors": {
"defaultRequire": 1
}
}
@@ -20,10 +20,18 @@
"entrypoints": {
"server": [
"com.coloryr.allmusic.server.AllMusicServer"
],
"main": [
"net.kyori.adventure.platform.fabric.impl.AdventureCommon"
],
"preLaunch": [
"net.kyori.adventure.platform.fabric.impl.AdventurePrelaunch"
]
},
"mixins": [
"allmusic_server.mixins.json"
"allmusic_server.mixins.json",
"adventure-platform-fabric.accessor.mixins.json",
"adventure-platform-fabric.mixins.json"
],
"depends": {
"fabricloader": ">=0.15.11",