diff --git a/.github/workflows/check_formatting.yml b/.github/workflows/check_formatting.yml new file mode 100644 index 00000000..8c721673 --- /dev/null +++ b/.github/workflows/check_formatting.yml @@ -0,0 +1,24 @@ +# This workflow will build a Java project with Gradle +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle + +name: Check Formatting + +on: [pull_request] + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 23 for x64 + uses: actions/setup-java@v4 + with: + java-version: '23' + distribution: 'temurin' + architecture: x64 + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-version: 8.13 + - name: Spotless Check + run: gradle spotlessCheck diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8aac6bd4..ff7f442a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,4 +28,17 @@ Run the gradle task `runClient` ```sh ./gradlew build ``` -2. The generated jar is in `build/libs` \ No newline at end of file +2. The generated jar is in `build/libs` + +# Formatting +The formatting configuration can be found in the [formatting directory](https://github.com/MinecraftTAS/TASmod/tree/develop/formatter) and can be imported into your IDE + +Alternatively you can run the task +```sh +./gradlew spotlessCheck +``` +To see if it fails and +```sh +./gradlew spotlessApply +``` +to fix any formatting issues. diff --git a/build.gradle b/build.gradle index dc23f8f3..53128ff5 100644 --- a/build.gradle +++ b/build.gradle @@ -4,6 +4,7 @@ plugins { // legacy looming (loom plugin improvements) id 'legacy-looming' version "${loom_version}" id 'com.palantir.git-version' version '3.1.0' + id 'com.diffplug.spotless' version '7.0.3' } @@ -100,3 +101,13 @@ tasks.named('test', Test) { events "passed", "skipped", "failed" } } + +spotless { + encoding 'UTF-8' + lineEndings 'UNIX' + java { + importOrderFile('formatter/TASmodImportorder.txt') + eclipse().configFile('formatter/TASmodFormatter.xml') + } + enforceCheck false +} \ No newline at end of file diff --git a/formatter/TASmodFormatter.xml b/formatter/TASmodFormatter.xml new file mode 100644 index 00000000..ce683b6f --- /dev/null +++ b/formatter/TASmodFormatter.xml @@ -0,0 +1,404 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/formatter/TASmodImportorder.txt b/formatter/TASmodImportorder.txt new file mode 100644 index 00000000..b5cf4b64 --- /dev/null +++ b/formatter/TASmodImportorder.txt @@ -0,0 +1,6 @@ +#Organize Import Order +#Wed Apr 16 21:35:01 CEST 2025 +0=java +1=javax +2=org +3=com diff --git a/src/main/java/com/minecrafttas/mctcommon/CommandRegistry.java b/src/main/java/com/minecrafttas/mctcommon/CommandRegistry.java index 71633bdf..4ce4553c 100644 --- a/src/main/java/com/minecrafttas/mctcommon/CommandRegistry.java +++ b/src/main/java/com/minecrafttas/mctcommon/CommandRegistry.java @@ -5,10 +5,10 @@ import net.minecraft.server.MinecraftServer; public class CommandRegistry { - + public static void registerServerCommand(ICommand command, MinecraftServer server) { CommandHandler ch = (CommandHandler) server.getCommandManager(); ch.registerCommand(command); } - + } diff --git a/src/main/java/com/minecrafttas/mctcommon/KeybindManager.java b/src/main/java/com/minecrafttas/mctcommon/KeybindManager.java index fcfdf5a2..6577275a 100644 --- a/src/main/java/com/minecrafttas/mctcommon/KeybindManager.java +++ b/src/main/java/com/minecrafttas/mctcommon/KeybindManager.java @@ -79,9 +79,9 @@ public KeybindManager(IsKeyDownFunc defaultFunction) { */ @Override public void onRunClientGameLoop(Minecraft mc) { - for (Keybind keybind : this.keybindings){ + for (Keybind keybind : this.keybindings) { IsKeyDownFunc keyDown = keybind.isKeyDownFunc != null ? keybind.isKeyDownFunc : defaultFunction; - if(keyDown.isKeyDown(keybind.vanillaKeyBinding)){ + if (keyDown.isKeyDown(keybind.vanillaKeyBinding)) { keybind.onKeyDown.run(); } } @@ -105,10 +105,10 @@ public void registerKeybind(Keybind keybind) { // add keybinding options.keyBindings = ArrayUtils.add(options.keyBindings, keyBinding); } - + @FunctionalInterface public static interface IsKeyDownFunc { public boolean isKeyDown(KeyBinding keybind); } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/mctcommon/LanguageManager.java b/src/main/java/com/minecrafttas/mctcommon/LanguageManager.java index acb7defe..6987a106 100644 --- a/src/main/java/com/minecrafttas/mctcommon/LanguageManager.java +++ b/src/main/java/com/minecrafttas/mctcommon/LanguageManager.java @@ -24,101 +24,101 @@ public class LanguageManager { - private static Set modids = new HashSet<>(); - private static final Splitter SPLITTER = Splitter.on('=').limit(2); - private static final Pattern PATTERN = Pattern.compile("%(\\d+\\$)?[\\d\\.]*[df]"); + private static Set modids = new HashSet<>(); + private static final Splitter SPLITTER = Splitter.on('=').limit(2); + private static final Pattern PATTERN = Pattern.compile("%(\\d+\\$)?[\\d\\.]*[df]"); - public static void onResourceManagerReload(Map original, IResourceManager iResourceManager, List languageList) { - for (String language : languageList) { // Go through all loaded languages - language = language.toLowerCase(); // Set everything to lowercase which prevents headaches in 1.10.2 and below - for (String modid : modids) { // Iterate through all registered modids - HashMap newTranslations = new HashMap<>(); - if (iResourceManager.getResourceDomains().contains(modid)) { - try { - newTranslations = getFromResourcePack(iResourceManager, modid, language); // Load .json translations from resource pack - } catch (IOException var9) { - } - } - if (newTranslations.isEmpty()) { - try { - newTranslations = loadLang(getFromResources(modid, language, "lang")); // Load .lang files from resources - } catch (IOException e) { - throw new RuntimeException(e); - } - } - if (newTranslations.isEmpty()) { - newTranslations = loadJson(getFromResources(modid, language, "json")); // Load .json translations from resources - } - /** - * Making this put if absent here creates the following hirarchy: - * Resourcepack .lang beats - * Resourcepack .json beats - * Resources .lang beats - * Resources .json - * - * Lang is preferred over json and resourcepacks are preferred over json - */ - newTranslations.forEach(original::putIfAbsent); - } - } - } + public static void onResourceManagerReload(Map original, IResourceManager iResourceManager, List languageList) { + for (String language : languageList) { // Go through all loaded languages + language = language.toLowerCase(); // Set everything to lowercase which prevents headaches in 1.10.2 and below + for (String modid : modids) { // Iterate through all registered modids + HashMap newTranslations = new HashMap<>(); + if (iResourceManager.getResourceDomains().contains(modid)) { + try { + newTranslations = getFromResourcePack(iResourceManager, modid, language); // Load .json translations from resource pack + } catch (IOException var9) { + } + } + if (newTranslations.isEmpty()) { + try { + newTranslations = loadLang(getFromResources(modid, language, "lang")); // Load .lang files from resources + } catch (IOException e) { + throw new RuntimeException(e); + } + } + if (newTranslations.isEmpty()) { + newTranslations = loadJson(getFromResources(modid, language, "json")); // Load .json translations from resources + } + /** + * Making this put if absent here creates the following hirarchy: + * Resourcepack .lang beats + * Resourcepack .json beats + * Resources .lang beats + * Resources .json + * + * Lang is preferred over json and resourcepacks are preferred over json + */ + newTranslations.forEach(original::putIfAbsent); + } + } + } - private static InputStream getFromResources(String resourceDomain, String language, String fileending) { - return LanguageManager.class.getResourceAsStream(String.format("/assets/%s/lang/%s.%s", resourceDomain, language, fileending)); - } + private static InputStream getFromResources(String resourceDomain, String language, String fileending) { + return LanguageManager.class.getResourceAsStream(String.format("/assets/%s/lang/%s.%s", resourceDomain, language, fileending)); + } - private static HashMap getFromResourcePack(IResourceManager iResourceManager, String resourceDomain, String language) throws IOException { - String languageFile = String.format("lang/%s.json", language); - HashMap out = new HashMap<>(); - Collection allResources = iResourceManager.getAllResources(new ResourceLocation(resourceDomain, languageFile)); - for (IResource iResource : allResources) { - InputStream inputStream = iResource.getInputStream(); - out.putAll(loadJson(inputStream)); - } - return out; - } + private static HashMap getFromResourcePack(IResourceManager iResourceManager, String resourceDomain, String language) throws IOException { + String languageFile = String.format("lang/%s.json", language); + HashMap out = new HashMap<>(); + Collection allResources = iResourceManager.getAllResources(new ResourceLocation(resourceDomain, languageFile)); + for (IResource iResource : allResources) { + InputStream inputStream = iResource.getInputStream(); + out.putAll(loadJson(inputStream)); + } + return out; + } - /** - * Registers your mod to be processed by the language manager
- * This will allow you to add .json and/or .lang files to assets/modid/lang
- * with en_us.lang/en_us.json (lowercase!) - * - * @param modid The modid of your mod - */ - public static void registerMod(String modid) { - modids.add(modid); - } + /** + * Registers your mod to be processed by the language manager
+ * This will allow you to add .json and/or .lang files to assets/modid/lang
+ * with en_us.lang/en_us.json (lowercase!) + * + * @param modid The modid of your mod + */ + public static void registerMod(String modid) { + modids.add(modid); + } - private static HashMap loadJson(InputStream inputStream) { - if (inputStream == null) { - return new HashMap(); - } - Gson gson = new Gson(); - HashMap template = new HashMap<>(); - - @SuppressWarnings("unchecked") + private static HashMap loadJson(InputStream inputStream) { + if (inputStream == null) { + return new HashMap(); + } + Gson gson = new Gson(); + HashMap template = new HashMap<>(); + + @SuppressWarnings("unchecked") HashMap out = (HashMap) gson.fromJson(new InputStreamReader(inputStream), template.getClass()); - out.forEach((key, value) -> { - value = PATTERN.matcher(value).replaceAll("%$1s"); - }); - return out; - } + out.forEach((key, value) -> { + value = PATTERN.matcher(value).replaceAll("%$1s"); + }); + return out; + } - private static HashMap loadLang(InputStream inputStream) throws IOException { - HashMap out = new HashMap<>(); - if (inputStream == null) { - return out; - } - for (String string : IOUtils.readLines(inputStream, StandardCharsets.UTF_8)) { - if (!string.isEmpty() && string.charAt(0) != '#') { - String[] key_value_pair = Iterables.toArray(SPLITTER.split(string), String.class); - if (key_value_pair != null && key_value_pair.length == 2) { - String key = key_value_pair[0]; - String value = PATTERN.matcher(key_value_pair[1]).replaceAll("%$1s"); - out.put(key, value); - } - } - } - return out; - } + private static HashMap loadLang(InputStream inputStream) throws IOException { + HashMap out = new HashMap<>(); + if (inputStream == null) { + return out; + } + for (String string : IOUtils.readLines(inputStream, StandardCharsets.UTF_8)) { + if (!string.isEmpty() && string.charAt(0) != '#') { + String[] key_value_pair = Iterables.toArray(SPLITTER.split(string), String.class); + if (key_value_pair != null && key_value_pair.length == 2) { + String key = key_value_pair[0]; + String value = PATTERN.matcher(key_value_pair[1]).replaceAll("%$1s"); + out.put(key, value); + } + } + } + return out; + } } diff --git a/src/main/java/com/minecrafttas/mctcommon/events/EventClient.java b/src/main/java/com/minecrafttas/mctcommon/events/EventClient.java index 14a58991..4dee7837 100644 --- a/src/main/java/com/minecrafttas/mctcommon/events/EventClient.java +++ b/src/main/java/com/minecrafttas/mctcommon/events/EventClient.java @@ -14,7 +14,7 @@ * @author Scribble */ public interface EventClient { - + /** * Fired when a gui is opened (Minecraft#displayGuiScreen) * @author Scribble @@ -22,7 +22,7 @@ public interface EventClient { */ @FunctionalInterface public static interface EventOpenGui extends EventBase { - + /** * Fired when a gui is opened (Minecraft#displayGuiScreen) * @param gui The gui that is opened @@ -30,7 +30,7 @@ public static interface EventOpenGui extends EventBase { */ public GuiScreen onOpenGui(GuiScreen gui); } - + /** * Fired when the integrated server is launched * @author Scribble @@ -38,7 +38,7 @@ public static interface EventOpenGui extends EventBase { */ @FunctionalInterface public static interface EventLaunchIntegratedServer extends EventBase { - + /** * Fired when the integrated server is launched */ @@ -58,7 +58,7 @@ public static interface EventDoneLoadingWorld extends EventBase { */ public void onDoneLoadingWorld(); } - + /** * Fired when the client ticks * @author Scribble @@ -66,14 +66,14 @@ public static interface EventDoneLoadingWorld extends EventBase { */ @FunctionalInterface public static interface EventClientTick extends EventBase { - + /** * Fired when the client ticks * @param mc The ticking Minecraft instance */ public void onClientTick(Minecraft mc); } - + /** * Fires after the client is initialised * @author Scribble @@ -81,7 +81,7 @@ public static interface EventClientTick extends EventBase { */ @FunctionalInterface public static interface EventClientInit extends EventBase { - + /** * Fires after the client is initialised * @param mc The initialized Minecraft instance @@ -96,7 +96,7 @@ public static interface EventClientInit extends EventBase { */ @FunctionalInterface public static interface EventClientGameLoop extends EventBase { - + /** * Fired when when the client runs a game loop, which is tick independent * @param mc The Minecraft instance that is looping @@ -111,32 +111,32 @@ public static interface EventClientGameLoop extends EventBase { */ @FunctionalInterface public static interface EventCamera extends EventBase { - + /** * Fired when the camera is updated * @param dataIn The pitch and yaw of the camera * @return The changed camera data. Can be changed during the event */ public CameraData onCameraEvent(CameraData dataIn); - - public static class CameraData{ + + public static class CameraData { public float pitch; public float yaw; public float roll; - + public CameraData(float pitch, float yaw) { this(pitch, yaw, 0f); } - + public CameraData(float pitch, float yaw, float roll) { this.pitch = pitch; this.yaw = yaw; this.roll = roll; } - + @Override public boolean equals(Object obj) { - if(obj instanceof CameraData) { + if (obj instanceof CameraData) { CameraData b = (CameraData) obj; return b.pitch == pitch && b.yaw == yaw; } @@ -152,14 +152,14 @@ public boolean equals(Object obj) { */ @FunctionalInterface public static interface EventPlayerLeaveClientSide extends EventBase { - + /** * Fired when a player leaves a server or a world * @param player The player that leaves the server or the world */ public void onPlayerLeaveClientSide(EntityPlayerSP player); } - + /** * Fired when a player joins a server or a world * @author Scribble @@ -189,13 +189,13 @@ public static interface EventOtherPlayerJoinedClientSide extends EventBase { */ public void onOtherPlayerJoinedClientSide(GameProfile profile); } - + /** * Fired when the connection to the custom server was closed on the client side. */ @FunctionalInterface public static interface EventDisconnectClient extends EventBase { - + /** * Fired when the connection to the custom server was closed on the client side. * @param client The client that is disconnecting diff --git a/src/main/java/com/minecrafttas/mctcommon/events/EventException.java b/src/main/java/com/minecrafttas/mctcommon/events/EventException.java index 3a1815ff..2383fa85 100644 --- a/src/main/java/com/minecrafttas/mctcommon/events/EventException.java +++ b/src/main/java/com/minecrafttas/mctcommon/events/EventException.java @@ -2,15 +2,15 @@ public class EventException extends RuntimeException { - public EventException(String message, Class eventClass) { - super(eventClass.getName() + ": " + message); - } + public EventException(String message, Class eventClass) { + super(eventClass.getName() + ": " + message); + } - public EventException(String message, Class eventClass, Throwable cause) { - super(eventClass.getName() + ": " + message, cause); - } + public EventException(String message, Class eventClass, Throwable cause) { + super(eventClass.getName() + ": " + message, cause); + } - public EventException(Class eventClass, Throwable cause) { - super(eventClass.getName(), cause); - } + public EventException(Class eventClass, Throwable cause) { + super(eventClass.getName(), cause); + } } diff --git a/src/main/java/com/minecrafttas/mctcommon/events/EventServer.java b/src/main/java/com/minecrafttas/mctcommon/events/EventServer.java index 0f8e6af2..ea26c691 100644 --- a/src/main/java/com/minecrafttas/mctcommon/events/EventServer.java +++ b/src/main/java/com/minecrafttas/mctcommon/events/EventServer.java @@ -25,13 +25,13 @@ public static interface EventServerInit extends EventBase { */ public void onServerInit(MinecraftServer server); } - + /** * Fired when the server ticks. */ @FunctionalInterface public static interface EventServerTick extends EventBase { - + /** * Fired when the server ticks. * @param server The ticking server @@ -79,7 +79,7 @@ public static interface EventPlayerJoinedServerSide extends EventBase { */ public void onPlayerJoinedServerSide(EntityPlayerMP player); } - + /** * Fired when a player leaves the server. */ @@ -92,26 +92,26 @@ public static interface EventPlayerLeaveServerSide extends EventBase { */ public void onPlayerLeaveServerSide(EntityPlayerMP player); } - + /** * Fired when authentication was successful on the server side */ @FunctionalInterface public static interface EventClientCompleteAuthentication extends EventBase { - + /** * Fired when authentication was successful on the server side * @param username The username of the client that is connecting */ public void onClientCompleteAuthentication(String username); } - + /** * Fired when the connection to the custom server was closed on the server side. */ @FunctionalInterface public static interface EventDisconnectServer extends EventBase { - + /** * Fired when the connection to the custom server was closed on the server side. * @param client The client that is disconnecting diff --git a/src/main/java/com/minecrafttas/mctcommon/mixin/AccessorKeyBinding.java b/src/main/java/com/minecrafttas/mctcommon/mixin/AccessorKeyBinding.java index 227f3aa5..5a20501b 100644 --- a/src/main/java/com/minecrafttas/mctcommon/mixin/AccessorKeyBinding.java +++ b/src/main/java/com/minecrafttas/mctcommon/mixin/AccessorKeyBinding.java @@ -9,8 +9,8 @@ import net.minecraft.client.settings.KeyBinding; @Mixin(KeyBinding.class) -public interface AccessorKeyBinding{ - +public interface AccessorKeyBinding { + @Accessor("CATEGORY_ORDER") public static Map getCategoryOrder() { throw new NotImplementedException("WEE WOO"); diff --git a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinLocale.java b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinLocale.java index 80c501f6..a2df9234 100644 --- a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinLocale.java +++ b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinLocale.java @@ -1,24 +1,27 @@ package com.minecrafttas.mctcommon.mixin; -import com.minecrafttas.mctcommon.LanguageManager; -import net.minecraft.client.resources.IResourceManager; -import net.minecraft.client.resources.Locale; +import java.util.List; +import java.util.Map; + 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; -import java.util.List; -import java.util.Map; +import com.minecrafttas.mctcommon.LanguageManager; + +import net.minecraft.client.resources.IResourceManager; +import net.minecraft.client.resources.Locale; @Mixin(Locale.class) public class MixinLocale { - @Shadow - private Map properties; - @Inject(method="loadLocaleDataFiles", at = @At("RETURN")) - private void inject_loadLocalDataFiles(IResourceManager iResourceManager, List list, CallbackInfo ci){ - LanguageManager.onResourceManagerReload(properties, iResourceManager, list); - } + @Shadow + private Map properties; + + @Inject(method = "loadLocaleDataFiles", at = @At("RETURN")) + private void inject_loadLocalDataFiles(IResourceManager iResourceManager, List list, CallbackInfo ci) { + LanguageManager.onResourceManagerReload(properties, iResourceManager, list); + } } diff --git a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraft.java b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraft.java index 54f7ccd2..9cfa1105 100644 --- a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraft.java +++ b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraft.java @@ -1,6 +1,5 @@ package com.minecrafttas.mctcommon.mixin; -import com.minecrafttas.mctcommon.events.EventListenerRegistry; import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -15,6 +14,7 @@ import com.minecrafttas.mctcommon.events.EventClient.EventDoneLoadingWorld; import com.minecrafttas.mctcommon.events.EventClient.EventLaunchIntegratedServer; import com.minecrafttas.mctcommon.events.EventClient.EventOpenGui; +import com.minecrafttas.mctcommon.events.EventListenerRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; @@ -22,37 +22,37 @@ @Mixin(Minecraft.class) public class MixinMinecraft { - @Inject(method = "init", at = @At(value = "RETURN")) - public void inject_init(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventClientInit.class, (Minecraft) (Object) this); - } - - @Inject(method = "runGameLoop", at = @At(value = "HEAD")) - public void inject_runGameLoop(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventClientGameLoop.class, (Minecraft) (Object) this); - } - - @Inject(method = "runTick", at = @At("HEAD")) - public void inject_runTick(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventClientTick.class, (Minecraft) (Object) this); - } - - @Inject(method = "launchIntegratedServer", at = @At("HEAD")) - public void inject_launchIntegratedServer(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventLaunchIntegratedServer.class); - } - - @Inject(method = "Lnet/minecraft/client/Minecraft;loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Ljava/lang/String;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/PlayerControllerMP;flipPlayer(Lnet/minecraft/entity/player/EntityPlayer;)V")) - public void inject_loadWorld(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventDoneLoadingWorld.class); - } - - @Shadow - private GuiScreen currentScreen; - - @Redirect(method = "displayGuiScreen", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;currentScreen:Lnet/minecraft/client/gui/GuiScreen;", opcode = Opcodes.PUTFIELD)) - public void modify_displayGuiScreen(Minecraft mc, GuiScreen guiScreen) { - guiScreen = (GuiScreen) EventListenerRegistry.fireEvent(EventOpenGui.class, guiScreen); - currentScreen = guiScreen; - } + @Inject(method = "init", at = @At(value = "RETURN")) + public void inject_init(CallbackInfo ci) { + EventListenerRegistry.fireEvent(EventClientInit.class, (Minecraft) (Object) this); + } + + @Inject(method = "runGameLoop", at = @At(value = "HEAD")) + public void inject_runGameLoop(CallbackInfo ci) { + EventListenerRegistry.fireEvent(EventClientGameLoop.class, (Minecraft) (Object) this); + } + + @Inject(method = "runTick", at = @At("HEAD")) + public void inject_runTick(CallbackInfo ci) { + EventListenerRegistry.fireEvent(EventClientTick.class, (Minecraft) (Object) this); + } + + @Inject(method = "launchIntegratedServer", at = @At("HEAD")) + public void inject_launchIntegratedServer(CallbackInfo ci) { + EventListenerRegistry.fireEvent(EventLaunchIntegratedServer.class); + } + + @Inject(method = "Lnet/minecraft/client/Minecraft;loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Ljava/lang/String;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/PlayerControllerMP;flipPlayer(Lnet/minecraft/entity/player/EntityPlayer;)V")) + public void inject_loadWorld(CallbackInfo ci) { + EventListenerRegistry.fireEvent(EventDoneLoadingWorld.class); + } + + @Shadow + private GuiScreen currentScreen; + + @Redirect(method = "displayGuiScreen", at = @At(value = "FIELD", target = "Lnet/minecraft/client/Minecraft;currentScreen:Lnet/minecraft/client/gui/GuiScreen;", opcode = Opcodes.PUTFIELD)) + public void modify_displayGuiScreen(Minecraft mc, GuiScreen guiScreen) { + guiScreen = (GuiScreen) EventListenerRegistry.fireEvent(EventOpenGui.class, guiScreen); + currentScreen = guiScreen; + } } diff --git a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraftServer.java b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraftServer.java index 8e6ba7fc..4ea7d14f 100644 --- a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraftServer.java +++ b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinMinecraftServer.java @@ -1,12 +1,12 @@ package com.minecrafttas.mctcommon.mixin; -import com.minecrafttas.mctcommon.events.EventListenerRegistry; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At.Shift; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import com.minecrafttas.mctcommon.events.EventListenerRegistry; import com.minecrafttas.mctcommon.events.EventServer.EventServerGameLoop; import com.minecrafttas.mctcommon.events.EventServer.EventServerInit; import com.minecrafttas.mctcommon.events.EventServer.EventServerStop; @@ -16,24 +16,24 @@ @Mixin(MinecraftServer.class) public class MixinMinecraftServer { - + @Inject(method = "run", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;init()Z", shift = Shift.AFTER)) public void inject_init(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventServerInit.class, (MinecraftServer)(Object)this); + EventListenerRegistry.fireEvent(EventServerInit.class, (MinecraftServer) (Object) this); } - + @Inject(method = "initiateShutdown", at = @At("HEAD")) public void inject_initiateShutDown(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventServerStop.class, (MinecraftServer)(Object)this); + EventListenerRegistry.fireEvent(EventServerStop.class, (MinecraftServer) (Object) this); } - + @Inject(method = "tick", at = @At("HEAD")) public void inject_tick(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventServerTick.class, (MinecraftServer)(Object)this); + EventListenerRegistry.fireEvent(EventServerTick.class, (MinecraftServer) (Object) this); } - + // @Inject(method = "run", at = @At(value = "FIELD", target = "Lnet/minecraft/server/MinecraftServer;serverRunning:Z", shift = Shift.AFTER)) public void inject_run(CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventServerGameLoop.class, (MinecraftServer)(Object)this); + EventListenerRegistry.fireEvent(EventServerGameLoop.class, (MinecraftServer) (Object) this); } } diff --git a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinNetHandlerPlayClient.java b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinNetHandlerPlayClient.java index 87e0aca2..84b5d226 100644 --- a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinNetHandlerPlayClient.java +++ b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinNetHandlerPlayClient.java @@ -2,7 +2,6 @@ import java.net.ConnectException; -import com.minecrafttas.mctcommon.events.EventListenerRegistry; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -11,6 +10,7 @@ import com.minecrafttas.mctcommon.events.EventClient.EventOtherPlayerJoinedClientSide; import com.minecrafttas.mctcommon.events.EventClient.EventPlayerJoinedClientSide; +import com.minecrafttas.mctcommon.events.EventListenerRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetHandlerPlayClient; diff --git a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinPlayerList.java b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinPlayerList.java index 024b3250..5476f418 100644 --- a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinPlayerList.java +++ b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinPlayerList.java @@ -1,11 +1,11 @@ package com.minecrafttas.mctcommon.mixin; -import com.minecrafttas.mctcommon.events.EventListenerRegistry; 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 com.minecrafttas.mctcommon.events.EventListenerRegistry; import com.minecrafttas.mctcommon.events.EventServer.EventPlayerJoinedServerSide; import com.minecrafttas.mctcommon.events.EventServer.EventPlayerLeaveServerSide; @@ -15,13 +15,13 @@ @Mixin(PlayerList.class) public class MixinPlayerList { - @Inject(method = "initializeConnectionToPlayer", at = @At("RETURN"), remap = false) - public void inject_initializeConnectionToPlayer(NetworkManager netManager, EntityPlayerMP playerIn, CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventPlayerJoinedServerSide.class, playerIn); - } + @Inject(method = "initializeConnectionToPlayer", at = @At("RETURN"), remap = false) + public void inject_initializeConnectionToPlayer(NetworkManager netManager, EntityPlayerMP playerIn, CallbackInfo ci) { + EventListenerRegistry.fireEvent(EventPlayerJoinedServerSide.class, playerIn); + } - @Inject(method = "playerLoggedOut", at = @At("HEAD")) - public void inject_playerLoggedOut(EntityPlayerMP playerIn, CallbackInfo ci) { - EventListenerRegistry.fireEvent(EventPlayerLeaveServerSide.class, playerIn); - } + @Inject(method = "playerLoggedOut", at = @At("HEAD")) + public void inject_playerLoggedOut(EntityPlayerMP playerIn, CallbackInfo ci) { + EventListenerRegistry.fireEvent(EventPlayerLeaveServerSide.class, playerIn); + } } diff --git a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinWorldClient.java b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinWorldClient.java index abf39e22..61f7f25c 100644 --- a/src/main/java/com/minecrafttas/mctcommon/mixin/MixinWorldClient.java +++ b/src/main/java/com/minecrafttas/mctcommon/mixin/MixinWorldClient.java @@ -1,12 +1,12 @@ package com.minecrafttas.mctcommon.mixin; -import com.minecrafttas.mctcommon.events.EventListenerRegistry; 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 com.minecrafttas.mctcommon.events.EventClient.EventPlayerLeaveClientSide; +import com.minecrafttas.mctcommon.events.EventListenerRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; @@ -17,4 +17,4 @@ public class MixinWorldClient { public void clientLeaveServerEvent(CallbackInfo ci) { EventListenerRegistry.fireEvent(EventPlayerLeaveClientSide.class, Minecraft.getMinecraft().player); } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/CompactPacketHandler.java b/src/main/java/com/minecrafttas/mctcommon/networking/CompactPacketHandler.java index 93bc10f1..e60a1efb 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/CompactPacketHandler.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/CompactPacketHandler.java @@ -6,6 +6,6 @@ @FunctionalInterface public interface CompactPacketHandler { - + public void onPacket(ByteBuffer buf, String username) throws PacketNotImplementedException; } diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/SecureList.java b/src/main/java/com/minecrafttas/mctcommon/networking/SecureList.java index 372efaec..bcb88e4b 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/SecureList.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/SecureList.java @@ -39,7 +39,7 @@ public int available() { return i; return -1; } - + /** * Lock and return byte buffer * @param i Index to lock @@ -52,7 +52,7 @@ public ByteBuffer lock(int i) { this.locked[i] = true; return (ByteBuffer) this.buffers[i].clear(); } - + /** * Unlocke byte buffer * @param index Index to unlock @@ -60,5 +60,5 @@ public ByteBuffer lock(int i) { public void unlock(int index) { this.locked[index] = false; } - + } diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/Server.java b/src/main/java/com/minecrafttas/mctcommon/networking/Server.java index da578d64..9d1d28c5 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/Server.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/Server.java @@ -48,22 +48,22 @@ public Server(int port, PacketID[] packetIDs) throws Exception { @Override public void completed(AsynchronousSocketChannel clientSocket, Object attachment) { - + ClientCallback callback = (client) -> { EventListenerRegistry.fireEvent(EventDisconnectServer.class, client); clients.remove(client); LOGGER.debug(Server, "Disconnecting player from server"); }; - + Client newclient = new Client(clientSocket, packetIDs, callback); clients.add(newclient); - + serverSocket.accept(null, this); } @Override public void failed(Throwable exc, Object attachment) { - if(exc instanceof AsynchronousCloseException) { + if (exc instanceof AsynchronousCloseException) { LOGGER.info(Server, "Connection to the player was closed!"); } else { LOGGER.error(Server, "Unable to accept client!", exc); @@ -96,7 +96,7 @@ public void sendToAll(ByteBufferBuilder builder) throws Exception { */ public void sendTo(String username, ByteBufferBuilder builder) throws Exception { Client client = getClient(username); - if(client != null && !client.isClosed()) { + if (client != null && !client.isClosed()) { client.send(builder); } else { MCTCommon.LOGGER.warn(Server, "Buffer with id {} could not be sent to the client {}: The client is closed", builder.getPacketID(), username); @@ -117,22 +117,21 @@ public void sendTo(EntityPlayer player, ByteBufferBuilder builder) throws Except sendTo(player.getName(), builder); } - public void disconnect(String username) { Client client = getClient(username); client.disconnect(); } - + public void disconnect(EntityPlayer player) { disconnect(player.getName()); } - + public void disconnectAll() { for (Client client : getClients()) { client.disconnect(); } } - + /** * Try to close socket * diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/exception/InvalidPacketException.java b/src/main/java/com/minecrafttas/mctcommon/networking/exception/InvalidPacketException.java index ef184e1c..fe90a57b 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/exception/InvalidPacketException.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/exception/InvalidPacketException.java @@ -5,7 +5,7 @@ public class InvalidPacketException extends Exception { public InvalidPacketException() { super(); } - + public InvalidPacketException(String msg) { super(msg); } diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/exception/PacketNotImplementedException.java b/src/main/java/com/minecrafttas/mctcommon/networking/exception/PacketNotImplementedException.java index 37994139..531af0d5 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/exception/PacketNotImplementedException.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/exception/PacketNotImplementedException.java @@ -9,13 +9,13 @@ public class PacketNotImplementedException extends Exception { public PacketNotImplementedException(String msg) { super(msg); } - + public PacketNotImplementedException(PacketID packet, Class clazz, Side side) { super(String.format("The packet %s is not implemented in %s on the %s-Side", packet.getName(), clazz.getCanonicalName(), side)); } - + public PacketNotImplementedException(PacketID packet, Side side) { super(String.format("The packet %s is not implemented or not registered in getAssociatedPacketIDs on the %s-Side", packet.getName(), side)); } - + } diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/exception/WrongSideException.java b/src/main/java/com/minecrafttas/mctcommon/networking/exception/WrongSideException.java index f19c8922..3812ec94 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/exception/WrongSideException.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/exception/WrongSideException.java @@ -6,13 +6,13 @@ public class WrongSideException extends Exception { private static final long serialVersionUID = 1439028694540465537L; - + public WrongSideException(PacketID packet, Client.Side side) { super(String.format("The packet %s is sent to the wrong side: %s", packet.getName(), side.name())); } - + public WrongSideException(String msg) { super(msg); } - + } diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ClientPacketHandler.java b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ClientPacketHandler.java index 2abbaad6..c4ba3d69 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ClientPacketHandler.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ClientPacketHandler.java @@ -5,7 +5,7 @@ import com.minecrafttas.mctcommon.networking.exception.PacketNotImplementedException; import com.minecrafttas.mctcommon.networking.exception.WrongSideException; -public interface ClientPacketHandler extends PacketHandlerBase{ - +public interface ClientPacketHandler extends PacketHandlerBase { + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception; } diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketHandlerBase.java b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketHandlerBase.java index 3651b45f..417649bb 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketHandlerBase.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketHandlerBase.java @@ -6,6 +6,6 @@ public interface PacketHandlerBase { *
* or {@link ServerPacketHandler#onServerPacket(PacketID, java.nio.ByteBuffer, java.util.UUID)} methods. */ - public PacketID[] getAcceptedPacketIDs(); - + public PacketID[] getAcceptedPacketIDs(); + } diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketID.java b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketID.java index 99506c07..d9f5ff35 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketID.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/PacketID.java @@ -1,29 +1,32 @@ package com.minecrafttas.mctcommon.networking.interfaces; +import com.minecrafttas.mctcommon.networking.Client.Side; import com.minecrafttas.mctcommon.networking.CompactPacketHandler; import com.minecrafttas.mctcommon.registry.Registerable; -import com.minecrafttas.mctcommon.networking.Client.Side; -public interface PacketID extends Registerable{ +public interface PacketID extends Registerable { /** * @return The numerical ID of the packet */ public int getID(); + /** * Only used in combination with {@link #getLambda()} * @return The side of the packet this is registered to */ public Side getSide(); + /** * Used for compact small lambda packet handlers * @return The lamda to run when receiving a packet */ public CompactPacketHandler getLambda(); + /** * @return The name of the packet */ public String getName(); - + /** * @return Whether the packet should be used in trace messages */ diff --git a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ServerPacketHandler.java b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ServerPacketHandler.java index ba66fb29..d860e44a 100644 --- a/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ServerPacketHandler.java +++ b/src/main/java/com/minecrafttas/mctcommon/networking/interfaces/ServerPacketHandler.java @@ -5,7 +5,7 @@ import com.minecrafttas.mctcommon.networking.exception.PacketNotImplementedException; import com.minecrafttas.mctcommon.networking.exception.WrongSideException; -public interface ServerPacketHandler extends PacketHandlerBase{ - +public interface ServerPacketHandler extends PacketHandlerBase { + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception; } diff --git a/src/main/java/com/minecrafttas/mctcommon/package-info.java b/src/main/java/com/minecrafttas/mctcommon/package-info.java index 1fc1c866..47647af2 100644 --- a/src/main/java/com/minecrafttas/mctcommon/package-info.java +++ b/src/main/java/com/minecrafttas/mctcommon/package-info.java @@ -2,4 +2,4 @@ /** * Common classes for interacting with the Minecraft codebase, like registering commands and keybinds, plus standard events. - */ \ No newline at end of file + */ diff --git a/src/main/java/com/minecrafttas/mctcommon/registry/AbstractRegistry.java b/src/main/java/com/minecrafttas/mctcommon/registry/AbstractRegistry.java index 292cef65..b2d6813a 100644 --- a/src/main/java/com/minecrafttas/mctcommon/registry/AbstractRegistry.java +++ b/src/main/java/com/minecrafttas/mctcommon/registry/AbstractRegistry.java @@ -16,7 +16,7 @@ public AbstractRegistry(String name, Map map) { public void register(V registryObject) { if (registryObject == null) { - throw new NullPointerException("Tried to register an object to "+name+" with value null"); + throw new NullPointerException("Tried to register an object to " + name + " with value null"); } if (containsClass(registryObject)) { @@ -24,11 +24,11 @@ public void register(V registryObject) { return; } - if(REGISTRY.containsKey(registryObject.getExtensionName())) { + if (REGISTRY.containsKey(registryObject.getExtensionName())) { TASmod.LOGGER.warn("Trying to register the an object in {}, but an extension with the same name is already registered: {}", registryObject.getExtensionName()); return; } - + REGISTRY.put(registryObject.getExtensionName(), registryObject); } @@ -36,7 +36,7 @@ public void register(V registryObject) { public final void register(V... registryObjects) { this.register(Arrays.asList(registryObjects)); } - + public final void register(Iterable registryObjects) { for (V registryObject : registryObjects) { this.register(registryObject); @@ -45,7 +45,7 @@ public final void register(Iterable registryObjects) { public void unregister(V registryObject) { if (registryObject == null) { - throw new NullPointerException("Tried to unregister an object from "+name+" with value null"); + throw new NullPointerException("Tried to unregister an object from " + name + " with value null"); } if (REGISTRY.containsKey(registryObject.getExtensionName())) { REGISTRY.remove(registryObject.getExtensionName()); @@ -58,13 +58,13 @@ public void unregister(V registryObject) { public final void unregister(V... registryObjects) { this.unregister(Arrays.asList(registryObjects)); } - + public final void unregister(Iterable registryObjects) { for (V registryObject : registryObjects) { this.unregister(registryObject); } } - + public void clear() { REGISTRY.clear(); } @@ -72,7 +72,7 @@ public void clear() { protected boolean containsClass(V newExtension) { return containsClazz(newExtension, REGISTRY.values()); } - + public static boolean containsClazz(W newExtension, Iterable iterable) { for (W extension : iterable) { if (extension.getClass().equals(newExtension.getClass())) { diff --git a/src/main/java/com/minecrafttas/mctcommon/registry/Registerable.java b/src/main/java/com/minecrafttas/mctcommon/registry/Registerable.java index a7b49278..72f0924f 100644 --- a/src/main/java/com/minecrafttas/mctcommon/registry/Registerable.java +++ b/src/main/java/com/minecrafttas/mctcommon/registry/Registerable.java @@ -11,4 +11,4 @@ public interface Registerable { * @return The name of the extension that is registered */ public String getExtensionName(); -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/tasmod/TASmod.java b/src/main/java/com/minecrafttas/tasmod/TASmod.java index 85a7d32a..fb9bdaaf 100644 --- a/src/main/java/com/minecrafttas/tasmod/TASmod.java +++ b/src/main/java/com/minecrafttas/tasmod/TASmod.java @@ -30,7 +30,7 @@ import com.minecrafttas.tasmod.playback.metadata.builtin.StartpositionMetadataExtension; import com.minecrafttas.tasmod.registries.TASmodPackets; import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; -import com.minecrafttas.tasmod.savestates.storage.SavestateMotionStorage; +import com.minecrafttas.tasmod.savestates.storage.builtin.SavestateMotionStorage; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer; import com.minecrafttas.tasmod.ticksync.TickSyncServer; import com.minecrafttas.tasmod.util.LoggerMarkers; @@ -43,7 +43,7 @@ /** * ModContainer for TASmod - * + * * @author Scribble */ public class TASmod implements ModInitializer, EventServerInit, EventServerStop { @@ -54,7 +54,7 @@ public class TASmod implements ModInitializer, EventServerInit, EventServerStop private static MinecraftServer serverInstance; - public static PlaybackControllerServer playbackControllerServer = new PlaybackControllerServer();; + public static PlaybackControllerServer playbackControllerServer = new PlaybackControllerServer(); public static SavestateHandlerServer savestateHandlerServer; @@ -172,7 +172,6 @@ public void onServerStop(MinecraftServer mcserver) { server.close(); } catch (IOException e) { LOGGER.error("Unable to close TASmod server: {}", e); - e.printStackTrace(); } } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java index 38f7337f..ec5035e0 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandClearInputs.java @@ -10,7 +10,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; -public class CommandClearInputs extends CommandBase{ +public class CommandClearInputs extends CommandBase { @Override public String getName() { @@ -24,7 +24,7 @@ public String getUsage(ICommandSender sender) { @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { - if(sender instanceof EntityPlayer) { + if (sender instanceof EntityPlayer) { try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_CLEAR_INPUTS)); } catch (Exception e) { @@ -32,6 +32,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } } } + @Override public int getRequiredPermissionLevel() { return 2; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java index 1ce20865..2aeb6974 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandLoadTAS.java @@ -40,7 +40,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args if (sender.canUseCommand(2, "load")) { if (args.length < 1) { sender.sendMessage(new TextComponentString(TextFormatting.RED + "Please add a filename, " + getUsage(sender))); - } else if(args.length == 1) { + } else if (args.length == 1) { String filename = args[0]; try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.PLAYBACK_LOAD).writeString(filename).writeString("")); @@ -61,7 +61,7 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args } } } - + @Override public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos targetPos) { List tab; @@ -83,7 +83,7 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen return super.getTabCompletions(server, sender, args, targetPos); } return getListOfStringsMatchingLastWord(args, tab); - + } else if (args.length == 2) { try { tab = TASmod.tabCompletionUtils.getFlavorList(getCommandSenderAsPlayer(sender).getName()); @@ -97,7 +97,7 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen return super.getTabCompletions(server, sender, args, targetPos); } return getListOfStringsMatchingLastWord(args, tab); - + } else return super.getTabCompletions(server, sender, args, targetPos); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java index deb96bc6..9dbdb86f 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandRestartAndPlay.java @@ -21,7 +21,7 @@ import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; -public class CommandRestartAndPlay extends CommandBase{ +public class CommandRestartAndPlay extends CommandBase { @Override public String getName() { @@ -43,9 +43,9 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args String spacer = " "; for (int i = 0; i < args.length; i++) { if (i == args.length - 1) { - spacer=""; + spacer = ""; } - name=name.concat(args[i]+spacer); + name = name.concat(args[i] + spacer); } try { TASmod.savestateHandlerServer.loadState(0, false); diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java index 1c4162af..e31c7392 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandSaveTAS.java @@ -70,7 +70,8 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen List tab = null; if (args.length == 1) { if (!check) { - sender.sendMessage(new TextComponentString(TextFormatting.BOLD + "" + TextFormatting.RED + "WARNING!" + TextFormatting.RESET + TextFormatting.RED + " Existing filenames will be overwritten! /fail to abort the recording if you accidentally started one")); + sender.sendMessage(new TextComponentString(TextFormatting.BOLD + "" + TextFormatting.RED + "WARNING!" + TextFormatting.RESET + TextFormatting.RED + + " Existing filenames will be overwritten! /fail to abort the recording if you accidentally started one")); check = true; } try { @@ -90,7 +91,7 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen return super.getTabCompletions(server, sender, args, targetPos); } return getListOfStringsMatchingLastWord(args, tab); - + } else if (args.length == 2) { try { tab = TASmod.tabCompletionUtils.getFlavorList(getCommandSenderAsPlayer(sender).getName()); @@ -104,7 +105,7 @@ public List getTabCompletions(MinecraftServer server, ICommandSender sen return super.getTabCompletions(server, sender, args, targetPos); } return getListOfStringsMatchingLastWord(args, tab); - + } else return super.getTabCompletions(server, sender, args, targetPos); } diff --git a/src/main/java/com/minecrafttas/tasmod/commands/CommandTickrate.java b/src/main/java/com/minecrafttas/tasmod/commands/CommandTickrate.java index 584e6a81..b125d604 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/CommandTickrate.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/CommandTickrate.java @@ -11,13 +11,14 @@ import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.TextComponentString; + /** * Command to change the tickrate of client and server * @author ScribbleLP * */ public class CommandTickrate extends CommandBase { - + @Override public String getName() { return "tickrate"; @@ -41,7 +42,7 @@ public int getRequiredPermissionLevel() { @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length == 0) { - sender.sendMessage(new TextComponentString( I18n.format("tickratechanger.tasmod.command.show", TASmod.tickratechanger.ticksPerSecond))); //"Current tickrate: " + sender.sendMessage(new TextComponentString(I18n.format("tickratechanger.tasmod.command.show", TASmod.tickratechanger.ticksPerSecond))); //"Current tickrate: " return; } float tickrate; diff --git a/src/main/java/com/minecrafttas/tasmod/commands/TabCompletionUtils.java b/src/main/java/com/minecrafttas/tasmod/commands/TabCompletionUtils.java index 69eae109..1ddd74b6 100644 --- a/src/main/java/com/minecrafttas/tasmod/commands/TabCompletionUtils.java +++ b/src/main/java/com/minecrafttas/tasmod/commands/TabCompletionUtils.java @@ -91,7 +91,7 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws String flavornames = String.join("|", TASmodAPIRegistry.SERIALISER_FLAVOR.getFlavorNames()); TASmodClient.client.send(new TASmodBufferBuilder(COMMAND_FLAVORLIST).writeString(flavornames)); break; - + default: break; } diff --git a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java index 7ddf8fad..023cf042 100644 --- a/src/main/java/com/minecrafttas/tasmod/events/EventServer.java +++ b/src/main/java/com/minecrafttas/tasmod/events/EventServer.java @@ -1,6 +1,7 @@ package com.minecrafttas.tasmod.events; import com.minecrafttas.mctcommon.events.EventListenerRegistry.EventBase; + import net.minecraft.server.MinecraftServer; /** diff --git a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java index da37107f..26f0781e 100644 --- a/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java +++ b/src/main/java/com/minecrafttas/tasmod/gui/InfoHud.java @@ -588,4 +588,4 @@ private int getBBDown(int y) { return y + 14; } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGMonitor.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGMonitor.java index baa32a5c..7cf6fa98 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGMonitor.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KTRNGMonitor.java @@ -2,7 +2,7 @@ @Deprecated public class KTRNGMonitor { - + // @CaptureRandomness(name = "jukeboxRecordDropPosition") public static void monitor(long seed, String value) { // System.out.println(String.format("Seed: %s, Value: %s", seed, value)); diff --git a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java index 8b4c53b7..d071cd81 100644 --- a/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/ktrng/KillTheRNGHandler.java @@ -58,7 +58,7 @@ public long advanceGlobalSeedServer() { // if (isLoaded()) { // return KillTheRNG.commonRandom.nextSeed(); // } else { - return 0; + return 0; // } } @@ -66,7 +66,7 @@ public long getGlobalSeedServer() { // if (isLoaded()) { // return KillTheRNG.commonRandom.GlobalServer.getSeed(); // } else { - return 0; + return 0; // } } @@ -83,7 +83,7 @@ public long getGlobalSeedClient() { // if (isLoaded()) // return KillTheRNG.clientRandom.GlobalClient.getSeed(); // else - return 0; + return 0; } /** diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/MixinFrustum.java b/src/main/java/com/minecrafttas/tasmod/mixin/MixinFrustum.java index 00c393ad..0a31837f 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/MixinFrustum.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/MixinFrustum.java @@ -26,5 +26,5 @@ public void hacked2(CallbackInfoReturnable cir) { cir.setReturnValue(true); cir.cancel(); } - + } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/events/MixinSaveFormatOld.java b/src/main/java/com/minecrafttas/tasmod/mixin/events/MixinSaveFormatOld.java index f1ab8f2b..1d34af03 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/events/MixinSaveFormatOld.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/events/MixinSaveFormatOld.java @@ -12,7 +12,7 @@ @Mixin(SaveFormatOld.class) public class MixinSaveFormatOld { - + @ModifyArgs(method = "getWorldData", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/datafix/DataFixer;process(Lnet/minecraft/util/datafix/FixTypes;Lnet/minecraft/nbt/NBTTagCompound;)Lnet/minecraft/nbt/NBTTagCompound;")) public NBTTagCompound modifyargs_getWorldData(NBTTagCompound compound) { EventListenerRegistry.fireEvent(EventNBT.EventWorldRead.class, compound); diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/fixes/MixinDragonFightManager.java b/src/main/java/com/minecrafttas/tasmod/mixin/fixes/MixinDragonFightManager.java index 489c91fd..ab75c472 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/fixes/MixinDragonFightManager.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/fixes/MixinDragonFightManager.java @@ -30,4 +30,4 @@ public void fixes_tick(CallbackInfo ci) { } } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGameSettings.java b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGameSettings.java index 7c01c628..08ea5fde 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGameSettings.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGameSettings.java @@ -11,7 +11,7 @@ @Mixin(GameSettings.class) public class MixinGameSettings { - + /** * Redirect Mouse.isButtonDown in keybindings * @param i The keycode diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiChat.java b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiChat.java index c4b0880d..2cb11f5e 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiChat.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiChat.java @@ -1,11 +1,11 @@ package com.minecrafttas.tasmod.mixin.playbackhooks; -import com.minecrafttas.tasmod.virtual.VirtualInput; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.virtual.VirtualInput; import net.minecraft.client.gui.GuiChat; diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiClickableScrolledSelectionListProxy.java b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiClickableScrolledSelectionListProxy.java index bfa57dd3..173ce45c 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiClickableScrolledSelectionListProxy.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiClickableScrolledSelectionListProxy.java @@ -1,17 +1,17 @@ package com.minecrafttas.tasmod.mixin.playbackhooks; -import com.minecrafttas.tasmod.virtual.VirtualInput; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.virtual.VirtualInput; import net.minecraft.client.gui.GuiClickableScrolledSelectionListProxy; @Mixin(GuiClickableScrolledSelectionListProxy.class) public class MixinGuiClickableScrolledSelectionListProxy { - + /** * @return {@link VirtualInput.VirtualMouseInput#getEventMouseState()} */ diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinKeyBinding.java b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinKeyBinding.java index 24ca5c6b..25b1640e 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinKeyBinding.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinKeyBinding.java @@ -1,6 +1,5 @@ package com.minecrafttas.tasmod.mixin.playbackhooks; - import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorAnvilChunkLoader.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorAnvilChunkLoader.java index b3b1eb9e..0f177c6a 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorAnvilChunkLoader.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorAnvilChunkLoader.java @@ -11,7 +11,7 @@ @Mixin(AnvilChunkLoader.class) public interface AccessorAnvilChunkLoader { - + @Accessor - public Map getChunksToSave(); + public Map getChunksToSave(); } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorChunkLoader.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorChunkLoader.java index b9f70691..6c486e46 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorChunkLoader.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorChunkLoader.java @@ -8,7 +8,7 @@ @Mixin(ChunkProviderServer.class) public interface AccessorChunkLoader { - + @Accessor public IChunkLoader getChunkLoader(); } diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorEntityLivingBase.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorEntityLivingBase.java index 271cf872..7bab9e91 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorEntityLivingBase.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorEntityLivingBase.java @@ -1,22 +1,22 @@ -package com.minecrafttas.tasmod.mixin.savestates; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - -import com.minecrafttas.tasmod.savestates.SavestateHandlerClient; - -import net.minecraft.entity.EntityLivingBase; - -@Mixin(EntityLivingBase.class) -public interface AccessorEntityLivingBase { - - /** - *

Clears potion particles. - *

Used to clear potion particles on the client still persisting
- * after loading a savestate across dimensions - * - * @see SavestateHandlerClient#loadPlayer(net.minecraft.nbt.NBTTagCompound) - */ - @Invoker("resetPotionEffectMetadata") - public void clearPotionEffects(); -} +package com.minecrafttas.tasmod.mixin.savestates; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +import com.minecrafttas.tasmod.savestates.SavestateHandlerClient; + +import net.minecraft.entity.EntityLivingBase; + +@Mixin(EntityLivingBase.class) +public interface AccessorEntityLivingBase { + + /** + *

Clears potion particles. + *

Used to clear potion particles on the client still persisting
+ * after loading a savestate across dimensions + * + * @see SavestateHandlerClient#loadPlayer(net.minecraft.nbt.NBTTagCompound) + */ + @Invoker("resetPotionEffectMetadata") + public void clearPotionEffects(); +} diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorPlayerChunkMap.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorPlayerChunkMap.java index bd85e03c..c2791f78 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorPlayerChunkMap.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/AccessorPlayerChunkMap.java @@ -1,22 +1,22 @@ -package com.minecrafttas.tasmod.mixin.savestates; - -import java.util.List; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import com.minecrafttas.tasmod.savestates.handlers.SavestateWorldHandler; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.management.PlayerChunkMap; - -@Mixin(PlayerChunkMap.class) -public interface AccessorPlayerChunkMap { - - /** - * @return The players from the specified chunk map - * @see SavestateWorldHandler#addPlayerToChunkMap() - */ - @Accessor - public List getPlayers(); -} +package com.minecrafttas.tasmod.mixin.savestates; + +import java.util.List; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import com.minecrafttas.tasmod.savestates.handlers.SavestateWorldHandler; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.management.PlayerChunkMap; + +@Mixin(PlayerChunkMap.class) +public interface AccessorPlayerChunkMap { + + /** + * @return The players from the specified chunk map + * @see SavestateWorldHandler#addPlayerToChunkMap() + */ + @Accessor + public List getPlayers(); +} diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinScoreboard.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinScoreboard.java index dc19b8b9..37838649 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinScoreboard.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinScoreboard.java @@ -1,50 +1,50 @@ -package com.minecrafttas.tasmod.mixin.savestates; - -import java.util.List; -import java.util.Map; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -import com.minecrafttas.tasmod.util.Ducks.ScoreboardDuck; - -import net.minecraft.scoreboard.IScoreCriteria; -import net.minecraft.scoreboard.Score; -import net.minecraft.scoreboard.ScoreObjective; -import net.minecraft.scoreboard.ScorePlayerTeam; -import net.minecraft.scoreboard.Scoreboard; - -@Mixin(Scoreboard.class) -public class MixinScoreboard implements ScoreboardDuck { - @Shadow - @Final - private Map scoreObjectives; - @Shadow - @Final - private Map> scoreObjectiveCriterias; - @Shadow - @Final - private Map> entitiesScoreObjectives; - @Shadow - @Final - private ScoreObjective[] objectiveDisplaySlots; - @Shadow - @Final - private Map teams; - @Shadow - @Final - private Map teamMemberships; - - @Override - public void clearScoreboard() { - scoreObjectives.clear(); - scoreObjectiveCriterias.clear(); - entitiesScoreObjectives.clear(); - for (int i = 0; i < objectiveDisplaySlots.length; i++) { - objectiveDisplaySlots[i] = null; - } - teams.clear(); - teamMemberships.clear(); - } -} +package com.minecrafttas.tasmod.mixin.savestates; + +import java.util.List; +import java.util.Map; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import com.minecrafttas.tasmod.util.Ducks.ScoreboardDuck; + +import net.minecraft.scoreboard.IScoreCriteria; +import net.minecraft.scoreboard.Score; +import net.minecraft.scoreboard.ScoreObjective; +import net.minecraft.scoreboard.ScorePlayerTeam; +import net.minecraft.scoreboard.Scoreboard; + +@Mixin(Scoreboard.class) +public class MixinScoreboard implements ScoreboardDuck { + @Shadow + @Final + private Map scoreObjectives; + @Shadow + @Final + private Map> scoreObjectiveCriterias; + @Shadow + @Final + private Map> entitiesScoreObjectives; + @Shadow + @Final + private ScoreObjective[] objectiveDisplaySlots; + @Shadow + @Final + private Map teams; + @Shadow + @Final + private Map teamMemberships; + + @Override + public void clearScoreboard() { + scoreObjectives.clear(); + scoreObjectiveCriterias.clear(); + entitiesScoreObjectives.clear(); + for (int i = 0; i < objectiveDisplaySlots.length; i++) { + objectiveDisplaySlots[i] = null; + } + teams.clear(); + teamMemberships.clear(); + } +} diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinWorldClient.java b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinWorldClient.java index 7027c68a..9e10f126 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinWorldClient.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/savestates/MixinWorldClient.java @@ -1,26 +1,26 @@ -package com.minecrafttas.tasmod.mixin.savestates; - -import java.util.Set; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -import com.minecrafttas.tasmod.util.Ducks.WorldClientDuck; - -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.entity.Entity; - -@Mixin(WorldClient.class) -public class MixinWorldClient implements WorldClientDuck { - - @Shadow - @Final - private Set entityList; - - @Override - public void clearEntityList() { - entityList.clear(); - } - -} +package com.minecrafttas.tasmod.mixin.savestates; + +import java.util.Set; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import com.minecrafttas.tasmod.util.Ducks.WorldClientDuck; + +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.entity.Entity; + +@Mixin(WorldClient.class) +public class MixinWorldClient implements WorldClientDuck { + + @Shadow + @Final + private Set entityList; + + @Override + public void clearEntityList() { + entityList.clear(); + } + +} diff --git a/src/main/java/com/minecrafttas/tasmod/mixin/shields/MixinRenderItem.java b/src/main/java/com/minecrafttas/tasmod/mixin/shields/MixinRenderItem.java index e6941427..f6780e62 100644 --- a/src/main/java/com/minecrafttas/tasmod/mixin/shields/MixinRenderItem.java +++ b/src/main/java/com/minecrafttas/tasmod/mixin/shields/MixinRenderItem.java @@ -14,8 +14,8 @@ @Mixin(RenderItem.class) public class MixinRenderItem { - @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/client/renderer/block/model/ItemCameraTransforms$TransformType;Z)V", at = @At("HEAD")) - public void getAbstractClientPlayer(ItemStack stack, EntityLivingBase entitylivingbaseIn, ItemCameraTransforms.TransformType transform, boolean leftHanded, CallbackInfo ci) { - ShieldDownloader.renderedEntity = entitylivingbaseIn; - } + @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/entity/EntityLivingBase;Lnet/minecraft/client/renderer/block/model/ItemCameraTransforms$TransformType;Z)V", at = @At("HEAD")) + public void getAbstractClientPlayer(ItemStack stack, EntityLivingBase entitylivingbaseIn, ItemCameraTransforms.TransformType transform, boolean leftHanded, CallbackInfo ci) { + ShieldDownloader.renderedEntity = entitylivingbaseIn; + } } diff --git a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java index 82e2b540..5fa93c51 100644 --- a/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java +++ b/src/main/java/com/minecrafttas/tasmod/networking/TASmodBufferBuilder.java @@ -10,7 +10,7 @@ import com.minecrafttas.mctcommon.networking.ByteBufferBuilder; import com.minecrafttas.mctcommon.networking.interfaces.PacketID; import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; -import com.minecrafttas.tasmod.savestates.storage.SavestateMotionStorage.MotionData; +import com.minecrafttas.tasmod.savestates.storage.builtin.SavestateMotionStorage.MotionData; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; import net.minecraft.nbt.CompressedStreamTools; diff --git a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/builtin/DesyncMonitorFileCommandExtension.java b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/builtin/DesyncMonitorFileCommandExtension.java index b035c66a..aa78fc36 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/filecommands/builtin/DesyncMonitorFileCommandExtension.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/filecommands/builtin/DesyncMonitorFileCommandExtension.java @@ -371,4 +371,4 @@ public void onClear() { public void onInputDelete(long index) { monitorContainer.remove(index); } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/tasmod/playback/metadata/PlaybackMetadataRegistry.java b/src/main/java/com/minecrafttas/tasmod/playback/metadata/PlaybackMetadataRegistry.java index f57d2953..c3cc685e 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/metadata/PlaybackMetadataRegistry.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/metadata/PlaybackMetadataRegistry.java @@ -31,29 +31,29 @@ public static void handleOnCreate() { public List handleOnStore() { List metadataList = new ArrayList<>(); - for(PlaybackMetadataExtension extension : REGISTRY.values()) { + for (PlaybackMetadataExtension extension : REGISTRY.values()) { metadataList.add(extension.onStore()); } return metadataList; } public void handleOnLoad(List meta) { - if(meta.isEmpty()) + if (meta.isEmpty()) return; - for(PlaybackMetadata metadata : meta) { - if(REGISTRY.containsKey(metadata.getExtensionName())) { + for (PlaybackMetadata metadata : meta) { + if (REGISTRY.containsKey(metadata.getExtensionName())) { PlaybackMetadataExtension extension = REGISTRY.get(metadata.getExtensionName()); - + extension.onLoad(metadata); } else { TASmod.LOGGER.warn("The metadata extension {} was not found while loading the TASfile. Things might not be correctly loaded!", metadata.getExtensionName()); } } } - + @Override public void onRecordingClear() { - REGISTRY.forEach((key, extension) ->{ + REGISTRY.forEach((key, extension) -> { extension.onClear(); }); } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackLoadException.java b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackLoadException.java index 09bdb9b5..f93e56f8 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackLoadException.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackLoadException.java @@ -3,51 +3,51 @@ import com.minecrafttas.tasmod.TASmod; public class PlaybackLoadException extends RuntimeException { - + public PlaybackLoadException(long line, long tick, int subtick, String msg) { - this(printTick(line, tick, subtick)+msg); + this(printTick(line, tick, subtick) + msg); } - + public PlaybackLoadException(String msg) { super(msg); } - + public PlaybackLoadException(long line, long tick, int subtick, String msg, Object... args) { - this(printTick(line, tick, subtick)+msg, args); + this(printTick(line, tick, subtick) + msg, args); } - + public PlaybackLoadException(String msg, Object... args) { super(String.format(msg, args)); } - + public PlaybackLoadException(long line, long tick, int subtick, Throwable cause) { this(printTick(line, tick, subtick), cause); } - + public PlaybackLoadException(Throwable cause) { super(cause); } public PlaybackLoadException(long line, long tick, int subtick, Throwable cause, String msg) { - this(cause, printTick(line, tick, subtick)+msg); + this(cause, printTick(line, tick, subtick) + msg); } - + public PlaybackLoadException(Throwable cause, String msg) { super(msg, cause, false, false); } - + public PlaybackLoadException(long line, long tick, int subtick, Throwable cause, String msg, Object... args) { - this(cause, printTick(line, tick, subtick)+msg, args); + this(cause, printTick(line, tick, subtick) + msg, args); } - + public PlaybackLoadException(Throwable cause, String msg, Object... args) { this(cause, String.format(msg, args)); } - + private static String printTick(long line, long tick, int subtick) { return String.format("Line %s, Tick %s, Subtick %s: ", line, tick, subtick); } - + @Override public void printStackTrace() { TASmod.LOGGER.catching(this); diff --git a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackSaveException.java b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackSaveException.java index a24f627e..c446113e 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackSaveException.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/exception/PlaybackSaveException.java @@ -9,11 +9,11 @@ public PlaybackSaveException(String msg) { public PlaybackSaveException(String msg, Object... args) { super(String.format(msg, args)); } - + public PlaybackSaveException(Throwable cause, String msg) { super(msg, cause, false, false); } - + public PlaybackSaveException(Throwable cause, String msg, Object... args) { super(cause, String.format(msg, args)); } diff --git a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/flavor/SerialiserFlavorRegistry.java b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/flavor/SerialiserFlavorRegistry.java index f9ad7344..059fae74 100644 --- a/src/main/java/com/minecrafttas/tasmod/playback/tasfile/flavor/SerialiserFlavorRegistry.java +++ b/src/main/java/com/minecrafttas/tasmod/playback/tasfile/flavor/SerialiserFlavorRegistry.java @@ -13,21 +13,21 @@ * * @author Scribble */ -public class SerialiserFlavorRegistry extends AbstractRegistry{ +public class SerialiserFlavorRegistry extends AbstractRegistry { public SerialiserFlavorRegistry() { super("FLAVOR_REGISTRY", new LinkedHashMap<>()); } - - public Set getFlavorNames(){ + + public Set getFlavorNames() { return REGISTRY.keySet(); } - + public SerialiserFlavorBase getFlavor(String name) { SerialiserFlavorBase out = REGISTRY.get(name); return out == null ? null : out.clone(); } - + public List getFlavors() { return new ArrayList<>(REGISTRY.values()); } diff --git a/src/main/java/com/minecrafttas/tasmod/registries/TASmodPackets.java b/src/main/java/com/minecrafttas/tasmod/registries/TASmodPackets.java index cc2fdb26..3e4e392b 100644 --- a/src/main/java/com/minecrafttas/tasmod/registries/TASmodPackets.java +++ b/src/main/java/com/minecrafttas/tasmod/registries/TASmodPackets.java @@ -8,7 +8,7 @@ import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.playback.filecommands.PlaybackFileCommand.PlaybackFileCommandExtension; import com.minecrafttas.tasmod.playback.tasfile.flavor.SerialiserFlavorBase; -import com.minecrafttas.tasmod.savestates.storage.SavestateMotionStorage.MotionData; +import com.minecrafttas.tasmod.savestates.storage.builtin.SavestateMotionStorage.MotionData; import com.minecrafttas.tasmod.tickratechanger.TickrateChangerServer.TickratePauseState; import com.minecrafttas.tasmod.util.Ducks.ScoreboardDuck; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java index c2d1d98d..66ef6b5d 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/SavestateHandlerClient.java @@ -19,8 +19,8 @@ import com.minecrafttas.tasmod.mixin.savestates.MixinChunkProviderClient; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; import com.minecrafttas.tasmod.playback.PlaybackControllerClient; -import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.playback.PlaybackControllerClient.InputContainer; +import com.minecrafttas.tasmod.playback.PlaybackControllerClient.TASstate; import com.minecrafttas.tasmod.playback.tasfile.PlaybackSerialiser; import com.minecrafttas.tasmod.registries.TASmodAPIRegistry; import com.minecrafttas.tasmod.registries.TASmodPackets; diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateTrackerFile.java b/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateTrackerFile.java index 6bec0bb3..bac408d6 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateTrackerFile.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/files/SavestateTrackerFile.java @@ -13,8 +13,7 @@ * */ public class SavestateTrackerFile extends AbstractDataFile { - - + // This shouldn't matter... static is fine! public SavestateTrackerFile(Path saveLocation) throws IOException { diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java index d0619aaa..74f89922 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateLoadingScreen.java @@ -8,9 +8,9 @@ public class GuiSavestateLoadingScreen extends GuiScreen { public GuiSavestateLoadingScreen() { - this.mc=Minecraft.getMinecraft(); + this.mc = Minecraft.getMinecraft(); } - + @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java index 92f16863..c9cfc9e4 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/gui/GuiSavestateSavingScreen.java @@ -10,7 +10,7 @@ public class GuiSavestateSavingScreen extends GuiScreen { public GuiSavestateSavingScreen() { this.mc = Minecraft.getMinecraft(); } - + @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestatePlayerHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestatePlayerHandler.java index cdab03e2..f86923bf 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestatePlayerHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestatePlayerHandler.java @@ -226,4 +226,4 @@ public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws break; } } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestateWorldHandler.java b/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestateWorldHandler.java index c8de811a..ad117d1f 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestateWorldHandler.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/handlers/SavestateWorldHandler.java @@ -246,4 +246,4 @@ public void loadAllWorlds(String string, String string2) { server.setDifficultyForAllWorlds(Minecraft.getMinecraft().gameSettings.difficulty); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/minecrafttas/tasmod/savestates/storage/SavestateMotionStorage.java b/src/main/java/com/minecrafttas/tasmod/savestates/storage/builtin/SavestateMotionStorage.java similarity index 96% rename from src/main/java/com/minecrafttas/tasmod/savestates/storage/SavestateMotionStorage.java rename to src/main/java/com/minecrafttas/tasmod/savestates/storage/builtin/SavestateMotionStorage.java index c79ec326..95e4e935 100644 --- a/src/main/java/com/minecrafttas/tasmod/savestates/storage/SavestateMotionStorage.java +++ b/src/main/java/com/minecrafttas/tasmod/savestates/storage/builtin/SavestateMotionStorage.java @@ -1,287 +1,288 @@ -package com.minecrafttas.tasmod.savestates.storage; - -import static com.minecrafttas.tasmod.TASmod.LOGGER; -import static com.minecrafttas.tasmod.registries.TASmodPackets.SAVESTATE_REQUEST_MOTION; -import static com.minecrafttas.tasmod.registries.TASmodPackets.SAVESTATE_SET_MOTION; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.minecrafttas.mctcommon.networking.Client.Side; -import com.minecrafttas.mctcommon.networking.exception.PacketNotImplementedException; -import com.minecrafttas.mctcommon.networking.exception.WrongSideException; -import com.minecrafttas.mctcommon.networking.interfaces.ClientPacketHandler; -import com.minecrafttas.mctcommon.networking.interfaces.PacketID; -import com.minecrafttas.mctcommon.networking.interfaces.ServerPacketHandler; -import com.minecrafttas.tasmod.TASmod; -import com.minecrafttas.tasmod.TASmodClient; -import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; -import com.minecrafttas.tasmod.registries.TASmodPackets; -import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; -import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; -import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; -import com.minecrafttas.tasmod.savestates.gui.GuiSavestateSavingScreen; -import com.minecrafttas.tasmod.util.LoggerMarkers; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.management.PlayerList; - -public class SavestateMotionStorage extends AbstractExtendStorage implements ClientPacketHandler, ServerPacketHandler { - - private static final Path fileName = Paths.get("clientMotion.json"); - private final Gson json; - - private final Map> futures; - - public SavestateMotionStorage() { - json = new GsonBuilder().setPrettyPrinting().create(); - futures = new HashMap<>(); - } - - @Override - public void onServerSavestate(MinecraftServer server, int index, Path target, Path current) { - LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); - - this.futures.clear(); - - List playerList = server.getPlayerList().getPlayers(); - playerList.forEach(player -> { - futures.put(player, new CompletableFuture<>()); - }); - - try { - // request client motion - TASmod.server.sendToAll(new TASmodBufferBuilder(SAVESTATE_REQUEST_MOTION)); - } catch (Exception e) { - e.printStackTrace(); - } - - JsonObject playerJsonObject = new JsonObject(); - - futures.forEach((player, future) -> { - try { - MotionData data = future.get(5L, TimeUnit.SECONDS); - - String uuid = player.getUniqueID().toString(); - if (player.getName().equals(server.getServerOwner())) { - uuid = "singleplayer"; - } - playerJsonObject.add(uuid, json.toJsonTree(data)); - - } catch (TimeoutException e) { - throw new SavestateException(e, "Writing client motion for %s timed out!", player.getName()); - } catch (ExecutionException | InterruptedException e) { - throw new SavestateException(e, "Writing client motion for %s", player.getName()); - } - }); - - saveJson(current, playerJsonObject); - } - - private void saveJson(Path current, JsonObject data) { - Path saveFile = current.resolve(SavestateHandlerServer.storageDir).resolve(fileName); - - String out = json.toJson(data); - - try { - Files.write(saveFile, out.getBytes()); - } catch (IOException e) { - throw new SavestateException(e, "Could not write to the file system"); - } - } - - @Override - public void onServerLoadstate(MinecraftServer server, int index, Path target, Path current) { - JsonObject playerJsonObject = loadMotionData(target); - PlayerList list = server.getPlayerList(); - - for (Entry motionDataJsonElement : playerJsonObject.entrySet()) { - String playerUUID = motionDataJsonElement.getKey(); - MotionData motionData = json.fromJson(motionDataJsonElement.getValue(), MotionData.class); - - EntityPlayerMP player; - if (playerUUID.equals("singleplayer")) { - String ownerName = server.getServerOwner(); - if (ownerName == null) { - continue; - } - player = list.getPlayerByUsername(ownerName); - } else { - player = list.getPlayerByUUID(UUID.fromString(playerUUID)); - } - - if (player == null) { - continue; - } - - try { - TASmod.server.sendTo(player, new TASmodBufferBuilder(SAVESTATE_SET_MOTION).writeMotionData(motionData)); - } catch (Exception e) { - logger.catching(e); - } - } - } - - private JsonObject loadMotionData(Path target) { - Path saveFile = target.resolve(SavestateHandlerServer.storageDir).resolve(fileName); - String in; - try { - in = new String(Files.readAllBytes(saveFile)); - } catch (IOException e) { - throw new LoadstateException(e, "Could not read from the file system"); - } - return json.fromJson(in, JsonObject.class); - } - - @Override - public PacketID[] getAcceptedPacketIDs() { - return new PacketID[] { SAVESTATE_REQUEST_MOTION, SAVESTATE_SET_MOTION }; - } - - @Environment(EnvType.CLIENT) - @Override - public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { - TASmodPackets packet = (TASmodPackets) id; - Minecraft mc = Minecraft.getMinecraft(); - EntityPlayerSP player = mc.player; - - switch (packet) { - case SAVESTATE_REQUEST_MOTION: - - if (player != null) { - if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) { - mc.displayGuiScreen(new GuiSavestateSavingScreen()); - } - //@formatter:off - MotionData motionData = new MotionData( - player.motionX, - player.motionY, - player.motionZ, - player.moveForward, - player.moveVertical, - player.moveStrafing, - player.isSprinting(), - player.jumpMovementFactor - ); - //@formatter:on - TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_REQUEST_MOTION).writeMotionData(motionData)); - } - break; - case SAVESTATE_SET_MOTION: - LOGGER.trace(LoggerMarkers.Savestate, "Loading client motion"); - - MotionData data = TASmodBufferBuilder.readMotionData(buf); - player.motionX = data.motionX; - player.motionY = data.motionY; - player.motionZ = data.motionZ; - - player.moveForward = data.deltaX; - player.moveVertical = data.deltaY; - player.moveStrafing = data.deltaZ; - - player.setSprinting(data.sprinting); - player.jumpMovementFactor = data.jumpMovementFactor; - break; - default: - break; - } - } - - @Override - public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { - TASmodPackets packet = (TASmodPackets) id; - EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUsername(username); - - switch (packet) { - case SAVESTATE_REQUEST_MOTION: - MotionData data = TASmodBufferBuilder.readMotionData(buf); - CompletableFuture future = this.futures.get(player); - future.complete(data); - break; - case SAVESTATE_SET_MOTION: - throw new WrongSideException(packet, Side.SERVER); - default: - break; - } - } - - public static class MotionData { - - private double motionX; - private double motionY; - private double motionZ; - private float deltaX; - private float deltaY; - private float deltaZ; - private boolean sprinting; - private float jumpMovementFactor; - - public MotionData(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { - motionX = x; - motionY = y; - motionZ = z; - deltaX = rx; - deltaY = ry; - deltaZ = rz; - this.sprinting = sprinting; - this.jumpMovementFactor = jumpMovementVector; - } - - public MotionData() { - this(0D, 0D, 0D, 0f, 0f, 0f, false, 0f); - } - - public double getClientX() { - return motionX; - } - - public double getClientY() { - return motionY; - } - - public double getClientZ() { - return motionZ; - } - - public float getClientrX() { - return deltaX; - } - - public float getClientrY() { - return deltaY; - } - - public float getClientrZ() { - return deltaZ; - } - - public boolean isSprinting() { - return sprinting; - } - - public float getJumpMovementVector() { - return jumpMovementFactor; - } - } -} +package com.minecrafttas.tasmod.savestates.storage.builtin; + +import static com.minecrafttas.tasmod.TASmod.LOGGER; +import static com.minecrafttas.tasmod.registries.TASmodPackets.SAVESTATE_REQUEST_MOTION; +import static com.minecrafttas.tasmod.registries.TASmodPackets.SAVESTATE_SET_MOTION; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.minecrafttas.mctcommon.networking.Client.Side; +import com.minecrafttas.mctcommon.networking.exception.PacketNotImplementedException; +import com.minecrafttas.mctcommon.networking.exception.WrongSideException; +import com.minecrafttas.mctcommon.networking.interfaces.ClientPacketHandler; +import com.minecrafttas.mctcommon.networking.interfaces.PacketID; +import com.minecrafttas.mctcommon.networking.interfaces.ServerPacketHandler; +import com.minecrafttas.tasmod.TASmod; +import com.minecrafttas.tasmod.TASmodClient; +import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; +import com.minecrafttas.tasmod.registries.TASmodPackets; +import com.minecrafttas.tasmod.savestates.SavestateHandlerServer; +import com.minecrafttas.tasmod.savestates.exceptions.LoadstateException; +import com.minecrafttas.tasmod.savestates.exceptions.SavestateException; +import com.minecrafttas.tasmod.savestates.gui.GuiSavestateSavingScreen; +import com.minecrafttas.tasmod.savestates.storage.AbstractExtendStorage; +import com.minecrafttas.tasmod.util.LoggerMarkers; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.management.PlayerList; + +public class SavestateMotionStorage extends AbstractExtendStorage implements ClientPacketHandler, ServerPacketHandler { + + private static final Path fileName = Paths.get("clientMotion.json"); + private final Gson json; + + private final Map> futures; + + public SavestateMotionStorage() { + json = new GsonBuilder().setPrettyPrinting().create(); + futures = new HashMap<>(); + } + + @Override + public void onServerSavestate(MinecraftServer server, int index, Path target, Path current) { + LOGGER.trace(LoggerMarkers.Savestate, "Request motion from client"); + + this.futures.clear(); + + List playerList = server.getPlayerList().getPlayers(); + playerList.forEach(player -> { + futures.put(player, new CompletableFuture<>()); + }); + + try { + // request client motion + TASmod.server.sendToAll(new TASmodBufferBuilder(SAVESTATE_REQUEST_MOTION)); + } catch (Exception e) { + e.printStackTrace(); + } + + JsonObject playerJsonObject = new JsonObject(); + + futures.forEach((player, future) -> { + try { + MotionData data = future.get(5L, TimeUnit.SECONDS); + + String uuid = player.getUniqueID().toString(); + if (player.getName().equals(server.getServerOwner())) { + uuid = "singleplayer"; + } + playerJsonObject.add(uuid, json.toJsonTree(data)); + + } catch (TimeoutException e) { + throw new SavestateException(e, "Writing client motion for %s timed out!", player.getName()); + } catch (ExecutionException | InterruptedException e) { + throw new SavestateException(e, "Writing client motion for %s", player.getName()); + } + }); + + saveJson(current, playerJsonObject); + } + + private void saveJson(Path current, JsonObject data) { + Path saveFile = current.resolve(SavestateHandlerServer.storageDir).resolve(fileName); + + String out = json.toJson(data); + + try { + Files.write(saveFile, out.getBytes()); + } catch (IOException e) { + throw new SavestateException(e, "Could not write to the file system"); + } + } + + @Override + public void onServerLoadstate(MinecraftServer server, int index, Path target, Path current) { + JsonObject playerJsonObject = loadMotionData(target); + PlayerList list = server.getPlayerList(); + + for (Entry motionDataJsonElement : playerJsonObject.entrySet()) { + String playerUUID = motionDataJsonElement.getKey(); + MotionData motionData = json.fromJson(motionDataJsonElement.getValue(), MotionData.class); + + EntityPlayerMP player; + if (playerUUID.equals("singleplayer")) { + String ownerName = server.getServerOwner(); + if (ownerName == null) { + continue; + } + player = list.getPlayerByUsername(ownerName); + } else { + player = list.getPlayerByUUID(UUID.fromString(playerUUID)); + } + + if (player == null) { + continue; + } + + try { + TASmod.server.sendTo(player, new TASmodBufferBuilder(SAVESTATE_SET_MOTION).writeMotionData(motionData)); + } catch (Exception e) { + logger.catching(e); + } + } + } + + private JsonObject loadMotionData(Path target) { + Path saveFile = target.resolve(SavestateHandlerServer.storageDir).resolve(fileName); + String in; + try { + in = new String(Files.readAllBytes(saveFile)); + } catch (IOException e) { + throw new LoadstateException(e, "Could not read from the file system"); + } + return json.fromJson(in, JsonObject.class); + } + + @Override + public PacketID[] getAcceptedPacketIDs() { + return new PacketID[] { SAVESTATE_REQUEST_MOTION, SAVESTATE_SET_MOTION }; + } + + @Environment(EnvType.CLIENT) + @Override + public void onClientPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + Minecraft mc = Minecraft.getMinecraft(); + EntityPlayerSP player = mc.player; + + switch (packet) { + case SAVESTATE_REQUEST_MOTION: + + if (player != null) { + if (!(mc.currentScreen instanceof GuiSavestateSavingScreen)) { + mc.displayGuiScreen(new GuiSavestateSavingScreen()); + } + //@formatter:off + MotionData motionData = new MotionData( + player.motionX, + player.motionY, + player.motionZ, + player.moveForward, + player.moveVertical, + player.moveStrafing, + player.isSprinting(), + player.jumpMovementFactor + ); + //@formatter:on + TASmodClient.client.send(new TASmodBufferBuilder(TASmodPackets.SAVESTATE_REQUEST_MOTION).writeMotionData(motionData)); + } + break; + case SAVESTATE_SET_MOTION: + LOGGER.trace(LoggerMarkers.Savestate, "Loading client motion"); + + MotionData data = TASmodBufferBuilder.readMotionData(buf); + player.motionX = data.motionX; + player.motionY = data.motionY; + player.motionZ = data.motionZ; + + player.moveForward = data.deltaX; + player.moveVertical = data.deltaY; + player.moveStrafing = data.deltaZ; + + player.setSprinting(data.sprinting); + player.jumpMovementFactor = data.jumpMovementFactor; + break; + default: + break; + } + } + + @Override + public void onServerPacket(PacketID id, ByteBuffer buf, String username) throws PacketNotImplementedException, WrongSideException, Exception { + TASmodPackets packet = (TASmodPackets) id; + EntityPlayerMP player = TASmod.getServerInstance().getPlayerList().getPlayerByUsername(username); + + switch (packet) { + case SAVESTATE_REQUEST_MOTION: + MotionData data = TASmodBufferBuilder.readMotionData(buf); + CompletableFuture future = this.futures.get(player); + future.complete(data); + break; + case SAVESTATE_SET_MOTION: + throw new WrongSideException(packet, Side.SERVER); + default: + break; + } + } + + public static class MotionData { + + private double motionX; + private double motionY; + private double motionZ; + private float deltaX; + private float deltaY; + private float deltaZ; + private boolean sprinting; + private float jumpMovementFactor; + + public MotionData(double x, double y, double z, float rx, float ry, float rz, boolean sprinting, float jumpMovementVector) { + motionX = x; + motionY = y; + motionZ = z; + deltaX = rx; + deltaY = ry; + deltaZ = rz; + this.sprinting = sprinting; + this.jumpMovementFactor = jumpMovementVector; + } + + public MotionData() { + this(0D, 0D, 0D, 0f, 0f, 0f, false, 0f); + } + + public double getClientX() { + return motionX; + } + + public double getClientY() { + return motionY; + } + + public double getClientZ() { + return motionZ; + } + + public float getClientrX() { + return deltaX; + } + + public float getClientrY() { + return deltaY; + } + + public float getClientrZ() { + return deltaZ; + } + + public boolean isSprinting() { + return sprinting; + } + + public float getJumpMovementVector() { + return jumpMovementFactor; + } + } +} diff --git a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java index 27fc8df3..bd871be9 100644 --- a/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java +++ b/src/main/java/com/minecrafttas/tasmod/ticksync/TickSyncServer.java @@ -1,6 +1,5 @@ package com.minecrafttas.tasmod.ticksync; - import static com.minecrafttas.tasmod.TASmod.LOGGER; import java.nio.ByteBuffer; @@ -25,14 +24,14 @@ * @see TickSyncClient */ public class TickSyncServer implements ServerPacketHandler, EventServerTickPost, EventClientCompleteAuthentication { - + private static List synchronizedList = Collections.synchronizedList(new ArrayList<>()); - + private boolean enabled = true; @Override public PacketID[] getAcceptedPacketIDs() { - return new TASmodPackets[]{TASmodPackets.TICKSYNC}; + return new TASmodPackets[] { TASmodPackets.TICKSYNC }; } /** @@ -46,11 +45,11 @@ public PacketID[] getAcceptedPacketIDs() { @Override public void onServerPacket(PacketID id, ByteBuffer buf, String username) { synchronized (synchronizedList) { - if(!synchronizedList.contains(username)) { + if (!synchronizedList.contains(username)) { synchronizedList.add(username); } } - if(TASmod.getServerInstance()==null) { // If the server is null, keep the clients ticking + if (TASmod.getServerInstance() == null) { // If the server is null, keep the clients ticking sendToClients(); } } @@ -59,14 +58,14 @@ public boolean shouldTick() { synchronized (synchronizedList) { int acknowledged = synchronizedList.size(); int totalConnections = TASmod.server.getClients().size(); - if(acknowledged >= totalConnections) { + if (acknowledged >= totalConnections) { return true; - }else { + } else { return false; } } } - + public static void clearList() { synchronizedList.clear(); } @@ -80,21 +79,21 @@ public void onServerTickPost(MinecraftServer server) { public void onClientCompleteAuthentication(String username) { sendToClients(); } - + private void sendToClients() { try { TASmod.server.sendToAll(new TASmodBufferBuilder(TASmodPackets.TICKSYNC)); } catch (Exception e) { LOGGER.error("Unable to send packet to all clients:", e); } - if(synchronizedList.size()>0) + if (synchronizedList.size() > 0) synchronizedList.clear(); } public boolean isEnabled() { return enabled; } - + public void setEnabled(boolean enabled) { this.enabled = enabled; } diff --git a/src/main/java/com/minecrafttas/tasmod/util/TrajectoriesCalculator.java b/src/main/java/com/minecrafttas/tasmod/util/TrajectoriesCalculator.java index 43274a4a..82b4dce2 100644 --- a/src/main/java/com/minecrafttas/tasmod/util/TrajectoriesCalculator.java +++ b/src/main/java/com/minecrafttas/tasmod/util/TrajectoriesCalculator.java @@ -11,71 +11,64 @@ public class TrajectoriesCalculator { public static Vec3d calculate() { - + EntityPlayerSP player = Minecraft.getMinecraft().player; - + // check if player is holding item ItemStack stack = player.inventory.getCurrentItem(); - if(stack == null) + if (stack == null) return null; - + boolean usingBow = stack.getItem() instanceof ItemBow; - + // calculate starting position double arrowPosX = player.lastTickPosX - + (player.posX - player.lastTickPosX) * Minecraft.getMinecraft().timer.renderPartialTicks - - Math.cos((float)Math.toRadians(player.rotationYaw)) * 0.16F; + + (player.posX - player.lastTickPosX) * Minecraft.getMinecraft().timer.renderPartialTicks + - Math.cos((float) Math.toRadians(player.rotationYaw)) * 0.16F; double arrowPosY = player.lastTickPosY - + (player.posY - player.lastTickPosY) - * Minecraft.getMinecraft().timer.renderPartialTicks - + player.getEyeHeight() - 0.1; + + (player.posY - player.lastTickPosY) + * Minecraft.getMinecraft().timer.renderPartialTicks + + player.getEyeHeight() - 0.1; double arrowPosZ = player.lastTickPosZ - + (player.posZ - player.lastTickPosZ) - * Minecraft.getMinecraft().timer.renderPartialTicks - - Math.sin((float)Math.toRadians(player.rotationYaw)) * 0.16F; - + + (player.posZ - player.lastTickPosZ) + * Minecraft.getMinecraft().timer.renderPartialTicks + - Math.sin((float) Math.toRadians(player.rotationYaw)) * 0.16F; + // calculate starting motion float arrowMotionFactor = usingBow ? 1F : 0.4F; - float yaw = (float)Math.toRadians(player.rotationYaw); - float pitch = (float)Math.toRadians(player.rotationPitch); - double arrowMotionX = - -Math.sin(yaw) * Math.cos(pitch) * arrowMotionFactor; + float yaw = (float) Math.toRadians(player.rotationYaw); + float pitch = (float) Math.toRadians(player.rotationPitch); + double arrowMotionX = -Math.sin(yaw) * Math.cos(pitch) * arrowMotionFactor; double arrowMotionY = -Math.sin(pitch) * arrowMotionFactor; - double arrowMotionZ = - Math.cos(yaw) * Math.cos(pitch) * arrowMotionFactor; + double arrowMotionZ = Math.cos(yaw) * Math.cos(pitch) * arrowMotionFactor; double arrowMotion = Math.sqrt(arrowMotionX * arrowMotionX - + arrowMotionY * arrowMotionY + arrowMotionZ * arrowMotionZ); + + arrowMotionY * arrowMotionY + arrowMotionZ * arrowMotionZ); arrowMotionX /= arrowMotion; arrowMotionY /= arrowMotion; arrowMotionZ /= arrowMotion; - if(usingBow) - { + if (usingBow) { float bowPower = (72000 - player.getItemInUseCount()) / 20F; bowPower = (bowPower * bowPower + bowPower * 2F) / 3F; - - if(bowPower > 1F || bowPower <= 0.1F) + + if (bowPower > 1F || bowPower <= 0.1F) bowPower = 1F; - + bowPower *= 3F; arrowMotionX *= bowPower; arrowMotionY *= bowPower; arrowMotionZ *= bowPower; - - }else - { + + } else { arrowMotionX *= 1.5D; arrowMotionY *= 1.5D; arrowMotionZ *= 1.5D; } - - double gravity = - usingBow ? 0.05D : stack.getItem() instanceof ItemPotion ? 0.4D - : stack.getItem() instanceof ItemFishingRod ? 0.15D : 0.03D; - Vec3d playerVector = new Vec3d(player.posX, - player.posY + player.getEyeHeight(), player.posZ); - - for(int i = 0; i < 1000; i++) { - + + double gravity = usingBow ? 0.05D : stack.getItem() instanceof ItemPotion ? 0.4D : stack.getItem() instanceof ItemFishingRod ? 0.15D : 0.03D; + Vec3d playerVector = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); + + for (int i = 0; i < 1000; i++) { + arrowPosX += arrowMotionX * 0.1; arrowPosY += arrowMotionY * 0.1; arrowPosZ += arrowMotionZ * 0.1; @@ -83,13 +76,12 @@ public static Vec3d calculate() { arrowMotionY *= 0.999D; arrowMotionZ *= 0.999D; arrowMotionY -= gravity * 0.1; - - if(Minecraft.getMinecraft().world.rayTraceBlocks(playerVector, - new Vec3d(arrowPosX, arrowPosY, arrowPosZ)) != null) + + if (Minecraft.getMinecraft().world.rayTraceBlocks(playerVector, new Vec3d(arrowPosX, arrowPosY, arrowPosZ)) != null) break; } - + return new Vec3d(arrowPosX, arrowPosY, arrowPosZ); } - + } diff --git a/src/main/java/com/minecrafttas/tasmod/virtual/event/VirtualKeyboardEvent.java b/src/main/java/com/minecrafttas/tasmod/virtual/event/VirtualKeyboardEvent.java index 3ad0e7c0..6139ec67 100644 --- a/src/main/java/com/minecrafttas/tasmod/virtual/event/VirtualKeyboardEvent.java +++ b/src/main/java/com/minecrafttas/tasmod/virtual/event/VirtualKeyboardEvent.java @@ -6,32 +6,32 @@ * @author Scribble */ public class VirtualKeyboardEvent extends VirtualEvent { - private final char character; + private final char character; - public VirtualKeyboardEvent(){ - this(0, false, Character.MIN_VALUE); - } + public VirtualKeyboardEvent() { + this(0, false, Character.MIN_VALUE); + } - public VirtualKeyboardEvent(int keycode, boolean keystate, char character) { - super(keycode, keystate); - this.character = character; - } + public VirtualKeyboardEvent(int keycode, boolean keystate, char character) { + super(keycode, keystate); + this.character = character; + } - public char getCharacter() { - return character; - } + public char getCharacter() { + return character; + } - @Override - public String toString() { - return String.format("%s, %s", super.toString(), character); - } + @Override + public String toString() { + return String.format("%s, %s", super.toString(), character); + } - @Override - public boolean equals(Object obj) { - if(obj instanceof VirtualKeyboardEvent){ - VirtualKeyboardEvent e = (VirtualKeyboardEvent) obj; - return keycode == e.keycode && keystate == e.keystate && character == e.character; - } - return super.equals(obj); - } + @Override + public boolean equals(Object obj) { + if (obj instanceof VirtualKeyboardEvent) { + VirtualKeyboardEvent e = (VirtualKeyboardEvent) obj; + return keycode == e.keycode && keystate == e.keystate && character == e.character; + } + return super.equals(obj); + } } diff --git a/src/test/java/mctcommon/event/EventTest.java b/src/test/java/mctcommon/event/EventTest.java index fa0eeec5..ee4eb3af 100644 --- a/src/test/java/mctcommon/event/EventTest.java +++ b/src/test/java/mctcommon/event/EventTest.java @@ -1,166 +1,167 @@ package mctcommon.event; -import com.minecrafttas.mctcommon.events.EventException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import com.minecrafttas.mctcommon.events.EventException; import com.minecrafttas.mctcommon.events.EventListenerRegistry; import com.minecrafttas.mctcommon.events.EventListenerRegistry.EventBase; -import static org.junit.jupiter.api.Assertions.*; - public class EventTest { - @FunctionalInterface - private interface TestEvent extends EventBase { + @FunctionalInterface + private interface TestEvent extends EventBase { - public int onTestEvent(); + public int onTestEvent(); - } + } - @FunctionalInterface - private interface AdditionEvent extends EventBase { + @FunctionalInterface + private interface AdditionEvent extends EventBase { - public int onAdditionEvent(int left, int right); + public int onAdditionEvent(int left, int right); - } + } - @AfterEach - void afterEach() { - EventListenerRegistry.clear(); - } + @AfterEach + void afterEach() { + EventListenerRegistry.clear(); + } - /** - * Registers an event which returns 5 - */ - @Test - void testSimpleEvent() { - TestEvent event = () -> 5; + /** + * Registers an event which returns 5 + */ + @Test + void testSimpleEvent() { + TestEvent event = () -> 5; - EventListenerRegistry.register(event); + EventListenerRegistry.register(event); - int actual = (int) EventListenerRegistry.fireEvent(TestEvent.class); - assertEquals(5, actual); - } + int actual = (int) EventListenerRegistry.fireEvent(TestEvent.class); + assertEquals(5, actual); + } - /** - * Test event with parameters - */ - @Test - void testParameterEvent() { - AdditionEvent event = Integer::sum; + /** + * Test event with parameters + */ + @Test + void testParameterEvent() { + AdditionEvent event = Integer::sum; - EventListenerRegistry.register(event); + EventListenerRegistry.register(event); - int actual = (int) EventListenerRegistry.fireEvent(AdditionEvent.class, 3, 6); + int actual = (int) EventListenerRegistry.fireEvent(AdditionEvent.class, 3, 6); - assertEquals(9, actual); - } + assertEquals(9, actual); + } - /** - * Test event with parameters, but too few parameters are fired - */ - @Test - void testParameterEventTooFew() { - AdditionEvent event = Integer::sum; + /** + * Test event with parameters, but too few parameters are fired + */ + @Test + void testParameterEventTooFew() { + AdditionEvent event = Integer::sum; - EventListenerRegistry.register(event); + EventListenerRegistry.register(event); - Exception exception = assertThrows(EventException.class, () -> { - EventListenerRegistry.fireEvent(AdditionEvent.class, 3); - }); + Exception exception = assertThrows(EventException.class, () -> { + EventListenerRegistry.fireEvent(AdditionEvent.class, 3); + }); - String expected = "mctcommon.event.EventTest$AdditionEvent: Event fired with the wrong number of parameters. Expected: 2, Actual: 1"; - assertEquals(expected, exception.getMessage()); - } + String expected = "mctcommon.event.EventTest$AdditionEvent: Event fired with the wrong number of parameters. Expected: 2, Actual: 1"; + assertEquals(expected, exception.getMessage()); + } - /** - * Test event with parameters, but too many parameters are fired - */ - @Test - void testParameterEventTooMany() { - AdditionEvent event = new AdditionEvent() { - @Override - public int onAdditionEvent(int left, int right) { - return left + right; - } - }; + /** + * Test event with parameters, but too many parameters are fired + */ + @Test + void testParameterEventTooMany() { + AdditionEvent event = new AdditionEvent() { + @Override + public int onAdditionEvent(int left, int right) { + return left + right; + } + }; - EventListenerRegistry.register(event); + EventListenerRegistry.register(event); - Exception exception = assertThrows(EventException.class, () -> { - EventListenerRegistry.fireEvent(AdditionEvent.class, 3, 1, 3); - }); + Exception exception = assertThrows(EventException.class, () -> { + EventListenerRegistry.fireEvent(AdditionEvent.class, 3, 1, 3); + }); - String expected = "mctcommon.event.EventTest$AdditionEvent: Event fired with the wrong number of parameters. Expected: 2, Actual: 3"; - assertEquals(expected, exception.getMessage()); - } + String expected = "mctcommon.event.EventTest$AdditionEvent: Event fired with the wrong number of parameters. Expected: 2, Actual: 3"; + assertEquals(expected, exception.getMessage()); + } - /** - * Test multiple return values - */ - @Test - void testMultipleReturnValues() { - TestEvent event = () -> 5; - TestEvent event2 = () -> 7; + /** + * Test multiple return values + */ + @Test + void testMultipleReturnValues() { + TestEvent event = () -> 5; + TestEvent event2 = () -> 7; - EventListenerRegistry.register(event); - EventListenerRegistry.register(event2); + EventListenerRegistry.register(event); + EventListenerRegistry.register(event2); - int actual = (int) EventListenerRegistry.fireEvent(TestEvent.class); - assertEquals(7, actual); - } + int actual = (int) EventListenerRegistry.fireEvent(TestEvent.class); + assertEquals(7, actual); + } - /** - * Tests a class which has an additional method with the same name but different parameters - */ - @Test - void testEventMethodwithSameName() { + /** + * Tests a class which has an additional method with the same name but different parameters + */ + @Test + void testEventMethodwithSameName() { - class TestClass implements TestEvent { + class TestClass implements TestEvent { - @Override - public int onTestEvent() { - return 1; - } - } + @Override + public int onTestEvent() { + return 1; + } + } - TestClass test = new TestClass(); - - EventListenerRegistry.register(test); + TestClass test = new TestClass(); + + EventListenerRegistry.register(test); - int actual = (int) EventListenerRegistry.fireEvent(TestEvent.class); - - assertEquals(1, actual); - } + int actual = (int) EventListenerRegistry.fireEvent(TestEvent.class); + + assertEquals(1, actual); + } - /** - * Test mismatched types - */ - @Test - void testParameterEventWrongTypes() { - AdditionEvent event = Integer::sum; + /** + * Test mismatched types + */ + @Test + void testParameterEventWrongTypes() { + AdditionEvent event = Integer::sum; - EventListenerRegistry.register(event); + EventListenerRegistry.register(event); - Exception exception = assertThrows(EventException.class, () -> EventListenerRegistry.fireEvent(AdditionEvent.class, 3, 6D)); + Exception exception = assertThrows(EventException.class, () -> EventListenerRegistry.fireEvent(AdditionEvent.class, 3, 6D)); - String expected = "mctcommon.event.EventTest$AdditionEvent: Event seems to be fired with the wrong parameter types or in the wrong order"; - assertEquals(expected, exception.getMessage()); - } + String expected = "mctcommon.event.EventTest$AdditionEvent: Event seems to be fired with the wrong parameter types or in the wrong order"; + assertEquals(expected, exception.getMessage()); + } - /** - * Test unregistering eventlistener - */ - @Test - void testUnregister() { - TestEvent event = () -> 5; - - EventListenerRegistry.register(event); - - EventListenerRegistry.unregister(event); - - EventListenerRegistry.fireEvent(TestEvent.class); - return; - } + /** + * Test unregistering eventlistener + */ + @Test + void testUnregister() { + TestEvent event = () -> 5; + + EventListenerRegistry.register(event); + + EventListenerRegistry.unregister(event); + + EventListenerRegistry.fireEvent(TestEvent.class); + return; + } } diff --git a/src/test/java/mctcommon/server/ByteBufferBuilderTest.java b/src/test/java/mctcommon/server/ByteBufferBuilderTest.java index dc3f5f02..901052f4 100644 --- a/src/test/java/mctcommon/server/ByteBufferBuilderTest.java +++ b/src/test/java/mctcommon/server/ByteBufferBuilderTest.java @@ -11,13 +11,12 @@ import org.junit.jupiter.api.Test; import com.minecrafttas.mctcommon.networking.ByteBufferBuilder; -import com.minecrafttas.mctcommon.networking.CompactPacketHandler; import com.minecrafttas.mctcommon.networking.Client.Side; +import com.minecrafttas.mctcommon.networking.CompactPacketHandler; import com.minecrafttas.mctcommon.networking.interfaces.PacketID; class ByteBufferBuilderTest { - private enum TestPacketIDs implements PacketID { TESTID_1, TESTID_2, @@ -28,12 +27,12 @@ private enum TestPacketIDs implements PacketID { private TestPacketIDs() { } - + private TestPacketIDs(Side side, CompactPacketHandler lambda) { this.side = side; this.lambda = lambda; } - + @Override public int getID() { return this.ordinal(); @@ -63,9 +62,9 @@ public boolean shouldTrace() { public String getExtensionName() { return "TestPackets"; } - + } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting the packetid */ @@ -74,7 +73,7 @@ void testId() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); ByteBuffer buf = builder.build(); buf.position(0); - + assertEquals(0, buf.getInt()); } @@ -86,10 +85,10 @@ void testId2() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_2); ByteBuffer buf = builder.build(); buf.position(0); - + assertEquals(1, buf.getInt()); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting the packetid */ @@ -98,162 +97,162 @@ void testId3() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_3); ByteBuffer buf = builder.build(); buf.position(0); - + assertEquals(2, buf.getInt()); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting an integer */ @Test void testInt() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeInt(1234); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals(1234, ByteBufferBuilder.readInt(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a float */ @Test void testFloat() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeFloat(12.2F); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals(12.2F, ByteBufferBuilder.readFloat(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a double */ @Test void testDouble() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeDouble(60.9D); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals(60.9D, ByteBufferBuilder.readDouble(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a long */ @Test void testLong() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeLong(800815L); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals(800815L, ByteBufferBuilder.readLong(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a short */ @Test void testShort() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - - builder.writeShort((short)12); - + + builder.writeShort((short) 12); + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals(12, ByteBufferBuilder.readShort(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a boolean */ @Test void testBoolean() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeBoolean(true); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals(true, ByteBufferBuilder.readBoolean(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a boolean */ @Test void testBoolean2() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeBoolean(false); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals(false, ByteBufferBuilder.readBoolean(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a string */ @Test void testString() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeString("Test"); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals("Test", ByteBufferBuilder.readString(buf)); } - + /** * Test */ @Test void testByteArray() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - - builder.writeByteArray(new byte[] {1,1,0,0,1,1,0}); - + + builder.writeByteArray(new byte[] { 1, 1, 0, 0, 1, 1, 0 }); + ByteBuffer buf = builder.build(); buf.position(4); - - assertArrayEquals(new byte[] {1,1,0,0,1,1,0}, ByteBufferBuilder.readByteArray(buf)); + + assertArrayEquals(new byte[] { 1, 1, 0, 0, 1, 1, 0 }, ByteBufferBuilder.readByteArray(buf)); } - + /** * Test creating a new ByteBuffer from a ByteBufferbuilder and getting a uuid */ @Test void testUUID() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); - + builder.writeUUID(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8")); - + ByteBuffer buf = builder.build(); buf.position(4); - + assertEquals("b8abdafc-5002-40df-ab68-63206ea4c7e8", ByteBufferBuilder.readUUID(buf).toString()); } - + // ==================================== - + /** * Test creating a clone from an existing ByteBufferBuilder */ @@ -261,7 +260,7 @@ void testUUID() { void testClone() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); builder.writeInt(1234); - + ByteBufferBuilder clone; try { clone = builder.clone(); @@ -269,15 +268,15 @@ void testClone() { fail(e); return; } - + ByteBuffer buf = clone.build(); buf.position(4); - + assertEquals(1234, ByteBufferBuilder.readInt(buf)); } - + // ===================================== - + /** * Test an exception for all types if a ByteBufferBuilder is already closed */ @@ -286,43 +285,43 @@ void testClosed() { ByteBufferBuilder builder = new ByteBufferBuilder(TestPacketIDs.TESTID_1); builder.close(); builder.close(); - + Exception exception; - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeInt(0); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeDouble(0D); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeFloat(0F); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeLong(0L); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeShort((short)0); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeBoolean(true); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeString(""); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.writeUUID(UUID.randomUUID()); - }); - assertEquals("This buffer is already closed", exception.getMessage()); - exception = assertThrows(IllegalStateException.class, () -> { - builder.build(); - }); - assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeInt(0); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeDouble(0D); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeFloat(0F); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeLong(0L); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeShort((short) 0); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeBoolean(true); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeString(""); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.writeUUID(UUID.randomUUID()); + }); + assertEquals("This buffer is already closed", exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { + builder.build(); + }); + assertEquals("This buffer is already closed", exception.getMessage()); } } diff --git a/src/test/java/mctcommon/server/ServerTest.java b/src/test/java/mctcommon/server/ServerTest.java index a2b46cd3..9d8e81c5 100644 --- a/src/test/java/mctcommon/server/ServerTest.java +++ b/src/test/java/mctcommon/server/ServerTest.java @@ -17,10 +17,10 @@ import com.minecrafttas.mctcommon.networking.ByteBufferBuilder; import com.minecrafttas.mctcommon.networking.Client; +import com.minecrafttas.mctcommon.networking.Client.Side; import com.minecrafttas.mctcommon.networking.CompactPacketHandler; import com.minecrafttas.mctcommon.networking.PacketHandlerRegistry; import com.minecrafttas.mctcommon.networking.Server; -import com.minecrafttas.mctcommon.networking.Client.Side; import com.minecrafttas.mctcommon.networking.exception.PacketNotImplementedException; import com.minecrafttas.mctcommon.networking.exception.WrongSideException; import com.minecrafttas.mctcommon.networking.interfaces.ClientPacketHandler; diff --git a/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java index 34a18a8b..b377af76 100644 --- a/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java +++ b/src/test/java/tasmod/networking/TASmodByteBufferBuilderTest.java @@ -10,8 +10,8 @@ import org.junit.jupiter.api.Test; -import com.minecrafttas.mctcommon.networking.CompactPacketHandler; import com.minecrafttas.mctcommon.networking.Client.Side; +import com.minecrafttas.mctcommon.networking.CompactPacketHandler; import com.minecrafttas.mctcommon.networking.interfaces.PacketID; import com.minecrafttas.tasmod.networking.TASmodBufferBuilder; @@ -27,12 +27,12 @@ private enum TestPacketIDs implements PacketID { private TestPacketIDs() { } - + private TestPacketIDs(Side side, CompactPacketHandler lambda) { this.side = side; this.lambda = lambda; } - + @Override public int getID() { return this.ordinal(); @@ -62,38 +62,38 @@ public boolean shouldTrace() { public String getExtensionName() { return "TestPacketIds"; } - + } - + /** * Test if NBTTagCompounds get correctly stored in a ByteBuffer */ @Test void testNBT() { - + NBTTagCompound tag = new NBTTagCompound(); NBTTagCompound tag2 = new NBTTagCompound(); - + tag.setString("String", "What"); tag.setShort("Short", (short) 3); tag.setLong("Long", 8008132L); tag.setInteger("Int", -5); - tag.setIntArray("IntArray", new int[] {1, 2, 3}); + tag.setIntArray("IntArray", new int[] { 1, 2, 3 }); tag.setDouble("Double", 1.2D); tag.setByte("Byte", (byte) 1); tag.setUniqueId("UUID", UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8")); tag.setFloat("Float", 1.0F); tag.setBoolean("Boolean", true); - tag.setByteArray("ByteArray", new byte[] {1, 0, 0}); - + tag.setByteArray("ByteArray", new byte[] { 1, 0, 0 }); + tag2.setTag("Data", tag); - + TASmodBufferBuilder bufferBuilder = new TASmodBufferBuilder(TestPacketIDs.TESTID_1).writeNBTTagCompound(tag2); - + ByteBuffer buf = bufferBuilder.build(); - + buf.position(4); - + NBTTagCompound tag3 = null; try { tag3 = TASmodBufferBuilder.readNBTTagCompound(buf); @@ -101,20 +101,20 @@ void testNBT() { fail(e); return; } - + NBTTagCompound tag4 = tag3.getCompoundTag("Data"); - + assertEquals("What", tag4.getString("String")); - assertEquals((short)3, tag4.getShort("Short")); + assertEquals((short) 3, tag4.getShort("Short")); assertEquals(8008132L, tag4.getLong("Long")); assertEquals(-5, tag4.getInteger("Int")); - assertArrayEquals(new int[] {1, 2, 3}, tag4.getIntArray("IntArray")); + assertArrayEquals(new int[] { 1, 2, 3 }, tag4.getIntArray("IntArray")); assertEquals(1.2D, tag4.getDouble("Double")); assertEquals((byte) 1, tag4.getByte("Byte")); assertEquals(UUID.fromString("b8abdafc-5002-40df-ab68-63206ea4c7e8"), tag4.getUniqueId("UUID")); assertEquals(1.0F, tag4.getFloat("Float")); assertEquals(true, tag4.getBoolean("Boolean")); - assertArrayEquals(new byte[] {1, 0, 0}, tag4.getByteArray("ByteArray")); + assertArrayEquals(new byte[] { 1, 0, 0 }, tag4.getByteArray("ByteArray")); } } diff --git a/src/test/java/tasmod/playback/metadata/PlaybackMetadataTest.java b/src/test/java/tasmod/playback/metadata/PlaybackMetadataTest.java index bbb7e94e..06f1bdb9 100644 --- a/src/test/java/tasmod/playback/metadata/PlaybackMetadataTest.java +++ b/src/test/java/tasmod/playback/metadata/PlaybackMetadataTest.java @@ -15,7 +15,7 @@ public class PlaybackMetadataTest { - class MetadataTest extends PlaybackMetadataExtension{ + class MetadataTest extends PlaybackMetadataExtension { @Override public String getExtensionName() { @@ -24,7 +24,7 @@ public String getExtensionName() { @Override public void onCreate() { - + } @Override @@ -39,9 +39,9 @@ public void onLoad(PlaybackMetadata metadata) { @Override public void onClear() { } - + } - + @Test void testConstructor() { MetadataTest test = new MetadataTest(); @@ -49,18 +49,18 @@ void testConstructor() { assertNotNull(metadata.getData()); assertEquals("Test", metadata.getExtensionName()); } - + @Test void testSettingAndReading() { MetadataTest test = new MetadataTest(); PlaybackMetadata metadata = new PlaybackMetadata(test); metadata.setValue("testProperty", "Test"); - + String actual = metadata.getValue("testProperty"); - + assertEquals("Test", actual); } - + @Test void testToString() { MetadataTest test = new MetadataTest(); @@ -69,17 +69,17 @@ void testToString() { metadata.setValue("2", "Two"); metadata.setValue("3", "Three"); metadata.setValue("4", "Four"); - + String actual = metadata.toString(); - + String expected = "1:One\n" + "2:Two\n" + "3:Three\n" + "4:Four\n"; - + assertEquals(expected, actual); } - + @Test void testToStringList() { MetadataTest test = new MetadataTest(); @@ -88,18 +88,18 @@ void testToStringList() { metadata.setValue("2", "Two"); metadata.setValue("3", "Three"); metadata.setValue("4", "Four"); - + List actual = metadata.toStringList(); - + List expected = new ArrayList<>(); expected.add("1:One\n"); expected.add("2:Two\n"); expected.add("3:Three\n"); expected.add("4:Four\n"); - + assertIterableEquals(expected, actual); } - + @Test void testEquals() { MetadataTest test = new MetadataTest(); @@ -108,17 +108,17 @@ void testEquals() { metadata.setValue("2", "Two"); metadata.setValue("3", "Three"); metadata.setValue("4", "Four"); - + MetadataTest test2 = new MetadataTest(); PlaybackMetadata metadata2 = new PlaybackMetadata(test2); metadata2.setValue("1", "One"); metadata2.setValue("2", "Two"); metadata2.setValue("3", "Three"); metadata2.setValue("4", "Four"); - + assertEquals(metadata, metadata2); } - + @Test void testFailedEquals() { //Key difference @@ -128,47 +128,46 @@ void testFailedEquals() { metadata.setValue("2", "Two"); metadata.setValue("3", "Three"); metadata.setValue("4", "Four"); - + MetadataTest test2 = new MetadataTest(); PlaybackMetadata metadata2 = new PlaybackMetadata(test2); metadata2.setValue("1", "One"); metadata2.setValue("2", "Two"); metadata2.setValue("3", "Three"); metadata2.setValue("4", "Four"); - + assertNotEquals(metadata, metadata2); - + // Value difference metadata = new PlaybackMetadata(test); metadata.setValue("1", "On"); metadata.setValue("2", "Two"); metadata.setValue("3", "Three"); metadata.setValue("4", "Four"); - + metadata2 = new PlaybackMetadata(test); metadata2.setValue("1", "One"); metadata2.setValue("2", "Two"); metadata2.setValue("3", "Three"); metadata2.setValue("4", "Four"); - + assertNotEquals(metadata, metadata2); - + // Name difference metadata2 = new PlaybackMetadata(test); metadata.setValue("1", "One"); metadata.setValue("2", "Two"); metadata.setValue("3", "Three"); metadata.setValue("4", "Four"); - - + List list = new ArrayList<>(); list.add("1:One"); list.add("2:Two"); list.add("3:Three"); list.add("4:Four"); - + metadata2 = PlaybackMetadata.fromStringList("Tes", list); - + assertNotEquals(metadata, metadata2); } } diff --git a/src/test/java/tasmod/virtual/VirtualInputEventFiring.java b/src/test/java/tasmod/virtual/VirtualInputEventFiring.java index e93e291a..7b5149f9 100644 --- a/src/test/java/tasmod/virtual/VirtualInputEventFiring.java +++ b/src/test/java/tasmod/virtual/VirtualInputEventFiring.java @@ -1,8 +1,10 @@ package tasmod.virtual; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; import com.minecrafttas.mctcommon.events.EventListenerRegistry; import com.minecrafttas.mctcommon.events.EventListenerRegistry.EventBase; @@ -10,23 +12,23 @@ import com.minecrafttas.tasmod.virtual.VirtualKeyboard; public class VirtualInputEventFiring { - - interface EventTest extends EventBase{ - + + interface EventTest extends EventBase { + void onTest(VirtualKeyboard keyboard); } - - interface EventCopy extends EventBase{ - + + interface EventCopy extends EventBase { + void onCopy(VirtualKeyboard keyboard); } - + @BeforeAll static void beforeAll() { - EventTest clear = (keyboard)-> { + EventTest clear = (keyboard) -> { keyboard.clear(); }; - EventCopy copy = (keyboard)-> { + EventCopy copy = (keyboard) -> { VirtualKeyboard newkeyboard = new VirtualKeyboard(); newkeyboard.updateFromEvent(VirtualKey.A, true, 'a'); newkeyboard.updateFromEvent(VirtualKey.D, true, 'd'); @@ -34,33 +36,33 @@ static void beforeAll() { }; EventListenerRegistry.register(clear, copy); } - + @Test void testClear() { VirtualKeyboard keyboard = new VirtualKeyboard(); - + keyboard.updateFromEvent(VirtualKey.W, true, 'w'); keyboard.updateFromEvent(VirtualKey.S, true, 's'); - + EventListenerRegistry.fireEvent(EventTest.class, keyboard); - + assertTrue(keyboard.getPressedKeys().isEmpty()); } - + @Test void testCopy() { - + VirtualKeyboard actual = new VirtualKeyboard(); - + actual.updateFromEvent(VirtualKey.W, true, 'w'); actual.updateFromEvent(VirtualKey.S, true, 's'); - + VirtualKeyboard expected = new VirtualKeyboard(); expected.updateFromEvent(VirtualKey.A, true, 'a'); expected.updateFromEvent(VirtualKey.D, true, 'd'); - + EventListenerRegistry.fireEvent(EventCopy.class, actual); - + assertEquals(expected, actual); } } diff --git a/src/test/java/tasmod/virtual/VirtualInputTest.java b/src/test/java/tasmod/virtual/VirtualInputTest.java index 04084feb..cb2b4582 100644 --- a/src/test/java/tasmod/virtual/VirtualInputTest.java +++ b/src/test/java/tasmod/virtual/VirtualInputTest.java @@ -22,27 +22,27 @@ class VirtualInputTest { private final Logger LOGGER = LogManager.getLogger("TASmod"); - + @BeforeAll static void beforeAll() { - EventVirtualInput.EventVirtualKeyboardTick kb = (keyboard)->null; - EventVirtualInput.EventVirtualMouseTick ms = (mouse)->null; - EventVirtualInput.EventVirtualCameraAngleTick cmra = (cameraangle)->null; + EventVirtualInput.EventVirtualKeyboardTick kb = (keyboard) -> null; + EventVirtualInput.EventVirtualMouseTick ms = (mouse) -> null; + EventVirtualInput.EventVirtualCameraAngleTick cmra = (cameraangle) -> null; EventListenerRegistry.register(kb, ms, cmra); } - + /** * Test constructor initializing keyboard, mouse and camera_angle */ @Test void testConstructor() { VirtualInput virtual = new VirtualInput(LOGGER); - + assertNotNull(virtual.KEYBOARD); assertNotNull(virtual.MOUSE); assertNotNull(virtual.CAMERA_ANGLE); } - + /** * Testing isKeyDown */ @@ -51,31 +51,31 @@ void testIsKeyDown() { VirtualKeyboard preloadedKeyboard = new VirtualKeyboard(); VirtualMouse preloadedMouse = new VirtualMouse(); VirtualCameraAngle preloadedCameraAngle = new VirtualCameraAngle(0f, 0f); - + preloadedKeyboard.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); preloadedMouse.updateFromEvent(VirtualKey.LC.getKeycode(), true, 15, 0, 0); preloadedCameraAngle.updateFromEvent(1f, 2f); - + VirtualInput input = new VirtualInput(LOGGER, preloadedKeyboard, preloadedMouse, preloadedCameraAngle); - + assertTrue(input.isKeyDown(VirtualKey.W.getKeycode())); assertTrue(input.isKeyDown(VirtualKey.LC.getKeycode())); } - + /** * Testing willKeyBeDown */ @Test void testWillKeyBeDown() { VirtualInput input = new VirtualInput(LOGGER); - + input.KEYBOARD.updateNextKeyboard(VirtualKey.W.getKeycode(), true, 'w'); input.MOUSE.updateNextMouse(VirtualKey.LC.getKeycode(), true, 15, 0, 0); - + assertTrue(input.willKeyBeDown(VirtualKey.W.getKeycode())); assertTrue(input.willKeyBeDown(VirtualKey.LC.getKeycode())); } - + /** * Tests if a keyboard can be preloaded */ @@ -84,71 +84,70 @@ void testPreloadedConstructor() { VirtualKeyboard preloadedKeyboard = new VirtualKeyboard(); VirtualMouse preloadedMouse = new VirtualMouse(); VirtualCameraAngle preloadedCameraAngle = new VirtualCameraAngle(0f, 0f); - + preloadedKeyboard.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); preloadedMouse.updateFromEvent(VirtualKey.LC.getKeycode(), true, 15, 0, 0); preloadedCameraAngle.updateFromEvent(1f, 2f); - - + VirtualInput virtual = new VirtualInput(LOGGER, preloadedKeyboard, preloadedMouse, preloadedCameraAngle); - + virtual.KEYBOARD.nextKeyboardTick(); assertTrue(virtual.KEYBOARD.nextKeyboardSubtick()); assertEquals(VirtualKey.W.getKeycode(), virtual.KEYBOARD.getEventKeyboardKey()); - + virtual.MOUSE.nextMouseTick(); assertTrue(virtual.MOUSE.nextMouseSubtick()); assertEquals(VirtualKey.LC.getKeycode(), virtual.MOUSE.getEventMouseKey()); - + assertEquals(1f, virtual.CAMERA_ANGLE.getCurrentPitch()); assertEquals(2f, virtual.CAMERA_ANGLE.getCurrentYaw()); } - + /** * Simulate key presses */ @Test void testKeyboardAddPresses() { VirtualInput virtual = new VirtualInput(LOGGER); - + // Simulate pressing keys WAS on the keyboard virtual.KEYBOARD.updateNextKeyboard(VirtualKey.W.getKeycode(), true, 'w'); virtual.KEYBOARD.updateNextKeyboard(VirtualKey.A.getKeycode(), true, 'a'); virtual.KEYBOARD.updateNextKeyboard(VirtualKey.S.getKeycode(), true, 's'); - + // Load the next keyboard events virtual.KEYBOARD.nextKeyboardTick(); - + // W - + // Load new subtick assertTrue(virtual.KEYBOARD.nextKeyboardSubtick()); - + // Read out values from the subtick assertEquals(VirtualKey.W.getKeycode(), virtual.KEYBOARD.getEventKeyboardKey()); assertTrue(virtual.KEYBOARD.getEventKeyboardState()); assertEquals('w', virtual.KEYBOARD.getEventKeyboardCharacter()); - + // A - + // Load new subtick assertTrue(virtual.KEYBOARD.nextKeyboardSubtick()); - + // Read out values from the subtick assertEquals(VirtualKey.A.getKeycode(), virtual.KEYBOARD.getEventKeyboardKey()); assertTrue(virtual.KEYBOARD.getEventKeyboardState()); assertEquals('a', virtual.KEYBOARD.getEventKeyboardCharacter()); - + // S - + // Load new subtick assertTrue(virtual.KEYBOARD.nextKeyboardSubtick()); - + // Read out values from the subtick assertEquals(VirtualKey.S.getKeycode(), virtual.KEYBOARD.getEventKeyboardKey()); assertTrue(virtual.KEYBOARD.getEventKeyboardState()); assertEquals('s', virtual.KEYBOARD.getEventKeyboardCharacter()); - + // Check if subtick list is empty assertFalse(virtual.KEYBOARD.nextKeyboardSubtick()); } @@ -159,69 +158,69 @@ void testKeyboardAddPresses() { @Test void testKeyboardRemovePresses() { VirtualKeyboard preloadedKeyboard = new VirtualKeyboard(); - + preloadedKeyboard.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); VirtualInput virtual = new VirtualInput(LOGGER, preloadedKeyboard, new VirtualMouse(), new VirtualCameraAngle()); - + virtual.KEYBOARD.updateNextKeyboard(VirtualKey.W.getKeycode(), false, Character.MIN_VALUE); - + // Load the next keyboard events virtual.KEYBOARD.nextKeyboardTick(); - + // Load a new subtick assertTrue(virtual.KEYBOARD.nextKeyboardSubtick()); - + // Read out values from the subtick assertEquals(VirtualKey.W.getKeycode(), virtual.KEYBOARD.getEventKeyboardKey()); assertFalse(virtual.KEYBOARD.getEventKeyboardState()); assertEquals(Character.MIN_VALUE, virtual.KEYBOARD.getEventKeyboardCharacter()); - + // Check if subtick list is empty assertFalse(virtual.KEYBOARD.nextKeyboardSubtick()); } - + /** * Test simulating mouse presses */ @Test void testMousePresses() { VirtualInput virtual = new VirtualInput(LOGGER); - + // Simulate mouse presses virtual.MOUSE.updateNextMouse(VirtualKey.LC.getKeycode(), true, 15, 10, 20); virtual.MOUSE.updateNextMouse(VirtualKey.MC.getKeycode(), true, -15, 30, 21); - + // Load the next mouse events virtual.MOUSE.nextMouseTick(); - + // LC - + // Load the new subtick assertTrue(virtual.MOUSE.nextMouseSubtick()); - + //Read out the values from the subtick assertEquals(VirtualKey.LC.getKeycode(), virtual.MOUSE.getEventMouseKey()); assertTrue(virtual.MOUSE.getEventMouseState()); assertEquals(15, virtual.MOUSE.getEventMouseScrollWheel()); assertEquals(10, virtual.MOUSE.getNormalizedCursorX()); assertEquals(20, virtual.MOUSE.getNormalizedCursorY()); - + // MC - + // Load new subtick assertTrue(virtual.MOUSE.nextMouseSubtick()); - + //Read out the values from the subtick assertEquals(VirtualKey.MC.getKeycode(), virtual.MOUSE.getEventMouseKey()); assertTrue(virtual.MOUSE.getEventMouseState()); assertEquals(-15, virtual.MOUSE.getEventMouseScrollWheel()); assertEquals(30, virtual.MOUSE.getNormalizedCursorX()); assertEquals(21, virtual.MOUSE.getNormalizedCursorY()); - + // Check if subtick list is empty assertFalse(virtual.MOUSE.nextMouseSubtick()); } - + /** * Test removing mouse presses */ @@ -229,29 +228,29 @@ void testMousePresses() { void testMouseRemovePresses() { VirtualMouse preloadedMouse = new VirtualMouse(); preloadedMouse.updateFromEvent(VirtualKey.LC.getKeycode(), true, 15, 10, 20); - + // Load preloaded mouse VirtualInput virtual = new VirtualInput(LOGGER, new VirtualKeyboard(), preloadedMouse, new VirtualCameraAngle()); - + // Unpress LC virtual.MOUSE.updateNextMouse(VirtualKey.LC.getKeycode(), false, 10, 20, 30); - + // Load the next mouse events virtual.MOUSE.nextMouseTick(); - + // Load new subtick assertTrue(virtual.MOUSE.nextMouseSubtick()); - + assertEquals(VirtualKey.LC.getKeycode(), virtual.MOUSE.getEventMouseKey()); assertFalse(virtual.MOUSE.getEventMouseState()); assertEquals(10, virtual.MOUSE.getEventMouseScrollWheel()); assertEquals(20, virtual.MOUSE.getNormalizedCursorX()); assertEquals(30, virtual.MOUSE.getNormalizedCursorY()); - + // Check if subtick list is empty assertFalse(virtual.MOUSE.nextMouseSubtick()); } - + /** * Test camera angle on tick */ @@ -273,14 +272,14 @@ void testCurrentCameraAngles() { * Test interpolation but with no playback running. Returns the valuies of nextCameraAngle */ @Test - void testInterpolationDisabled(){ + void testInterpolationDisabled() { VirtualInput virtual = new VirtualInput(LOGGER); virtual.CAMERA_ANGLE.setCamera(0f, 0f); virtual.CAMERA_ANGLE.updateNextCameraAngle(10f, 20f); virtual.CAMERA_ANGLE.updateNextCameraAngle(20f, 30f); - Triple expected = Triple.of(30f, 50f+180f, 0f); + Triple expected = Triple.of(30f, 50f + 180f, 0f); Triple actual = virtual.CAMERA_ANGLE.getInterpolatedState(0f, 1f, 2f, false); assertEquals(expected, actual); @@ -290,7 +289,7 @@ void testInterpolationDisabled(){ * Test interpolation but with playback running. */ @Test - void testInterpolationEnabled(){ + void testInterpolationEnabled() { VirtualInput virtual = new VirtualInput(LOGGER); virtual.CAMERA_ANGLE.setCamera(0f, 0f); diff --git a/src/test/java/tasmod/virtual/VirtualKeyboardTest.java b/src/test/java/tasmod/virtual/VirtualKeyboardTest.java index 713a2c8e..02f6722e 100644 --- a/src/test/java/tasmod/virtual/VirtualKeyboardTest.java +++ b/src/test/java/tasmod/virtual/VirtualKeyboardTest.java @@ -1,8 +1,18 @@ package tasmod.virtual; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Queue; +import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import org.junit.jupiter.api.Test; @@ -13,211 +23,211 @@ class VirtualKeyboardTest { - /** - * Test the empty constructor - */ - @Test - void testEmptyConstructor(){ - VirtualKeyboard actual = new VirtualKeyboard(); - assertTrue(actual.getPressedKeys().isEmpty()); - assertTrue(actual.getCharList().isEmpty()); - assertTrue(actual.isParent()); - } - - /** - * Test constructor with premade keycode sets - */ - @Test - void testSubtickConstructor(){ - Set testKeycodeSet = new HashSet<>(); - testKeycodeSet.add(VirtualKey.W.getKeycode()); - testKeycodeSet.add(VirtualKey.S.getKeycode()); - - List testCharList = new ArrayList<>(); - testCharList.add('w'); - testCharList.add('s'); - - VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); - - assertIterableEquals(testKeycodeSet, actual.getPressedKeys()); - assertIterableEquals(testCharList, actual.getCharList()); - assertFalse(actual.isParent()); - } - - /** - * Test setting the keycodes via setPressed to "pressed" - */ - @Test - void testSetPressedByKeycode(){ - VirtualKeyboard actual = new VirtualKeyboard(); - actual.setPressed(VirtualKey.W.getKeycode(), true); - - assertIterableEquals(Arrays.asList(VirtualKey.W.getKeycode()), actual.getPressedKeys()); - assertTrue(actual.isParent()); - } - - /** - * Test setting the keycodes via setPressed to "pressed" - */ - @Test - void testFailingSetPressedByKeycode(){ - VirtualKeyboard actual = new VirtualKeyboard(); - actual.setPressed(VirtualKey.LC.getKeycode(), true); - - assertTrue(actual.getPressedKeys().isEmpty()); - assertTrue(actual.isParent()); - } - - /** - * Test setting the keynames via setPressed to "pressed" - */ - @Test - void testSetPressedByKeyname(){ - VirtualKeyboard actual = new VirtualKeyboard(); - actual.setPressed("W", true); - - assertIterableEquals(Arrays.asList(VirtualKey.W.getKeycode()), actual.getPressedKeys()); - assertTrue(actual.isParent()); - } - - /** - * Test setting the keycodes via setPressed to "unpressed" - */ - @Test - void testSetUnPressedByKeycode(){ - Set testKeycodeSet = new HashSet<>(); - testKeycodeSet.add(VirtualKey.W.getKeycode()); - testKeycodeSet.add(VirtualKey.S.getKeycode()); - VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, new ArrayList<>()); - actual.setPressed(VirtualKey.W.getKeycode(), false); - - assertIterableEquals(Arrays.asList(VirtualKey.S.getKeycode()), actual.getPressedKeys()); - } - - /** - * Test setting the keynames via setPressed to "unpressed" - */ - @Test - void testSetUnPressedByKeyname(){ - Set testKeycodeSet = new HashSet<>(); - testKeycodeSet.add(VirtualKey.W.getKeycode()); - testKeycodeSet.add(VirtualKey.S.getKeycode()); - VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, new ArrayList<>()); - actual.setPressed("S", false); - - assertIterableEquals(Arrays.asList(VirtualKey.W.getKeycode()), actual.getPressedKeys()); - } - - /** - * Test adding a character to the keyboard - */ - @Test - void testAddCharacter(){ - VirtualKeyboard actual = new VirtualKeyboard(); - actual.addChar('w', false); - - assertIterableEquals(Arrays.asList('w'), actual.getCharList()); - } - - /** - * Test the toString method without subticks - */ - @Test - void testToString(){ - Set testKeycodeSet = new LinkedHashSet<>(); - testKeycodeSet.add(VirtualKey.W.getKeycode()); - testKeycodeSet.add(VirtualKey.S.getKeycode()); - - List testCharList = new ArrayList<>(); - testCharList.add('w'); - testCharList.add('s'); - - VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); - VirtualKeyboard actual2 = new VirtualKeyboard(testKeycodeSet, new ArrayList<>()); - - assertEquals("W,S;ws", actual.toString()); - assertEquals("W,S;", actual2.toString()); - } - - /** - * Test the toString method with subticks - */ - @Test - void testToStringSubticks(){ - VirtualKeyboard actual = new VirtualKeyboard(); - - actual.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - actual.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); - - assertEquals("W;w\nW,S;s", actual.toString()); - } - - /** - * Test equals method - */ - @Test - void testEquals() { - Set testKeycodeSet = new HashSet<>(); - testKeycodeSet.add(VirtualKey.W.getKeycode()); - testKeycodeSet.add(VirtualKey.S.getKeycode()); - - List testCharList = new ArrayList<>(); - testCharList.add('w'); - testCharList.add('s'); - - VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); - VirtualKeyboard actual2 = new VirtualKeyboard(testKeycodeSet, testCharList); - - assertEquals(actual, actual2); - } - - /** - * Test where equals will fail - */ - @Test - void testNotEquals() { - Set testKeycodeSet = new HashSet<>(); - testKeycodeSet.add(VirtualKey.W.getKeycode()); - testKeycodeSet.add(VirtualKey.S.getKeycode()); - - List testCharList = new ArrayList<>(); - testCharList.add('w'); - testCharList.add('s'); - - List testCharList2 = new ArrayList<>(); - testCharList2.add('w'); - testCharList2.add('S'); - - List testCharList3 = new ArrayList<>(); - testCharList3.add('w'); - - VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); - VirtualKeyboard test2 = new VirtualKeyboard(testKeycodeSet, testCharList2); - VirtualKeyboard test3 = new VirtualKeyboard(testKeycodeSet, testCharList3); - - assertNotEquals(actual, test2); - assertNotEquals(actual, test3); - assertNotEquals(actual, null); - } - - /** - * Test shallow cloning the keyboard - */ - @Test - void testShallowClone() { - Set testKeycodeSet = new HashSet<>(); - testKeycodeSet.add(VirtualKey.W.getKeycode()); - testKeycodeSet.add(VirtualKey.S.getKeycode()); - - List testCharList = new ArrayList<>(); - testCharList.add('w'); - testCharList.add('s'); - - VirtualKeyboard expected = new VirtualKeyboard(testKeycodeSet, testCharList); - VirtualKeyboard actual = expected.shallowClone(); - - assertEquals(expected, actual); - } + /** + * Test the empty constructor + */ + @Test + void testEmptyConstructor() { + VirtualKeyboard actual = new VirtualKeyboard(); + assertTrue(actual.getPressedKeys().isEmpty()); + assertTrue(actual.getCharList().isEmpty()); + assertTrue(actual.isParent()); + } + + /** + * Test constructor with premade keycode sets + */ + @Test + void testSubtickConstructor() { + Set testKeycodeSet = new HashSet<>(); + testKeycodeSet.add(VirtualKey.W.getKeycode()); + testKeycodeSet.add(VirtualKey.S.getKeycode()); + + List testCharList = new ArrayList<>(); + testCharList.add('w'); + testCharList.add('s'); + + VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); + + assertIterableEquals(testKeycodeSet, actual.getPressedKeys()); + assertIterableEquals(testCharList, actual.getCharList()); + assertFalse(actual.isParent()); + } + + /** + * Test setting the keycodes via setPressed to "pressed" + */ + @Test + void testSetPressedByKeycode() { + VirtualKeyboard actual = new VirtualKeyboard(); + actual.setPressed(VirtualKey.W.getKeycode(), true); + + assertIterableEquals(Arrays.asList(VirtualKey.W.getKeycode()), actual.getPressedKeys()); + assertTrue(actual.isParent()); + } + + /** + * Test setting the keycodes via setPressed to "pressed" + */ + @Test + void testFailingSetPressedByKeycode() { + VirtualKeyboard actual = new VirtualKeyboard(); + actual.setPressed(VirtualKey.LC.getKeycode(), true); + + assertTrue(actual.getPressedKeys().isEmpty()); + assertTrue(actual.isParent()); + } + + /** + * Test setting the keynames via setPressed to "pressed" + */ + @Test + void testSetPressedByKeyname() { + VirtualKeyboard actual = new VirtualKeyboard(); + actual.setPressed("W", true); + + assertIterableEquals(Arrays.asList(VirtualKey.W.getKeycode()), actual.getPressedKeys()); + assertTrue(actual.isParent()); + } + + /** + * Test setting the keycodes via setPressed to "unpressed" + */ + @Test + void testSetUnPressedByKeycode() { + Set testKeycodeSet = new HashSet<>(); + testKeycodeSet.add(VirtualKey.W.getKeycode()); + testKeycodeSet.add(VirtualKey.S.getKeycode()); + VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, new ArrayList<>()); + actual.setPressed(VirtualKey.W.getKeycode(), false); + + assertIterableEquals(Arrays.asList(VirtualKey.S.getKeycode()), actual.getPressedKeys()); + } + + /** + * Test setting the keynames via setPressed to "unpressed" + */ + @Test + void testSetUnPressedByKeyname() { + Set testKeycodeSet = new HashSet<>(); + testKeycodeSet.add(VirtualKey.W.getKeycode()); + testKeycodeSet.add(VirtualKey.S.getKeycode()); + VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, new ArrayList<>()); + actual.setPressed("S", false); + + assertIterableEquals(Arrays.asList(VirtualKey.W.getKeycode()), actual.getPressedKeys()); + } + + /** + * Test adding a character to the keyboard + */ + @Test + void testAddCharacter() { + VirtualKeyboard actual = new VirtualKeyboard(); + actual.addChar('w', false); + + assertIterableEquals(Arrays.asList('w'), actual.getCharList()); + } + + /** + * Test the toString method without subticks + */ + @Test + void testToString() { + Set testKeycodeSet = new LinkedHashSet<>(); + testKeycodeSet.add(VirtualKey.W.getKeycode()); + testKeycodeSet.add(VirtualKey.S.getKeycode()); + + List testCharList = new ArrayList<>(); + testCharList.add('w'); + testCharList.add('s'); + + VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); + VirtualKeyboard actual2 = new VirtualKeyboard(testKeycodeSet, new ArrayList<>()); + + assertEquals("W,S;ws", actual.toString()); + assertEquals("W,S;", actual2.toString()); + } + + /** + * Test the toString method with subticks + */ + @Test + void testToStringSubticks() { + VirtualKeyboard actual = new VirtualKeyboard(); + + actual.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + actual.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); + + assertEquals("W;w\nW,S;s", actual.toString()); + } + + /** + * Test equals method + */ + @Test + void testEquals() { + Set testKeycodeSet = new HashSet<>(); + testKeycodeSet.add(VirtualKey.W.getKeycode()); + testKeycodeSet.add(VirtualKey.S.getKeycode()); + + List testCharList = new ArrayList<>(); + testCharList.add('w'); + testCharList.add('s'); + + VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); + VirtualKeyboard actual2 = new VirtualKeyboard(testKeycodeSet, testCharList); + + assertEquals(actual, actual2); + } + + /** + * Test where equals will fail + */ + @Test + void testNotEquals() { + Set testKeycodeSet = new HashSet<>(); + testKeycodeSet.add(VirtualKey.W.getKeycode()); + testKeycodeSet.add(VirtualKey.S.getKeycode()); + + List testCharList = new ArrayList<>(); + testCharList.add('w'); + testCharList.add('s'); + + List testCharList2 = new ArrayList<>(); + testCharList2.add('w'); + testCharList2.add('S'); + + List testCharList3 = new ArrayList<>(); + testCharList3.add('w'); + + VirtualKeyboard actual = new VirtualKeyboard(testKeycodeSet, testCharList); + VirtualKeyboard test2 = new VirtualKeyboard(testKeycodeSet, testCharList2); + VirtualKeyboard test3 = new VirtualKeyboard(testKeycodeSet, testCharList3); + + assertNotEquals(actual, test2); + assertNotEquals(actual, test3); + assertNotEquals(actual, null); + } + + /** + * Test shallow cloning the keyboard + */ + @Test + void testShallowClone() { + Set testKeycodeSet = new HashSet<>(); + testKeycodeSet.add(VirtualKey.W.getKeycode()); + testKeycodeSet.add(VirtualKey.S.getKeycode()); + + List testCharList = new ArrayList<>(); + testCharList.add('w'); + testCharList.add('s'); + + VirtualKeyboard expected = new VirtualKeyboard(testKeycodeSet, testCharList); + VirtualKeyboard actual = expected.shallowClone(); + + assertEquals(expected, actual); + } /** * Test deep cloning the keyboard @@ -234,219 +244,219 @@ void testDeepClone() { assertIterableEquals(expected.getSubticks(), actual.getSubticks()); } - /** - * Test moveFrom method - */ - @Test - void testMoveFrom(){ - VirtualKeyboard moveFrom = new VirtualKeyboard(); - VirtualKeyboard actual = new VirtualKeyboard(); - - moveFrom.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - moveFrom.updateFromEvent(VirtualKey.A.getKeycode(), true, 'a'); - - VirtualKeyboard expected = moveFrom.clone(); - - actual.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); - actual.updateFromEvent(VirtualKey.D.getKeycode(), true, 'd'); - - actual.moveFrom(null); - actual.moveFrom(moveFrom); - - assertIterableEquals(expected.getPressedKeys(), actual.getPressedKeys()); - assertIterableEquals(expected.getCharList(), actual.getCharList()); - - assertTrue(moveFrom.getSubticks().isEmpty()); - assertTrue(moveFrom.getCharList().isEmpty()); - } - - /** - * Test copyFrom method - */ - @Test - void testCopyFrom() { - VirtualKeyboard copyFrom = new VirtualKeyboard(); - VirtualKeyboard actual = new VirtualKeyboard(); - - copyFrom.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - copyFrom.updateFromEvent(VirtualKey.A.getKeycode(), true, 'a'); - - VirtualKeyboard expected = copyFrom.clone(); - - actual.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); - actual.updateFromEvent(VirtualKey.D.getKeycode(), true, 'd'); - - actual.copyFrom(null); - actual.copyFrom(copyFrom); - - assertIterableEquals(expected.getPressedKeys(), actual.getPressedKeys()); - assertIterableEquals(expected.getCharList(), actual.getCharList()); - - assertFalse(copyFrom.getSubticks().isEmpty()); - assertFalse(copyFrom.getCharList().isEmpty()); - } - - /** - * Test subtick list being filled via update - */ - @Test - void testUpdate(){ - VirtualKeyboard actual = new VirtualKeyboard(); - actual.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - actual.updateFromEvent(VirtualKey.A.getKeycode(), true, 'A'); - - List expected = new ArrayList<>(); - expected.add(new VirtualKeyboard(new HashSet(Arrays.asList(VirtualKey.W.getKeycode())), Arrays.asList('w'))); - expected.add(new VirtualKeyboard(new HashSet(Arrays.asList(VirtualKey.W.getKeycode(), VirtualKey.A.getKeycode())), Arrays.asList('A'))); - - assertIterableEquals(expected, actual.getAll()); - } - - /** - * Tests update method on a subtick. Should not add a subtick - */ - @Test - void testUpdateOnSubtick() { - VirtualKeyboard actual = new VirtualKeyboard(new LinkedHashSet<>(), new ArrayList<>(), null, false); - - actual.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - } - - /** - * Tests getDifference - */ - @Test - void testGetDifference(){ - VirtualKeyboard test = new VirtualKeyboard(new HashSet<>(Arrays.asList(VirtualKey.W.getKeycode())), Arrays.asList('w')); - VirtualKeyboard test2 = new VirtualKeyboard(new HashSet<>(Arrays.asList(VirtualKey.W.getKeycode(), VirtualKey.S.getKeycode())), Arrays.asList('S')); - Queue actual = new ConcurrentLinkedQueue<>(); - test.getDifference(test2, actual); - Queue expected = new ConcurrentLinkedQueue<>(Arrays.asList(new VirtualKeyboardEvent(VirtualKey.S.getKeycode(), true, 'S'))); - - assertIterableEquals(expected, actual); - } - - /** - * Tests generating virtual events going from an unpressed keyboard to a pressed keyboard state - */ - @Test - void testGetVirtualEventsPress() { - VirtualKeyboard unpressed = new VirtualKeyboard(); - - VirtualKeyboard pressed = new VirtualKeyboard(); - pressed.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - - // Load actual with the events - Queue actual = new ConcurrentLinkedQueue<>(); - unpressed.getVirtualEvents(pressed, actual); - - // Load expected - List expected = Arrays.asList(new VirtualKeyboardEvent(VirtualKey.W.getKeycode(), true, 'w')); - - assertIterableEquals(expected, actual); - } - - /** - * Tests generating virtual events going from a pressed keyboard to an unpressed keyboard state - */ - @Test - void testGetVirtualEventsUnpress() { - VirtualKeyboard unpressed = new VirtualKeyboard(); - - VirtualKeyboard pressed = new VirtualKeyboard(); - pressed.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - - // Load actual with the events - Queue actual = new ConcurrentLinkedQueue<>(); - pressed.getVirtualEvents(unpressed, actual); - - // Load expected - List expected = Arrays.asList(new VirtualKeyboardEvent(VirtualKey.W.getKeycode(), false, Character.MIN_VALUE)); - - assertIterableEquals(expected, actual); - } - - /** - * Test clearing the keyboard - */ - @Test - void testClear(){ - VirtualKeyboard pressed = new VirtualKeyboard(); - pressed.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); - pressed.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); - pressed.updateFromEvent(VirtualKey.A.getKeycode(), true, 'a'); - - pressed.clear(); - - assertTrue(pressed.getPressedKeys().isEmpty()); - assertTrue(pressed.getSubticks().isEmpty()); - assertTrue(pressed.getCharList().isEmpty()); - } - - /** - * Tests virtualEvents behaviour on a subtick, should fail - */ - @Test - void testGetVirtualEventsOnSubtick() { - - VirtualKeyboard pressed = new VirtualKeyboard(new HashSet<>(), new ArrayList<>(), null, false); - - // Load actual with the events - Queue actual = new ConcurrentLinkedQueue<>(); - pressed.getVirtualEvents(pressed, actual); - - assertTrue(actual.isEmpty()); - } - - /** - * Test repeat events enabled - */ - @Test - void testRepeatEvents(){ - VirtualKeyboard testKb = new VirtualKeyboard(); - - int keycode = VirtualKey.BACK.getKeycode(); - - // Update the keyboard multiple times with the same value - testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, true); - testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, true); - testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, true); - - Queue actual = new ConcurrentLinkedQueue<>(); - // Fill "actual" with VirtualKeyboardEvents - new VirtualKeyboard().getVirtualEvents(testKb, actual); - - List expected = new ArrayList<>(); - // Add expected VirtualKeyboardEvents - expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); - expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); - expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); - - assertIterableEquals(expected, actual); - } - - /** - * Same as {@link #testRepeatEvents()} but with repeat events disabled - */ - @Test - void testRepeatEventsFail(){ - VirtualKeyboard testKb = new VirtualKeyboard(); - - int keycode = VirtualKey.BACK.getKeycode(); - // Update the keyboard multiple times with the same value. - testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, false); - testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, false); - testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, false); - - Queue actual = new ConcurrentLinkedQueue<>(); - // Fill "actual" with VirtualKeyboardEvents - new VirtualKeyboard().getVirtualEvents(testKb, actual); - - List expected = new ArrayList<>(); - - // Only one keyboard event should be added - expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); - - assertIterableEquals(expected, actual); - } + /** + * Test moveFrom method + */ + @Test + void testMoveFrom() { + VirtualKeyboard moveFrom = new VirtualKeyboard(); + VirtualKeyboard actual = new VirtualKeyboard(); + + moveFrom.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + moveFrom.updateFromEvent(VirtualKey.A.getKeycode(), true, 'a'); + + VirtualKeyboard expected = moveFrom.clone(); + + actual.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); + actual.updateFromEvent(VirtualKey.D.getKeycode(), true, 'd'); + + actual.moveFrom(null); + actual.moveFrom(moveFrom); + + assertIterableEquals(expected.getPressedKeys(), actual.getPressedKeys()); + assertIterableEquals(expected.getCharList(), actual.getCharList()); + + assertTrue(moveFrom.getSubticks().isEmpty()); + assertTrue(moveFrom.getCharList().isEmpty()); + } + + /** + * Test copyFrom method + */ + @Test + void testCopyFrom() { + VirtualKeyboard copyFrom = new VirtualKeyboard(); + VirtualKeyboard actual = new VirtualKeyboard(); + + copyFrom.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + copyFrom.updateFromEvent(VirtualKey.A.getKeycode(), true, 'a'); + + VirtualKeyboard expected = copyFrom.clone(); + + actual.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); + actual.updateFromEvent(VirtualKey.D.getKeycode(), true, 'd'); + + actual.copyFrom(null); + actual.copyFrom(copyFrom); + + assertIterableEquals(expected.getPressedKeys(), actual.getPressedKeys()); + assertIterableEquals(expected.getCharList(), actual.getCharList()); + + assertFalse(copyFrom.getSubticks().isEmpty()); + assertFalse(copyFrom.getCharList().isEmpty()); + } + + /** + * Test subtick list being filled via update + */ + @Test + void testUpdate() { + VirtualKeyboard actual = new VirtualKeyboard(); + actual.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + actual.updateFromEvent(VirtualKey.A.getKeycode(), true, 'A'); + + List expected = new ArrayList<>(); + expected.add(new VirtualKeyboard(new HashSet(Arrays.asList(VirtualKey.W.getKeycode())), Arrays.asList('w'))); + expected.add(new VirtualKeyboard(new HashSet(Arrays.asList(VirtualKey.W.getKeycode(), VirtualKey.A.getKeycode())), Arrays.asList('A'))); + + assertIterableEquals(expected, actual.getAll()); + } + + /** + * Tests update method on a subtick. Should not add a subtick + */ + @Test + void testUpdateOnSubtick() { + VirtualKeyboard actual = new VirtualKeyboard(new LinkedHashSet<>(), new ArrayList<>(), null, false); + + actual.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + } + + /** + * Tests getDifference + */ + @Test + void testGetDifference() { + VirtualKeyboard test = new VirtualKeyboard(new HashSet<>(Arrays.asList(VirtualKey.W.getKeycode())), Arrays.asList('w')); + VirtualKeyboard test2 = new VirtualKeyboard(new HashSet<>(Arrays.asList(VirtualKey.W.getKeycode(), VirtualKey.S.getKeycode())), Arrays.asList('S')); + Queue actual = new ConcurrentLinkedQueue<>(); + test.getDifference(test2, actual); + Queue expected = new ConcurrentLinkedQueue<>(Arrays.asList(new VirtualKeyboardEvent(VirtualKey.S.getKeycode(), true, 'S'))); + + assertIterableEquals(expected, actual); + } + + /** + * Tests generating virtual events going from an unpressed keyboard to a pressed keyboard state + */ + @Test + void testGetVirtualEventsPress() { + VirtualKeyboard unpressed = new VirtualKeyboard(); + + VirtualKeyboard pressed = new VirtualKeyboard(); + pressed.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + + // Load actual with the events + Queue actual = new ConcurrentLinkedQueue<>(); + unpressed.getVirtualEvents(pressed, actual); + + // Load expected + List expected = Arrays.asList(new VirtualKeyboardEvent(VirtualKey.W.getKeycode(), true, 'w')); + + assertIterableEquals(expected, actual); + } + + /** + * Tests generating virtual events going from a pressed keyboard to an unpressed keyboard state + */ + @Test + void testGetVirtualEventsUnpress() { + VirtualKeyboard unpressed = new VirtualKeyboard(); + + VirtualKeyboard pressed = new VirtualKeyboard(); + pressed.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + + // Load actual with the events + Queue actual = new ConcurrentLinkedQueue<>(); + pressed.getVirtualEvents(unpressed, actual); + + // Load expected + List expected = Arrays.asList(new VirtualKeyboardEvent(VirtualKey.W.getKeycode(), false, Character.MIN_VALUE)); + + assertIterableEquals(expected, actual); + } + + /** + * Test clearing the keyboard + */ + @Test + void testClear() { + VirtualKeyboard pressed = new VirtualKeyboard(); + pressed.updateFromEvent(VirtualKey.W.getKeycode(), true, 'w'); + pressed.updateFromEvent(VirtualKey.S.getKeycode(), true, 's'); + pressed.updateFromEvent(VirtualKey.A.getKeycode(), true, 'a'); + + pressed.clear(); + + assertTrue(pressed.getPressedKeys().isEmpty()); + assertTrue(pressed.getSubticks().isEmpty()); + assertTrue(pressed.getCharList().isEmpty()); + } + + /** + * Tests virtualEvents behaviour on a subtick, should fail + */ + @Test + void testGetVirtualEventsOnSubtick() { + + VirtualKeyboard pressed = new VirtualKeyboard(new HashSet<>(), new ArrayList<>(), null, false); + + // Load actual with the events + Queue actual = new ConcurrentLinkedQueue<>(); + pressed.getVirtualEvents(pressed, actual); + + assertTrue(actual.isEmpty()); + } + + /** + * Test repeat events enabled + */ + @Test + void testRepeatEvents() { + VirtualKeyboard testKb = new VirtualKeyboard(); + + int keycode = VirtualKey.BACK.getKeycode(); + + // Update the keyboard multiple times with the same value + testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, true); + testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, true); + testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, true); + + Queue actual = new ConcurrentLinkedQueue<>(); + // Fill "actual" with VirtualKeyboardEvents + new VirtualKeyboard().getVirtualEvents(testKb, actual); + + List expected = new ArrayList<>(); + // Add expected VirtualKeyboardEvents + expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); + expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); + expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); + + assertIterableEquals(expected, actual); + } + + /** + * Same as {@link #testRepeatEvents()} but with repeat events disabled + */ + @Test + void testRepeatEventsFail() { + VirtualKeyboard testKb = new VirtualKeyboard(); + + int keycode = VirtualKey.BACK.getKeycode(); + // Update the keyboard multiple times with the same value. + testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, false); + testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, false); + testKb.updateFromEvent(keycode, true, Character.MIN_VALUE, false); + + Queue actual = new ConcurrentLinkedQueue<>(); + // Fill "actual" with VirtualKeyboardEvents + new VirtualKeyboard().getVirtualEvents(testKb, actual); + + List expected = new ArrayList<>(); + + // Only one keyboard event should be added + expected.add(new VirtualKeyboardEvent(keycode, true, Character.MIN_VALUE)); + + assertIterableEquals(expected, actual); + } } diff --git a/src/test/java/tasmod/virtual/VirtualMouseTest.java b/src/test/java/tasmod/virtual/VirtualMouseTest.java index 127fbb26..665bc10e 100644 --- a/src/test/java/tasmod/virtual/VirtualMouseTest.java +++ b/src/test/java/tasmod/virtual/VirtualMouseTest.java @@ -15,10 +15,10 @@ import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; -import com.minecrafttas.tasmod.virtual.VirtualMouse; import org.junit.jupiter.api.Test; import com.minecrafttas.tasmod.virtual.VirtualKey; +import com.minecrafttas.tasmod.virtual.VirtualMouse; import com.minecrafttas.tasmod.virtual.event.VirtualMouseEvent; class VirtualMouseTest {