├── .idea ├── .name ├── .gitignore ├── vcs.xml ├── discord.xml ├── gradle.xml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml └── uiDesigner.xml ├── jitpack.yml ├── settings.gradle ├── README.md ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ └── java │ └── studio │ └── mevera │ └── scofi │ ├── base │ ├── LegacyBoardAdapter.java │ ├── ModernBoardAdapter.java │ ├── BoardUpdate.java │ ├── BoardAdapter.java │ ├── impl │ │ ├── AdventureBoard.java │ │ └── LegacyBoard.java │ └── BoardBase.java │ ├── animation │ ├── ScrollAnimation.java │ ├── core │ │ ├── Animation.java │ │ ├── ChangeSequenceController.java │ │ └── ChangesSequence.java │ ├── HighlightingAnimation.java │ ├── HighLighter.java │ └── Scroller.java │ ├── entity │ ├── Body.java │ ├── Title.java │ └── Line.java │ ├── util │ └── FastReflection.java │ └── Scofi.java ├── .gitignore ├── LICENSE ├── gradlew.bat └── gradlew /.idea/.name: -------------------------------------------------------------------------------- 1 | Scofi -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | jdk: 2 | - openjdk17 -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'Scofi' 2 | 3 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mBoard (OUTDATED) 2 | MIGRATED TO [Scofi](https://github.com/MeveraStudios/Scofi) 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mqzn/mBoard/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/base/LegacyBoardAdapter.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.base; 2 | 3 | public interface LegacyBoardAdapter extends BoardAdapter { 4 | } 5 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/base/ModernBoardAdapter.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.base; 2 | 3 | import net.kyori.adventure.text.Component; 4 | 5 | public interface ModernBoardAdapter extends BoardAdapter { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /.idea/discord.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Aug 02 11:58:26 EEST 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/base/BoardUpdate.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.base; 2 | 3 | @FunctionalInterface 4 | public interface BoardUpdate { 5 | /** 6 | * How you identify the actions that yet to be executed 7 | * when the board is updated in a scheduled task 8 | * 9 | * @param board the board to be updated 10 | */ 11 | void update(BoardBase board); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 16 | 17 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea/modules.xml 9 | .idea/jarRepositories.xml 10 | .idea/compiler.xml 11 | .idea/libraries/ 12 | *.iws 13 | *.iml 14 | *.ipr 15 | out/ 16 | !**/src/main/**/out/ 17 | !**/src/test/**/out/ 18 | 19 | ### Eclipse ### 20 | .apt_generated 21 | .classpath 22 | .factorypath 23 | .project 24 | .settings 25 | .springBeans 26 | .sts4-cache 27 | bin/ 28 | !**/src/main/**/bin/ 29 | !**/src/test/**/bin/ 30 | 31 | ### NetBeans ### 32 | /nbproject/private/ 33 | /nbbuild/ 34 | /dist/ 35 | /nbdist/ 36 | /.nb-gradle/ 37 | 38 | ### VS Code ### 39 | .vscode/ 40 | 41 | ### Mac OS ### 42 | .DS_Store -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/animation/ScrollAnimation.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.animation; 2 | 3 | import studio.mevera.scofi.animation.core.Animation; 4 | import studio.mevera.scofi.animation.core.ChangesSequence; 5 | import org.bukkit.ChatColor; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public final class ScrollAnimation extends Animation { 9 | private final @NotNull Scroller scroller; 10 | 11 | private ScrollAnimation(String original, int width, int spaceBetween) { 12 | super(original, ChangesSequence.of()); 13 | this.scroller = Scroller.of(ChatColor.translateAlternateColorCodes('&', original), width, spaceBetween); 14 | } 15 | 16 | public static ScrollAnimation of(String msg, int width, int spaceBetween) { 17 | return new ScrollAnimation(msg, width, spaceBetween); 18 | } 19 | 20 | @Override 21 | public String fetchNextChange() { 22 | return scroller.next(); 23 | } 24 | 25 | @Override 26 | public String fetchPreviousChange() { 27 | return scroller.next(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Mqzn 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/animation/core/Animation.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.animation.core; 2 | 3 | import lombok.Getter; 4 | 5 | /** 6 | * A simple class that caches the sequence of an animation 7 | * and the original value of the sequence 8 | * in order to switch to the next phase of the animation 9 | * using the class {@link ChangeSequenceController} 10 | * 11 | * @since 1.0 12 | * @author Mqzen (aka Mqzn) 13 | * @param the object type that's going be changed through 14 | * a sequence of changes 15 | */ 16 | public class Animation { 17 | protected final @Getter T original; 18 | private final ChangeSequenceController controller; 19 | 20 | public Animation(T original, ChangesSequence sequence) { 21 | this.original = original; 22 | this.controller = ChangeSequenceController.newController(sequence); 23 | } 24 | @SafeVarargs 25 | public Animation(T original, T... sequence) { 26 | this.original = original; 27 | this.controller = ChangeSequenceController.newController(ChangesSequence.of(sequence)); 28 | } 29 | 30 | public T fetchNextChange() { 31 | return controller.next(); 32 | } 33 | 34 | public T fetchPreviousChange() { 35 | return controller.previous(); 36 | } 37 | 38 | public int current() { 39 | return controller.getChangeIndex(); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/animation/core/ChangeSequenceController.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.animation.core; 2 | 3 | import lombok.Getter; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | /** 7 | * 8 | * The class that controls the sequence of changes 9 | * of each phase of the animation 10 | * 11 | * @see Animation 12 | * @since 1.0 13 | * @author Mqzen (aka Mqzn) 14 | * 15 | * @param the type to be changed 16 | */ 17 | 18 | public class ChangeSequenceController { 19 | 20 | private @Getter int changeIndex = 0; 21 | private final ChangesSequence sequence; 22 | 23 | protected ChangeSequenceController(ChangesSequence sequence) { 24 | this.sequence = sequence; 25 | } 26 | 27 | public static ChangeSequenceController newController(ChangesSequence sequence){ 28 | return new ChangeSequenceController<>(sequence); 29 | } 30 | 31 | 32 | public @NotNull T next() { 33 | if(changeIndex >= sequence.length()) { 34 | changeIndex = 0; 35 | } 36 | 37 | T change = sequence.getChange(changeIndex); 38 | assert change != null; 39 | 40 | changeIndex++; 41 | return change; 42 | } 43 | 44 | public @NotNull T previous() { 45 | changeIndex--; 46 | 47 | if(changeIndex < 0) { 48 | changeIndex = sequence.length()-1; 49 | } 50 | 51 | T change = sequence.getChange(changeIndex); 52 | assert change != null; 53 | return change; 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/base/BoardAdapter.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.base; 2 | 3 | import studio.mevera.scofi.entity.Body; 4 | import studio.mevera.scofi.entity.Title; 5 | import org.bukkit.entity.Player; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | public interface BoardAdapter { 10 | 11 | 12 | /** 13 | * Fetches the title to be represented 14 | * on the board that has this adapter instance; 15 | * 16 | * @param player the player who will view the title 17 | * @return the title of the scoreboard 18 | */ 19 | @NotNull 20 | Title getTitle(Player player); 21 | 22 | /** 23 | * Gets the body to be represented 24 | * as the body of the scoreboard 25 | * which will occupy this adapter as it's 26 | * model or template to take data from. 27 | * 28 | * @param player the player who will view the lines 29 | * @return the body of the scoreboard 30 | */ 31 | @NotNull 32 | Body getBody(Player player); 33 | 34 | /** 35 | * Returns an update action if 36 | * the board has any type of animations 37 | * this is recommended to implement and return 38 | * your own implementation.However, the best implementation recommended is this: 39 | *

40 | * return (board) -> { 41 | * board.updateTitle(); 42 | * board.updateBody(); 43 | * }; 44 | *

45 | * 46 | * @return the actions to be executed as an update to the board 47 | */ 48 | @Nullable 49 | default BoardUpdate getBoardUpdate() { 50 | return BoardBase::update; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/animation/core/ChangesSequence.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.animation.core; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | import java.util.*; 7 | 8 | 9 | /** 10 | * 11 | * The class which is responsible for 12 | * caching the change phases 13 | * it's also iterable, so you can put it 14 | * in an enhanced for loop to 15 | * 16 | * e.g: 17 | * ChangeSequence sequence = ChangeSequence.of("Hello", "Welcome !) 18 | * for(String change : sequence) { 19 | * //your code here 20 | * } 21 | * 22 | * @since 1.0 23 | * @author Mqzen (aka Mqzn) 24 | * 25 | * @param the type to be changed 26 | */ 27 | public class ChangesSequence implements Iterable { 28 | 29 | private final List changes = new ArrayList<>(); 30 | 31 | @SafeVarargs 32 | ChangesSequence(T... changes) { 33 | this.changes.addAll(Arrays.asList(changes)); 34 | } 35 | 36 | ChangesSequence(Collection changes) { 37 | this.changes.addAll(changes); 38 | } 39 | 40 | @SafeVarargs 41 | public static ChangesSequence of(T... changes) { 42 | return new ChangesSequence<>(changes); 43 | } 44 | 45 | public static ChangesSequence of(Collection changes) { 46 | return new ChangesSequence<>(changes); 47 | } 48 | 49 | @NotNull 50 | @Override 51 | public Iterator iterator() { 52 | return changes.iterator(); 53 | } 54 | 55 | public @Nullable T getChange(int index) { 56 | if(index >= changes.size() || index < 0) { 57 | return null; 58 | } 59 | return changes.get(index); 60 | } 61 | 62 | public void add(T change) { 63 | changes.add(change); 64 | } 65 | 66 | int length() { 67 | return changes.size(); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/animation/HighlightingAnimation.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.animation; 2 | 3 | import studio.mevera.scofi.animation.core.Animation; 4 | import org.bukkit.ChatColor; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | public final class HighlightingAnimation extends Animation { 8 | 9 | private final @NotNull HighLighter highLighter; 10 | private int position=0; 11 | 12 | private HighlightingAnimation(@NotNull String message, 13 | @NotNull String primaryColor, 14 | @NotNull String secondaryColor) { 15 | super(message); 16 | this.highLighter = HighLighter.of(message, primaryColor, secondaryColor); 17 | } 18 | 19 | private HighlightingAnimation(@NotNull String message, 20 | @NotNull ChatColor primaryColor, 21 | @NotNull ChatColor secondaryColor) { 22 | super(message); 23 | this.highLighter = HighLighter.of(message, primaryColor, secondaryColor); 24 | } 25 | 26 | public static HighlightingAnimation of(@NotNull String message, 27 | @NotNull ChatColor primaryColor, 28 | @NotNull ChatColor secondaryColor) { 29 | return new HighlightingAnimation(message, primaryColor, secondaryColor); 30 | } 31 | 32 | public static HighlightingAnimation of(@NotNull String message, 33 | @NotNull String primaryColor, 34 | @NotNull String secondaryColor) { 35 | return new HighlightingAnimation(message, primaryColor, secondaryColor); 36 | } 37 | 38 | @Override 39 | public String fetchNextChange() { 40 | return this.highLighter.nextResult(); 41 | } 42 | 43 | @Override 44 | public String fetchPreviousChange() { 45 | if(position < 0) { 46 | position = 0; 47 | } 48 | String prev = highLighter.getHighLighted(position); 49 | position--; 50 | return prev; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/animation/HighLighter.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.animation; 2 | 3 | import org.bukkit.ChatColor; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public final class HighLighter { 10 | 11 | private final StringBuilder text; 12 | private final String primaryColor, secondaryColor; 13 | private final List highLighted = new ArrayList<>(); 14 | private int position; 15 | private final int limit; 16 | 17 | private HighLighter(String text, String primaryColor, String secondaryColor) { 18 | 19 | this.text = new StringBuilder(text); 20 | this.primaryColor = ChatColor.translateAlternateColorCodes('&', primaryColor); 21 | this.secondaryColor = ChatColor.translateAlternateColorCodes('&', secondaryColor); 22 | this.limit = text.length(); 23 | } 24 | 25 | private HighLighter(String text, ChatColor primary, ChatColor secondary) { 26 | this(text, primary.toString(), secondary.toString()); 27 | } 28 | 29 | public String nextResult() { 30 | StringBuilder builder = new StringBuilder(); 31 | 32 | if (position >= limit) { 33 | position = 0; 34 | } 35 | 36 | if (position > 0) { 37 | builder.append(primaryColor).append(text, 0, position); 38 | } 39 | String secondaryTarget = text.substring(position, position + 1); 40 | builder.append(secondaryColor).append(secondaryTarget); 41 | 42 | if (position < limit-1) { 43 | builder.append(primaryColor).append(text.substring(position+1)); 44 | } 45 | 46 | position++; 47 | return builder.toString(); 48 | } 49 | 50 | public @NotNull List getHighLighted() { 51 | return highLighted; 52 | } 53 | 54 | public static HighLighter of(String text, String primaryColor, String secondaryColor) { 55 | return new HighLighter(text, primaryColor, secondaryColor); 56 | } 57 | 58 | public static HighLighter of(String text, ChatColor primary, ChatColor secondary) { 59 | return new HighLighter(text, primary, secondary); 60 | } 61 | 62 | public String getHighLighted(int index) { 63 | return this.highLighted.get(index); 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/animation/Scroller.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.animation; 2 | 3 | import org.bukkit.ChatColor; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public final class Scroller { 10 | 11 | private int position; 12 | private final List list; 13 | private ChatColor color = ChatColor.RESET; 14 | 15 | private Scroller(String message, int width, int spaceBetween) { 16 | message = ChatColor.translateAlternateColorCodes('&', message); 17 | list = new ArrayList<>(); 18 | // String is too short for window? 19 | if (message.length() < width) { 20 | StringBuilder sb = new StringBuilder(message); 21 | while (sb.length() < width) 22 | sb.append(" "); 23 | message = sb.toString(); 24 | } 25 | // Allow for colours which add 2 to the width 26 | width -= 2; 27 | // Invalid width/space size 28 | if (width < 1) 29 | width = 1; 30 | 31 | if (spaceBetween < 0) 32 | spaceBetween = 0; 33 | // Add substrings 34 | for (int i = 0; i < message.length() - width; i++) 35 | list.add(message.substring(i, i + width)); 36 | // Add space between repeats 37 | StringBuilder space = new StringBuilder(); 38 | for (int i = 0; i < spaceBetween; ++i) { 39 | list.add(message.substring(message.length() - width + (Math.min(i, width))) + space); 40 | if (space.length() < width) 41 | space.append(" "); 42 | } 43 | // Wrap 44 | for (int i = 0; i < width - spaceBetween; ++i) 45 | list.add(message.substring(message.length() - width + spaceBetween + i) + space + message.substring(0, i)); 46 | // Join up 47 | for (int i = 0; i < spaceBetween; i++) { 48 | if (i > space.length()) 49 | break; 50 | list.add(space.substring(0, space.length() - i) + message.substring(0, width - (Math.min(spaceBetween, width)) + i)); 51 | } 52 | } 53 | 54 | public static @NotNull Scroller of(String message, int width, int spaceBetween) { 55 | return new Scroller(message, width, spaceBetween); 56 | } 57 | 58 | 59 | public String next() { 60 | StringBuilder sb = getNext(); 61 | if (sb.charAt(sb.length() - 1) == ChatColor.COLOR_CHAR) { 62 | sb.setCharAt(sb.length() - 1, ' '); 63 | } 64 | if (sb.charAt(0) == ChatColor.COLOR_CHAR) { 65 | ChatColor c = ChatColor.getByChar(sb.charAt(1)); 66 | if (c != null) { 67 | color = c; 68 | 69 | sb = getNext(); 70 | if (sb.charAt(0) != ' ') { 71 | sb.setCharAt(0, ' '); 72 | } 73 | } 74 | 75 | } 76 | return color + sb.toString(); 77 | } 78 | 79 | private StringBuilder getNext() { 80 | return new StringBuilder(list.get(position++ % list.size())); 81 | } 82 | 83 | 84 | 85 | 86 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/entity/Body.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.entity; 2 | 3 | import lombok.Getter; 4 | import net.kyori.adventure.text.Component; 5 | import net.md_5.bungee.api.ChatColor; 6 | 7 | import java.util.Arrays; 8 | import java.util.List; 9 | import java.util.concurrent.CopyOnWriteArrayList; 10 | 11 | 12 | public interface Body { 13 | 14 | void addLine(T content); 15 | 16 | void addLine(Line line); 17 | 18 | List> getLines(); 19 | 20 | default void setLine(int index, Line line) { 21 | if(index < 0 || index >= getLines().size()) return; 22 | // Ensure the line has the correct index 23 | line.setIndex(index); 24 | getLines().set(index, line); 25 | } 26 | 27 | static BodyImplementation.LegacyBody legacy(String... lines) { 28 | return legacy(Arrays.asList(lines)); 29 | } 30 | 31 | static BodyImplementation.LegacyBody legacy(List lines) { 32 | return new BodyImplementation.LegacyBody(lines); 33 | } 34 | 35 | 36 | static BodyImplementation.AdventureBody adventure(Component... components) { 37 | return adventure(Arrays.asList(components)); 38 | } 39 | 40 | static BodyImplementation.AdventureBody adventure(List components) { 41 | return new BodyImplementation.AdventureBody(components); 42 | } 43 | 44 | @Getter 45 | abstract class BodyImplementation implements Body{ 46 | private final List> lines; 47 | 48 | public BodyImplementation() { 49 | lines = new CopyOnWriteArrayList<>(); 50 | } 51 | 52 | public static class LegacyBody extends BodyImplementation{ 53 | 54 | public LegacyBody(List lines) { 55 | super(); 56 | for (String line : lines) { 57 | addLine(line); 58 | } 59 | } 60 | 61 | @Override 62 | public void addLine(String content) { 63 | int correctIndex = getLines().size(); 64 | getLines().add(Line.legacy(ChatColor.translateAlternateColorCodes('&', content), correctIndex)); 65 | } 66 | 67 | @Override 68 | public void addLine(Line line) { 69 | // FIXED: Always ensure the line gets the correct index based on its position 70 | int correctIndex = getLines().size(); 71 | line.setIndex(correctIndex); 72 | getLines().add(line); 73 | } 74 | } 75 | 76 | public static class AdventureBody extends BodyImplementation{ 77 | 78 | public AdventureBody(List lines) { 79 | super(); 80 | for (Component line : lines) { 81 | addLine(line); 82 | } 83 | } 84 | 85 | @Override 86 | public void addLine(Component content) { 87 | int correctIndex = getLines().size(); 88 | getLines().add(Line.adventure(content, correctIndex)); 89 | } 90 | 91 | @Override 92 | public void addLine(Line line) { 93 | // FIXED: Always ensure the line gets the correct index based on its position 94 | int correctIndex = getLines().size(); 95 | line.setIndex(correctIndex); 96 | getLines().add(line); 97 | } 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 32 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/entity/Title.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.entity; 2 | 3 | import studio.mevera.scofi.animation.HighlightingAnimation; 4 | import studio.mevera.scofi.animation.ScrollAnimation; 5 | import studio.mevera.scofi.animation.core.Animation; 6 | import studio.mevera.scofi.base.BoardAdapter; 7 | import net.kyori.adventure.text.Component; 8 | import net.md_5.bungee.api.ChatColor; 9 | import org.jetbrains.annotations.NotNull; 10 | import org.jetbrains.annotations.Nullable; 11 | import java.util.Optional; 12 | 13 | /** 14 | * 15 | * A simple interface to represent the data required 16 | * to be obtained about the title of a scoreboard 17 | * 18 | * @see BoardAdapter 19 | * @since 1.0 20 | * @author Mqzen (aka Mqzn) 21 | * 22 | */ 23 | public interface Title { 24 | 25 | /** 26 | * 27 | * A simple method to provide the text of the title 28 | * that will be viewed to a certain player 29 | * If animation is present, returns the next animation frame 30 | * Otherwise returns the static content 31 | * 32 | * @return the text/content of this title 33 | */ 34 | Optional get(); 35 | 36 | /** 37 | * Sets a {@link Animation} for the title 38 | * @param animation the animation 39 | * @return the title animation 40 | * @param the type of title instance to return 41 | */ 42 | <TITLE extends Title<T>> TITLE withAnimation(@Nullable Animation<T> animation); 43 | 44 | /** 45 | * A method to provide the animation of the title 46 | * By default, a title has no animation unless 47 | * you set its animation by overriding this method 48 | * and returning your animation object 49 | * e.g: Optional.ofNullable(yourAnimationInstance) 50 | * 51 | * @return the Animation of the title if present 52 | */ 53 | default Optional<Animation<T>> loadAnimation() { 54 | return Optional.empty(); 55 | } 56 | 57 | static TitleImplementation.LegacyTitle legacy() { 58 | return new TitleImplementation.LegacyTitle(); 59 | } 60 | static TitleImplementation.AdventureTitle adventure() { 61 | return new TitleImplementation.AdventureTitle(); 62 | } 63 | 64 | default boolean hasAnimation() { 65 | return loadAnimation().isPresent(); 66 | } 67 | 68 | class TitleImplementation<T> implements Title<T>{ 69 | protected T content; 70 | private Animation<T> titleAnimation; 71 | public TitleImplementation() { 72 | 73 | } 74 | public TitleImplementation(T content) { 75 | this.content = content; 76 | } 77 | 78 | @Override 79 | public @NotNull Optional<T> get() { 80 | // FIXED: Check for animation first, similar to Line.fetchContent() 81 | if (titleAnimation != null) { 82 | return Optional.of(titleAnimation.fetchNextChange()); 83 | } 84 | return Optional.of(content); 85 | } 86 | 87 | public void setContent(T content) { 88 | if(titleAnimation != null) { 89 | throw new IllegalStateException("You cannot set a title content while being based on animation"); 90 | } 91 | this.content = content; 92 | } 93 | 94 | public void setTitleAnimation(Animation<T> titleAnimation) { 95 | this.titleAnimation = titleAnimation; 96 | if(titleAnimation != null) { 97 | this.content = titleAnimation.getOriginal(); 98 | } 99 | } 100 | 101 | @Override @SuppressWarnings("unchecked") 102 | public <TITLE extends Title<T>> TITLE withAnimation(@Nullable Animation<T> animation) { 103 | setTitleAnimation(animation); 104 | return (TITLE) this; 105 | } 106 | 107 | /** 108 | * A method to provide the animation of the title 109 | * By default, a title has no animation unless 110 | * you set its animation by overriding this method 111 | * and returning your animation object 112 | * e.g: Optional.ofNullable(yourAnimationInstance) 113 | * 114 | * @return the Animation of the title if present 115 | */ 116 | @Override 117 | public Optional<Animation<T>> loadAnimation() { 118 | return Optional.ofNullable(titleAnimation); 119 | } 120 | 121 | public static class LegacyTitle extends TitleImplementation<String> { 122 | 123 | public LegacyTitle ofText(String content) { 124 | super.setContent(ChatColor.translateAlternateColorCodes('&', content)); 125 | return this; 126 | } 127 | 128 | public LegacyTitle withScroll(int width, int spaceBetween) { 129 | if(this.content == null) { 130 | throw new IllegalArgumentException("You cannot call withScroll() without calling #ofText() before it to set the text, " + 131 | "the scrolling animation will be based on no text," + 132 | " Alternatively you can set it using #withAnimation"); 133 | } 134 | return super.withAnimation(ScrollAnimation.of(this.content, width, spaceBetween)); 135 | } 136 | 137 | public LegacyTitle withHighlight(org.bukkit.ChatColor primaryColor, org.bukkit.ChatColor secondaryColor) { 138 | if(this.content == null) { 139 | throw new IllegalArgumentException("You cannot call withHighlight() without calling #ofText() before it to set the text, " + 140 | "the scrolling animation will be based on no text," + 141 | " Alternatively you can set it using #withAnimation"); 142 | } 143 | return super.withAnimation(HighlightingAnimation.of(this.content, primaryColor, secondaryColor)); 144 | } 145 | } 146 | public static class AdventureTitle extends TitleImplementation<Component> { 147 | 148 | public AdventureTitle ofComponent(Component content) { 149 | super.setContent(content); 150 | return this; 151 | } 152 | } 153 | } 154 | 155 | } -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/util/FastReflection.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.util; 2 | 3 | import org.bukkit.Bukkit; 4 | 5 | import java.lang.invoke.MethodHandle; 6 | import java.lang.invoke.MethodHandles; 7 | import java.lang.invoke.MethodType; 8 | import java.lang.reflect.Field; 9 | import java.util.Optional; 10 | import java.util.function.Predicate; 11 | 12 | 13 | public final class FastReflection { 14 | 15 | private static final String NM_PACKAGE = "net.minecraft"; 16 | private static final String OBC_PACKAGE = Bukkit.getServer().getClass().getPackage().getName(); 17 | private static final String NMS_PACKAGE = OBC_PACKAGE.replace("org.bukkit.craftbukkit", NM_PACKAGE + ".server"); 18 | 19 | private static final MethodType VOID_METHOD_TYPE = MethodType.methodType(void.class); 20 | private static final boolean NMS_REPACKAGED = optionalClass(NM_PACKAGE + ".network.protocol.Packet").isPresent(); 21 | private static final boolean MOJANG_MAPPINGS = optionalClass(NM_PACKAGE + ".network.chat.Component").isPresent(); 22 | 23 | private static volatile Object theUnsafe; 24 | 25 | private FastReflection() { 26 | throw new UnsupportedOperationException(); 27 | } 28 | 29 | public static boolean isRepackaged() { 30 | return NMS_REPACKAGED; 31 | } 32 | 33 | public static String nmsClassName(String post1_17package, String className) { 34 | if (NMS_REPACKAGED) { 35 | String classPackage = post1_17package == null ? NM_PACKAGE : NM_PACKAGE + '.' + post1_17package; 36 | 37 | return classPackage + '.' + className; 38 | } 39 | 40 | return NMS_PACKAGE + '.' + className; 41 | } 42 | 43 | public static Class<?> nmsClass(String post1_17package, String className) throws ClassNotFoundException { 44 | return Class.forName(nmsClassName(post1_17package, className)); 45 | } 46 | 47 | public static Class<?> nmsClass(String post1_17package, String spigotClass, String mojangClass) throws ClassNotFoundException { 48 | return nmsClass(post1_17package, MOJANG_MAPPINGS ? mojangClass : spigotClass); 49 | } 50 | 51 | public static Optional<Class<?>> nmsOptionalClass(String post1_17package, String className) { 52 | return optionalClass(nmsClassName(post1_17package, className)); 53 | } 54 | 55 | public static String obcClassName(String className) { 56 | return OBC_PACKAGE + '.' + className; 57 | } 58 | 59 | public static Class<?> obcClass(String className) throws ClassNotFoundException { 60 | return Class.forName(obcClassName(className)); 61 | } 62 | 63 | public static Optional<Class<?>> obcOptionalClass(String className) { 64 | return optionalClass(obcClassName(className)); 65 | } 66 | 67 | public static Optional<Class<?>> optionalClass(String className) { 68 | try { 69 | return Optional.of(Class.forName(className)); 70 | } catch (ClassNotFoundException e) { 71 | return Optional.empty(); 72 | } 73 | } 74 | 75 | public static Object enumValueOf(Class<?> enumClass, String enumName) { 76 | return Enum.valueOf(enumClass.asSubclass(Enum.class), enumName); 77 | } 78 | 79 | public static Object enumValueOf(Class<?> enumClass, String enumName, int fallbackOrdinal) { 80 | try { 81 | return enumValueOf(enumClass, enumName); 82 | } catch (IllegalArgumentException e) { 83 | Object[] constants = enumClass.getEnumConstants(); 84 | if (constants.length > fallbackOrdinal) { 85 | return constants[fallbackOrdinal]; 86 | } 87 | throw e; 88 | } 89 | } 90 | 91 | public static Class<?> innerClass(Class<?> parentClass, Predicate<Class<?>> classPredicate) throws ClassNotFoundException { 92 | for (Class<?> innerClass : parentClass.getDeclaredClasses()) { 93 | if (classPredicate.test(innerClass)) { 94 | return innerClass; 95 | } 96 | } 97 | throw new ClassNotFoundException("No class in " + parentClass.getCanonicalName() + " matches the predicate."); 98 | } 99 | 100 | public static Optional<MethodHandle> optionalConstructor(Class<?> declaringClass, MethodHandles.Lookup lookup, MethodType type) throws IllegalAccessException { 101 | try { 102 | return Optional.of(lookup.findConstructor(declaringClass, type)); 103 | } catch (NoSuchMethodException e) { 104 | return Optional.empty(); 105 | } 106 | } 107 | 108 | public static PacketConstructor findPacketConstructor(Class<?> packetClass, MethodHandles.Lookup lookup) throws Exception { 109 | try { 110 | MethodHandle constructor = lookup.findConstructor(packetClass, VOID_METHOD_TYPE); 111 | return constructor::invoke; 112 | } catch (NoSuchMethodException | IllegalAccessException e) { 113 | // try below with Unsafe 114 | } 115 | 116 | if (theUnsafe == null) { 117 | synchronized (FastReflection.class) { 118 | if (theUnsafe == null) { 119 | Class<?> unsafeClass = Class.forName("sun.misc.Unsafe"); 120 | Field theUnsafeField = unsafeClass.getDeclaredField("theUnsafe"); 121 | theUnsafeField.setAccessible(true); 122 | theUnsafe = theUnsafeField.get(null); 123 | } 124 | } 125 | } 126 | 127 | MethodType allocateMethodType = MethodType.methodType(Object.class, Class.class); 128 | MethodHandle allocateMethod = lookup.findVirtual(theUnsafe.getClass(), "allocateInstance", allocateMethodType); 129 | return () -> allocateMethod.invoke(theUnsafe, packetClass); 130 | } 131 | 132 | @FunctionalInterface 133 | public interface PacketConstructor { 134 | Object invoke() throws Throwable; 135 | } 136 | } -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/Scofi.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi; 2 | 3 | import studio.mevera.scofi.base.*; 4 | import studio.mevera.scofi.base.impl.LegacyBoard; 5 | import studio.mevera.scofi.base.impl.AdventureBoard; 6 | import studio.mevera.scofi.util.FastReflection; 7 | import lombok.Getter; 8 | import org.bukkit.Bukkit; 9 | import org.bukkit.entity.Player; 10 | import org.bukkit.plugin.Plugin; 11 | import org.jetbrains.annotations.NotNull; 12 | import org.jetbrains.annotations.Nullable; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | import java.util.UUID; 16 | import java.util.logging.Level; 17 | import java.util.logging.Logger; 18 | 19 | /** 20 | * A manager class to hold the created boards for players online 21 | * and also to update them in a scheduled task 22 | * 23 | * @since 1.0 24 | * @author Mqzen (aka Mqzn) 25 | */ 26 | public class Scofi { 27 | 28 | private final @NotNull Plugin plugin; 29 | private @Nullable Integer updateTaskId = null; 30 | private final @NotNull Map<UUID, BoardBase<?>> boards = new HashMap<>(); 31 | public static final boolean ADVENTURE_SUPPORT; 32 | private final @Getter Logger logger = Logger.getLogger(this.getClass().getSimpleName()); 33 | 34 | static { 35 | ADVENTURE_SUPPORT = FastReflection 36 | .optionalClass("io.papermc.paper.adventure.PaperAdventure") 37 | .isPresent(); 38 | } 39 | 40 | private @Getter long updateInterval = 3L; // in ticks 41 | private Scofi(@NotNull Plugin plugin) { 42 | this.plugin = plugin; 43 | } 44 | 45 | 46 | /** 47 | * Loads the Scofi instance into memory 48 | * since the class follows The Singleton pattern 49 | * there will be only copy of it's instance in memory 50 | * 51 | * @param plugin the plugin that's using mBoard 52 | */ 53 | public static Scofi load(Plugin plugin) { 54 | if(plugin == null ) 55 | throw new IllegalArgumentException("Plugin cannot be null"); 56 | return new Scofi(plugin); 57 | } 58 | 59 | /** 60 | * Sets the update interval of the boards 61 | * @param interval the interval in ticks 62 | */ 63 | public void setUpdateInterval(long interval) { 64 | if(updateTaskId == null) { 65 | this.updateInterval = interval; 66 | return; 67 | } 68 | Bukkit.getScheduler().cancelTask(updateTaskId); 69 | this.updateInterval = interval; 70 | this.startBoardUpdaters(); 71 | } 72 | 73 | /** 74 | * Fetches the board created for the player 75 | * whose uuid matches that of the parameter 76 | * 77 | * @param uuid the uuid of the player who is 78 | * the owner of a board 79 | * 80 | * @return the board made for that player 81 | * returns null if the player has no board registered ! 82 | */ 83 | @SuppressWarnings("unchecked") 84 | public @Nullable <T> BoardBase<T> getBoard(@NotNull UUID uuid) throws ClassCastException { 85 | return (BoardBase<T>) boards.get(uuid); 86 | } 87 | 88 | /** 89 | * Registers a board for a player's uuid 90 | * @param uuid the uuid of the player to register the board for. 91 | * @param mBoard the board to be registered for that uuid 92 | */ 93 | private void registerBoard(UUID uuid, BoardBase<?> mBoard) { 94 | boards.put(uuid, mBoard); 95 | } 96 | 97 | /** 98 | * Creates a new board and registers it for the player 99 | * using an adapter class that represents some data of the board 100 | * that are needed to be obtained 101 | * 102 | * @param player the player to have the new board created and registered 103 | * @param adapter the info carrier of the board 104 | */ 105 | public void setupNewBoard(Player player, BoardAdapter<?> adapter) { 106 | if(adapter instanceof ModernBoardAdapter && !ADVENTURE_SUPPORT) { 107 | throw new UnsupportedOperationException("Use of modern board adapter is not supported in this mc version."); 108 | } 109 | 110 | BoardBase<?> board; 111 | if (ADVENTURE_SUPPORT) { 112 | if (!(adapter instanceof ModernBoardAdapter)) { 113 | throw new IllegalStateException("You cannot use legacy board adapter in a modern mc version !"); 114 | } 115 | ModernBoardAdapter modernBoardAdapter = (ModernBoardAdapter)adapter; 116 | board = new AdventureBoard(this, player, modernBoardAdapter); 117 | } else { 118 | board = new LegacyBoard(this, player, (LegacyBoardAdapter) adapter); 119 | } 120 | 121 | registerBoard(player.getUniqueId(), board); 122 | } 123 | 124 | /** 125 | * This deletes the board created for the player 126 | * and unregister it from memory 127 | * 128 | * @param player the owner of a board. 129 | */ 130 | public void removeBoard(@NotNull Player player) { 131 | BoardBase<?> board = getBoard(player.getUniqueId()); 132 | if(board != null) { 133 | board.delete(); 134 | } 135 | boards.remove(player.getUniqueId()); 136 | } 137 | 138 | /** 139 | * Start the task of the board updates 140 | * to allow boards to get updated every certain period 141 | * 142 | * @see Scofi#setUpdateInterval(long) 143 | */ 144 | public void startBoardUpdaters() { 145 | updateTaskId = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, ()-> { 146 | for(BoardBase<?> board : boards.values()) { 147 | if(board.isDeleted())continue; 148 | BoardUpdate update = board.getUpdate(); 149 | if(update == null) continue; 150 | try { 151 | update.update(board); 152 | }catch (Exception ex) { 153 | plugin.getLogger().log(Level.SEVERE, ex, ()-> "Failed to update " + board.getPlayer().getName() + "'s scoreboard."); 154 | } 155 | } 156 | }, 1L, updateInterval).getTaskId(); 157 | } 158 | 159 | /** 160 | * Stops the scheduled task for board updates 161 | * Seemed useless to me but thought perhaps someone 162 | * may get a use of it in the future lol 163 | * 164 | * @see Scofi#startBoardUpdaters() 165 | */ 166 | public void stopBoardUpdaters() { 167 | if(updateTaskId != null) 168 | Bukkit.getScheduler().cancelTask(updateTaskId); 169 | } 170 | 171 | 172 | } 173 | -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/entity/Line.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.entity; 2 | 3 | import studio.mevera.scofi.animation.HighlightingAnimation; 4 | import studio.mevera.scofi.animation.ScrollAnimation; 5 | import studio.mevera.scofi.animation.core.Animation; 6 | import lombok.Getter; 7 | import lombok.Setter; 8 | import net.kyori.adventure.text.Component; 9 | import org.bukkit.ChatColor; 10 | 11 | public interface Line<T> { 12 | T getContent(); 13 | void setContent(T content); 14 | int getIndex(); 15 | void setIndex(int index); 16 | Animation<T> getAnimation(); 17 | void setAnimation(Animation<T> animation); 18 | 19 | default T fetchContent(){ 20 | return getAnimation() == null ? getContent() : getAnimation().fetchNextChange(); 21 | } 22 | 23 | // Builder factory methods 24 | static LegacyLineBuilder legacy(String content){ 25 | return new LegacyLineBuilder(content); 26 | } 27 | 28 | static AdventureLineBuilder adventure(Component content){ 29 | return new AdventureLineBuilder(content); 30 | } 31 | 32 | // Backwards compatibility 33 | static LineImplementation.LegacyLine legacy(String content, int index){ 34 | return new LineImplementation.LegacyLine(content, index); 35 | } 36 | 37 | static LineImplementation.AdventureLine adventure(Component content, int index){ 38 | return new LineImplementation.AdventureLine(content, index); 39 | } 40 | 41 | // Builder classes 42 | class LegacyLineBuilder { 43 | private final String content; 44 | private Animation<String> animation; 45 | 46 | public LegacyLineBuilder(String content) { 47 | this.content = ChatColor.translateAlternateColorCodes('&', content); 48 | } 49 | 50 | /** 51 | * Add a highlighting animation to the line's content 52 | */ 53 | public LegacyLineBuilder withHighlight(String primaryColor, String secondaryColor) { 54 | this.animation = HighlightingAnimation.of(this.content, primaryColor, secondaryColor); 55 | return this; 56 | } 57 | 58 | /** 59 | * Add a highlighting animation to the line's content 60 | */ 61 | public LegacyLineBuilder withHighlight(ChatColor primary, ChatColor secondary) { 62 | this.animation = HighlightingAnimation.of(this.content, primary, secondary); 63 | return this; 64 | } 65 | 66 | /** 67 | * Add a scroll animation to the line's content 68 | */ 69 | public LegacyLineBuilder withScroll(int width, int spaceBetween) { 70 | this.animation = ScrollAnimation.of(this.content, width, spaceBetween); 71 | return this; 72 | } 73 | 74 | /** 75 | * Add a custom animation (must use the line's content as base) 76 | */ 77 | public LegacyLineBuilder withAnimation(Animation<String> customAnimation) { 78 | // Validate that the animation is based on this line's content 79 | if (customAnimation != null && !this.content.equals(customAnimation.getOriginal())) { 80 | throw new IllegalStateException("Animation's content '" + customAnimation.getOriginal() + "' does not match the line's content '" + content + "'"); 81 | } 82 | this.animation = customAnimation; 83 | return this; 84 | } 85 | 86 | /** 87 | * Build the Line instance 88 | */ 89 | public LineImplementation.LegacyLine build() { 90 | LineImplementation.LegacyLine line = new LineImplementation.LegacyLine(content, -1); 91 | if (animation != null) { 92 | line.setAnimation(animation); 93 | } 94 | return line; 95 | } 96 | } 97 | 98 | class AdventureLineBuilder { 99 | private final Component content; 100 | private Animation<Component> animation; 101 | 102 | public AdventureLineBuilder(Component content) { 103 | this.content = content; 104 | } 105 | 106 | /** 107 | * Add a highlighting animation to the line's content 108 | * Note: For components, this converts to legacy format for animation 109 | */ 110 | public AdventureLineBuilder withHighlight(ChatColor primary, ChatColor secondary) { 111 | // Convert component to legacy for highlighting animation 112 | // This is a limitation - proper component animation would need a component-aware highlighter 113 | String legacy = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer 114 | .legacySection().serialize(this.content); 115 | 116 | // Create animation and convert back 117 | Animation<String> legacyAnim = HighlightingAnimation.of(legacy, primary, secondary); 118 | 119 | this.animation = new Animation<Component>(this.content) { 120 | @Override 121 | public Component fetchNextChange() { 122 | String animatedLegacy = legacyAnim.fetchNextChange(); 123 | return net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer 124 | .legacySection().deserialize(animatedLegacy); 125 | } 126 | }; 127 | return this; 128 | } 129 | 130 | /** 131 | * Add a scroll animation to the line's content 132 | */ 133 | public AdventureLineBuilder withScroll(int width, int spaceBetween) { 134 | String legacy = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer 135 | .legacySection().serialize(this.content); 136 | Animation<String> legacyAnim = ScrollAnimation.of(legacy, width, spaceBetween); 137 | 138 | this.animation = new Animation<Component>(this.content) { 139 | @Override 140 | public Component fetchNextChange() { 141 | String animatedLegacy = legacyAnim.fetchNextChange(); 142 | return net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer 143 | .legacySection().deserialize(animatedLegacy); 144 | } 145 | }; 146 | return this; 147 | } 148 | 149 | /** 150 | * Add a custom animation 151 | */ 152 | public AdventureLineBuilder withAnimation(Animation<Component> customAnimation) { 153 | this.animation = customAnimation; 154 | return this; 155 | } 156 | 157 | /** 158 | * Build the Line instance 159 | */ 160 | public LineImplementation.AdventureLine build() { 161 | LineImplementation.AdventureLine line = new LineImplementation.AdventureLine(content, -1); 162 | if (animation != null) { 163 | line.setAnimation(animation); 164 | } 165 | return line; 166 | } 167 | } 168 | 169 | @Getter 170 | @Setter 171 | class LineImplementation<T> implements Line<T>{ 172 | private T content; 173 | private int index; 174 | private Animation<T> animation; 175 | 176 | public LineImplementation(T content, int index) { 177 | this.content = content; 178 | this.index = index; 179 | this.animation = null; 180 | } 181 | 182 | public static class LegacyLine extends LineImplementation<String>{ 183 | public LegacyLine(String content, int index) { 184 | super(content, index); 185 | } 186 | } 187 | 188 | public static class AdventureLine extends LineImplementation<Component>{ 189 | public AdventureLine(Component content, int index) { 190 | super(content, index); 191 | } 192 | } 193 | } 194 | } -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/base/impl/AdventureBoard.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.base.impl; 2 | 3 | import studio.mevera.scofi.Scofi; 4 | import studio.mevera.scofi.animation.core.Animation; 5 | import studio.mevera.scofi.base.BoardBase; 6 | import studio.mevera.scofi.base.BoardUpdate; 7 | import studio.mevera.scofi.base.ModernBoardAdapter; 8 | import studio.mevera.scofi.entity.Line; 9 | import studio.mevera.scofi.entity.Title; 10 | import studio.mevera.scofi.util.FastReflection; 11 | import lombok.Getter; 12 | import net.kyori.adventure.text.Component; 13 | import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; 14 | import org.bukkit.entity.Player; 15 | 16 | import java.lang.invoke.MethodHandle; 17 | import java.lang.invoke.MethodHandles; 18 | import java.lang.reflect.Array; 19 | import java.lang.reflect.Method; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | import java.util.Objects; 23 | 24 | import static studio.mevera.scofi.Scofi.ADVENTURE_SUPPORT; 25 | 26 | 27 | @Getter 28 | public class AdventureBoard extends BoardBase<Component> { 29 | 30 | private static final MethodHandle COMPONENT_METHOD; 31 | private static final Object EMPTY_COMPONENT; 32 | 33 | static { 34 | 35 | MethodHandles.Lookup lookup = MethodHandles.lookup(); 36 | 37 | try { 38 | if (ADVENTURE_SUPPORT) { 39 | Class<?> paperAdventure = Class.forName("io.papermc.paper.adventure.PaperAdventure"); 40 | Method method = paperAdventure.getDeclaredMethod("asVanilla", Component.class); 41 | COMPONENT_METHOD = lookup.unreflect(method); 42 | EMPTY_COMPONENT = COMPONENT_METHOD.invoke(Component.empty()); 43 | } else { 44 | Class<?> craftChatMessageClass = FastReflection.obcClass("util.CraftChatMessage"); 45 | COMPONENT_METHOD = lookup.unreflect(craftChatMessageClass.getMethod("fromString", String.class)); 46 | EMPTY_COMPONENT = Array.get(COMPONENT_METHOD.invoke(""), 0); 47 | } 48 | } catch (Throwable t) { 49 | throw new ExceptionInInitializerError(t); 50 | } 51 | } 52 | 53 | private final ModernBoardAdapter adapter; 54 | 55 | // Cache for animations to preserve their state 56 | private Animation<Component> cachedTitleAnimation; 57 | private final Map<Integer, Animation<Component>> cachedLineAnimations = new HashMap<>(); 58 | 59 | public AdventureBoard(Scofi scofi, Player player, ModernBoardAdapter adapter) { 60 | super(scofi, player); 61 | this.adapter = adapter; 62 | 63 | if (!update()) { 64 | scofi.getLogger().warning("Hey! Looks like you're using legacy text for your board instead of components," + 65 | " legacy text has been automatically converted for now. It is better that you use kyori adventure for modern minecraft."); 66 | } 67 | } 68 | 69 | @Override 70 | public BoardUpdate getUpdate() { 71 | return adapter.getBoardUpdate(); 72 | } 73 | 74 | @Override 75 | protected void sendLineChange(int score) throws Throwable { 76 | Component line = getLineByScore(score); 77 | 78 | sendTeamPacket(score, BoardBase.TeamMode.UPDATE, line, null); 79 | } 80 | 81 | @Override 82 | protected Object toMinecraftComponent(Component component) throws Throwable { 83 | if (component == null) { 84 | return EMPTY_COMPONENT; 85 | } 86 | 87 | // If the server isn't running adventure natively, we convert the component to legacy text 88 | // and then to a Minecraft chat component 89 | if (!ADVENTURE_SUPPORT) { 90 | String legacy = serializeLine(component); 91 | 92 | return Array.get(COMPONENT_METHOD.invoke(legacy), 0); 93 | } 94 | 95 | return COMPONENT_METHOD.invoke(component); 96 | } 97 | 98 | @Override 99 | protected String serializeLine(Component value) { 100 | return LegacyComponentSerializer.legacySection().serialize(value); 101 | } 102 | 103 | @Override 104 | protected Component emptyLine() { 105 | return Component.empty(); 106 | } 107 | 108 | @Override 109 | public boolean update() { 110 | try { 111 | // Get new title and body from adapter (for dynamic content) 112 | Title<Component> newTitle = adapter.getTitle(getPlayer()); 113 | 114 | // Handle title animation caching 115 | if (newTitle.loadAnimation().isPresent()) { 116 | Animation<Component> newTitleAnimation = newTitle.loadAnimation().get(); 117 | 118 | // If we don't have a cached animation or it's a different animation, cache it 119 | if (cachedTitleAnimation == null || !isSameAnimation(cachedTitleAnimation, newTitleAnimation)) { 120 | cachedTitleAnimation = newTitleAnimation; 121 | } else { 122 | // Use the cached animation to preserve state 123 | ((Title.TitleImplementation<Component>) newTitle).setTitleAnimation(cachedTitleAnimation); 124 | } 125 | } else { 126 | cachedTitleAnimation = null; 127 | } 128 | 129 | // Update title with preserved animation state 130 | updateTitle(newTitle.get().orElseThrow(IllegalStateException::new)); 131 | 132 | // Handle body/lines with animation caching 133 | for (Line<Component> line : adapter.getBody(getPlayer()).getLines()) { 134 | int index = line.getIndex(); 135 | Component content; 136 | 137 | // Handle line animation caching 138 | if (line.getAnimation() != null) { 139 | Animation<Component> lineAnimation = line.getAnimation(); 140 | Animation<Component> cachedAnimation = cachedLineAnimations.get(index); 141 | 142 | // If we don't have a cached animation or it's different, cache the new one 143 | if (cachedAnimation == null || !isSameAnimation(cachedAnimation, lineAnimation)) { 144 | cachedLineAnimations.put(index, lineAnimation); 145 | line.setAnimation(lineAnimation); 146 | } else { 147 | // Use cached animation to preserve state 148 | line.setAnimation(cachedAnimation); 149 | } 150 | 151 | content = line.fetchContent(); 152 | } else { 153 | // Remove cached animation if line no longer has one 154 | cachedLineAnimations.remove(index); 155 | content = line.getContent(); 156 | } 157 | 158 | updateLine(index, content); 159 | } 160 | 161 | // Clean up cached animations for lines that no longer exist 162 | int bodySize = adapter.getBody(getPlayer()).getLines().size(); 163 | cachedLineAnimations.entrySet().removeIf(entry -> entry.getKey() >= bodySize); 164 | 165 | return true; 166 | } catch (ClassCastException e) { 167 | // Fallback for legacy text 168 | for (Line<?> line : adapter.getBody(getPlayer()).getLines()) { 169 | updateLine(line.getIndex(), deserialize(line.fetchContent())); 170 | } 171 | updateTitle(deserialize(adapter.getTitle(getPlayer()).get().orElseThrow(IllegalStateException::new))); 172 | return false; 173 | } 174 | } 175 | 176 | private Component deserialize(Object o) { 177 | return LegacyComponentSerializer.legacyAmpersand().deserialize(o.toString()); 178 | } 179 | 180 | /** 181 | * Helper method to check if two animations are the "same" 182 | * (same original content and type) 183 | */ 184 | private boolean isSameAnimation(Animation<Component> cached, Animation<Component> newAnim) { 185 | // Check if they're the same type and have the same original content 186 | return cached.getClass().equals(newAnim.getClass()) 187 | && Objects.equals(cached.getOriginal(), newAnim.getOriginal()); 188 | } 189 | } -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/base/impl/LegacyBoard.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.base.impl; 2 | 3 | import studio.mevera.scofi.Scofi; 4 | import studio.mevera.scofi.animation.core.Animation; 5 | import studio.mevera.scofi.base.BoardBase; 6 | import studio.mevera.scofi.base.BoardUpdate; 7 | import studio.mevera.scofi.base.LegacyBoardAdapter; 8 | import studio.mevera.scofi.entity.Line; 9 | import studio.mevera.scofi.entity.Title; 10 | import studio.mevera.scofi.util.FastReflection; 11 | import lombok.Getter; 12 | import org.bukkit.ChatColor; 13 | import org.bukkit.entity.Player; 14 | 15 | import java.lang.invoke.MethodHandle; 16 | import java.lang.invoke.MethodHandles; 17 | import java.lang.reflect.Array; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | import java.util.Objects; 21 | 22 | @Getter 23 | public class LegacyBoard extends BoardBase<String> { 24 | 25 | private static final MethodHandle MESSAGE_FROM_STRING; 26 | private static final Object EMPTY_MESSAGE; 27 | 28 | static { 29 | try { 30 | MethodHandles.Lookup lookup = MethodHandles.lookup(); 31 | Class<?> craftChatMessageClass = FastReflection.obcClass("util.CraftChatMessage"); 32 | MESSAGE_FROM_STRING = lookup.unreflect(craftChatMessageClass.getMethod("fromString", String.class)); 33 | EMPTY_MESSAGE = Array.get(MESSAGE_FROM_STRING.invoke(""), 0); 34 | } catch (Throwable t) { 35 | throw new ExceptionInInitializerError(t); 36 | } 37 | } 38 | 39 | /** 40 | * Creates a new FastBoard. 41 | */ 42 | private final LegacyBoardAdapter adapter; 43 | 44 | // Cache for animations to preserve their state 45 | private Animation<String> cachedTitleAnimation; 46 | private final Map<Integer, Animation<String>> cachedLineAnimations = new HashMap<>(); 47 | 48 | public LegacyBoard(Scofi scofi, Player player, LegacyBoardAdapter adapter) { 49 | super(scofi, player); 50 | this.adapter = adapter; 51 | update(); 52 | } 53 | 54 | @Override 55 | public void updateTitle(String title) { 56 | Objects.requireNonNull(title, "title"); 57 | 58 | if (!VersionType.V1_13.isHigherOrEqual() && title.length() > 32) { 59 | throw new IllegalArgumentException("Title is longer than 32 chars"); 60 | } 61 | 62 | super.updateTitle(title); 63 | } 64 | 65 | /** 66 | * {@inheritDoc} 67 | */ 68 | @Override 69 | public void updateLines(String... lines) { 70 | Objects.requireNonNull(lines, "lines"); 71 | 72 | if (!VersionType.V1_13.isHigherOrEqual()) { 73 | int lineCount = 0; 74 | for (String s : lines) { 75 | if (s != null && s.length() > 30) { 76 | throw new IllegalArgumentException("Line " + lineCount + " is longer than 30 chars"); 77 | } 78 | lineCount++; 79 | } 80 | } 81 | 82 | super.updateLines(lines); 83 | } 84 | 85 | @Override 86 | public BoardUpdate getUpdate() { 87 | return adapter.getBoardUpdate(); 88 | } 89 | 90 | @Override 91 | protected void sendLineChange(int score) throws Throwable { 92 | int maxLength = hasLinesMaxLength() ? 16 : 1024; 93 | String line = getLineByScore(score); 94 | String prefix; 95 | String suffix = ""; 96 | 97 | if (line == null || line.isEmpty()) { 98 | prefix = COLOR_CODES[score] + ChatColor.RESET; 99 | } else if (line.length() <= maxLength) { 100 | prefix = line; 101 | } else { 102 | // Prevent splitting color codes 103 | int index = line.charAt(maxLength - 1) == ChatColor.COLOR_CHAR 104 | ? (maxLength - 1) : maxLength; 105 | prefix = line.substring(0, index); 106 | String suffixTmp = line.substring(index); 107 | ChatColor chatColor = null; 108 | 109 | if (suffixTmp.length() >= 2 && suffixTmp.charAt(0) == ChatColor.COLOR_CHAR) { 110 | chatColor = ChatColor.getByChar(suffixTmp.charAt(1)); 111 | } 112 | 113 | String color = ChatColor.getLastColors(prefix); 114 | boolean addColor = chatColor == null || chatColor.isFormat(); 115 | 116 | suffix = (addColor ? (color.isEmpty() ? ChatColor.RESET.toString() : color) : "") + suffixTmp; 117 | } 118 | 119 | if (prefix.length() > maxLength || suffix.length() > maxLength) { 120 | // Something went wrong, just cut to prevent client crash/kick 121 | prefix = prefix.substring(0, Math.min(maxLength, prefix.length())); 122 | suffix = suffix.substring(0, Math.min(maxLength, suffix.length())); 123 | } 124 | 125 | sendTeamPacket(score, TeamMode.UPDATE, prefix, suffix); 126 | } 127 | 128 | @Override 129 | protected Object toMinecraftComponent(String line) throws Throwable { 130 | if (line == null || line.isEmpty()) { 131 | return EMPTY_MESSAGE; 132 | } 133 | 134 | return Array.get(MESSAGE_FROM_STRING.invoke(line), 0); 135 | } 136 | 137 | @Override 138 | protected String serializeLine(String value) { 139 | return value; 140 | } 141 | 142 | @Override 143 | protected String emptyLine() { 144 | return ""; 145 | } 146 | 147 | @Override 148 | public boolean update() { 149 | // Get new title and body from adapter (for dynamic content) 150 | Title<String> newTitle = adapter.getTitle(getPlayer()); 151 | 152 | // Handle title animation caching 153 | if (newTitle.loadAnimation().isPresent()) { 154 | Animation<String> newTitleAnimation = newTitle.loadAnimation().get(); 155 | 156 | // If we don't have a cached animation or it's a different animation, cache it 157 | if (cachedTitleAnimation == null || !isSameAnimation(cachedTitleAnimation, newTitleAnimation)) { 158 | cachedTitleAnimation = newTitleAnimation; 159 | } else { 160 | // Use the cached animation to preserve state 161 | ((Title.TitleImplementation<String>) newTitle).setTitleAnimation(cachedTitleAnimation); 162 | } 163 | } else { 164 | cachedTitleAnimation = null; 165 | } 166 | 167 | // Update title with preserved animation state 168 | updateTitle(newTitle.get().orElseThrow(IllegalStateException::new)); 169 | 170 | // Handle body/lines with animation caching 171 | for (Line<String> line : adapter.getBody(getPlayer()).getLines()) { 172 | int index = line.getIndex(); 173 | 174 | // Handle line animation caching 175 | if (line.getAnimation() != null) { 176 | Animation<String> lineAnimation = line.getAnimation(); 177 | Animation<String> cachedAnimation = cachedLineAnimations.get(index); 178 | 179 | // If we don't have a cached animation or it's different, cache the new one 180 | if (cachedAnimation == null || !isSameAnimation(cachedAnimation, lineAnimation)) { 181 | cachedLineAnimations.put(index, lineAnimation); 182 | } else { 183 | // Use cached animation to preserve state 184 | line.setAnimation(cachedAnimation); 185 | } 186 | } else { 187 | // Remove cached animation if line no longer has one 188 | cachedLineAnimations.remove(index); 189 | } 190 | 191 | updateLine(index, line.fetchContent()); 192 | } 193 | 194 | // Clean up cached animations for lines that no longer exist 195 | int bodySize = adapter.getBody(getPlayer()).getLines().size(); 196 | cachedLineAnimations.entrySet().removeIf(entry -> entry.getKey() >= bodySize); 197 | 198 | return true; 199 | } 200 | 201 | /** 202 | * Helper method to check if two animations are the "same" 203 | * (same original content and type) 204 | */ 205 | private boolean isSameAnimation(Animation<String> cached, Animation<String> newAnim) { 206 | // Check if they're the same type and have the same original content 207 | return cached.getClass().equals(newAnim.getClass()) 208 | && Objects.equals(cached.getOriginal(), newAnim.getOriginal()); 209 | } 210 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <project version="4"> 3 | <component name="Palette2"> 4 | <group name="Swing"> 5 | <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 6 | <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" /> 7 | </item> 8 | <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 9 | <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" /> 10 | </item> 11 | <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 12 | <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" /> 13 | </item> 14 | <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true"> 15 | <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" /> 16 | </item> 17 | <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 18 | <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" /> 19 | <initial-values> 20 | <property name="text" value="Button" /> 21 | </initial-values> 22 | </item> 23 | <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 24 | <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> 25 | <initial-values> 26 | <property name="text" value="RadioButton" /> 27 | </initial-values> 28 | </item> 29 | <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 30 | <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> 31 | <initial-values> 32 | <property name="text" value="CheckBox" /> 33 | </initial-values> 34 | </item> 35 | <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 36 | <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" /> 37 | <initial-values> 38 | <property name="text" value="Label" /> 39 | </initial-values> 40 | </item> 41 | <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 42 | <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> 43 | <preferred-size width="150" height="-1" /> 44 | </default-constraints> 45 | </item> 46 | <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 47 | <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> 48 | <preferred-size width="150" height="-1" /> 49 | </default-constraints> 50 | </item> 51 | <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 52 | <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> 53 | <preferred-size width="150" height="-1" /> 54 | </default-constraints> 55 | </item> 56 | <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 57 | <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> 58 | <preferred-size width="150" height="50" /> 59 | </default-constraints> 60 | </item> 61 | <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 62 | <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> 63 | <preferred-size width="150" height="50" /> 64 | </default-constraints> 65 | </item> 66 | <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 67 | <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> 68 | <preferred-size width="150" height="50" /> 69 | </default-constraints> 70 | </item> 71 | <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 72 | <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" /> 73 | </item> 74 | <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 75 | <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> 76 | <preferred-size width="150" height="50" /> 77 | </default-constraints> 78 | </item> 79 | <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 80 | <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3"> 81 | <preferred-size width="150" height="50" /> 82 | </default-constraints> 83 | </item> 84 | <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 85 | <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> 86 | <preferred-size width="150" height="50" /> 87 | </default-constraints> 88 | </item> 89 | <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 90 | <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> 91 | <preferred-size width="200" height="200" /> 92 | </default-constraints> 93 | </item> 94 | <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 95 | <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> 96 | <preferred-size width="200" height="200" /> 97 | </default-constraints> 98 | </item> 99 | <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true"> 100 | <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> 101 | </item> 102 | <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 103 | <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> 104 | </item> 105 | <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 106 | <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" /> 107 | </item> 108 | <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 109 | <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" /> 110 | </item> 111 | <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 112 | <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1"> 113 | <preferred-size width="-1" height="20" /> 114 | </default-constraints> 115 | </item> 116 | <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false"> 117 | <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" /> 118 | </item> 119 | <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false"> 120 | <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" /> 121 | </item> 122 | </group> 123 | </component> 124 | </project> -------------------------------------------------------------------------------- /src/main/java/studio/mevera/scofi/base/BoardBase.java: -------------------------------------------------------------------------------- 1 | package studio.mevera.scofi.base; 2 | 3 | import studio.mevera.scofi.Scofi; 4 | import studio.mevera.scofi.util.FastReflection; 5 | import lombok.Getter; 6 | import net.md_5.bungee.api.ChatColor; 7 | import org.bukkit.entity.Player; 8 | 9 | import java.lang.invoke.MethodHandle; 10 | import java.lang.invoke.MethodHandles; 11 | import java.lang.invoke.MethodType; 12 | import java.lang.reflect.Field; 13 | import java.lang.reflect.Method; 14 | import java.lang.reflect.Modifier; 15 | import java.util.*; 16 | import java.util.concurrent.ThreadLocalRandom; 17 | import java.util.stream.Stream; 18 | 19 | /** 20 | * @Author <a href="https://github.com/MrMicky-FR">MrMicky-FR</a> 21 | */ 22 | 23 | public abstract class BoardBase<T> { 24 | 25 | private static final Map<Class<?>, Field[]> PACKETS = new HashMap<>(8); 26 | protected static final String[] COLOR_CODES = Arrays.stream(ChatColor.values()) 27 | .map(Object::toString) 28 | .toArray(String[]::new); 29 | private static final VersionType VERSION_TYPE; 30 | // Packets and components 31 | private static final Class<?> CHAT_COMPONENT_CLASS; 32 | private static final Class<?> CHAT_FORMAT_ENUM; 33 | private static final Object RESET_FORMATTING; 34 | private static final MethodHandle PLAYER_CONNECTION; 35 | private static final MethodHandle SEND_PACKET; 36 | private static final MethodHandle PLAYER_GET_HANDLE; 37 | private static final MethodHandle FIXED_NUMBER_FORMAT; 38 | // Scoreboard packets 39 | private static final FastReflection.PacketConstructor PACKET_SB_OBJ; 40 | private static final FastReflection.PacketConstructor PACKET_SB_DISPLAY_OBJ; 41 | private static final FastReflection.PacketConstructor PACKET_SB_TEAM; 42 | private static final FastReflection.PacketConstructor PACKET_SB_SERIALIZABLE_TEAM; 43 | private static final MethodHandle PACKET_SB_SET_SCORE; 44 | private static final MethodHandle PACKET_SB_RESET_SCORE; 45 | private static final boolean SCORE_OPTIONAL_COMPONENTS; 46 | // Scoreboard enums 47 | private static final Class<?> DISPLAY_SLOT_TYPE; 48 | private static final Class<?> ENUM_SB_HEALTH_DISPLAY; 49 | private static final Class<?> ENUM_SB_ACTION; 50 | private static final Class<?> ENUM_VISIBILITY; 51 | private static final Class<?> ENUM_COLLISION_RULE; 52 | private static final Object BLANK_NUMBER_FORMAT; 53 | private static final Object SIDEBAR_DISPLAY_SLOT; 54 | private static final Object ENUM_SB_HEALTH_DISPLAY_INTEGER; 55 | private static final Object ENUM_SB_ACTION_CHANGE; 56 | private static final Object ENUM_SB_ACTION_REMOVE; 57 | private static final Object ENUM_VISIBILITY_ALWAYS; 58 | private static final Object ENUM_COLLISION_RULE_ALWAYS; 59 | 60 | static { 61 | try { 62 | MethodHandles.Lookup lookup = MethodHandles.lookup(); 63 | 64 | if (FastReflection.isRepackaged()) { 65 | VERSION_TYPE = VersionType.V1_17; 66 | } else if (FastReflection.nmsOptionalClass(null, "ScoreboardServer$Action").isPresent() 67 | || FastReflection.nmsOptionalClass(null, "ServerScoreboard$Method").isPresent()) { 68 | VERSION_TYPE = VersionType.V1_13; 69 | } else if (FastReflection.nmsOptionalClass(null, "IScoreboardCriteria$EnumScoreboardHealthDisplay").isPresent() 70 | || FastReflection.nmsOptionalClass(null, "ObjectiveCriteria$RenderType").isPresent()) { 71 | VERSION_TYPE = VersionType.V1_8; 72 | } else { 73 | VERSION_TYPE = VersionType.V1_7; 74 | } 75 | 76 | String gameProtocolPackage = "network.protocol.game"; 77 | Class<?> craftPlayerClass = FastReflection.obcClass("entity.CraftPlayer"); 78 | Class<?> entityPlayerClass = FastReflection.nmsClass("server.level", "EntityPlayer", "ServerPlayer"); 79 | Class<?> playerConnectionClass = FastReflection.nmsClass("server.network", "PlayerConnection", "ServerGamePacketListenerImpl"); 80 | Class<?> packetClass = FastReflection.nmsClass("network.protocol", "Packet"); 81 | Class<?> packetSbObjClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardObjective", "ClientboundSetObjectivePacket"); 82 | Class<?> packetSbDisplayObjClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardDisplayObjective", "ClientboundSetDisplayObjectivePacket"); 83 | Class<?> packetSbScoreClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardScore", "ClientboundSetScorePacket"); 84 | Class<?> packetSbTeamClass = FastReflection.nmsClass(gameProtocolPackage, "PacketPlayOutScoreboardTeam", "ClientboundSetPlayerTeamPacket"); 85 | Class<?> sbTeamClass = VersionType.V1_17.isHigherOrEqual() 86 | ? FastReflection.innerClass(packetSbTeamClass, innerClass -> !innerClass.isEnum()) : null; 87 | Field playerConnectionField = Arrays.stream(entityPlayerClass.getFields()) 88 | .filter(field -> field.getType().isAssignableFrom(playerConnectionClass)) 89 | .findFirst().orElseThrow(NoSuchFieldException::new); 90 | Method sendPacketMethod = Stream.concat( 91 | Arrays.stream(playerConnectionClass.getSuperclass().getMethods()), 92 | Arrays.stream(playerConnectionClass.getMethods()) 93 | ) 94 | .filter(m -> m.getParameterCount() == 1 && m.getParameterTypes()[0] == packetClass) 95 | .findFirst().orElseThrow(NoSuchMethodException::new); 96 | Optional<Class<?>> displaySlotEnum = FastReflection.nmsOptionalClass("world.scores", "DisplaySlot"); 97 | CHAT_COMPONENT_CLASS = FastReflection.nmsClass("network.chat", "IChatBaseComponent","Component"); 98 | CHAT_FORMAT_ENUM = FastReflection.nmsClass(null, "EnumChatFormat", "ChatFormatting"); 99 | DISPLAY_SLOT_TYPE = displaySlotEnum.orElse(int.class); 100 | RESET_FORMATTING = FastReflection.enumValueOf(CHAT_FORMAT_ENUM, "RESET", 21); 101 | SIDEBAR_DISPLAY_SLOT = displaySlotEnum.isPresent() ? FastReflection.enumValueOf(DISPLAY_SLOT_TYPE, "SIDEBAR", 1) : 1; 102 | PLAYER_GET_HANDLE = lookup.findVirtual(craftPlayerClass, "getHandle", MethodType.methodType(entityPlayerClass)); 103 | PLAYER_CONNECTION = lookup.unreflectGetter(playerConnectionField); 104 | SEND_PACKET = lookup.unreflect(sendPacketMethod); 105 | PACKET_SB_OBJ = FastReflection.findPacketConstructor(packetSbObjClass, lookup); 106 | PACKET_SB_DISPLAY_OBJ = FastReflection.findPacketConstructor(packetSbDisplayObjClass, lookup); 107 | 108 | Optional<Class<?>> numberFormat = FastReflection.nmsOptionalClass("network.chat.numbers", "NumberFormat"); 109 | MethodHandle packetSbSetScore; 110 | MethodHandle packetSbResetScore = null; 111 | MethodHandle fixedFormatConstructor = null; 112 | Object blankNumberFormat = null; 113 | boolean scoreOptionalComponents = false; 114 | 115 | if (numberFormat.isPresent()) { // 1.20.3 116 | Class<?> blankFormatClass = FastReflection.nmsClass("network.chat.numbers", "BlankFormat"); 117 | Class<?> fixedFormatClass = FastReflection.nmsClass("network.chat.numbers", "FixedFormat"); 118 | Class<?> resetScoreClass = FastReflection.nmsClass(gameProtocolPackage, "ClientboundResetScorePacket"); 119 | MethodType scoreType = MethodType.methodType(void.class, String.class, String.class, int.class, CHAT_COMPONENT_CLASS, numberFormat.get()); 120 | MethodType scoreTypeOptional = MethodType.methodType(void.class, String.class, String.class, int.class, Optional.class, Optional.class); 121 | MethodType removeScoreType = MethodType.methodType(void.class, String.class, String.class); 122 | MethodType fixedFormatType = MethodType.methodType(void.class, CHAT_COMPONENT_CLASS); 123 | Optional<Field> blankField = Arrays.stream(blankFormatClass.getFields()).filter(f -> f.getType() == blankFormatClass).findAny(); 124 | // Fields are of type Optional in 1.20.5+ 125 | Optional<MethodHandle> optionalScorePacket = FastReflection.optionalConstructor(packetSbScoreClass, lookup, scoreTypeOptional); 126 | fixedFormatConstructor = lookup.findConstructor(fixedFormatClass, fixedFormatType); 127 | packetSbSetScore = optionalScorePacket.isPresent() ? optionalScorePacket.get() 128 | : lookup.findConstructor(packetSbScoreClass, scoreType); 129 | scoreOptionalComponents = optionalScorePacket.isPresent(); 130 | packetSbResetScore = lookup.findConstructor(resetScoreClass, removeScoreType); 131 | blankNumberFormat = blankField.isPresent() ? blankField.get().get(null) : null; 132 | } else if (VersionType.V1_17.isHigherOrEqual()) { 133 | Class<?> enumSbAction = FastReflection.nmsClass("server", "ScoreboardServer$Action", "ServerScoreboard$Method"); 134 | MethodType scoreType = MethodType.methodType(void.class, enumSbAction, String.class, String.class, int.class); 135 | packetSbSetScore = lookup.findConstructor(packetSbScoreClass, scoreType); 136 | } else { 137 | packetSbSetScore = lookup.findConstructor(packetSbScoreClass, MethodType.methodType(void.class)); 138 | } 139 | 140 | PACKET_SB_SET_SCORE = packetSbSetScore; 141 | PACKET_SB_RESET_SCORE = packetSbResetScore; 142 | PACKET_SB_TEAM = FastReflection.findPacketConstructor(packetSbTeamClass, lookup); 143 | PACKET_SB_SERIALIZABLE_TEAM = sbTeamClass == null ? null : FastReflection.findPacketConstructor(sbTeamClass, lookup); 144 | FIXED_NUMBER_FORMAT = fixedFormatConstructor; 145 | BLANK_NUMBER_FORMAT = blankNumberFormat; 146 | SCORE_OPTIONAL_COMPONENTS = scoreOptionalComponents; 147 | 148 | if (VersionType.V1_17.isHigherOrEqual()) { 149 | ENUM_VISIBILITY = FastReflection.nmsClass("world.scores", "ScoreboardTeamBase$EnumNameTagVisibility", "Team$Visibility"); 150 | ENUM_COLLISION_RULE = FastReflection.nmsClass("world.scores", "ScoreboardTeamBase$EnumTeamPush", "Team$CollisionRule"); 151 | ENUM_VISIBILITY_ALWAYS = FastReflection.enumValueOf(ENUM_VISIBILITY, "ALWAYS", 0); 152 | ENUM_COLLISION_RULE_ALWAYS = FastReflection.enumValueOf(ENUM_COLLISION_RULE, "ALWAYS", 0); 153 | } else { 154 | ENUM_VISIBILITY = null; 155 | ENUM_COLLISION_RULE = null; 156 | ENUM_VISIBILITY_ALWAYS = null; 157 | ENUM_COLLISION_RULE_ALWAYS = null; 158 | } 159 | 160 | for (Class<?> clazz : Arrays.asList(packetSbObjClass, packetSbDisplayObjClass, packetSbScoreClass, packetSbTeamClass, sbTeamClass)) { 161 | if (clazz == null) { 162 | continue; 163 | } 164 | Field[] fields = Arrays.stream(clazz.getDeclaredFields()) 165 | .filter(field -> !Modifier.isStatic(field.getModifiers())) 166 | .toArray(Field[]::new); 167 | for (Field field : fields) { 168 | field.setAccessible(true); 169 | } 170 | PACKETS.put(clazz, fields); 171 | } 172 | 173 | if (VersionType.V1_8.isHigherOrEqual()) { 174 | String enumSbActionClass = VersionType.V1_13.isHigherOrEqual() 175 | ? "ScoreboardServer$Action" 176 | : "PacketPlayOutScoreboardScore$EnumScoreboardAction"; 177 | ENUM_SB_HEALTH_DISPLAY = FastReflection.nmsClass("world.scores.criteria", "IScoreboardCriteria$EnumScoreboardHealthDisplay", "ObjectiveCriteria$RenderType"); 178 | ENUM_SB_ACTION = FastReflection.nmsClass("server", enumSbActionClass, "ServerScoreboard$Method"); 179 | ENUM_SB_HEALTH_DISPLAY_INTEGER = FastReflection.enumValueOf(ENUM_SB_HEALTH_DISPLAY, "INTEGER", 0); 180 | ENUM_SB_ACTION_CHANGE = FastReflection.enumValueOf(ENUM_SB_ACTION, "CHANGE", 0); 181 | ENUM_SB_ACTION_REMOVE = FastReflection.enumValueOf(ENUM_SB_ACTION, "REMOVE", 1); 182 | } else { 183 | ENUM_SB_HEALTH_DISPLAY = null; 184 | ENUM_SB_ACTION = null; 185 | ENUM_SB_HEALTH_DISPLAY_INTEGER = null; 186 | ENUM_SB_ACTION_CHANGE = null; 187 | ENUM_SB_ACTION_REMOVE = null; 188 | } 189 | } catch (Throwable t) { 190 | throw new ExceptionInInitializerError(t); 191 | } 192 | } 193 | 194 | /** 195 | * -- GETTER -- 196 | * Get the player who has the scoreboard. 197 | * 198 | * @return current player for this FastBoard 199 | */ 200 | @Getter 201 | private final Player player; 202 | /** 203 | * -- GETTER -- 204 | * Get the scoreboard id. 205 | * 206 | * @return the id 207 | */ 208 | @Getter 209 | private final String id; 210 | 211 | private final List<T> lines = new ArrayList<>(); 212 | private final List<T> scores = new ArrayList<>(); 213 | /** 214 | * -- GETTER -- 215 | * Get the scoreboard title. 216 | * 217 | * @return the scoreboard title 218 | */ 219 | @Getter 220 | private T title = emptyLine(); 221 | 222 | /** 223 | * -- GETTER -- 224 | * Get if the scoreboard is deleted. 225 | * 226 | * @return true if the scoreboard is deleted 227 | */ 228 | @Getter 229 | private boolean deleted = false; 230 | 231 | /** 232 | * Creates a new FastBoard. 233 | * 234 | * @param player the owner of the scoreboard 235 | */ 236 | protected BoardBase(Scofi scofi, Player player) { 237 | this.player = Objects.requireNonNull(player, "player"); 238 | this.id = "fb-" + Integer.toHexString(ThreadLocalRandom.current().nextInt()); 239 | 240 | try { 241 | sendObjectivePacket(ObjectiveMode.CREATE); 242 | sendDisplayObjectivePacket(); 243 | } catch (Throwable t) { 244 | throw new RuntimeException("Unable to create scoreboard", t); 245 | } 246 | 247 | /* updateTitle(); 248 | updateLines();*/ 249 | } 250 | 251 | /** 252 | * Update the scoreboard title. 253 | * 254 | * @param title the new scoreboard title 255 | * @throws IllegalArgumentException if the title is longer than 32 chars on 1.12 or lower 256 | * @throws IllegalStateException if {@link #delete()} was call before 257 | */ 258 | public void updateTitle(T title) { 259 | if (this.title.equals(Objects.requireNonNull(title, "title"))) { 260 | return; 261 | } 262 | 263 | this.title = title; 264 | 265 | try { 266 | sendObjectivePacket(ObjectiveMode.UPDATE); 267 | } catch (Throwable t) { 268 | throw new RuntimeException("Unable to update scoreboard title", t); 269 | } 270 | } 271 | 272 | /** 273 | * Get the scoreboard lines. 274 | * 275 | * @return the scoreboard lines 276 | */ 277 | public List<T> getLines() { 278 | return new ArrayList<>(this.lines); 279 | } 280 | 281 | /** 282 | * Get the specified scoreboard line. 283 | * 284 | * @param line the line number 285 | * @return the line 286 | * @throws IndexOutOfBoundsException if the line is higher than {@code size} 287 | */ 288 | public T getLine(int line) { 289 | checkLineNumber(line, true, false); 290 | return this.lines.get(line); 291 | } 292 | 293 | /** 294 | * Get how a specific line's score is displayed. On 1.20.2 or below, the value returned isn't used. 295 | * 296 | * @param line the line number 297 | * @return the text of how the line is displayed 298 | * @throws IndexOutOfBoundsException if the line is higher than {@code size} 299 | */ 300 | public Optional<T> getScore(int line) { 301 | checkLineNumber(line, true, false); 302 | 303 | return Optional.ofNullable(this.scores.get(line)); 304 | } 305 | 306 | /** 307 | * Update a single scoreboard line. 308 | * 309 | * @param line the line number 310 | * @param text the new line text 311 | * @throws IndexOutOfBoundsException if the line is higher than {@link #size() size() + 1} 312 | */ 313 | public synchronized void updateLine(int line, T text) { 314 | updateLine(line, text, null); 315 | 316 | } 317 | 318 | /** 319 | * Update a single scoreboard line including how its score is displayed. 320 | * The score will only be displayed on 1.20.3 and higher. 321 | * 322 | * @param line the line number 323 | * @param text the new line text 324 | * @param scoreText the new line's score, if null will not change current value 325 | * @throws IndexOutOfBoundsException if the line is higher than {@link #size() size() + 1} 326 | */ 327 | public synchronized void updateLine(int line, T text, T scoreText) { 328 | checkLineNumber(line, false, false); 329 | try { 330 | if (line < size()) { 331 | this.lines.set(line, text); 332 | this.scores.set(line, scoreText); 333 | 334 | sendLineChange(getScoreByLine(line)); 335 | 336 | if (customScoresSupported()) { 337 | sendScorePacket(getScoreByLine(line), ScoreboardAction.CHANGE); 338 | } 339 | 340 | return; 341 | } 342 | 343 | List<T> newLines = new ArrayList<>(this.lines); 344 | List<T> newScores = new ArrayList<>(this.scores); 345 | 346 | if (line > size()) { 347 | for (int i = size(); i < line; i++) { 348 | newLines.add(emptyLine()); 349 | newScores.add(null); 350 | } 351 | } 352 | 353 | newLines.add(text); 354 | newScores.add(scoreText); 355 | 356 | updateLines(newLines, newScores); 357 | } catch (Throwable t) { 358 | throw new RuntimeException("Unable to update scoreboard lines", t); 359 | } 360 | } 361 | 362 | /** 363 | * Remove a scoreboard line. 364 | * 365 | * @param line the line number 366 | */ 367 | public synchronized void removeLine(int line) { 368 | checkLineNumber(line, false, false); 369 | 370 | if (line >= size()) { 371 | return; 372 | } 373 | 374 | List<T> newLines = new ArrayList<>(this.lines); 375 | List<T> newScores = new ArrayList<>(this.scores); 376 | newLines.remove(line); 377 | newScores.remove(line); 378 | updateLines(newLines, newScores); 379 | } 380 | 381 | /** 382 | * Update all the scoreboard lines. 383 | * 384 | * @param lines the new lines 385 | * @throws IllegalArgumentException if one line is longer than 30 chars on 1.12 or lower 386 | * @throws IllegalStateException if {@link #delete()} was call before 387 | */ 388 | public void updateLines(T... lines) { 389 | updateLines(Arrays.asList(lines)); 390 | } 391 | 392 | public void updateLines() { 393 | updateLines(this.getLines()); 394 | } 395 | 396 | /** 397 | * Update the lines of the scoreboard 398 | * 399 | * @param lines the new scoreboard lines 400 | * @throws IllegalArgumentException if one line is longer than 30 chars on 1.12 or lower 401 | * @throws IllegalStateException if {@link #delete()} was call before 402 | */ 403 | public synchronized void updateLines(Collection<T> lines) { 404 | updateLines(lines, null); 405 | } 406 | 407 | /** 408 | * Update the lines and how their score is displayed on the scoreboard. 409 | * The scores will only be displayed for servers on 1.20.3 and higher. 410 | * 411 | * @param lines the new scoreboard lines 412 | * @param scores the set for how each line's score should be, if null will fall back to default (blank) 413 | * @throws IllegalArgumentException if one line is longer than 30 chars on 1.12 or lower 414 | * @throws IllegalArgumentException if lines and scores are not the same size 415 | * @throws IllegalStateException if {@link #delete()} was call before 416 | */ 417 | public synchronized void updateLines(Collection<T> lines, Collection<T> scores) { 418 | Objects.requireNonNull(lines, "lines"); 419 | checkLineNumber(lines.size(), false, true); 420 | 421 | if (scores != null && scores.size() != lines.size()) { 422 | throw new IllegalArgumentException("The size of the scores must match the size of the board"); 423 | } 424 | 425 | List<T> oldLines = new ArrayList<>(this.lines); 426 | this.lines.clear(); 427 | this.lines.addAll(lines); 428 | 429 | List<T> oldScores = new ArrayList<>(this.scores); 430 | this.scores.clear(); 431 | this.scores.addAll(scores != null ? scores : Collections.nCopies(lines.size(), null)); 432 | 433 | int linesSize = this.lines.size(); 434 | 435 | try { 436 | if (oldLines.size() != linesSize) { 437 | List<T> oldLinesCopy = new ArrayList<>(oldLines); 438 | 439 | if (oldLines.size() > linesSize) { 440 | for (int i = oldLinesCopy.size(); i > linesSize; i--) { 441 | sendTeamPacket(i - 1, TeamMode.REMOVE); 442 | sendScorePacket(i - 1, ScoreboardAction.REMOVE); 443 | oldLines.remove(0); 444 | } 445 | } else { 446 | for (int i = oldLinesCopy.size(); i < linesSize; i++) { 447 | sendScorePacket(i, ScoreboardAction.CHANGE); 448 | sendTeamPacket(i, TeamMode.CREATE, null, null); 449 | } 450 | } 451 | } 452 | 453 | for (int i = 0; i < linesSize; i++) { 454 | if (!Objects.equals(getLineByScore(oldLines, i), getLineByScore(i))) { 455 | sendLineChange(i); 456 | } 457 | if (!Objects.equals(getLineByScore(oldScores, i), getLineByScore(this.scores, i))) { 458 | sendScorePacket(i, ScoreboardAction.CHANGE); 459 | } 460 | } 461 | } catch (Throwable t) { 462 | throw new RuntimeException("Unable to update scoreboard lines", t); 463 | } 464 | } 465 | 466 | /** 467 | * Update how a specified line's score is displayed on the scoreboard. A null value will reset the displayed 468 | * text back to default. The scores will only be displayed for servers on 1.20.3 and higher. 469 | * 470 | * @param line the line number 471 | * @param text the text to be displayed as the score. if null, no score will be displayed 472 | * @throws IllegalArgumentException if the line number is not in range 473 | * @throws IllegalStateException if {@link #delete()} was call before 474 | */ 475 | public synchronized void updateScore(int line, T text) { 476 | checkLineNumber(line, true, false); 477 | 478 | this.scores.set(line, text); 479 | 480 | try { 481 | if (customScoresSupported()) { 482 | sendScorePacket(getScoreByLine(line), ScoreboardAction.CHANGE); 483 | } 484 | } catch (Throwable e) { 485 | throw new RuntimeException("Unable to update line score", e); 486 | } 487 | } 488 | 489 | /** 490 | * Reset a line's score back to default (blank). The score will only be displayed for servers on 1.20.3 and higher. 491 | * 492 | * @param line the line number 493 | * @throws IllegalArgumentException if the line number is not in range 494 | * @throws IllegalStateException if {@link #delete()} was call before 495 | */ 496 | public synchronized void removeScore(int line) { 497 | updateScore(line, null); 498 | } 499 | 500 | /** 501 | * Update how all lines' scores are displayed. A value of null will reset the displayed text back to default. 502 | * The scores will only be displayed for servers on 1.20.3 and higher. 503 | * 504 | * @param texts the set of texts to be displayed as the scores 505 | * @throws IllegalArgumentException if the size of the texts does not match the current size of the board 506 | * @throws IllegalStateException if {@link #delete()} was call before 507 | */ 508 | public synchronized void updateScores(T... texts) { 509 | updateScores(Arrays.asList(texts)); 510 | } 511 | 512 | /** 513 | * Update how all lines' scores are displayed. A null value will reset the displayed 514 | * text back to default (blank). Only available on 1.20.3+ servers. 515 | * 516 | * @param texts the set of texts to be displayed as the scores 517 | * @throws IllegalArgumentException if the size of the texts does not match the current size of the board 518 | * @throws IllegalStateException if {@link #delete()} was call before 519 | */ 520 | public synchronized void updateScores(Collection<T> texts) { 521 | Objects.requireNonNull(texts, "texts"); 522 | 523 | if (this.scores.size() != this.lines.size()) { 524 | throw new IllegalArgumentException("The size of the scores must match the size of the board"); 525 | } 526 | 527 | List<T> newScores = new ArrayList<>(texts); 528 | for (int i = 0; i < this.scores.size(); i++) { 529 | if (Objects.equals(this.scores.get(i), newScores.get(i))) { 530 | continue; 531 | } 532 | 533 | this.scores.set(i, newScores.get(i)); 534 | 535 | try { 536 | if (customScoresSupported()) { 537 | sendScorePacket(getScoreByLine(i), ScoreboardAction.CHANGE); 538 | } 539 | } catch (Throwable e) { 540 | throw new RuntimeException("Unable to update scores", e); 541 | } 542 | } 543 | } 544 | 545 | /** 546 | * Get if the server supports custom scoreboard scores (1.20.3+ servers only). 547 | * 548 | * @return true if the server supports custom scores 549 | */ 550 | public boolean customScoresSupported() { 551 | return BLANK_NUMBER_FORMAT != null; 552 | } 553 | 554 | /** 555 | * Get the scoreboard size (the number of lines). 556 | * 557 | * @return the size 558 | */ 559 | public int size() { 560 | return this.lines.size(); 561 | } 562 | 563 | /** 564 | * Delete this FastBoard, and will remove the scoreboard for the associated player if he is online. 565 | * After this, all uses of {@link #updateLines} and {@link #updateTitle} will throw an {@link IllegalStateException} 566 | * 567 | * @throws IllegalStateException if this was already call before 568 | */ 569 | public void delete() { 570 | try { 571 | for (int i = 0; i < this.lines.size(); i++) { 572 | sendTeamPacket(i, TeamMode.REMOVE); 573 | } 574 | 575 | sendObjectivePacket(ObjectiveMode.REMOVE); 576 | } catch (Throwable t) { 577 | throw new RuntimeException("Unable to delete scoreboard", t); 578 | } 579 | 580 | this.deleted = true; 581 | } 582 | public abstract BoardUpdate getUpdate(); 583 | 584 | protected abstract void sendLineChange(int score) throws Throwable; 585 | 586 | protected abstract Object toMinecraftComponent(T value) throws Throwable; 587 | 588 | protected abstract String serializeLine(T value); 589 | 590 | protected abstract T emptyLine(); 591 | 592 | private void checkLineNumber(int line, boolean checkInRange, boolean checkMax) { 593 | if (line < 0) { 594 | throw new IllegalArgumentException("Line number must be positive"); 595 | } 596 | 597 | if (checkInRange && line >= this.lines.size()) { 598 | throw new IllegalArgumentException("Line number must be under " + this.lines.size()); 599 | } 600 | 601 | if (checkMax && line >= COLOR_CODES.length - 1) { 602 | throw new IllegalArgumentException("Line number is too high: " + line); 603 | } 604 | } 605 | 606 | protected int getScoreByLine(int line) { 607 | return this.lines.size() - line - 1; 608 | } 609 | 610 | protected T getLineByScore(int score) { 611 | return getLineByScore(this.lines, score); 612 | } 613 | 614 | protected T getLineByScore(List<T> lines, int score) { 615 | return score < lines.size() ? lines.get(lines.size() - score - 1) : null; 616 | } 617 | 618 | protected void sendObjectivePacket(ObjectiveMode mode) throws Throwable { 619 | Object packet = PACKET_SB_OBJ.invoke(); 620 | 621 | setField(packet, String.class, this.id); 622 | setField(packet, int.class, mode.ordinal()); 623 | 624 | if (mode != ObjectiveMode.REMOVE) { 625 | setComponentField(packet, this.title, 1); 626 | setField(packet, Optional.class, Optional.empty()); // Number format for 1.20.5+, previously nullable 627 | 628 | if (VersionType.V1_8.isHigherOrEqual()) { 629 | setField(packet, ENUM_SB_HEALTH_DISPLAY, ENUM_SB_HEALTH_DISPLAY_INTEGER); 630 | } 631 | } else if (VERSION_TYPE == VersionType.V1_7) { 632 | setField(packet, String.class, "", 1); 633 | } 634 | 635 | sendPacket(packet); 636 | } 637 | 638 | protected void sendDisplayObjectivePacket() throws Throwable { 639 | Object packet = PACKET_SB_DISPLAY_OBJ.invoke(); 640 | 641 | setField(packet, DISPLAY_SLOT_TYPE, SIDEBAR_DISPLAY_SLOT); // Position 642 | setField(packet, String.class, this.id); // Score Name 643 | 644 | sendPacket(packet); 645 | } 646 | 647 | protected void sendScorePacket(int score, ScoreboardAction action) throws Throwable { 648 | if (VersionType.V1_17.isHigherOrEqual()) { 649 | sendModernScorePacket(score, action); 650 | return; 651 | } 652 | 653 | Object packet = PACKET_SB_SET_SCORE.invoke(); 654 | 655 | setField(packet, String.class, COLOR_CODES[score], 0); // Player Name 656 | 657 | if (VersionType.V1_8.isHigherOrEqual()) { 658 | Object enumAction = action == ScoreboardAction.REMOVE 659 | ? ENUM_SB_ACTION_REMOVE : ENUM_SB_ACTION_CHANGE; 660 | setField(packet, ENUM_SB_ACTION, enumAction); 661 | } else { 662 | setField(packet, int.class, action.ordinal(), 1); // Action 663 | } 664 | 665 | if (action == ScoreboardAction.CHANGE) { 666 | setField(packet, String.class, this.id, 1); // Objective Name 667 | setField(packet, int.class, score); // Score 668 | } 669 | 670 | sendPacket(packet); 671 | } 672 | 673 | private void sendModernScorePacket(int score, ScoreboardAction action) throws Throwable { 674 | String objName = COLOR_CODES[score]; 675 | Object enumAction = action == ScoreboardAction.REMOVE 676 | ? ENUM_SB_ACTION_REMOVE : ENUM_SB_ACTION_CHANGE; 677 | 678 | if (PACKET_SB_RESET_SCORE == null) { // Pre 1.20.3 679 | sendPacket(PACKET_SB_SET_SCORE.invoke(enumAction, this.id, objName, score)); 680 | return; 681 | } 682 | 683 | if (action == ScoreboardAction.REMOVE) { 684 | sendPacket(PACKET_SB_RESET_SCORE.invoke(objName, this.id)); 685 | return; 686 | } 687 | 688 | T scoreFormat = getLineByScore(this.scores, score); 689 | Object format = scoreFormat != null 690 | ? FIXED_NUMBER_FORMAT.invoke(toMinecraftComponent(scoreFormat)) 691 | : BLANK_NUMBER_FORMAT; 692 | Object scorePacket = SCORE_OPTIONAL_COMPONENTS 693 | ? PACKET_SB_SET_SCORE.invoke(objName, this.id, score, Optional.empty(), Optional.of(format)) 694 | : PACKET_SB_SET_SCORE.invoke(objName, this.id, score, null, format); 695 | 696 | sendPacket(scorePacket); 697 | } 698 | 699 | protected void sendTeamPacket(int score, TeamMode mode) throws Throwable { 700 | sendTeamPacket(score, mode, null, null); 701 | } 702 | 703 | protected void sendTeamPacket(int score, TeamMode mode, T prefix, T suffix) 704 | throws Throwable { 705 | if (mode == TeamMode.ADD_PLAYERS || mode == TeamMode.REMOVE_PLAYERS) { 706 | throw new UnsupportedOperationException(); 707 | } 708 | 709 | Object packet = PACKET_SB_TEAM.invoke(); 710 | 711 | setField(packet, String.class, this.id + ':' + score); // Team name 712 | setField(packet, int.class, mode.ordinal(), VERSION_TYPE == VersionType.V1_8 ? 1 : 0); // Update mode 713 | 714 | if (mode == TeamMode.REMOVE) { 715 | sendPacket(packet); 716 | return; 717 | } 718 | 719 | if (VersionType.V1_17.isHigherOrEqual()) { 720 | Object team = PACKET_SB_SERIALIZABLE_TEAM.invoke(); 721 | // Since the packet is initialized with null values, we need to change more things. 722 | setComponentField(team, null, 0); // Display name 723 | setField(team, CHAT_FORMAT_ENUM, RESET_FORMATTING); // Color 724 | setComponentField(team, prefix, 1); // Prefix 725 | setComponentField(team, suffix, 2); // Suffix 726 | setField(team, String.class, "always", 0); // Visibility 727 | setField(team, String.class, "always", 1); // Collisions 728 | setField(team, ENUM_VISIBILITY, ENUM_VISIBILITY_ALWAYS, 0); // 1.21.5+ 729 | setField(team, ENUM_COLLISION_RULE, ENUM_COLLISION_RULE_ALWAYS, 0); 730 | setField(packet, Optional.class, Optional.of(team)); 731 | } else { 732 | setComponentField(packet, prefix, 2); // Prefix 733 | setComponentField(packet, suffix, 3); // Suffix 734 | setField(packet, String.class, "always", 4); // Visibility for 1.8+ 735 | setField(packet, String.class, "always", 5); // Collisions for 1.9+ 736 | } 737 | 738 | if (mode == TeamMode.CREATE) { 739 | setField(packet, Collection.class, Collections.singletonList(COLOR_CODES[score])); // Players in the team 740 | } 741 | 742 | sendPacket(packet); 743 | } 744 | 745 | private void sendPacket(Object packet) throws Throwable { 746 | if (this.deleted) { 747 | throw new IllegalStateException("This FastBoard is deleted"); 748 | } 749 | 750 | if (this.player.isOnline()) { 751 | Object entityPlayer = PLAYER_GET_HANDLE.invoke(this.player); 752 | Object playerConnection = PLAYER_CONNECTION.invoke(entityPlayer); 753 | SEND_PACKET.invoke(playerConnection, packet); 754 | } 755 | } 756 | 757 | private void setField(Object object, Class<?> fieldType, Object value) 758 | throws ReflectiveOperationException { 759 | setField(object, fieldType, value, 0); 760 | } 761 | 762 | private void setField(Object packet, Class<?> fieldType, Object value, int count) 763 | throws ReflectiveOperationException { 764 | int i = 0; 765 | for (Field field : PACKETS.get(packet.getClass())) { 766 | if (field.getType() == fieldType && count == i++) { 767 | field.set(packet, value); 768 | } 769 | } 770 | } 771 | 772 | private void setComponentField(Object packet, T value, int count) throws Throwable { 773 | if (!VersionType.V1_13.isHigherOrEqual()) { 774 | String line = value != null ? serializeLine(value) : ""; 775 | setField(packet, String.class, line, count); 776 | return; 777 | } 778 | 779 | int i = 0; 780 | for (Field field : PACKETS.get(packet.getClass())) { 781 | if ((field.getType() == String.class || field.getType() == CHAT_COMPONENT_CLASS) && count == i++) { 782 | field.set(packet, toMinecraftComponent(value)); 783 | } 784 | } 785 | } 786 | 787 | public void updateTitle() { 788 | updateTitle(this.getTitle()); 789 | } 790 | 791 | public abstract boolean update(); 792 | 793 | 794 | public enum ObjectiveMode { 795 | CREATE, REMOVE, UPDATE 796 | } 797 | 798 | public enum TeamMode { 799 | CREATE, REMOVE, UPDATE, ADD_PLAYERS, REMOVE_PLAYERS 800 | } 801 | 802 | public enum ScoreboardAction { 803 | CHANGE, REMOVE 804 | } 805 | 806 | public enum VersionType { 807 | V1_7, V1_8, V1_13, V1_17; 808 | 809 | public boolean isHigherOrEqual() { 810 | return VERSION_TYPE.ordinal() >= ordinal(); 811 | } 812 | } 813 | /** 814 | * Return if the player has a prefix/suffix characters limit. 815 | * By default, it returns true only in 1.12 or lower. 816 | * This method can be overridden to fix compatibility with some versions support plugin. 817 | * 818 | * @return max length 819 | */ 820 | protected boolean hasLinesMaxLength() { 821 | return !VersionType.V1_13.isHigherOrEqual(); 822 | } 823 | } 824 | --------------------------------------------------------------------------------