chore: pre-commit changes

This commit is contained in:
Sekwah 2024-06-16 04:00:49 +01:00
parent 5f44e24824
commit c0cdcc327d
82 changed files with 1400 additions and 1090 deletions

View File

@ -1,4 +1,4 @@
name: "Pre-commit consistency check"
name: Pre-commit consistency check
on:
workflow_dispatch:
@ -13,29 +13,35 @@ jobs:
name: Run pre-commit checks
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up JDK 11
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '11'
- uses: dorny/paths-filter@v2
id: filter
with:
list-files: shell
filters: |
addedOrModified:
- added|modified: '**'
- uses: dorny/paths-filter@v2
id: filter
with:
list-files: shell
filters: |
addedOrModified:
- added|modified: '**'
# run only if changed files were detected
- name: Run against changes
uses: pre-commit/action@v2.0.3
if: steps.filter.outputs.addedOrModified == 'true'
with:
extra_args: --files ${{ steps.filter.outputs.addedOrModified_files }}
- name: Run against changes
uses: pre-commit/action@v2.0.3
if: steps.filter.outputs.addedOrModified == 'true'
with:
extra_args: --files ${{ steps.filter.outputs.addedOrModified_files }}
# run if no changed files were detected (e.g. workflow_dispatch on master branch)
- name: Run against all files
uses: pre-commit/action@v2.0.3
if: steps.filter.outputs.addedOrModified != 'true'
with:
extra_args: --all-files
- name: Run against all files
uses: pre-commit/action@v2.0.3
if: steps.filter.outputs.addedOrModified != 'true'
with:
extra_args: --all-files

View File

@ -2,7 +2,7 @@ on:
workflow_dispatch:
push:
branches:
- master
- master
name: release-please
jobs:
release-please:
@ -12,11 +12,11 @@ jobs:
upload_url: ${{ steps.release.outputs.upload_url }}
# https://github.com/google-github-actions/release-please-action in case more config is needed
steps:
- uses: google-github-actions/release-please-action@v3
id: release
with:
command: manifest
token: ${{ secrets.PAT }}
- uses: google-github-actions/release-please-action@v3
id: release
with:
command: manifest
token: ${{ secrets.PAT }}
# See how to configure file https://github.com/googleapis/release-please/blob/main/docs/manifest-releaser.md
# See output info at https://github.com/google-github-actions/release-please-action#configuration for variables
@ -30,28 +30,28 @@ jobs:
runs-on: ubuntu-latest
if: ${{ needs.release-please.outputs.release_created }}
steps:
- uses: actions/checkout@v3
- name: Cache Gradle packages
uses: actions/cache@v3
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
distribution: 'zulu'
java-version: 17
- name: Download MC assets
run: ./gradlew downloadAssets || ./gradlew downloadAssets || (sleep 30s && ./gradlew downloadAssets)
- name: Run DataGen
run: ./gradlew runData
- name: Build and publish (release)
env:
CURSE_API: ${{ secrets.CURSE_API }}
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }}
IS_RELEASE: true
run: |
# Build
./gradlew build ${{ matrix.release-task }}
- uses: actions/checkout@v3
- name: Cache Gradle packages
uses: actions/cache@v3
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
distribution: zulu
java-version: 17
- name: Download MC assets
run: ./gradlew downloadAssets || ./gradlew downloadAssets || (sleep 30s && ./gradlew downloadAssets)
- name: Run DataGen
run: ./gradlew runData
- name: Build and publish (release)
env:
CURSE_API: ${{ secrets.CURSE_API }}
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }}
IS_RELEASE: true
run: |
# Build
./gradlew build ${{ matrix.release-task }}

View File

@ -1,7 +1,7 @@
on:
push:
branches-ignore:
- master
- master
workflow_dispatch:
name: Build
jobs:
@ -10,28 +10,28 @@ jobs:
runs-on: ubuntu-latest
# https://github.com/google-github-actions/release-please-action in case more config is needed
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v3
# these if statements ensure that a publication only occurs when
# a new release is created:
- name: Cache Gradle packages
uses: actions/cache@v3
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: 17
- name: Cache Gradle packages
uses: actions/cache@v3
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: 17
# - name: Download MC assets
# run: ./gradlew downloadAssets --info --debug || ./gradlew downloadAssets --info --debug || (sleep 30s && ./gradlew downloadAssets --info --debug)
# - name: Run DataGen
# run: ./gradlew runData
- name: Build and upload preview (run for non-release builds)
if: ${{ github.ref && !contains( github.ref, 'renovate/deps') }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
run: |
# Build
./gradlew build
- name: Build and upload preview (run for non-release builds)
if: ${{ github.ref && !contains( github.ref, 'renovate/deps') }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
run: |
# Build
./gradlew build

View File

@ -1,17 +1,27 @@
# See https://pre-commit.com for more information
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: fix-byte-order-marker
- id: mixed-line-ending
- id: check-merge-conflict
- id: check-case-conflict
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: fix-byte-order-marker
- id: mixed-line-ending
- id: check-merge-conflict
- id: check-case-conflict
- repo: https://github.com/Lucas-C/pre-commit-hooks
rev: v1.1.10
hooks:
- id: remove-crlf
- id: remove-tabs
- repo: https://github.com/Lucas-C/pre-commit-hooks
rev: v1.1.10
hooks:
- id: remove-crlf
- id: remove-tabs
- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks
rev: v2.13.0
hooks:
- id: pretty-format-java
args: [--autofix, --aosp, --google-java-formatter-version=1.16.0]
- id: pretty-format-yaml
args: [--autofix]
- id: pretty-format-toml
args: [--autofix]

View File

@ -55,6 +55,9 @@ Please ensure that your commits are in the following style for PR's
https://www.conventionalcommits.org/en/v1.0.0/
Also if you could, please run `pre-commit run --files ...` or `pre-commit run --all-files` to ensure that the code is formatted correctly.
You will need to run this command with Java 11 for the java formatter.
## Types available
* **build**: Changes that affect the build system or external dependencies
* **ci**: Changes to our CI configuration files and scripts

View File

@ -8,14 +8,14 @@ import com.sekwah.advancedportals.core.commands.subcommands.desti.*;
import com.sekwah.advancedportals.core.commands.subcommands.portal.*;
import com.sekwah.advancedportals.core.connector.commands.CommandRegister;
import com.sekwah.advancedportals.core.connector.containers.ServerContainer;
import com.sekwah.advancedportals.core.module.AdvancedPortalsModule;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.repository.IPlayerDataRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.module.AdvancedPortalsModule;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.services.PlayerDataServices;
import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.tags.activation.*;
import com.sekwah.advancedportals.core.util.GameScheduler;
import com.sekwah.advancedportals.core.util.InfoLogger;
@ -26,7 +26,6 @@ import java.util.Arrays;
public class AdvancedPortalsCore {
public static final String version = "1.0.0";
private final InfoLogger infoLogger;
@ -35,8 +34,8 @@ public class AdvancedPortalsCore {
private final AdvancedPortalsModule module;
/**
* Use this to enable or alter certain features for different versions.
* If there is an issue parsing it for any reason it will be set to 0.0.0
* Use this to enable or alter certain features for different versions. If there is an issue
* parsing it for any reason it will be set to 0.0.0
*/
private final int[] mcVersion;
@ -44,35 +43,31 @@ public class AdvancedPortalsCore {
private static AdvancedPortalsCore instance;
@Inject
private CommandRegister commandRegister;
@Inject private CommandRegister commandRegister;
private CommandWithSubCommands portalCommand;
private CommandWithSubCommands destiCommand;
@Inject
private ConfigRepository configRepository;
@Inject private ConfigRepository configRepository;
@Inject
private TagRegistry tagRegistry;
@Inject private TagRegistry tagRegistry;
@Inject
private PortalServices portalServices;
@Inject private PortalServices portalServices;
@Inject
private DestinationServices destinationServices;
@Inject private DestinationServices destinationServices;
@Inject
private PlayerDataServices playerDataRepository;
@Inject private PlayerDataServices playerDataRepository;
@Inject
private GameScheduler gameScheduler;
@Inject private GameScheduler gameScheduler;
// TEMP REMOVE THIS THIS IS JUST FOR DEV
@Inject
private IPlayerDataRepository tempDataRepository;
@Inject private IPlayerDataRepository tempDataRepository;
public AdvancedPortalsCore(String mcVersion, File dataStorageLoc, InfoLogger infoLogger, ServerContainer serverContainer) {
public AdvancedPortalsCore(
String mcVersion,
File dataStorageLoc,
InfoLogger infoLogger,
ServerContainer serverContainer) {
instance = this;
this.serverContainer = serverContainer;
this.dataStorage = new DataStorage(dataStorageLoc);
@ -81,14 +76,15 @@ public class AdvancedPortalsCore {
int[] mcVersionTemp;
infoLogger.info("Loading Advanced Portals Core v" + version + " for MC: " + mcVersion);
try {
mcVersionTemp = Arrays.stream(mcVersion.split("\\.")).mapToInt(Integer::parseInt).toArray();
mcVersionTemp =
Arrays.stream(mcVersion.split("\\.")).mapToInt(Integer::parseInt).toArray();
} catch (NumberFormatException e) {
infoLogger.info("Failed to parse MC version: " + mcVersion);
e.printStackTrace();
mcVersionTemp = new int[]{0, 0, 0};
mcVersionTemp = new int[] {0, 0, 0};
}
if(mcVersionTemp.length == 2) {
mcVersionTemp = new int[]{mcVersionTemp[0], mcVersionTemp[1], 0};
if (mcVersionTemp.length == 2) {
mcVersionTemp = new int[] {mcVersionTemp[0], mcVersionTemp[1], 0};
}
this.mcVersion = mcVersionTemp;
@ -96,16 +92,18 @@ public class AdvancedPortalsCore {
}
/**
* For some platforms we could do this on construction but this just allows for a bit more control
* For some platforms we could do this on construction but this just allows for a bit more
* control
*/
public void onEnable() {
// Force values to get injected, either because the initial ones were created too early or to ensure they are not null.
// Force values to get injected, either because the initial ones were created too early or
// to ensure they are not null.
// Do it here to give implementations a chance to interact with the module.
Injector injector = module.getInjector();
injector.injectMembers(this);
injector.injectMembers(Lang.instance);
//AdvancedPortalsModule module = new AdvancedPortalsModule(this);
// AdvancedPortalsModule module = new AdvancedPortalsModule(this);
this.dataStorage.copyDefaultFile("lang/en_GB.lang", false);
this.loadPortalConfig();
Lang.loadLanguage(configRepository.getTranslation());
@ -126,9 +124,7 @@ public class AdvancedPortalsCore {
this.tagRegistry.registerTag(new PermissionTag());
}
/**
*
*/
/** */
public void registerCommands() {
this.registerPortalCommand(commandRegister);
this.registerDestinationCommand(commandRegister);
@ -172,8 +168,8 @@ public class AdvancedPortalsCore {
}
/**
* Loads the portal config into the memory and saves from the memory to check in case certain things have changed
* (basically if values are missing or whatever)
* Loads the portal config into the memory and saves from the memory to check in case certain
* things have changed (basically if values are missing or whatever)
*/
public void loadPortalConfig() {
this.configRepository.loadConfig(this.dataStorage);
@ -181,7 +177,7 @@ public class AdvancedPortalsCore {
}
public void onDisable() {
for(var playerContainer : this.serverContainer.getPlayers()) {
for (var playerContainer : this.serverContainer.getPlayers()) {
playerDataRepository.playerLeave(playerContainer);
}
this.infoLogger.info(Lang.translate("logger.plugindisable"));

View File

@ -7,7 +7,8 @@ import java.util.List;
/**
* Already know spigot's auto complete possibilities
*
* Sponge https://docs.spongepowered.org/stable/en/plugin/commands/arguments.html#custom-command-elements
* <p>Sponge
* https://docs.spongepowered.org/stable/en/plugin/commands/arguments.html#custom-command-elements
*/
public interface CommandTemplate {
@ -15,10 +16,10 @@ public interface CommandTemplate {
/**
* Fired when someone asks for a tab complete action.
*
* @param sender whoever triggered the command e.g. command block, server or player
* @param args arguments for the command
* @return a lot of strings that are possible completions
*/
List<String> onTabComplete(CommandSenderContainer sender, String[] args);
}

View File

@ -9,15 +9,14 @@ public interface SubCommand {
/**
* @param sender
* @param args arguments including the subcommand that has been specified.
* @return if the command has worked (if false it will just display a message from the command suggesting to check help)
* @return if the command has worked (if false it will just display a message from the command
* suggesting to check help)
*/
void onCommand(CommandSenderContainer sender, String[] args);
boolean hasPermission(CommandSenderContainer sender);
/**
*
*
* @param sender
* @param args arguments including the subcommand that has been specified.
* @return tab completion for the subcommand

View File

@ -5,9 +5,9 @@ import com.sekwah.advancedportals.core.commands.subcommands.common.CreateTaggedS
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.destination.Destination;
import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.services.DestinationServices;
import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.util.TagReader;
@ -19,56 +19,68 @@ import java.util.List;
public class CreateDestiSubCommand extends CreateTaggedSubCommand {
@Inject
TagRegistry tagRegistry;
@Inject TagRegistry tagRegistry;
@Inject
DestinationServices destinationServices;
@Inject DestinationServices destinationServices;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(args.length > 1) {
if (args.length > 1) {
PlayerContainer player = sender.getPlayerContainer();
if(player == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.create.destination.console"));
if (player == null) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.create.destination.console"));
return;
}
ArrayList<DataTag> destinationTags = TagReader.getTagsFromArgs(args);
// Find the tag with the "name" NAME
DataTag nameTag = destinationTags.stream().filter(tag -> tag.NAME.equals("name")).findFirst().orElse(null);
DataTag nameTag =
destinationTags.stream()
.filter(tag -> tag.NAME.equals("name"))
.findFirst()
.orElse(null);
// If the tag is null, check if arg[1] has a : to check it's not a tag.
if(nameTag == null && !args[1].contains(":")) {
if (nameTag == null && !args[1].contains(":")) {
nameTag = new DataTag("name", args[1]);
destinationTags.add(nameTag);
}
if (nameTag == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.error.noname"));
return;
}
sender.sendMessage(Lang.centeredTitle(Lang.translate("command.create.destination.prep")));
sender.sendMessage(
Lang.centeredTitle(Lang.translate("command.create.destination.prep")));
sender.sendMessage("");
sender.sendMessage(Lang.translate("command.create.tags"));
if(!destinationTags.isEmpty()) {
if (!destinationTags.isEmpty()) {
this.filterAndProcessTags(destinationTags);
this.printTags(sender, destinationTags);
}
sender.sendMessage("");
Destination destination = destinationServices.createDesti(player, player.getLoc(), destinationTags);
if(destination != null) {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.create.destination.complete"));
}
else {
Destination destination =
destinationServices.createDesti(player, player.getLoc(), destinationTags);
if (destination != null) {
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.create.destination.complete"));
} else {
sender.sendMessage("");
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.create.destination.error"));
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.create.destination.error"));
}
}
else {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
} else {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.error.noname"));
}
}
@ -81,7 +93,9 @@ public class CreateDestiSubCommand extends CreateTaggedSubCommand {
protected List<Tag> getRelatedTags() {
var tags = tagRegistry.getTags();
// Filter tags that support Destination
return tags.stream().filter(tag -> Arrays.asList(tag.getTagTypes()).contains(Tag.TagType.DESTINATION)).toList();
return tags.stream()
.filter(tag -> Arrays.asList(tag.getTagTypes()).contains(Tag.TagType.DESTINATION))
.toList();
}
@Override

View File

@ -11,13 +11,17 @@ import java.util.stream.Collectors;
public class ListDestiSubCommand implements SubCommand {
@Inject
DestinationServices portalServices;
@Inject DestinationServices portalServices;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.destination.list")
+ " " + portalServices.getDestinationNames().stream().sorted().collect(Collectors.joining(", ")));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.list")
+ " "
+ portalServices.getDestinationNames().stream()
.sorted()
.collect(Collectors.joining(", ")));
}
@Override

View File

@ -12,22 +12,21 @@ import java.util.List;
public class RemoveDestiSubCommand implements SubCommand {
@Inject
DestinationServices destinationServices;
@Inject DestinationServices destinationServices;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(args.length > 1) {
if(destinationServices.removeDestination(args[1], sender.getPlayerContainer())) {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.destination.remove.complete"));
if (args.length > 1) {
if (destinationServices.removeDestination(args[1], sender.getPlayerContainer())) {
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.remove.complete"));
} else {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.destination.remove.error"));
}
else {
sender.sendMessage(Lang.translate("messageprefix.negative")
+ Lang.translate("command.destination.remove.error"));
}
}
else {
} else {
sender.sendMessage(Lang.translate("command.destination.noname"));
}
}
@ -39,7 +38,7 @@ public class RemoveDestiSubCommand implements SubCommand {
@Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) {
if(args.length > 2) {
if (args.length > 2) {
return Collections.emptyList();
}
List<String> destiNames = destinationServices.getDestinationNames();

View File

@ -19,40 +19,41 @@ import java.util.List;
import java.util.Objects;
/**
* This will be different from the old show command and I believe it is 1.16+ till the latest version as of writing this.
* This will be different from the old show command and I believe it is 1.16+ till the latest
* version as of writing this.
*/
public class ShowDestiSubCommand implements SubCommand, SubCommand.SubCommandOnInit {
@Inject
PlayerDataServices tempDataServices;
@Inject PlayerDataServices tempDataServices;
@Inject
GameScheduler gameScheduler;
@Inject GameScheduler gameScheduler;
@Inject
AdvancedPortalsCore core;
@Inject AdvancedPortalsCore core;
@Inject
DestinationServices destinationServices;
@Inject DestinationServices destinationServices;
@Inject
ServerContainer serverContainer;
@Inject ServerContainer serverContainer;
@Inject
ConfigRepository config;
@Inject ConfigRepository config;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(core.getMcVersion()[1] < 16) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.portal.show.unsupported"));
if (core.getMcVersion()[1] < 16) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.show.unsupported"));
return;
}
var tempData = tempDataServices.getPlayerData(sender.getPlayerContainer());
if(tempData.isDestiVisible()) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.destination.show.disabled"));
if (tempData.isDestiVisible()) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.destination.show.disabled"));
} else {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.destination.show.enabled"));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.show.enabled"));
}
tempData.setDestiVisible(!tempData.isDestiVisible());
}
@ -79,20 +80,30 @@ public class ShowDestiSubCommand implements SubCommand, SubCommand.SubCommandOnI
@Override
public void registered() {
gameScheduler.intervalTickEvent("show_portal", () -> {
for(PlayerContainer player : serverContainer.getPlayers()) {
var tempData = tempDataServices.getPlayerData(player);
if(!tempData.isDestiVisible()) {
continue;
}
gameScheduler.intervalTickEvent(
"show_portal",
() -> {
for (PlayerContainer player : serverContainer.getPlayers()) {
var tempData = tempDataServices.getPlayerData(player);
if (!tempData.isDestiVisible()) {
continue;
}
for (Destination destination : destinationServices.getDestinations()) {
var pos = destination.getLoc();
if(Objects.equals(pos.getWorldName(), player.getWorldName()) && pos.distanceTo(player.getLoc()) < config.getVisibleRange()) {
Debug.addMarker(player, pos.toBlockPos(), destination.getArgValues("name")[0], new Color(100, 100, 100, 100), 1300);
for (Destination destination : destinationServices.getDestinations()) {
var pos = destination.getLoc();
if (Objects.equals(pos.getWorldName(), player.getWorldName())
&& pos.distanceTo(player.getLoc()) < config.getVisibleRange()) {
Debug.addMarker(
player,
pos.toBlockPos(),
destination.getArgValues("name")[0],
new Color(100, 100, 100, 100),
1300);
}
}
}
}
}
}, 1, 20);
},
1,
20);
}
}

View File

@ -12,19 +12,21 @@ import java.util.List;
public class TeleportDestiSubCommand implements SubCommand {
@Inject
DestinationServices destinationServices;
@Inject DestinationServices destinationServices;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(args.length > 1) {
if(destinationServices.teleportToDestination(args[1], sender.getPlayerContainer())) {
sender.sendMessage(Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.teleport.success")
.replaceAll("@destiname", args[1]));
if (args.length > 1) {
if (destinationServices.teleportToDestination(args[1], sender.getPlayerContainer())) {
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.destination.teleport.success")
.replaceAll("@destiname", args[1]));
} else {
sender.sendMessage(Lang.translate("messageprefix.negative") +
Lang.translate("command.destination.teleport.error")
.replaceAll("@destiname", args[1]));
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.destination.teleport.error")
.replaceAll("@destiname", args[1]));
}
} else {
sender.sendMessage(Lang.translate("command.destination.noname"));
@ -38,7 +40,7 @@ public class TeleportDestiSubCommand implements SubCommand {
@Override
public List<String> onTabComplete(CommandSenderContainer sender, String[] args) {
if(args.length > 2) {
if (args.length > 2) {
return Collections.emptyList();
}
List<String> destiNames = destinationServices.getDestinationNames();

View File

@ -4,11 +4,11 @@ import com.google.inject.Inject;
import com.sekwah.advancedportals.core.commands.subcommands.common.CreateTaggedSubCommand;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.tags.activation.NameTag;
import com.sekwah.advancedportals.core.tags.activation.TriggerBlockTag;
@ -23,44 +23,50 @@ import java.util.List;
public class CreatePortalSubCommand extends CreateTaggedSubCommand {
@Inject
PortalServices portalServices;
@Inject PortalServices portalServices;
@Inject
TagRegistry tagRegistry;
@Inject TagRegistry tagRegistry;
@Inject
InfoLogger infoLogger;
@Inject InfoLogger infoLogger;
@Inject
ConfigRepository config;
@Inject ConfigRepository config;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(args.length > 1) {
if (args.length > 1) {
PlayerContainer player = sender.getPlayerContainer();
if(player == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.create.console"));
if (player == null) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.create.console"));
return;
}
ArrayList<DataTag> portalTags = TagReader.getTagsFromArgs(args);
// Find the tag with the "name" NAME
DataTag nameTag = portalTags.stream().filter(tag -> {
this.infoLogger.info("Tag: " + tag.NAME);
this.infoLogger.info("Equals: " + tag.NAME.equals(NameTag.TAG_NAME));
return tag.NAME.equals(NameTag.TAG_NAME);
}).findFirst().orElse(null);
DataTag nameTag =
portalTags.stream()
.filter(
tag -> {
this.infoLogger.info("Tag: " + tag.NAME);
this.infoLogger.info(
"Equals: " + tag.NAME.equals(NameTag.TAG_NAME));
return tag.NAME.equals(NameTag.TAG_NAME);
})
.findFirst()
.orElse(null);
// If the tag is null, check if arg[1] has a : to check it's not a tag.
if(nameTag == null && !args[1].contains(":")) {
if (nameTag == null && !args[1].contains(":")) {
nameTag = new DataTag("name", args[1]);
portalTags.add(nameTag);
}
if (nameTag == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.error.noname"));
return;
}
@ -68,29 +74,39 @@ public class CreatePortalSubCommand extends CreateTaggedSubCommand {
sender.sendMessage("");
sender.sendMessage(Lang.translate("command.create.tags"));
if(!portalTags.isEmpty()) {
if (!portalTags.isEmpty()) {
this.filterAndProcessTags(portalTags);
this.printTags(sender, portalTags);
}
sender.sendMessage("");
var triggerBlockTag = portalTags.stream().filter(tag -> tag.NAME.equals(TriggerBlockTag.TAG_NAME)).findFirst().orElse(null);
var triggerBlockTag =
portalTags.stream()
.filter(tag -> tag.NAME.equals(TriggerBlockTag.TAG_NAME))
.findFirst()
.orElse(null);
if(triggerBlockTag == null) {
portalTags.add(new DataTag(TriggerBlockTag.TAG_NAME, config.getDefaultTriggerBlock()));
if (triggerBlockTag == null) {
portalTags.add(
new DataTag(TriggerBlockTag.TAG_NAME, config.getDefaultTriggerBlock()));
}
AdvancedPortal portal = portalServices.createPortal(player, portalTags);
if(portal != null) {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.create.complete"));
if (portal != null) {
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.create.complete"));
sender.sendMessage(Lang.translate("command.create.tags"));
this.printTags(sender, portal.getArgs());
} else {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.create.error"));
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.create.error"));
}
}
else {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.error.notags"));
} else {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.error.notags"));
}
}
@ -103,7 +119,9 @@ public class CreatePortalSubCommand extends CreateTaggedSubCommand {
protected List<Tag> getRelatedTags() {
var tags = tagRegistry.getTags();
// Filter tags that support Destination
return tags.stream().filter(tag -> Arrays.asList(tag.getTagTypes()).contains(Tag.TagType.PORTAL)).toList();
return tags.stream()
.filter(tag -> Arrays.asList(tag.getTagTypes()).contains(Tag.TagType.PORTAL))
.toList();
}
@Override

View File

@ -12,22 +12,25 @@ import java.util.List;
public class EndGatewayBlockSubCommand implements SubCommand {
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer();
if(player == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
if (player == null) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.playeronly"));
} else {
player.giveItem(
"BLACK_WOOL",
"\u00A78Gateway Block Placer",
"\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A7eRight Click\u00A77: Place portal block");
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.gatewayblock"));
}
else {
player.giveItem("BLACK_WOOL", "\u00A78Gateway Block Placer"
, "\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A7eRight Click\u00A77: Place portal block");
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.gatewayblock"));
}
}
@Override

View File

@ -12,22 +12,25 @@ import java.util.List;
public class EndPortalBlockSubCommand implements SubCommand {
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer();
if(player == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
if (player == null) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.playeronly"));
} else {
player.giveItem(
"BLACK_WOOL",
"\u00A78End Portal Block Placer",
"\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A7eRight Click\u00A77: Place portal block");
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.endportalblock"));
}
else {
player.giveItem("BLACK_WOOL", "\u00A78End Portal Block Placer"
, "\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A7eRight Click\u00A77: Place portal block");
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.endportalblock"));
}
}
@Override

View File

@ -19,48 +19,65 @@ import java.util.stream.Collectors;
public class LangUpdateSubCommand implements SubCommand {
@Inject
private AdvancedPortalsCore portalsCore;
@Inject
private ConfigRepository configRepository;
@Inject private AdvancedPortalsCore portalsCore;
@Inject private ConfigRepository configRepository;
public LangUpdateSubCommand() {
}
public LangUpdateSubCommand() {}
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(args.length > 1 && args[1].equalsIgnoreCase("overwrite")) {
this.portalsCore.getDataStorage().copyDefaultFile("lang/" + configRepository.getTranslation() + ".lang", true);
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("translatedata.replaced"));
if (args.length > 1 && args[1].equalsIgnoreCase("overwrite")) {
this.portalsCore
.getDataStorage()
.copyDefaultFile("lang/" + configRepository.getTranslation() + ".lang", true);
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("translatedata.replaced"));
Lang.loadLanguage(configRepository.getTranslation());
} else {
// TODO check what keys are missing and append them to the end of the file, check the translation first then GB
// TODO check what keys are missing and append them to the end of the file, check the
// translation first then GB
Lang lang = Lang.instance;
Map<String, String> internalTranslation = lang.getInternalLanguageMap(Lang.DEFAULT_LANG);
internalTranslation.putAll(lang.getInternalLanguageMap(configRepository.getTranslation()));
Map<String, String> internalTranslation =
lang.getInternalLanguageMap(Lang.DEFAULT_LANG);
internalTranslation.putAll(
lang.getInternalLanguageMap(configRepository.getTranslation()));
Map<String, String> currentTranslation = lang.getLanguageMap(configRepository.getTranslation());
Map<String, String> currentTranslation =
lang.getLanguageMap(configRepository.getTranslation());
// Remove everything to leave just the missing keys
for(Map.Entry<String, String> entry : currentTranslation.entrySet()) {
for (Map.Entry<String, String> entry : currentTranslation.entrySet()) {
internalTranslation.remove(entry.getKey());
}
List<String> newTranslations = new ArrayList<>();
for(Map.Entry<String, String> entry : internalTranslation.entrySet()) {
for (Map.Entry<String, String> entry : internalTranslation.entrySet()) {
newTranslations.add(entry.getKey() + "=" + entry.getValue());
}
String appendText = String.join("\n", newTranslations);
InputStream translationFile = this.portalsCore.getDataStorage().loadResource("lang/" + configRepository.getTranslation() + ".lang");
String result = new BufferedReader(new InputStreamReader(translationFile))
.lines().collect(Collectors.joining("\n"));
InputStream withExtras = new ByteArrayInputStream(result.concat("\n").concat(appendText).getBytes());
this.portalsCore.getDataStorage().writeResource(withExtras, "lang/" + configRepository.getTranslation() + ".lang");
InputStream translationFile =
this.portalsCore
.getDataStorage()
.loadResource("lang/" + configRepository.getTranslation() + ".lang");
String result =
new BufferedReader(new InputStreamReader(translationFile))
.lines()
.collect(Collectors.joining("\n"));
InputStream withExtras =
new ByteArrayInputStream(result.concat("\n").concat(appendText).getBytes());
this.portalsCore
.getDataStorage()
.writeResource(
withExtras, "lang/" + configRepository.getTranslation() + ".lang");
Lang.loadLanguage(configRepository.getTranslation());
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translateInsertVariables("translatedata.updated", newTranslations.size()));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translateInsertVariables(
"translatedata.updated", newTranslations.size()));
}
}

View File

@ -7,18 +7,21 @@ import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.Lang;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListPortalsSubCommand implements SubCommand {
@Inject
PortalServices portalServices;
@Inject PortalServices portalServices;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.portal.list")
+ " " + portalServices.getPortalNames().stream().sorted().collect(Collectors.joining(", ")));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.portal.list")
+ " "
+ portalServices.getPortalNames().stream()
.sorted()
.collect(Collectors.joining(", ")));
}
@Override

View File

@ -12,24 +12,30 @@ import java.util.List;
public class PortalBlockSubCommand implements SubCommand {
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer();
if(player == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
if (player == null) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.playeronly"));
} else {
player.giveItem(
"PURPLE_WOOL",
"\u00A75Portal Block Placer",
"\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A7e"
+ Lang.translate("items.interact.left")
+ "\u00A77: Rotate portal block",
"\u00A7r\u00A7e"
+ Lang.translate("items.interact.right")
+ "\u00A77: Place portal block");
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.portalblock"));
}
else {
player.giveItem("PURPLE_WOOL", "\u00A75Portal Block Placer"
, "\u00A7r\u00A77This wool is made of a magical substance",
"\u00A7r\u00A7e" + Lang.translate("items.interact.left") + "\u00A77: Rotate portal block",
"\u00A7r\u00A7e" + Lang.translate("items.interact.right") + "\u00A77: Place portal block");
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.portalblock"));
}
}
@Override

View File

@ -14,17 +14,13 @@ import java.util.List;
public class ReloadPortalSubCommand implements SubCommand {
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
@Inject
PortalServices portalServices;
@Inject PortalServices portalServices;
@Inject
DestinationServices destinationServices;
@Inject DestinationServices destinationServices;
@Inject
ConfigRepository configRepository;
@Inject ConfigRepository configRepository;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
@ -32,7 +28,9 @@ public class ReloadPortalSubCommand implements SubCommand {
portalServices.loadPortals();
destinationServices.loadDestinations();
Lang.loadLanguage(configRepository.getTranslation());
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.reload.reloaded"));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.reload.reloaded"));
}
@Override

View File

@ -3,35 +3,29 @@ package com.sekwah.advancedportals.core.commands.subcommands.portal;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.commands.SubCommand;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.Lang;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class RemovePortalSubCommand implements SubCommand {
@Inject
PortalServices portalServices;
@Inject PortalServices portalServices;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(args.length > 1) {
if(portalServices.removePortal(args[1], sender.getPlayerContainer())) {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.portal.remove.complete"));
if (args.length > 1) {
if (portalServices.removePortal(args[1], sender.getPlayerContainer())) {
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.portal.remove.complete"));
} else {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.remove.error"));
}
else {
sender.sendMessage(Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.remove.error"));
}
}
else {
} else {
sender.sendMessage(Lang.translate("command.portal.remove.noname"));
}
}

View File

@ -13,28 +13,35 @@ import java.util.List;
public class SelectorSubCommand implements SubCommand {
@Inject
private ConfigRepository configRepo;
@Inject private ConfigRepository configRepo;
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
PlayerContainer player = sender.getPlayerContainer();
if(player == null) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.playeronly"));
}
else {
player.giveItem(configRepo.getSelectorMaterial(), "\u00A7e" + Lang.translate("items.selector.name")
, "\u00A7r\u00A77This wand with has the power to help",
if (player == null) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.playeronly"));
} else {
player.giveItem(
configRepo.getSelectorMaterial(),
"\u00A7e" + Lang.translate("items.selector.name"),
"\u00A7r\u00A77This wand with has the power to help",
"\u00A7r\u00A77 create portals bistowed upon it!",
"",
"\u00A7r\u00A7e" + Lang.translate("items.interact.left") + "\u00A77: " + Lang.translateInsertVariables("items.selector.pos", "1"),
"\u00A7r\u00A7e" + Lang.translate("items.interact.right") + "\u00A77: " + Lang.translateInsertVariables("items.selector.pos", "2"));
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.selector"));
"\u00A7r\u00A7e"
+ Lang.translate("items.interact.left")
+ "\u00A77: "
+ Lang.translateInsertVariables("items.selector.pos", "1"),
"\u00A7r\u00A7e"
+ Lang.translate("items.interact.right")
+ "\u00A77: "
+ Lang.translateInsertVariables("items.selector.pos", "2"));
sender.sendMessage(
Lang.translate("messageprefix.positive") + Lang.translate("command.selector"));
}
}
@Override

View File

@ -9,8 +9,8 @@ import com.sekwah.advancedportals.core.connector.containers.ServerContainer;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.services.PlayerDataServices;
import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.tags.activation.NameTag;
import com.sekwah.advancedportals.core.util.Debug;
import com.sekwah.advancedportals.core.util.GameScheduler;
@ -21,7 +21,8 @@ import java.util.List;
import java.util.Objects;
/**
* This will be different from the old show command and I believe it is 1.16+ till the latest version as of writing this.
* This will be different from the old show command and I believe it is 1.16+ till the latest
* version as of writing this.
*/
public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOnInit {
@ -29,23 +30,17 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
boolean alternate_show_trigger = true;
@Inject
PlayerDataServices playerDataServices;
@Inject PlayerDataServices playerDataServices;
@Inject
GameScheduler gameScheduler;
@Inject GameScheduler gameScheduler;
@Inject
AdvancedPortalsCore core;
@Inject AdvancedPortalsCore core;
@Inject
ServerContainer serverContainer;
@Inject ServerContainer serverContainer;
@Inject
PortalServices portalServices;
@Inject PortalServices portalServices;
@Inject
ConfigRepository config;
@Inject ConfigRepository config;
final Color POS1_COLOR = new Color(0, 255, 0);
final Color POS2_COLOR = new Color(255, 0, 0);
@ -60,16 +55,22 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(core.getMcVersion()[1] < 16) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.portal.show.unsupported"));
if (core.getMcVersion()[1] < 16) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.show.unsupported"));
return;
}
var tempData = playerDataServices.getPlayerData(sender.getPlayerContainer());
if(tempData.isPortalVisible()) {
sender.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.portal.show.disabled"));
if (tempData.isPortalVisible()) {
sender.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.portal.show.disabled"));
} else {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translate("command.portal.show.enabled"));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translate("command.portal.show.enabled"));
}
tempData.setPortalVisible(!tempData.isPortalVisible());
}
@ -96,63 +97,110 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
@Override
public void registered() {
gameScheduler.intervalTickEvent("show_portal", () -> {
alternate_show_trigger = !alternate_show_trigger;
for(PlayerContainer player : serverContainer.getPlayers()) {
var tempData = playerDataServices.getPlayerData(player);
if(!tempData.isPortalVisible()) {
continue;
}
if (tempData.getPos1() != null && tempData.getPos2() != null && tempData.getPos1().getWorldName().equals(player.getWorldName()) && tempData.getPos2().getWorldName().equals(player.getWorldName())) {
debugVisuals(player, tempData.getPos1(), tempData.getPos2(), SELECTION_COLOR, SHOW_TICKS);
}
if(tempData.getPos1() != null && tempData.getPos1().getWorldName().equals(player.getWorldName())) {
Debug.addMarker(player, tempData.getPos1(), "Pos1", POS1_COLOR, SHOW_TICKS);
}
if(tempData.getPos2() != null && tempData.getPos2().getWorldName().equals(player.getWorldName())) {
Debug.addMarker(player, tempData.getPos2(), "Pos2", POS2_COLOR, SHOW_TICKS);
}
var world = player.getWorld();
for (var portal : portalServices.getPortals()) {
if(Objects.equals(portal.getMinLoc().getWorldName(), player.getWorldName()) && portal.isLocationInPortal(player.getLoc(), config.getVisibleRange())) {
BlockLocation minLoc = portal.getMinLoc();
BlockLocation maxLoc = portal.getMaxLoc();
int midX = (minLoc.getPosX() + maxLoc.getPosX()) / 2;
int midZ = (minLoc.getPosZ() + maxLoc.getPosZ()) / 2;
BlockLocation midPoint = new BlockLocation(minLoc.getWorldName(), midX, maxLoc.getPosY(), midZ);
Color color;
if(portal.isTriggerBlock(world.getBlock(midPoint))) {
color = TRIGGER_OUTLINE_COLOR;
} else {
if(midPoint.getPosX() == minLoc.getPosX() || midPoint.getPosX() == maxLoc.getPosX() || midPoint.getPosZ() == minLoc.getPosZ() || midPoint.getPosZ() == maxLoc.getPosZ())
color = OUTLINE_COLOR;
else
color = new Color(0, 0, 0, 0);
gameScheduler.intervalTickEvent(
"show_portal",
() -> {
alternate_show_trigger = !alternate_show_trigger;
for (PlayerContainer player : serverContainer.getPlayers()) {
var tempData = playerDataServices.getPlayerData(player);
if (!tempData.isPortalVisible()) {
continue;
}
debugVisuals(player, portal, OUTLINE_COLOR, SHOW_TICKS, TRIGGER_COLOR);
var name = portal.getArgValues(NameTag.TAG_NAME);
if(name != null && name.length > 0) {
Debug.addMarker(player, midPoint, name[0], color, SHOW_TICKS);
if (tempData.getPos1() != null
&& tempData.getPos2() != null
&& tempData.getPos1().getWorldName().equals(player.getWorldName())
&& tempData.getPos2()
.getWorldName()
.equals(player.getWorldName())) {
debugVisuals(
player,
tempData.getPos1(),
tempData.getPos2(),
SELECTION_COLOR,
SHOW_TICKS);
}
if (tempData.getPos1() != null
&& tempData.getPos1()
.getWorldName()
.equals(player.getWorldName())) {
Debug.addMarker(
player, tempData.getPos1(), "Pos1", POS1_COLOR, SHOW_TICKS);
}
if (tempData.getPos2() != null
&& tempData.getPos2()
.getWorldName()
.equals(player.getWorldName())) {
Debug.addMarker(
player, tempData.getPos2(), "Pos2", POS2_COLOR, SHOW_TICKS);
}
var world = player.getWorld();
for (var portal : portalServices.getPortals()) {
if (Objects.equals(
portal.getMinLoc().getWorldName(),
player.getWorldName())
&& portal.isLocationInPortal(
player.getLoc(), config.getVisibleRange())) {
BlockLocation minLoc = portal.getMinLoc();
BlockLocation maxLoc = portal.getMaxLoc();
int midX = (minLoc.getPosX() + maxLoc.getPosX()) / 2;
int midZ = (minLoc.getPosZ() + maxLoc.getPosZ()) / 2;
BlockLocation midPoint =
new BlockLocation(
minLoc.getWorldName(),
midX,
maxLoc.getPosY(),
midZ);
Color color;
if (portal.isTriggerBlock(world.getBlock(midPoint))) {
color = TRIGGER_OUTLINE_COLOR;
} else {
if (midPoint.getPosX() == minLoc.getPosX()
|| midPoint.getPosX() == maxLoc.getPosX()
|| midPoint.getPosZ() == minLoc.getPosZ()
|| midPoint.getPosZ() == maxLoc.getPosZ())
color = OUTLINE_COLOR;
else color = new Color(0, 0, 0, 0);
}
debugVisuals(
player, portal, OUTLINE_COLOR, SHOW_TICKS, TRIGGER_COLOR);
var name = portal.getArgValues(NameTag.TAG_NAME);
if (name != null && name.length > 0) {
Debug.addMarker(player, midPoint, name[0], color, SHOW_TICKS);
}
}
}
}
}
}
}, 1, 20);
},
1,
20);
}
private void debugVisuals(PlayerContainer player, BlockLocation pos1, BlockLocation pos2, Color color, int time) {
private void debugVisuals(
PlayerContainer player, BlockLocation pos1, BlockLocation pos2, Color color, int time) {
debugVisuals(player, pos1, pos2, color, time, null, null);
}
private void debugVisuals(PlayerContainer player, AdvancedPortal portal, Color color, int time, Color triggerColor) {
debugVisuals(player, portal.getMinLoc(), portal.getMaxLoc(), color, time, triggerColor, portal);
private void debugVisuals(
PlayerContainer player,
AdvancedPortal portal,
Color color,
int time,
Color triggerColor) {
debugVisuals(
player, portal.getMinLoc(), portal.getMaxLoc(), color, time, triggerColor, portal);
}
private void debugVisuals(PlayerContainer player, BlockLocation pos1, BlockLocation pos2, Color color, int time, Color triggerColor, AdvancedPortal portal) {
private void debugVisuals(
PlayerContainer player,
BlockLocation pos1,
BlockLocation pos2,
Color color,
int time,
Color triggerColor,
AdvancedPortal portal) {
int minX = Math.min(pos1.getPosX(), pos2.getPosX());
int minY = Math.min(pos1.getPosY(), pos2.getPosY());
int minZ = Math.min(pos1.getPosZ(), pos2.getPosZ());
@ -163,26 +211,30 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
var world = player.getWorld();
int widthX = maxX - minX + 1;
int widthY = maxY - minY + 1;
int widthZ = maxZ - minZ + 1;
int totalBlocks = widthX * widthY * widthZ;
if(totalBlocks <= config.getMaxTriggerVisualisationSize()) {
if (totalBlocks <= config.getMaxTriggerVisualisationSize()) {
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
for (int z = minZ; z <= maxZ; z++) {
var pos = new BlockLocation(pos1.getWorldName(), x, y, z);
boolean isTrigger = portal != null && portal.isTriggerBlock(world.getBlock(pos));
boolean isOutline = (y == minY || y == maxY) && (x == minX || x == maxX || z == minZ || z == maxZ) || (z == minZ || z == maxZ) && (x == minX || x == maxX);
boolean isTrigger =
portal != null && portal.isTriggerBlock(world.getBlock(pos));
boolean isOutline =
(y == minY || y == maxY)
&& (x == minX || x == maxX || z == minZ
|| z == maxZ)
|| (z == minZ || z == maxZ) && (x == minX || x == maxX);
if (isTrigger && isOutline && alternate_show_trigger) {
Debug.addMarker(player, pos, "", TRIGGER_OUTLINE_COLOR, time);
} else if (isOutline) {
Debug.addMarker(player, pos, "", color, time);
} else if(isTrigger) {
if(alternate_show_trigger)
} else if (isTrigger) {
if (alternate_show_trigger)
Debug.addMarker(player, pos, "", triggerColor, time);
}
}
@ -191,23 +243,83 @@ public class ShowPortalSubCommand implements SubCommand, SubCommand.SubCommandOn
} else {
for (int x = minX; x <= maxX; x++) {
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), x, minY, minZ), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), x, minY, maxZ), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), x, maxY, minZ), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), x, maxY, maxZ), "", color, time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), x, minY, minZ),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), x, minY, maxZ),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), x, maxY, minZ),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), x, maxY, maxZ),
"",
color,
time);
}
for (int z = minZ + 1; z < maxZ; z++) {
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), minX, minY, z), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), maxX, minY, z), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), minX, maxY, z), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), maxX, maxY, z), "", color, time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), minX, minY, z),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), maxX, minY, z),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), minX, maxY, z),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), maxX, maxY, z),
"",
color,
time);
}
for (int y = minY + 1; y < maxY; y++) {
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), minX, y, minZ), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), maxX, y, minZ), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), minX, y, maxZ), "", color, time);
Debug.addMarker(player, new BlockLocation(pos1.getWorldName(), maxX, y, maxZ), "", color, time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), minX, y, minZ),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), maxX, y, minZ),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), minX, y, maxZ),
"",
color,
time);
Debug.addMarker(
player,
new BlockLocation(pos1.getWorldName(), maxX, y, maxZ),
"",
color,
time);
}
}
}

View File

@ -11,7 +11,10 @@ public class VersionSubCommand implements SubCommand {
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
sender.sendMessage(Lang.translate("messageprefix.positive") + " Advanced Portals v" + AdvancedPortalsCore.version);
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ " Advanced Portals v"
+ AdvancedPortalsCore.version);
}
@Override

View File

@ -1,11 +1,9 @@
package com.sekwah.advancedportals.core.connector.commands;
import com.sekwah.advancedportals.core.commands.CommandTemplate;
public abstract class CommandHandler {
private final CommandTemplate commandExecutor;
public CommandHandler(CommandTemplate commandExecutor) {

View File

@ -6,9 +6,9 @@ public interface CommandRegister {
/**
* Registers the command to the appropriate system
*
* @param commandName
* @param commandExecutor
*/
void registerCommand(String commandName, CommandTemplate commandExecutor);
}

View File

@ -12,5 +12,4 @@ public interface CommandSenderContainer {
PlayerContainer getPlayerContainer();
boolean hasPermission(String permission);
}

View File

@ -1,13 +1,10 @@
package com.sekwah.advancedportals.core.connector.containers;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import java.util.UUID;
/**
* Just a temporary container for whenever advanced portals needs to get data from a player
*/
/** Just a temporary container for whenever advanced portals needs to get data from a player */
public interface PlayerContainer extends EntityContainer {
UUID getUUID();
@ -26,6 +23,7 @@ public interface PlayerContainer extends EntityContainer {
/**
* Only 1.12 and below supported
*
* @param blockPos
* @param material
* @param data

View File

@ -14,5 +14,4 @@ public interface ServerContainer {
List<String> getTriggerBlocks();
PlayerContainer[] getPlayers();
}

View File

@ -1,14 +1,12 @@
package com.sekwah.advancedportals.core.data;
public enum Direction {
NORTH(0, 0, -1),
EAST(1, 0, 0),
SOUTH(0, 0, 1),
WEST(-1, 0, 0),
UP(0, 1, 0),
DOWN(0, -1, 0)
;
DOWN(0, -1, 0);
public final int x;
public final int y;

View File

@ -2,10 +2,10 @@ package com.sekwah.advancedportals.core.destination;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.registry.TagTarget;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag;
@ -15,18 +15,18 @@ import java.util.Map;
import java.util.Set;
/**
* Possibly look at adding the ability to add some tags to destinations such as permissions. Would make it easier
* to add permissions to block access to certain areas and such. Could be a different permission system or just
* it takes the tags on the destination and automatically applies them when a portal wants to warp to there.
* (Of course it would not work cross server unless the data was communicated and checked first however that
* could affect performance and would definitely affect speed)
* Possibly look at adding the ability to add some tags to destinations such as permissions. Would
* make it easier to add permissions to block access to certain areas and such. Could be a different
* permission system or just it takes the tags on the destination and automatically applies them
* when a portal wants to warp to there. (Of course it would not work cross server unless the data
* was communicated and checked first however that could affect performance and would definitely
* affect speed)
*
* @author sekwah41
*/
public class Destination implements TagTarget {
@Inject
transient TagRegistry tagRegistry;
@Inject transient TagRegistry tagRegistry;
private PlayerLocation loc;
@ -53,9 +53,7 @@ public class Destination implements TagTarget {
}
@Override
public void addArg(String argName, String argValues) {
}
public void addArg(String argName, String argValues) {}
public void setArgValues(DataTag portalTag) {
this.setArgValues(portalTag.NAME, portalTag.VALUES);
@ -75,18 +73,19 @@ public class Destination implements TagTarget {
public boolean portalActivate(PlayerContainer player, ActivationData data) {
DataTag[] destiTags = new DataTag[args.size()];
int i = 0;
for(Map.Entry<String, String[]> entry : args.entrySet()) {
for (Map.Entry<String, String[]> entry : args.entrySet()) {
destiTags[i++] = new DataTag(entry.getKey(), entry.getValue());
}
for(DataTag destiTag : destiTags) {
for (DataTag destiTag : destiTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(destiTag.NAME);
if(activationHandler != null) {
activationHandler.preActivated(this, player, data, this.getArgValues(destiTag.NAME));
if (activationHandler != null) {
activationHandler.preActivated(
this, player, data, this.getArgValues(destiTag.NAME));
}
}
for(DataTag destiTag : destiTags) {
for (DataTag destiTag : destiTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(destiTag.NAME);
if(activationHandler != null) {
if (activationHandler != null) {
activationHandler.activated(this, player, data, this.getArgValues(destiTag.NAME));
}
}
@ -96,20 +95,21 @@ public class Destination implements TagTarget {
public void postActivate(PlayerContainer player, ActivationData data) {
DataTag[] destiTags = new DataTag[args.size()];
int i = 0;
for(Map.Entry<String, String[]> entry : args.entrySet()) {
for (Map.Entry<String, String[]> entry : args.entrySet()) {
destiTags[i++] = new DataTag(entry.getKey(), entry.getValue());
}
for(DataTag destiTag : destiTags) {
for (DataTag destiTag : destiTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(destiTag.NAME);
if(activationHandler != null) {
activationHandler.postActivated(this, player, data, this.getArgValues(destiTag.NAME));
if (activationHandler != null) {
activationHandler.postActivated(
this, player, data, this.getArgValues(destiTag.NAME));
}
}
}
public ArrayList<DataTag> getArgs() {
ArrayList<DataTag> tagList = new ArrayList<>();
for(Map.Entry<String, String[]> entry : this.args.entrySet()){
for (Map.Entry<String, String[]> entry : this.args.entrySet()) {
tagList.add(new DataTag(entry.getKey(), entry.getValue()));
}
return tagList;

View File

@ -1,8 +1,6 @@
package com.sekwah.advancedportals.core.effect;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
public interface WarpEffect {
@ -14,12 +12,10 @@ public interface WarpEffect {
interface Sound extends WarpEffect {
void onWarpSound(PlayerContainer player, Action action);
}
interface Visual extends WarpEffect {
void onWarpVisual(PlayerContainer player, Action action);
}
}

View File

@ -5,25 +5,25 @@ import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.connector.containers.ServerContainer;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.registry.WarpEffectRegistry;
import com.sekwah.advancedportals.core.repository.IPlayerDataRepository;
import com.sekwah.advancedportals.core.repository.impl.PlayerDataRepositoryImpl;
import com.sekwah.advancedportals.core.serializeddata.config.Config;
import com.sekwah.advancedportals.core.serializeddata.config.ConfigProvider;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.repository.IDestinationRepository;
import com.sekwah.advancedportals.core.repository.IPlayerDataRepository;
import com.sekwah.advancedportals.core.repository.IPortalRepository;
import com.sekwah.advancedportals.core.repository.impl.ConfigRepositoryImpl;
import com.sekwah.advancedportals.core.repository.impl.DestinationRepositoryImpl;
import com.sekwah.advancedportals.core.repository.impl.PlayerDataRepositoryImpl;
import com.sekwah.advancedportals.core.repository.impl.PortalRepositoryImpl;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.serializeddata.config.Config;
import com.sekwah.advancedportals.core.serializeddata.config.ConfigProvider;
import com.sekwah.advancedportals.core.util.InfoLogger;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
public class AdvancedPortalsModule extends AbstractModule {
import javax.annotation.Nonnull;
public class AdvancedPortalsModule extends AbstractModule {
private Injector injector;
private AdvancedPortalsCore advancedPortalsCore;
@ -35,9 +35,7 @@ public class AdvancedPortalsModule extends AbstractModule {
this.advancedPortalsCore = advancedPortalsCore;
}
/**
* https://github.com/google/guice/wiki/Bindings
*/
/** https://github.com/google/guice/wiki/Bindings */
@Override
protected void configure() {
bind(IPortalRepository.class).to(PortalRepositoryImpl.class).in(Scopes.SINGLETON);
@ -57,7 +55,7 @@ public class AdvancedPortalsModule extends AbstractModule {
bind(WarpEffectRegistry.class).asEagerSingleton();
// Delayed Bindings
for(DelayedBinding delayedBinding : delayedBindings) {
for (DelayedBinding delayedBinding : delayedBindings) {
bind(delayedBinding.clazz).toInstance(delayedBinding.instance);
}
}
@ -80,7 +78,7 @@ public class AdvancedPortalsModule extends AbstractModule {
// Call this later than the calls to addInstanceBinding
@Nonnull
public Injector getInjector() {
if(injector == null) {
if (injector == null) {
injector = Guice.createInjector(this);
}
return injector;

View File

@ -15,9 +15,9 @@ public class PortalPermissions {
public static final PermissionBuilder LANG_UPDATE = PERMISSIONS.createChild("langupdate");
public static final PermissionBuilder RELOAD = PERMISSIONS.createChild("reload");
/**
* this will not currently build the permissions for the files, but maybe at some point. It'll just make it easier though.
* this will not currently build the permissions for the files, but maybe at some point. It'll
* just make it easier though.
*/
public static class PermissionBuilder {
private final String permissionTag;
@ -42,7 +42,7 @@ public class PortalPermissions {
@Override
public String toString() {
if(parent != null) {
if (parent != null) {
return parent + "." + permissionTag;
} else {
return permissionTag;

View File

@ -2,11 +2,11 @@ package com.sekwah.advancedportals.core.portal;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.registry.TagTarget;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.services.PlayerDataServices;
import com.sekwah.advancedportals.core.tags.activation.TriggerBlockTag;
@ -21,8 +21,7 @@ import java.util.*;
*/
public class AdvancedPortal implements TagTarget {
@Inject
private transient TagRegistry tagRegistry;
@Inject private transient TagRegistry tagRegistry;
private BlockLocation maxLoc;
@ -30,18 +29,20 @@ public class AdvancedPortal implements TagTarget {
private final HashMap<String, String[]> args = new HashMap<>();
@Inject
private transient PlayerDataServices playerDataServices;
@Inject private transient PlayerDataServices playerDataServices;
@Inject
transient ConfigRepository configRepository;
@Inject transient ConfigRepository configRepository;
public AdvancedPortal() {
this.minLoc = new BlockLocation();
this.maxLoc = new BlockLocation();
}
public AdvancedPortal(BlockLocation minLoc, BlockLocation maxLoc, TagRegistry tagRegistry, PlayerDataServices playerDataServices) {
public AdvancedPortal(
BlockLocation minLoc,
BlockLocation maxLoc,
TagRegistry tagRegistry,
PlayerDataServices playerDataServices) {
this.tagRegistry = tagRegistry;
this.playerDataServices = playerDataServices;
this.updateBounds(minLoc, maxLoc);
@ -60,7 +61,6 @@ public class AdvancedPortal implements TagTarget {
return this.args.get(argName);
}
@Override
public void setArgValues(String argName, String[] argValues) {
this.args.put(argName, argValues);
@ -105,20 +105,22 @@ public class AdvancedPortal implements TagTarget {
}*/
/**
*
* @param player The player on the server attempting to use an advanced portal
* @param moveActivated if the portal was activated by a move event (won't trigger knockback)
* @return
*/
public boolean activate(PlayerContainer player, boolean moveActivated) {
var playerData = playerDataServices.getPlayerData(player);
if(playerData.isInPortal()) return false;
if (playerData.isInPortal()) return false;
playerData.setInPortal(true);
if(playerData.hasJoinCooldown()) {
if (playerData.hasJoinCooldown()) {
var cooldown = (int) Math.ceil(playerData.getJoinCooldownLeft() / 1000D);
player.sendMessage(Lang.translateInsertVariables("portal.cooldown.join", cooldown,
Lang.translate(cooldown == 1 ? "time.second" : "time.seconds")));
if(configRepository.playFailSound()) {
player.sendMessage(
Lang.translateInsertVariables(
"portal.cooldown.join",
cooldown,
Lang.translate(cooldown == 1 ? "time.second" : "time.seconds")));
if (configRepository.playFailSound()) {
var rand = new Random();
player.playSound("block.portal.travel", 0.05f, rand.nextFloat() * 0.4F + 0.8F);
}
@ -128,33 +130,36 @@ public class AdvancedPortal implements TagTarget {
ActivationData data = new ActivationData(moveActivated);
DataTag[] portalTags = new DataTag[args.size()];
int i = 0;
for(Map.Entry<String, String[]> entry : args.entrySet()) {
for (Map.Entry<String, String[]> entry : args.entrySet()) {
portalTags[i++] = new DataTag(entry.getKey(), entry.getValue());
}
for(DataTag portalTag : portalTags) {
for (DataTag portalTag : portalTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(portalTag.NAME);
if(activationHandler != null) {
if(!activationHandler.preActivated(this, player, data, this.getArgValues(portalTag.NAME))) {
if (activationHandler != null) {
if (!activationHandler.preActivated(
this, player, data, this.getArgValues(portalTag.NAME))) {
return false;
}
}
}
for(DataTag portalTag : portalTags) {
for (DataTag portalTag : portalTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(portalTag.NAME);
if(activationHandler != null) {
if(!activationHandler.activated(this, player, data, this.getArgValues(portalTag.NAME))) {
if (activationHandler != null) {
if (!activationHandler.activated(
this, player, data, this.getArgValues(portalTag.NAME))) {
return false;
}
}
}
for(DataTag portalTag : portalTags) {
for (DataTag portalTag : portalTags) {
Tag.Activation activationHandler = tagRegistry.getActivationHandler(portalTag.NAME);
if(activationHandler != null) {
activationHandler.postActivated(this, player, data, this.getArgValues(portalTag.NAME));
if (activationHandler != null) {
activationHandler.postActivated(
this, player, data, this.getArgValues(portalTag.NAME));
}
}
if(data.hasActivated()) {
if (data.hasActivated()) {
playerData.setNetherPortalCooldown(1000);
return true;
}
@ -178,22 +183,22 @@ public class AdvancedPortal implements TagTarget {
double playerY = loc.getPosY();
double playerZ = loc.getPosZ();
return Objects.equals(loc.getWorldName(), this.minLoc.getWorldName()) && playerX >= this.minLoc.getPosX() - additionalArea &&
playerX < this.maxLoc.getPosX() + 1 + additionalArea &&
playerY >= this.minLoc.getPosY() - additionalArea &&
playerY < this.maxLoc.getPosY() + 1 + additionalArea &&
playerZ >= this.minLoc.getPosZ() - additionalArea &&
playerZ < this.maxLoc.getPosZ() + 1 + additionalArea;
return Objects.equals(loc.getWorldName(), this.minLoc.getWorldName())
&& playerX >= this.minLoc.getPosX() - additionalArea
&& playerX < this.maxLoc.getPosX() + 1 + additionalArea
&& playerY >= this.minLoc.getPosY() - additionalArea
&& playerY < this.maxLoc.getPosY() + 1 + additionalArea
&& playerZ >= this.minLoc.getPosZ() - additionalArea
&& playerZ < this.maxLoc.getPosZ() + 1 + additionalArea;
}
public void setArgValues(DataTag portalTag) {
this.setArgValues(portalTag.NAME, portalTag.VALUES);
}
public ArrayList<DataTag> getArgs() {
ArrayList<DataTag> tagList = new ArrayList<>();
for(Map.Entry<String, String[]> entry : this.args.entrySet()){
for (Map.Entry<String, String[]> entry : this.args.entrySet()) {
tagList.add(new DataTag(entry.getKey(), entry.getValue()));
}
return tagList;
@ -201,9 +206,9 @@ public class AdvancedPortal implements TagTarget {
public boolean isTriggerBlock(String blockMaterial) {
var triggerBlocks = this.getArgValues(TriggerBlockTag.TAG_NAME);
if(triggerBlocks != null) {
for(String triggerBlock : triggerBlocks) {
if(blockMaterial.equals(triggerBlock)) {
if (triggerBlocks != null) {
for (String triggerBlock : triggerBlocks) {
if (blockMaterial.equals(triggerBlock)) {
return true;
}
}

View File

@ -4,8 +4,5 @@ public enum CommandErrorCode {
INSUFFICIENT_ARGUMENTS(""),
NO_PERMISSION("");
CommandErrorCode(String message) {
}
CommandErrorCode(String message) {}
}

View File

@ -4,9 +4,17 @@ import com.google.common.collect.ImmutableList;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
public interface CommandHandler {
void onExecute(String commandName, String parentCommand, CommandSenderContainer sender, ImmutableList<String> args);
void onExecute(
String commandName,
String parentCommand,
CommandSenderContainer sender,
ImmutableList<String> args);
default void onCommandFailure(String[] command, CommandSenderContainer sender, CommandException exception, ImmutableList<String> args) {
default void onCommandFailure(
String[] command,
CommandSenderContainer sender,
CommandException exception,
ImmutableList<String> args) {
sender.sendMessage(exception.getMessage());
}
}

View File

@ -1,28 +1,21 @@
package com.sekwah.advancedportals.core.registry;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.ClassPath;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RegisterBuilder<T extends CommandHandler> {
public static RegisterBuilder newBuilder() {
return new RegisterBuilder();
}
private RegisterBuilder() {
}
private RegisterBuilder() {}
private boolean allowPermissionInheritance;
private String scanDirectory;
private final Class<T> genericType = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
private final Class<T> genericType =
(Class<T>)
((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
public RegisterBuilder<T> inheritPermissions(boolean allowInheritance) {
allowPermissionInheritance = allowInheritance;
@ -33,5 +26,4 @@ public class RegisterBuilder<T extends CommandHandler> {
this.scanDirectory = directoryName;
return this;
}
}

View File

@ -11,8 +11,8 @@ import java.util.Map;
/**
* Do not register to here. Register to the sprcific subcommand registry classes.
* <p>
* Designed to let addons add new command sections to access, edit or add new functonality.
*
* <p>Designed to let addons add new command sections to access, edit or add new functonality.
*
* @author sekwah41
*/
@ -20,13 +20,10 @@ public class SubCommandRegistry {
protected Map<String, SubCommand> subCommandMap = new HashMap<>();
/**
* List of subcommand names which should be in order alphabetically
*/
/** List of subcommand names which should be in order alphabetically */
protected ArrayList<String> subCommands = new ArrayList<>();
@Inject
private InfoLogger infoLogger;
@Inject private InfoLogger infoLogger;
/**
* @param arg argument needed to activate
@ -40,7 +37,7 @@ public class SubCommandRegistry {
return false;
}
if(this.subCommandMap.containsKey(arg)){
if (this.subCommandMap.containsKey(arg)) {
this.infoLogger.warning("The subcommand '" + arg + "' already exists.");
return false;
}
@ -57,28 +54,30 @@ public class SubCommandRegistry {
/**
* @return a list of arguments of registered subcommands
*/
public ArrayList<String> getSubCommands(){
public ArrayList<String> getSubCommands() {
return this.subCommands;
}
/**
* I may be wrong but for larger lists containsKey is faster with a hashmap than arraylist.
*
* Though im not sure at what size it becomes more efficient.
* <p>Though im not sure at what size it becomes more efficient.
*
* @param arg
* @return if the argument is registered
*/
public boolean isArgRegistered(String arg){
public boolean isArgRegistered(String arg) {
return this.subCommandMap.containsKey(arg.toLowerCase());
}
/**
* Gets the subcommand corresponding to the string argument
*
* @param arg
* @return the subcommand linked to the arg
*/
public SubCommand getSubCommand(String arg){
if(this.subCommandMap.containsKey(arg.toLowerCase())){
public SubCommand getSubCommand(String arg) {
if (this.subCommandMap.containsKey(arg.toLowerCase())) {
return this.subCommandMap.get(arg.toLowerCase());
}
return null;

View File

@ -1,12 +1,11 @@
package com.sekwah.advancedportals.core.registry;
/**
* Something that a tag can be executed on.
*/
/** Something that a tag can be executed on. */
public interface TagTarget {
/**
* Get the values for the arg
*
* @param argName
* @return
*/
@ -14,6 +13,7 @@ public interface TagTarget {
/**
* Set the values for the arg
*
* @param argName
* @param argValues
*/
@ -21,6 +21,7 @@ public interface TagTarget {
/**
* Add a new arg to the tag
*
* @param argName
* @param argValues
*/
@ -28,6 +29,7 @@ public interface TagTarget {
/**
* Remove the arg entirely from the target
*
* @param arg
*/
void removeArg(String arg);

View File

@ -2,8 +2,4 @@ package com.sekwah.advancedportals.core.repository;
import com.sekwah.advancedportals.core.destination.Destination;
import java.io.IOException;
public interface IDestinationRepository extends IJsonRepository<Destination> {
}
public interface IDestinationRepository extends IJsonRepository<Destination> {}

View File

@ -1,11 +1,5 @@
package com.sekwah.advancedportals.core.repository;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerData;
import java.util.UUID;
public interface IPlayerDataRepository extends IJsonRepository<PlayerData> {
}
public interface IPlayerDataRepository extends IJsonRepository<PlayerData> {}

View File

@ -2,6 +2,4 @@ package com.sekwah.advancedportals.core.repository;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
public interface IPortalRepository extends IJsonRepository<AdvancedPortal> {
}
public interface IPortalRepository extends IJsonRepository<AdvancedPortal> {}

View File

@ -1,9 +1,9 @@
package com.sekwah.advancedportals.core.repository.impl;
import com.google.inject.Singleton;
import com.sekwah.advancedportals.core.serializeddata.config.Config;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.serializeddata.config.Config;
import java.util.HashMap;
@ -15,7 +15,7 @@ public class ConfigRepositoryImpl implements ConfigRepository {
private DataStorage dataStorage;
public ConfigRepositoryImpl() {
configs = new HashMap<String,Config>();
configs = new HashMap<String, Config>();
}
public <T> T getValue(String output) {
@ -103,5 +103,4 @@ public class ConfigRepositoryImpl implements ConfigRepository {
public void storeConfig() {
this.dataStorage.storeFile(this.config, "config.yaml");
}
}

View File

@ -6,16 +6,16 @@ import com.sekwah.advancedportals.core.repository.IDestinationRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.tags.activation.NameTag;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Singleton;
@Singleton
public class DestinationRepositoryImpl implements IDestinationRepository {
private final String fileLocation = "desti/";
@Inject
DataStorage dataStorage;
@Inject DataStorage dataStorage;
@Override
public boolean save(String name, Destination destination) {
@ -48,8 +48,8 @@ public class DestinationRepositoryImpl implements IDestinationRepository {
Destination destination = this.get(fileName);
// Forces the name tag to be up-to-date on load
String[] name = destination.getArgValues(NameTag.TAG_NAME);
if(name != null && name.length > 0) {
destination.setArgValues(NameTag.TAG_NAME, new String[]{fileName});
if (name != null && name.length > 0) {
destination.setArgValues(NameTag.TAG_NAME, new String[] {fileName});
}
destinations.add(destination);
}

View File

@ -11,8 +11,7 @@ public class PlayerDataRepositoryImpl implements IPlayerDataRepository {
private final String fileLocation = "playerData/";
@Inject
DataStorage dataStorage;
@Inject DataStorage dataStorage;
@Override
public boolean save(String name, PlayerData playerData) {

View File

@ -4,8 +4,8 @@ import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.repository.IPortalRepository;
import com.sekwah.advancedportals.core.serializeddata.DataStorage;
import com.sekwah.advancedportals.core.tags.activation.NameTag;
import java.util.*;
@ -15,13 +15,13 @@ public class PortalRepositoryImpl implements IPortalRepository {
private final String fileLocation = "portals/";
@Inject
DataStorage dataStorage;
@Inject DataStorage dataStorage;
/**
* In memory copy of the portal files as they will be accessed every movement tick.
*
* If we need to get it by name we can just load it from the file, but this is good for looping fast for the player move events.
* <p>If we need to get it by name we can just load it from the file, but this is good for
* looping fast for the player move events.
*/
private List<AdvancedPortal> portals = new ArrayList<>();
@ -43,7 +43,7 @@ public class PortalRepositoryImpl implements IPortalRepository {
@Override
public AdvancedPortal get(String name) {
var portal = dataStorage.loadFile(AdvancedPortal.class, fileLocation + name + ".yaml");
if(portal != null) {
if (portal != null) {
AdvancedPortalsCore.getInstance().getModule().getInjector().injectMembers(portal);
}
return portal;
@ -59,11 +59,12 @@ public class PortalRepositoryImpl implements IPortalRepository {
List<AdvancedPortal> portals = new ArrayList<>();
List<String> allFiles = dataStorage.listAllFiles(fileLocation, false);
for (String fileName : allFiles) {
AdvancedPortal portal = dataStorage.loadFile(AdvancedPortal.class, fileLocation + fileName);
AdvancedPortal portal =
dataStorage.loadFile(AdvancedPortal.class, fileLocation + fileName);
// Forces the name tag to be up-to-date on load
String[] name = portal.getArgValues(NameTag.TAG_NAME);
if(name != null && name.length > 0) {
portal.setArgValues(NameTag.TAG_NAME, new String[]{fileName.replace(".yaml", "")});
if (name != null && name.length > 0) {
portal.setArgValues(NameTag.TAG_NAME, new String[] {fileName.replace(".yaml", "")});
}
portals.add(portal);
}

View File

@ -2,8 +2,6 @@ package com.sekwah.advancedportals.core.serializeddata;
import com.sekwah.advancedportals.core.data.Direction;
import java.io.Serializable;
public class BlockLocation {
// These should be treated as final, they only are not for serialization purposes
@ -34,7 +32,6 @@ public class BlockLocation {
this.posX = location.posX + direction.x;
this.posY = location.posY + direction.y;
this.posZ = location.posZ + direction.z;
}
public int getPosX() {
@ -54,7 +51,10 @@ public class BlockLocation {
}
public boolean equals(BlockLocation location) {
return location.posX == this.posX && location.posY == this.posY && location.posZ == this.posZ && location.worldName.equals(this.worldName);
return location.posX == this.posX
&& location.posY == this.posY
&& location.posZ == this.posZ
&& location.worldName.equals(this.worldName);
}
public double distanceTo(BlockLocation pos) {

View File

@ -3,12 +3,12 @@ package com.sekwah.advancedportals.core.serializeddata;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.util.InfoLogger;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.inspector.TagInspector;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
@ -21,11 +21,9 @@ public class DataStorage {
private final File dataFolder;
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
@Inject
private InfoLogger infoLogger;
@Inject private InfoLogger infoLogger;
public DataStorage(File dataStorageLoc) {
this.dataFolder = dataStorageLoc;
@ -66,7 +64,10 @@ public class DataStorage {
if (yamlResource == null) {
try {
return dataHolder.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
} catch (InstantiationException
| IllegalAccessException
| NoSuchMethodException
| InvocationTargetException e) {
e.printStackTrace();
}
return null;
@ -102,7 +103,8 @@ public class DataStorage {
* Copies the specified file out of the plugin and into the plugins folder.
*
* @param fileLoc
* @return if the file is copied, will be false if override is false and the file already existed.
* @return if the file is copied, will be false if override is false and the file already
* existed.
*/
public boolean copyDefaultFile(String fileLoc, boolean overwrite) {
return this.copyDefaultFile(fileLoc, fileLoc, overwrite);
@ -113,7 +115,8 @@ public class DataStorage {
*
* @param sourceLoc - location of the file in the jar
* @param fileLoc - location to save the file
* @return if the file is copied, will be false if override is false and the file already existed.
* @return if the file is copied, will be false if override is false and the file already
* existed.
*/
public boolean copyDefaultFile(String sourceLoc, String fileLoc, boolean overwrite) {
File outFile = new File(this.dataFolder, fileLoc);
@ -122,16 +125,20 @@ public class DataStorage {
}
if (!outFile.exists() || overwrite) {
try {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(sourceLoc);
if(inputStream == null) {
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream(sourceLoc);
if (inputStream == null) {
return false;
}
writeToFile(inputStream, outFile);
} catch (NullPointerException e) {
e.printStackTrace();
this.infoLogger.warning("Could not load " + sourceLoc + ". The file does" +
"not exist or there has been an error reading the file.");
this.infoLogger.warning(
"Could not load "
+ sourceLoc
+ ". The file does"
+ "not exist or there has been an error reading the file.");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
@ -145,8 +152,11 @@ public class DataStorage {
}
/**
* A method to try to grab the files from the plugin and if its in the plugin folder load from there instead.
* A method to try to grab the files from the plugin and if its in the plugin folder load from
* there instead.
*
* <p>
*
* @param location
* @return
*/
@ -165,8 +175,11 @@ public class DataStorage {
return this.getClass().getClassLoader().getResourceAsStream(location);
} catch (NullPointerException e) {
e.printStackTrace();
this.infoLogger.warning("Could not load " + location + ". The file does" +
"not exist or there has been an error reading the file.");
this.infoLogger.warning(
"Could not load "
+ location
+ ". The file does"
+ "not exist or there has been an error reading the file.");
return null;
}
}
@ -216,7 +229,8 @@ public class DataStorage {
for (File file : files) {
if (file.isFile()) {
String fileName = file.getName();
boolean extensionMatches = (extension == null || fileName.endsWith("." + extension));
boolean extensionMatches =
(extension == null || fileName.endsWith("." + extension));
if (extensionMatches) {
if (trimExtension) {

View File

@ -9,5 +9,4 @@ public class DataTag {
this.NAME = argName;
this.VALUES = values;
}
}

View File

@ -5,40 +5,30 @@ import java.util.HashMap;
/**
* Possibly one of the only files in this package not designed to be serialised.
*
* Any temporary data about players will be stored here and cleaned up when the player leaves the server.
* <p>Any temporary data about players will be stored here and cleaned up when the player leaves the
* server.
*
* This is not a place to store long term data e.g. if you want to make a player unable to use a portal over hours/days.
* <p>This is not a place to store long term data e.g. if you want to make a player unable to use a
* portal over hours/days.
*/
public class PlayerData {
/**
* Portal selection position 1
*/
/** Portal selection position 1 */
private BlockLocation pos1;
/**
* Portal selection position 2
*/
/** Portal selection position 2 */
private BlockLocation pos2;
/**
* If to show portals near the player
*/
/** If to show portals near the player */
private boolean portalVisible = false;
/**
* If to show destination blocks near the player
*/
/** If to show destination blocks near the player */
private boolean destiVisible;
/**
* If the player is in a portal. Stops re-triggering.
*/
/** If the player is in a portal. Stops re-triggering. */
private transient boolean isInPortal = false;
/**
* The next time System.currentTimeMillis() a player can use a portal.
*/
/** The next time System.currentTimeMillis() a player can use a portal. */
private transient long joinCooldown;
private transient long netherPortalCooldown;
@ -120,7 +110,8 @@ public class PlayerData {
}
public boolean hasPortalCooldown(String portalName) {
return perPortalCooldowns.containsKey(portalName) && System.currentTimeMillis() < perPortalCooldowns.get(portalName);
return perPortalCooldowns.containsKey(portalName)
&& System.currentTimeMillis() < perPortalCooldowns.get(portalName);
}
public double getPortalCooldownLeft(String portalName) {

View File

@ -1,6 +1,5 @@
package com.sekwah.advancedportals.core.serializeddata;
public class PlayerLocation extends WorldLocation {
private final float yaw;
@ -19,7 +18,8 @@ public class PlayerLocation extends WorldLocation {
this.pitch = 0;
}
public PlayerLocation(String worldName, double posX, double posY, double posZ, float yaw, float pitch) {
public PlayerLocation(
String worldName, double posX, double posY, double posZ, float yaw, float pitch) {
super(worldName, posX, posY, posZ);
this.yaw = yaw;
this.pitch = pitch;

View File

@ -10,6 +10,10 @@ public class WorldLocation extends Vector {
}
public BlockLocation toBlockPos() {
return new BlockLocation(this.worldName, (int) Math.floor(this.x), (int) Math.floor(this.y), (int) Math.floor(this.z));
return new BlockLocation(
this.worldName,
(int) Math.floor(this.x),
(int) Math.floor(this.y),
(int) Math.floor(this.z));
}
}

View File

@ -1,8 +1,6 @@
package com.sekwah.advancedportals.core.serializeddata.config;
/**
* To store the data for config
*/
/** To store the data for config */
public class Config {
public boolean useOnlySpecialAxe = true;

View File

@ -1,31 +1,28 @@
package com.sekwah.advancedportals.core.services;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.destination.Destination;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.repository.IDestinationRepository;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.destination.Destination;
import com.sekwah.advancedportals.core.repository.IDestinationRepository;
import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
@Singleton
public class DestinationServices {
@Inject
private IDestinationRepository destinationRepository;
@Inject private IDestinationRepository destinationRepository;
@Inject
TagRegistry tagRegistry;
@Inject TagRegistry tagRegistry;
private final Map<String, Destination> destinationCache = new HashMap<>();
@ -50,23 +47,34 @@ public class DestinationServices {
return createDesti(null, playerLocation, tags);
}
public Destination createDesti(PlayerContainer player, PlayerLocation playerLocation, List<DataTag> tags) {
public Destination createDesti(
PlayerContainer player, PlayerLocation playerLocation, List<DataTag> tags) {
// Find the tag with the "name" NAME
DataTag nameTag = tags.stream().filter(tag -> tag.NAME.equals("name")).findFirst().orElse(null);
DataTag nameTag =
tags.stream().filter(tag -> tag.NAME.equals("name")).findFirst().orElse(null);
String name = nameTag == null ? null : nameTag.VALUES[0];
// If the name is null, send an error saying that the name is required.
if (nameTag == null) {
if (player != null) player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("desti.error.noname"));
if (player != null)
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("desti.error.noname"));
return null;
}
if (name == null || name.equals("")) {
if (player != null) player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
if (player != null)
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.error.noname"));
return null;
} else if (this.destinationRepository.containsKey(name)) {
if (player != null) player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translateInsertVariables("command.error.nametaken", name));
if (player != null)
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translateInsertVariables("command.error.nametaken", name));
return null;
}
@ -76,28 +84,29 @@ public class DestinationServices {
}
for (DataTag destiTag : tags) {
Tag.Creation creation = tagRegistry.getCreationHandler(destiTag.NAME);
if(creation != null) {
if(!creation.created(desti, player, destiTag.VALUES)) {
if (creation != null) {
if (!creation.created(desti, player, destiTag.VALUES)) {
return null;
}
}
}
try {
if(this.destinationRepository.save(name, desti)) {
if (this.destinationRepository.save(name, desti)) {
this.destinationCache.put(name, desti);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("desti.error.save"));
player.sendMessage(
Lang.translate("messageprefix.negative") + Lang.translate("desti.error.save"));
}
return desti;
}
public boolean removeDestination(String name, PlayerContainer playerContainer) {
this.destinationCache.remove(name);
if(this.destinationRepository.containsKey(name)) {
if (this.destinationRepository.containsKey(name)) {
this.destinationRepository.delete(name);
return true;
}
@ -109,7 +118,7 @@ public class DestinationServices {
}
public boolean teleportToDestination(String name, PlayerContainer playerContainer) {
if(this.destinationRepository.containsKey(name)) {
if (this.destinationRepository.containsKey(name)) {
playerContainer.teleport(this.destinationRepository.get(name).getLoc());
return true;
}

View File

@ -8,35 +8,33 @@ import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerData;
import com.sekwah.advancedportals.core.util.Lang;
import javax.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.inject.Singleton;
@Singleton
public final class PlayerDataServices {
/**
* Possibly change to the cache map Aztec was talking about
*/
/** Possibly change to the cache map Aztec was talking about */
private Map<UUID, PlayerData> tempDataMap = new HashMap<>();
@Inject
private IPlayerDataRepository tempDataRepository;
@Inject private IPlayerDataRepository tempDataRepository;
@Inject
private ConfigRepository configRepository;
@Inject private ConfigRepository configRepository;
public PlayerData getPlayerData(PlayerContainer player) {
return tempDataMap.computeIfAbsent(player.getUUID(), uuid -> {
var tempData = tempDataRepository.get(player.getUUID().toString());
return tempDataMap.computeIfAbsent(
player.getUUID(),
uuid -> {
var tempData = tempDataRepository.get(player.getUUID().toString());
if(tempData == null) {
tempData = new PlayerData();
}
return tempData;
});
if (tempData == null) {
tempData = new PlayerData();
}
return tempData;
});
}
public void setJoinCooldown(PlayerContainer player) {
@ -49,13 +47,20 @@ public final class PlayerDataServices {
tempDataMap.remove(player.getUUID());
}
public void playerSelectorActivate(PlayerContainer player, BlockLocation blockLoc, boolean leftClick) {
public void playerSelectorActivate(
PlayerContainer player, BlockLocation blockLoc, boolean leftClick) {
var tempData = getPlayerData(player);
if(leftClick) {
if (leftClick) {
tempData.setPos1(blockLoc);
} else {
tempData.setPos2(blockLoc);
}
player.sendMessage(Lang.translateInsertVariables("portal.selector.poschange", leftClick ? "1" : "2", blockLoc.getPosX(), blockLoc.getPosY(), blockLoc.getPosZ()));
player.sendMessage(
Lang.translateInsertVariables(
"portal.selector.poschange",
leftClick ? "1" : "2",
blockLoc.getPosX(),
blockLoc.getPosY(),
blockLoc.getPosZ()));
}
}

View File

@ -2,56 +2,52 @@ package com.sekwah.advancedportals.core.services;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.registry.TagRegistry;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.repository.IPortalRepository;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.serializeddata.PlayerData;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.tags.activation.NameTag;
import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.util.PlayerUtils;
import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.inject.Singleton;
import java.util.*;
import javax.inject.Singleton;
@Singleton
public class PortalServices {
@Inject
private IPortalRepository portalRepository;
@Inject private IPortalRepository portalRepository;
@Inject
private transient PlayerDataServices playerDataServices;
@Inject private transient PlayerDataServices playerDataServices;
@Inject
private ConfigRepository configRepository;
@Inject private ConfigRepository configRepository;
private final Map<String, AdvancedPortal> portalCache = new HashMap<>();
@Inject
TagRegistry tagRegistry;
@Inject TagRegistry tagRegistry;
public void loadPortals() {
List<String> portalNames = portalRepository.getAllNames();
portalCache.clear();
for (String name : portalNames) {
AdvancedPortal portal = portalRepository.get(name);
if(portal == null) {
if (portal == null) {
continue;
}
portalCache.put(name, portal);
portal.updateBounds(portal.getMinLoc(), portal.getMaxLoc());
}
}
public boolean inPortalRegionProtected(BlockLocation loc) {
for (AdvancedPortal portal : portalCache.values()) {
if(portal.isLocationInPortal(loc, configRepository.getProtectionRadius())) {
if (portal.isLocationInPortal(loc, configRepository.getProtectionRadius())) {
return true;
}
}
@ -60,7 +56,7 @@ public class PortalServices {
public boolean inPortalRegionProtected(PlayerLocation loc) {
for (AdvancedPortal portal : portalCache.values()) {
if(portal.isLocationInPortal(loc, configRepository.getProtectionRadius())) {
if (portal.isLocationInPortal(loc, configRepository.getProtectionRadius())) {
return true;
}
}
@ -69,7 +65,7 @@ public class PortalServices {
public boolean inPortalRegion(BlockLocation loc, int extraBlocks) {
for (AdvancedPortal portal : portalCache.values()) {
if(portal.isLocationInPortal(loc, extraBlocks)) {
if (portal.isLocationInPortal(loc, extraBlocks)) {
return true;
}
}
@ -86,10 +82,9 @@ public class PortalServices {
var notInPortal = true;
for (AdvancedPortal portal : portalCache.values()) {
if ((portal.isLocationInPortal(toLoc)
&& portal.isTriggerBlock(blockMaterial))
if ((portal.isLocationInPortal(toLoc) && portal.isTriggerBlock(blockMaterial))
|| (portal.isLocationInPortal(blockEntityTopLoc)
&& portal.isTriggerBlock(blockEntityTopMaterial))) {
&& portal.isTriggerBlock(blockEntityTopMaterial))) {
notInPortal = false;
if (portal.activate(player, true)) {
return;
@ -116,7 +111,7 @@ public class PortalServices {
public boolean removePortal(String name, PlayerContainer player) {
this.portalCache.remove(name);
if(this.portalRepository.containsKey(name)) {
if (this.portalRepository.containsKey(name)) {
this.portalRepository.delete(name);
return true;
}
@ -130,30 +125,44 @@ public class PortalServices {
public AdvancedPortal createPortal(PlayerContainer player, ArrayList<DataTag> tags) {
PlayerData tempData = playerDataServices.getPlayerData(player);
if(tempData.getPos1() == null || tempData.getPos2() == null) {
player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("portal.error.selection.missing"));
if (tempData.getPos1() == null || tempData.getPos2() == null) {
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("portal.error.selection.missing"));
return null;
}
if(!tempData.getPos1().getWorldName().equals(tempData.getPos2().getWorldName())) {
player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("portal.error.selection.differentworlds"));
if (!tempData.getPos1().getWorldName().equals(tempData.getPos2().getWorldName())) {
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("portal.error.selection.differentworlds"));
return null;
}
return createPortal(player, tempData.getPos1(), tempData.getPos2(), tags);
}
public AdvancedPortal createPortal(PlayerContainer player, BlockLocation pos1, BlockLocation pos2, List<DataTag> tags) {
public AdvancedPortal createPortal(
PlayerContainer player, BlockLocation pos1, BlockLocation pos2, List<DataTag> tags) {
// Find the tag with the "name" NAME
DataTag nameTag = tags.stream().filter(tag -> tag.NAME.equals(NameTag.TAG_NAME)).findFirst().orElse(null);
DataTag nameTag =
tags.stream()
.filter(tag -> tag.NAME.equals(NameTag.TAG_NAME))
.findFirst()
.orElse(null);
String name = nameTag == null ? null : nameTag.VALUES[0];
if(nameTag == null || name == null || name.isEmpty()) {
if(player != null) player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("command.error.noname"));
if (nameTag == null || name == null || name.isEmpty()) {
if (player != null)
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("command.error.noname"));
return null;
}
else if(this.portalRepository.containsKey(name)) {
if(player != null) player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translateInsertVariables("command.error.nametaken", name));
} else if (this.portalRepository.containsKey(name)) {
if (player != null)
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translateInsertVariables("command.error.nametaken", name));
return null;
}
@ -165,22 +174,25 @@ public class PortalServices {
for (DataTag portalTag : tags) {
Tag.Creation creation = tagRegistry.getCreationHandler(portalTag.NAME);
if(creation != null) {
if(!creation.created(portal, player, portalTag.VALUES)) {
if (creation != null) {
if (!creation.created(portal, player, portalTag.VALUES)) {
return null;
}
}
}
try {
if(this.portalRepository.save(name, portal)) {
if (this.portalRepository.save(name, portal)) {
this.portalCache.put(name, portal);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
if(player != null) player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("portal.error.save"));
if (player != null)
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("portal.error.save"));
}
return portal;

View File

@ -11,19 +11,18 @@ import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.annotation.Nullable;
import java.util.List;
import javax.annotation.Nullable;
public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split {
public static String TAG_NAME = "destination";
@Inject
DestinationServices destinationServices;
@Inject DestinationServices destinationServices;
@Inject
WarpEffectRegistry warpEffectRegistry;
@Inject WarpEffectRegistry warpEffectRegistry;
private final TagType[] tagTypes = new TagType[]{ TagType.PORTAL };
private final TagType[] tagTypes = new TagType[] {TagType.PORTAL};
@Override
public TagType[] getTagTypes() {
@ -37,7 +36,7 @@ public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split {
@Override
public String[] getAliases() {
return new String[]{"desti"};
return new String[] {"desti"};
}
@Override
@ -46,7 +45,8 @@ public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split {
}
@Override
public boolean preActivated(TagTarget target, PlayerContainer player, ActivationData activeData, String[] argData) {
public boolean preActivated(
TagTarget target, PlayerContainer player, ActivationData activeData, String[] argData) {
// Check that the destination exists.
for (String destiName : destinationServices.getDestinationNames()) {
if (destiName.equalsIgnoreCase(argData[0])) {
@ -57,12 +57,18 @@ public class DestiTag implements Tag.Activation, Tag.AutoComplete, Tag.Split {
}
@Override
public void postActivated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData) {
}
public void postActivated(
TagTarget target,
PlayerContainer player,
ActivationData activationData,
String[] argData) {}
@Override
public boolean activated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData) {
public boolean activated(
TagTarget target,
PlayerContainer player,
ActivationData activationData,
String[] argData) {
Destination destination = destinationServices.getDestination(argData[0]);
if (destination != null) {
var warpEffectVisual = warpEffectRegistry.getVisualEffect("ender");

View File

@ -3,24 +3,25 @@ package com.sekwah.advancedportals.core.tags.activation;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.registry.TagTarget;
import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.ActivationData;
import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.annotation.Nullable;
import java.util.List;
import javax.annotation.Nullable;
/**
* The name of the destination or portal.
* <p>
* Most of the implementation of this tag is external, this is just to allow for the tag to be used.
* <p>
* Most tags shouldn't be like this unless they are to be paired with another tag.
*
* <p>Most of the implementation of this tag is external, this is just to allow for the tag to be
* used.
*
* <p>Most tags shouldn't be like this unless they are to be paired with another tag.
*/
public class NameTag implements Tag.AutoComplete, Tag.Creation {
public static String TAG_NAME = "name";
private final TagType[] tagTypes = new TagType[]{ TagType.PORTAL, TagType.DESTINATION };
private final TagType[] tagTypes = new TagType[] {TagType.PORTAL, TagType.DESTINATION};
@Override
public TagType[] getTagTypes() {
@ -58,7 +59,9 @@ public class NameTag implements Tag.AutoComplete, Tag.Creation {
if (argData.length > 0) {
String name = argData[0];
if (name.contains(" ")) {
player.sendMessage(Lang.translate("messageprefix.negative") + Lang.translate("tag.name.error.nospaces"));
player.sendMessage(
Lang.translate("messageprefix.negative")
+ Lang.translate("tag.name.error.nospaces"));
return false;
}
}
@ -66,7 +69,5 @@ public class NameTag implements Tag.AutoComplete, Tag.Creation {
}
@Override
public void destroyed(TagTarget target, PlayerContainer player, String[] argData) {
}
public void destroyed(TagTarget target, PlayerContainer player, String[] argData) {}
}

View File

@ -1,8 +1,6 @@
package com.sekwah.advancedportals.core.tags.activation;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.permissions.PortalPermissions;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.registry.TagTarget;
import com.sekwah.advancedportals.core.repository.ConfigRepository;
import com.sekwah.advancedportals.core.services.PlayerDataServices;
@ -13,24 +11,20 @@ import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.List;
public class PermissionTag implements Tag.Activation{
public class PermissionTag implements Tag.Activation {
@Inject
transient PlayerDataServices playerDataServices;
@Inject transient PlayerDataServices playerDataServices;
@Inject
transient ConfigRepository configRepository;
@Inject transient ConfigRepository configRepository;
@Inject
private InfoLogger infoLogger;
@Inject private InfoLogger infoLogger;
public static String TAG_NAME = "permission";
private final String[] aliases = new String[]{ "perm" };
private final String[] aliases = new String[] {"perm"};
private final TagType[] tagTypes = new TagType[]{ TagType.PORTAL };
private final TagType[] tagTypes = new TagType[] {TagType.PORTAL};
@Override
public TagType[] getTagTypes() {
@ -54,7 +48,8 @@ public class PermissionTag implements Tag.Activation{
}
@Override
public boolean preActivated(TagTarget target, PlayerContainer player, ActivationData activeData, String[] argData) {
public boolean preActivated(
TagTarget target, PlayerContainer player, ActivationData activeData, String[] argData) {
if (!player.hasPermission(argData[1])) {
player.sendMessage(Lang.translate("portal.error.nopermission"));
return false;
@ -63,12 +58,18 @@ public class PermissionTag implements Tag.Activation{
}
@Override
public void postActivated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData) {
}
public void postActivated(
TagTarget target,
PlayerContainer player,
ActivationData activationData,
String[] argData) {}
@Override
public boolean activated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData) {
public boolean activated(
TagTarget target,
PlayerContainer player,
ActivationData activationData,
String[] argData) {
return true;
}
}

View File

@ -5,17 +5,17 @@ import com.sekwah.advancedportals.core.connector.containers.ServerContainer;
import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.core.warphandler.Tag;
import javax.annotation.Nullable;
import java.util.List;
import javax.annotation.Nullable;
public class TriggerBlockTag implements Tag.AutoComplete, Tag.Split {
@Inject
private ServerContainer serverContainer;
@Inject private ServerContainer serverContainer;
public static String TAG_NAME = "triggerblock";
private final TagType[] tagTypes = new TagType[]{ TagType.PORTAL };
private final TagType[] tagTypes = new TagType[] {TagType.PORTAL};
@Override
public TagType[] getTagTypes() {

View File

@ -2,12 +2,16 @@ package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.util.FriendlyDataOutput;
import java.awt.*;
public class Debug {
public static boolean addMarker(PlayerContainer player, BlockLocation blockPos, String name, Color color, int milliseconds) {
public static boolean addMarker(
PlayerContainer player,
BlockLocation blockPos,
String name,
Color color,
int milliseconds) {
FriendlyDataOutput out = new FriendlyDataOutput();
out.writeBlock(blockPos);
out.writeInt(color(color));
@ -34,18 +38,18 @@ public class Debug {
}
public float getR(int color) {
return (float)(color >> 16 & 255) / 255.0F;
return (float) (color >> 16 & 255) / 255.0F;
}
public float getG(int color) {
return (float)(color >> 8 & 255) / 255.0F;
return (float) (color >> 8 & 255) / 255.0F;
}
public float getB(int color) {
return (float)(color & 255) / 255.0F;
return (float) (color & 255) / 255.0F;
}
public float getA(int color) {
return (float)(color >> 24 & 255) / 255.0F;
return (float) (color >> 24 & 255) / 255.0F;
}
}

View File

@ -1,15 +1,14 @@
package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.EncoderException;
import java.nio.charset.StandardCharsets;
/**
* Meant to be similar to FriendlyByteBuf if you have used that before.
*/
/** Meant to be similar to FriendlyByteBuf if you have used that before. */
public class FriendlyDataOutput {
private final ByteBuf dataOutput;
@ -52,12 +51,14 @@ public class FriendlyDataOutput {
public void writeUtf(String text, int maxLength) {
if (text.length() > maxLength) {
throw new EncoderException("String too big (was " + text.length() + " characters, max " + maxLength + ")");
throw new EncoderException(
"String too big (was " + text.length() + " characters, max " + maxLength + ")");
} else {
byte[] abyte = text.getBytes(StandardCharsets.UTF_8);
int i = getMaxEncodedUtfLength(maxLength);
if (abyte.length > i) {
throw new EncoderException("String too big (was " + abyte.length + " bytes encoded, max " + i + ")");
throw new EncoderException(
"String too big (was " + abyte.length + " bytes encoded, max " + i + ")");
} else {
this.writeVarInt(abyte.length);
this.writeBytes(abyte);
@ -66,7 +67,7 @@ public class FriendlyDataOutput {
}
public void writeVarInt(int p_130131_) {
while((p_130131_ & -128) != 0) {
while ((p_130131_ & -128) != 0) {
this.writeByte(p_130131_ & 127 | 128);
p_130131_ >>>= 7;
}
@ -97,7 +98,9 @@ public class FriendlyDataOutput {
}
// Only for block serialising and such
private static final int PACKED_X_LENGTH = 26; // 1 + Mth.log2(Mth.smallestEncompassingPowerOfTwo(30000000)) (im not gonna add all the mojang math stuff to calculate this.
private static final int PACKED_X_LENGTH =
26; // 1 + Mth.log2(Mth.smallestEncompassingPowerOfTwo(30000000)) (im not gonna add all
// the mojang math stuff to calculate this.
private static final int PACKED_Z_LENGTH = PACKED_X_LENGTH;
public static final int PACKED_Y_LENGTH = 64 - PACKED_X_LENGTH - PACKED_Z_LENGTH;
private static final long PACKED_X_MASK = (1L << PACKED_X_LENGTH) - 1L;
@ -113,8 +116,8 @@ public class FriendlyDataOutput {
private long blockAsLong(BlockLocation blockLoc) {
long i = 0L;
i |= ((long)blockLoc.getPosX() & PACKED_X_MASK) << X_OFFSET;
i |= ((long)blockLoc.getPosY() & PACKED_Y_MASK) << 0;
return i | ((long)blockLoc.getPosZ() & PACKED_Z_MASK) << Z_OFFSET;
i |= ((long) blockLoc.getPosX() & PACKED_X_MASK) << X_OFFSET;
i |= ((long) blockLoc.getPosY() & PACKED_Y_MASK) << 0;
return i | ((long) blockLoc.getPosZ() & PACKED_Z_MASK) << Z_OFFSET;
}
}

View File

@ -1,19 +1,17 @@
package com.sekwah.advancedportals.core.util;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Iterator;
/**
* For all delayed and repeating tasks.
*/
import javax.inject.Singleton;
/** For all delayed and repeating tasks. */
@Singleton
public final class GameScheduler {
private final ArrayList<DelayedGameTickEvent> newTickEvents = new ArrayList<>();
private final ArrayList<DelayedGameTickEvent> delayedTickEvents = new ArrayList<>();
public void tick() {
this.delayedTickEvents.addAll(this.newTickEvents);
this.newTickEvents.clear();
@ -23,8 +21,7 @@ public final class GameScheduler {
event.tick();
if (event.shouldRun()) {
event.run();
if(!(event instanceof DelayedGameIntervalEvent))
tickEventIterator.remove();
if (!(event instanceof DelayedGameIntervalEvent)) tickEventIterator.remove();
}
}
}
@ -81,6 +78,5 @@ public final class GameScheduler {
this.ticks = interval;
super.run();
}
}
}

View File

@ -1,16 +1,17 @@
package com.sekwah.advancedportals.core.util;
public abstract class InfoLogger {
/**
* Problematic messages
*
* @param s warning message
*/
public abstract void warning(String s);
/**
* General information logging
*
* @param s info message
*/
public abstract void info(String s);

View File

@ -13,27 +13,24 @@ import java.util.Scanner;
/**
* @author sekwah41
* <p>
* The language translation file for the game. Will always load english first
* so that if the translations are missing any then they are still readable and can then be translated.
* (It's better than a raw translate string)
* <p>
* <p>The language translation file for the game. Will always load english first so that if the
* translations are missing any then they are still readable and can then be translated. (It's
* better than a raw translate string)
* <p>
*/
public class Lang {
public static final Lang instance = new Lang();
private final HashMap<String, String> languageMap = new HashMap<>();
@Inject
private DataStorage dataStorage;
@Inject private DataStorage dataStorage;
@Inject
private InfoLogger infoLogger;
@Inject private InfoLogger infoLogger;
public static final String DEFAULT_LANG = "en_GB";
public static void loadLanguage(String fileName) {
if(!DEFAULT_LANG.equals(fileName)) {
if (!DEFAULT_LANG.equals(fileName)) {
instance.injectTranslations(DEFAULT_LANG);
}
instance.injectTranslations(fileName);
@ -53,7 +50,7 @@ public class Lang {
public static String translateInsertVariables(String s, Object... args) {
String translation = translate(s);
for (int i = 1; i <= args.length; i++) {
translation = translation.replaceAll("%" + i + "\\$s", args[i-1].toString());
translation = translation.replaceAll("%" + i + "\\$s", args[i - 1].toString());
}
return translation;
}
@ -67,7 +64,8 @@ public class Lang {
}
public Map<String, String> getInternalLanguageMap(String fileName) {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("lang/" + fileName + ".lang");
InputStream stream =
this.getClass().getClassLoader().getResourceAsStream("lang/" + fileName + ".lang");
if (stream != null) {
return Lang.parseLang(stream);
}
@ -76,6 +74,7 @@ public class Lang {
/**
* Length of text excluding colour codes
*
* @param text
* @return
*/
@ -83,10 +82,9 @@ public class Lang {
int length = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if(c == '\u00A7') {
if (c == '\u00A7') {
i++;
}
else {
} else {
length++;
}
}
@ -94,7 +92,9 @@ public class Lang {
}
/**
* The default font is not monospaced, so this will likely be a little thinner to be on the safe side
* The default font is not monospaced, so this will likely be a little thinner to be on the safe
* side
*
* @param title
* @return
*/
@ -108,19 +108,27 @@ public class Lang {
private void injectTranslations(String fileName) {
try {
URL url = Lang.instance.getClass().getClassLoader().getResource("lang/" + fileName + ".lang");
URL url =
Lang.instance
.getClass()
.getClassLoader()
.getResource("lang/" + fileName + ".lang");
if (url != null) {
Map<String, String> initialMap = Lang.parseLang(url.openStream());
Lang.instance.languageMap.putAll(initialMap);
} else {
this.infoLogger.warning("Could not load " + fileName + ".lang from within Advanced Portals as it doesn't exist.");
this.infoLogger.warning(
"Could not load "
+ fileName
+ ".lang from within Advanced Portals as it doesn't exist.");
}
} catch (IOException e) {
e.printStackTrace();
this.infoLogger.warning("Could not load " + fileName + ".lang from within Advanced Portals.");
this.infoLogger.warning(
"Could not load " + fileName + ".lang from within Advanced Portals.");
}
Map<String, String> newLangMap = this.getLanguageMap(fileName );
Map<String, String> newLangMap = this.getLanguageMap(fileName);
Lang.instance.languageMap.putAll(newLangMap);
}

View File

@ -1,11 +1,9 @@
package com.sekwah.advancedportals.core.util;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.warphandler.Tag;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TagReader {
@ -43,10 +41,9 @@ public class TagReader {
if (arg.contains(":") && !inQuotes) {
if (currentIdentifier != null) {
ArrayList<String> tags;
if(tagMap.containsKey(currentIdentifier)) {
if (tagMap.containsKey(currentIdentifier)) {
tags = tagMap.get(currentIdentifier);
}
else {
} else {
tags = new ArrayList<>();
tagMap.put(currentIdentifier, tags);
}
@ -70,10 +67,9 @@ public class TagReader {
if (currentIdentifier != null) {
ArrayList<String> tags;
if(tagMap.containsKey(currentIdentifier)) {
if (tagMap.containsKey(currentIdentifier)) {
tags = tagMap.get(currentIdentifier);
}
else {
} else {
tags = new ArrayList<>();
tagMap.put(currentIdentifier, tags);
}
@ -89,13 +85,11 @@ public class TagReader {
return tags;
}
public static String getTag(String arg) {
int splitLoc = arg.indexOf(":");
if(splitLoc != -1) {
return arg.substring(0,splitLoc);
if (splitLoc != -1) {
return arg.substring(0, splitLoc);
}
return null;
}
}

View File

@ -1,6 +1,5 @@
package com.sekwah.advancedportals.core.warphandler;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
/**
@ -36,7 +35,8 @@ public class ActivationData {
}
/**
* In case you need to set the status back down a step for whatever reason. However it is not recommended.
* In case you need to set the status back down a step for whatever reason. However it is not
* recommended.
*
* @param warped
*/
@ -57,18 +57,11 @@ public class ActivationData {
}
public enum WarpedStatus {
/**
* Player has moved or something major has happened. (only one of these should activate)
*/
/** Player has moved or something major has happened. (only one of these should activate) */
WARPED,
/**
* Shows that the portal has been activated even if a major function is not performed.
*/
/** Shows that the portal has been activated even if a major function is not performed. */
ACTIVATED,
/**
* Nothing has activated on the portal (may need to come up with a new name)
*/
/** Nothing has activated on the portal (may need to come up with a new name) */
NOTACTIVATED;
}
}

View File

@ -3,18 +3,19 @@ package com.sekwah.advancedportals.core.warphandler;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.registry.TagTarget;
import javax.annotation.Nullable;
import java.util.List;
import javax.annotation.Nullable;
/**
* If a tag can be used for any of them then either make it cast the target or if it doesn't need a target
* then the exact same tag can be registered into both and ignore the portal info.
* If a tag can be used for any of them then either make it cast the target or if it doesn't need a
* target then the exact same tag can be registered into both and ignore the portal info.
*
* Will probably make better documentation on how to do so or some tutorial videos though take a look at the source code
* on GitHub for how the current tags are added.
* <p>Will probably make better documentation on how to do so or some tutorial videos though take a
* look at the source code on GitHub for how the current tags are added.
*
* Also, not sure if its good practice or not in java however these all extend TagHandler, so they can be accepted in 1
* method nicer than if they didn't
* <p>Also, not sure if its good practice or not in java however these all extend TagHandler, so
* they can be accepted in 1 method nicer than if they didn't
*
* @author sekwah41
*/
@ -23,8 +24,7 @@ public interface Tag {
/**
* By default, all tags should be able to use either.
*
* Though you may have use cases where you want to limit it to one or the other.
*
* <p>Though you may have use cases where you want to limit it to one or the other.
*/
enum TagType {
PORTAL,
@ -33,6 +33,7 @@ public interface Tag {
/**
* Used to flag where the auto complete should show more or less info.
*
* @return
*/
TagType[] getTagTypes();
@ -47,7 +48,8 @@ public interface Tag {
interface AutoComplete extends Tag {
/**
* This is used to get the auto complete for the tag. This is called when the player is typing the tag.
* This is used to get the auto complete for the tag. This is called when the player is
* typing the tag.
*
* @param argData
* @return
@ -68,12 +70,9 @@ public interface Tag {
*/
@Nullable
String splitString();
}
/**
* The events for portal creation and destroying
*/
/** The events for portal creation and destroying */
interface Creation extends Tag {
/**
@ -92,68 +91,69 @@ public interface Tag {
* @param argData
*/
void destroyed(TagTarget target, PlayerContainer player, String[] argData);
}
/**
* Order of activation
* Portal and Desti:
* preActivated
* activated
* postActivated
* Order of activation Portal and Desti: preActivated activated postActivated
*
* Order of them combined:
* Portal.preActivated
* Portal.activated - when desti tag is hit (if listed) then next two actions are activated
* - Desti.preActivate
* - Desti.activate
* Portal.postActivate - when desti tag is hit (if listed) then the next action is activated
* - Desti.postActivate
* <p>Order of them combined: Portal.preActivated Portal.activated - when desti tag is hit (if
* listed) then next two actions are activated - Desti.preActivate - Desti.activate
* Portal.postActivate - when desti tag is hit (if listed) then the next action is activated -
* Desti.postActivate
*/
interface Activation extends Tag {
/**
* Activates before the main part of activation. This should be for prechecks e.g. if the player has enough
* money before then taking the money in postActivated.
* Activates before the main part of activation. This should be for prechecks e.g. if the
* player has enough money before then taking the money in postActivated.
*
* @param player
* @param activeData
* @param argData
*
* @return If the tag has allowed the warp
*/
boolean preActivated(TagTarget target, PlayerContainer player, ActivationData activeData, String[] argData);
boolean preActivated(
TagTarget target,
PlayerContainer player,
ActivationData activeData,
String[] argData);
/**
* Activates after activation, should be used for actions such as removing money for a teleport.
* Activates after activation, should be used for actions such as removing money for a
* teleport.
*
* Any actions to do with player location should be done in activate
* <p>Any actions to do with player location should be done in activate
*
* @param player
* @param activationData
* @param argData
*/
void postActivated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData);
void postActivated(
TagTarget target,
PlayerContainer player,
ActivationData activationData,
String[] argData);
/**
* Activates if the portal is allowed from preActivating. Should be used to set the intended warp location
* Activates if the portal is allowed from preActivating. Should be used to set the intended
* warp location
*
* You should do some second checks if it can be dependent on the preActivate, the destination tags will also be
* triggered here if a desti is listed.
* <p>You should do some second checks if it can be dependent on the preActivate, the
* destination tags will also be triggered here if a desti is listed.
*
* @param player
* @param activationData
* @param argData
*
* @return Action performed (only return false if the tag failed to do anything)
*/
boolean activated(TagTarget target, PlayerContainer player, ActivationData activationData, String[] argData);
boolean activated(
TagTarget target,
PlayerContainer player,
ActivationData activationData,
String[] argData);
}
/**
* Triggers when a tag is added or removed from a portal or destination
*/
/** Triggers when a tag is added or removed from a portal or destination */
interface TagStatus extends Tag {
/**
@ -168,7 +168,8 @@ public interface Tag {
boolean tagAdded(TagTarget target, PlayerContainer player, int index, String argData);
/**
* If the user has access to remove the tag (this does not include being added on destruction)
* If the user has access to remove the tag (this does not include being added on
* destruction)
*
* @param target the target of the tag
* @param player if null then removed by the server or a plugin
@ -177,7 +178,5 @@ public interface Tag {
* @return if the tag will be removed.
*/
boolean tagRemoved(TagTarget target, PlayerContainer player, int index, String argData);
}
}

View File

@ -20,17 +20,16 @@ import org.bukkit.event.player.*;
import java.util.List;
/**
* Some of these will be passed to the core listener to handle the events, others it's easier to just check directly.
* Some of these will be passed to the core listener to handle the events, others it's easier to
* just check directly.
*/
public class Listeners implements Listener {
private CoreListeners coreListeners = AdvancedPortalsCore.getInstance().getCoreListeners();
@Inject
private PortalServices portalServices;
@Inject private PortalServices portalServices;
@Inject
private ConfigRepository configRepository;
@Inject private ConfigRepository configRepository;
// Entity and portal events
@EventHandler
@ -60,7 +59,10 @@ public class Listeners implements Listener {
@EventHandler
public void onItemInteract(PlayerInteractEvent event) {
if (!event.isCancelled() && (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK) && event.getItem() != null) {
if (!event.isCancelled()
&& (event.getAction() == Action.LEFT_CLICK_BLOCK
|| event.getAction() == Action.RIGHT_CLICK_BLOCK)
&& event.getItem() != null) {
Location blockloc = event.getClickedBlock().getLocation();
boolean allowEvent = this.coreListeners.playerInteractWithBlock(new SpigotPlayerContainer(event.getPlayer()),
event.getClickedBlock().getType().toString(),
@ -74,7 +76,9 @@ public class Listeners implements Listener {
@EventHandler(ignoreCancelled = true)
public void spawnMobEvent(CreatureSpawnEvent event) {
if(event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NETHER_PORTAL && portalServices.inPortalRegionProtected(ContainerHelpers.toPlayerLocation(event.getLocation()))) {
if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NETHER_PORTAL
&& portalServices.inPortalRegionProtected(
ContainerHelpers.toPlayerLocation(event.getLocation()))) {
event.setCancelled(true);
}
}
@ -83,18 +87,21 @@ public class Listeners implements Listener {
@EventHandler(priority = EventPriority.HIGH)
public void onBlockFromTo(BlockFromToEvent event) {
if(!configRepository.getStopWaterFlow()) {
if (!configRepository.getStopWaterFlow()) {
return;
}
if(!coreListeners.blockPlace(null,
ContainerHelpers.toBlockLocation(event.getBlock().getLocation()),
event.getBlock().getType().toString(),
null,
null) || !coreListeners.blockPlace(null,
ContainerHelpers.toBlockLocation(event.getToBlock().getLocation()),
event.getBlock().getType().toString(),
null,
null)) {
if (!coreListeners.blockPlace(
null,
ContainerHelpers.toBlockLocation(event.getBlock().getLocation()),
event.getBlock().getType().toString(),
null,
null)
|| !coreListeners.blockPlace(
null,
ContainerHelpers.toBlockLocation(event.getToBlock().getLocation()),
event.getBlock().getType().toString(),
null,
null)) {
event.setCancelled(true);
}
}
@ -102,24 +109,27 @@ public class Listeners implements Listener {
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBreak(BlockBreakEvent event) {
var itemInHand = event.getPlayer().getItemInHand();
if(!coreListeners.blockBreak(new SpigotPlayerContainer(event.getPlayer()),
if (!coreListeners.blockBreak(
new SpigotPlayerContainer(event.getPlayer()),
ContainerHelpers.toBlockLocation(event.getBlock().getLocation()),
event.getBlock().getType().toString(),
itemInHand == null ? null : itemInHand.getType().toString(),
itemInHand == null || itemInHand.getItemMeta() == null ? null : itemInHand.getItemMeta().getDisplayName())) {
itemInHand == null || itemInHand.getItemMeta() == null
? null
: itemInHand.getItemMeta().getDisplayName())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onExplosion(EntityExplodeEvent event) {
if(!configRepository.getPortalProtection()) return;
if (!configRepository.getPortalProtection()) return;
List<Block> blockList = event.blockList();
for (int i = 0; i < blockList.size(); i++) {
Block block = blockList.get(i);
if (portalServices.inPortalRegionProtected(ContainerHelpers.toBlockLocation(block.getLocation()))) {
if (portalServices.inPortalRegionProtected(
ContainerHelpers.toBlockLocation(block.getLocation()))) {
blockList.remove(i);
i--;
}

View File

@ -26,6 +26,4 @@ public class SpigotInfoLogger extends InfoLogger {
public void error(Exception e) {
plugin.getLogger().log(Level.SEVERE, e.getMessage(), e);
}
}

View File

@ -3,8 +3,6 @@ package com.sekwah.advancedportals.spigot.commands.subcommands.portal;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.commands.SubCommand;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import com.sekwah.advancedportals.core.destination.Destination;
import com.sekwah.advancedportals.core.portal.AdvancedPortal;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.DataTag;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
@ -13,92 +11,109 @@ import com.sekwah.advancedportals.core.services.PortalServices;
import com.sekwah.advancedportals.core.util.Lang;
import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.spigot.commands.subcommands.portal.update.ConfigAccessor;
import org.bukkit.configuration.ConfigurationSection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class UpdatePortalSubCommand implements SubCommand {
@Inject
PortalServices portalServices;
@Inject PortalServices portalServices;
@Inject
DestinationServices destinationServices;
@Inject DestinationServices destinationServices;
@Inject
PortalServices portalService;
@Inject PortalServices portalService;
@Override
public void onCommand(CommandSenderContainer sender, String[] args) {
if(args.length > 1 && "confirm".equals(args[1])) {
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translateInsertVariables("command.portal.update.confirm"));
if (args.length > 1 && "confirm".equals(args[1])) {
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translateInsertVariables("command.portal.update.confirm"));
int destinations = importDestinations();
int portals = importPortals();
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translateInsertVariables("command.portal.update.complete", portals, destinations));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translateInsertVariables(
"command.portal.update.complete", portals, destinations));
return;
}
sender.sendMessage(Lang.translate("messageprefix.positive") + Lang.translateInsertVariables("command.portal.update", getPortalCount(), getDestinationCount()));
sender.sendMessage(
Lang.translate("messageprefix.positive")
+ Lang.translateInsertVariables(
"command.portal.update", getPortalCount(), getDestinationCount()));
}
private int importPortals() {
ConfigAccessor portalConfig = new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "portals.yaml");
ConfigAccessor portalConfig =
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "portals.yaml");
var config = portalConfig.getConfig();
Set<String> portalSet = config.getKeys(false);
int count = 0;
for(String portalName : portalSet) {
BlockLocation pos1 = new BlockLocation(config.getString(portalName + ".world"),
config.getInt(portalName + ".pos1.X"),
config.getInt(portalName + ".pos1.Y"),
config.getInt(portalName + ".pos1.Z"));
BlockLocation pos2 = new BlockLocation(config.getString(portalName + ".world"),
config.getInt(portalName + ".pos2.X"),
config.getInt(portalName + ".pos2.Y"),
config.getInt(portalName + ".pos2.Z"));
for (String portalName : portalSet) {
BlockLocation pos1 =
new BlockLocation(
config.getString(portalName + ".world"),
config.getInt(portalName + ".pos1.X"),
config.getInt(portalName + ".pos1.Y"),
config.getInt(portalName + ".pos1.Z"));
BlockLocation pos2 =
new BlockLocation(
config.getString(portalName + ".world"),
config.getInt(portalName + ".pos2.X"),
config.getInt(portalName + ".pos2.Y"),
config.getInt(portalName + ".pos2.Z"));
List<DataTag> args = new ArrayList<>();
args.add(new DataTag("name", portalName));
var triggerblock = config.getString(portalName + ".triggerblock");
if(triggerblock != null) args.add(new DataTag("triggerblock", triggerblock.split(",")));
if (triggerblock != null)
args.add(new DataTag("triggerblock", triggerblock.split(",")));
// It's called bungee as that's the implementation behind it
var bungee = config.getString(portalName + ".bungee");
if(bungee != null) args.add(new DataTag("bungee", bungee.split(",")));
if (bungee != null) args.add(new DataTag("bungee", bungee.split(",")));
var destination = config.getString(portalName + ".destination");
if(destination != null) args.add(new DataTag("destination", destination.split(",")));
if (destination != null) args.add(new DataTag("destination", destination.split(",")));
ConfigurationSection portalConfigSection = config.getConfigurationSection(portalName);
ConfigurationSection portalArgsConf = portalConfigSection.getConfigurationSection("portalArgs");
ConfigurationSection portalArgsConf =
portalConfigSection.getConfigurationSection("portalArgs");
if (portalArgsConf != null) {
Set<String> argsSet = portalArgsConf.getKeys(true);
for (Object argName : argsSet.toArray()) {
// skip if it argName starts with command.
if (portalArgsConf.isString(argName.toString())) {
args.add(new DataTag(argName.toString(), portalArgsConf.getString(argName.toString())));
args.add(
new DataTag(
argName.toString(),
portalArgsConf.getString(argName.toString())));
}
}
}
// Check if command.1 is set
List<String> commands = new ArrayList<>();
if(getArg(args, "command.1") != null) {
if (getArg(args, "command.1") != null) {
int i = 1;
while(getArg(args, "command." + i) != null) {
while (getArg(args, "command." + i) != null) {
commands.add(getArg(args, "command." + i));
i++;
}
}
if(!commands.isEmpty()) {
if (!commands.isEmpty()) {
args.add(new DataTag("commands", commands.toArray(new String[0])));
}
args.stream().filter(dataTag -> dataTag.NAME.startsWith("command.")).toList().forEach(args::remove);
args.stream()
.filter(dataTag -> dataTag.NAME.startsWith("command."))
.toList()
.forEach(args::remove);
var portal = portalService.createPortal(pos1, pos2, args);
if(portal != null) count++;
if (portal != null) count++;
}
return count;
@ -114,26 +129,32 @@ public class UpdatePortalSubCommand implements SubCommand {
}
public int importDestinations() {
ConfigAccessor destiConfig = new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "destinations.yaml");
ConfigAccessor destiConfig =
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "destinations.yaml");
var config = destiConfig.getConfig();
Set<String> destiSet = config.getKeys(false);
int count = 0;
for(String destiName : destiSet) {
for (String destiName : destiSet) {
var destiPos = destiName + ".pos";
var desti = destinationServices.createDesti(new PlayerLocation(config.getString(destiName + ".world"),
config.getDouble(destiPos + ".X"),
config.getDouble(destiPos + ".Y"),
config.getDouble(destiPos + ".Z"),
(float) config.getDouble(destiPos + ".yaw"),
(float) config.getDouble(destiPos + ".pitch")), List.of(new DataTag("name", destiName)));
if(desti != null) count++;
var desti =
destinationServices.createDesti(
new PlayerLocation(
config.getString(destiName + ".world"),
config.getDouble(destiPos + ".X"),
config.getDouble(destiPos + ".Y"),
config.getDouble(destiPos + ".Z"),
(float) config.getDouble(destiPos + ".yaw"),
(float) config.getDouble(destiPos + ".pitch")),
List.of(new DataTag("name", destiName)));
if (desti != null) count++;
}
return count;
}
public int getDestinationCount() {
ConfigAccessor destiConfig = new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "destinations.yaml");
ConfigAccessor destiConfig =
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "destinations.yaml");
var config = destiConfig.getConfig();
Set<String> destiSet = config.getKeys(false);
@ -141,7 +162,8 @@ public class UpdatePortalSubCommand implements SubCommand {
}
public int getPortalCount() {
ConfigAccessor portalConfig = new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "portals.yaml");
ConfigAccessor portalConfig =
new ConfigAccessor(AdvancedPortalsPlugin.getInstance(), "portals.yaml");
var config = portalConfig.getConfig();
Set<String> portalSet = config.getKeys(false);

View File

@ -25,8 +25,7 @@ public class ConfigAccessor {
public void reloadConfig() {
if (configFile == null) {
File dataFolder = plugin.getDataFolder();
if (dataFolder == null)
throw new IllegalStateException();
if (dataFolder == null) throw new IllegalStateException();
configFile = new File(dataFolder, fileName);
}
fileConfiguration = YamlConfiguration.loadConfiguration(configFile);
@ -55,11 +54,8 @@ public class ConfigAccessor {
// Saves
/**
* public void saveDefaultConfig() {
* if (!configFile.exists()) {
* this.plugin.saveResource(fileName, false);
* }
* }
* public void saveDefaultConfig() { if (!configFile.exists()) {
* this.plugin.saveResource(fileName, false); } }
*/
// New save default config saving code, it checks if the needed config is in the jar file before
@ -72,5 +68,4 @@ public class ConfigAccessor {
plugin.saveResource(fileName, false);
}
}
}

View File

@ -2,6 +2,7 @@ package com.sekwah.advancedportals.spigot.connector.command;
import com.sekwah.advancedportals.core.commands.CommandTemplate;
import com.sekwah.advancedportals.spigot.connector.container.SpigotCommandSenderContainer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@ -18,13 +19,17 @@ public class SpigotCommandHandler implements CommandExecutor, TabCompleter {
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) {
this.commandExecutor.onCommand(new SpigotCommandSenderContainer(commandSender), command.getName(), args);
public boolean onCommand(
CommandSender commandSender, Command command, String s, String[] args) {
this.commandExecutor.onCommand(
new SpigotCommandSenderContainer(commandSender), command.getName(), args);
return true;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
return this.commandExecutor.onTabComplete(new SpigotCommandSenderContainer(commandSender), args);
public List<String> onTabComplete(
CommandSender commandSender, Command command, String s, String[] args) {
return this.commandExecutor.onTabComplete(
new SpigotCommandSenderContainer(commandSender), args);
}
}

View File

@ -4,9 +4,7 @@ import com.sekwah.advancedportals.core.commands.CommandTemplate;
import com.sekwah.advancedportals.core.connector.commands.CommandRegister;
import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin;
/**
* Register the CommandTemplate files to the appropriate system
*/
/** Register the CommandTemplate files to the appropriate system */
public class SpigotCommandRegister implements CommandRegister {
private final AdvancedPortalsPlugin plugin;
@ -17,6 +15,7 @@ public class SpigotCommandRegister implements CommandRegister {
/**
* Registers the command to the appropriate system
*
* @param commandName
* @param commandExecutor
*/

View File

@ -1,6 +1,7 @@
package com.sekwah.advancedportals.spigot.connector.container;
import com.sekwah.advancedportals.core.connector.containers.CommandSenderContainer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

View File

@ -7,17 +7,15 @@ import com.sekwah.advancedportals.core.connector.containers.WorldContainer;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.core.serializeddata.Vector;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
/**
* Just a temporary container for whenever advanced portals needs to get data from a player
*/
/** Just a temporary container for whenever advanced portals needs to get data from a player */
public class SpigotEntityContainer implements EntityContainer {
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
private final Entity entity;
@ -28,13 +26,20 @@ public class SpigotEntityContainer implements EntityContainer {
@Override
public PlayerLocation getLoc() {
Location loc = this.entity.getLocation();
return new PlayerLocation(loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch());
return new PlayerLocation(
loc.getWorld().getName(),
loc.getX(),
loc.getY(),
loc.getZ(),
loc.getYaw(),
loc.getPitch());
}
@Override
public BlockLocation getBlockLoc() {
Location loc = this.entity.getLocation();
return new BlockLocation(loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
return new BlockLocation(
loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
@Override
@ -44,7 +49,12 @@ public class SpigotEntityContainer implements EntityContainer {
@Override
public boolean teleport(PlayerLocation location) {
return this.entity.teleport(new Location(Bukkit.getWorld(location.getWorldName()), location.getPosX(), location.getPosY(), location.getPosZ()));
return this.entity.teleport(
new Location(
Bukkit.getWorld(location.getWorldName()),
location.getPosX(),
location.getPosY(),
location.getPosZ()));
}
@Override
@ -64,6 +74,7 @@ public class SpigotEntityContainer implements EntityContainer {
@Override
public void setVelocity(Vector vector) {
this.entity.setVelocity(new org.bukkit.util.Vector(vector.getX(), vector.getY(), vector.getZ()));
this.entity.setVelocity(
new org.bukkit.util.Vector(vector.getX(), vector.getY(), vector.getZ()));
}
}

View File

@ -3,11 +3,11 @@ package com.sekwah.advancedportals.spigot.connector.container;
import com.google.inject.Inject;
import com.sekwah.advancedportals.core.AdvancedPortalsCore;
import com.sekwah.advancedportals.core.connector.containers.PlayerContainer;
import com.sekwah.advancedportals.core.connector.containers.WorldContainer;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import com.sekwah.advancedportals.spigot.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.spigot.reflection.MinecraftCustomPayload;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
@ -18,13 +18,10 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.Arrays;
import java.util.UUID;
/**
* Just a temporary container for whenever advanced portals needs to get data from a player
*/
/** Just a temporary container for whenever advanced portals needs to get data from a player */
public class SpigotPlayerContainer extends SpigotEntityContainer implements PlayerContainer {
@Inject
private AdvancedPortalsCore portalsCore;
@Inject private AdvancedPortalsCore portalsCore;
private final Player player;
@ -50,7 +47,12 @@ public class SpigotPlayerContainer extends SpigotEntityContainer implements Play
@Override
public boolean teleport(PlayerLocation location) {
return this.player.teleport(new Location(Bukkit.getWorld(location.getWorldName()), location.getPosX(), location.getPosY(), location.getPosZ()));
return this.player.teleport(
new Location(
Bukkit.getWorld(location.getWorldName()),
location.getPosX(),
location.getPosY(),
location.getPosZ()));
}
@Override
@ -63,20 +65,17 @@ public class SpigotPlayerContainer extends SpigotEntityContainer implements Play
* @param material
*/
@Override
public void sendFakeBlock(BlockLocation blockPos, String material) {
}
public void sendFakeBlock(BlockLocation blockPos, String material) {}
/**
* Only 1.12 and below supported
*
* @param blockPos
* @param material
* @param data
*/
@Override
public void sendFakeBlockWithData(BlockLocation blockPos, String material, byte data) {
}
public void sendFakeBlockWithData(BlockLocation blockPos, String material, byte data) {}
@Override
public void giveItem(String material, String itemName, String... itemDescription) {
@ -90,7 +89,7 @@ public class SpigotPlayerContainer extends SpigotEntityContainer implements Play
@Override
public boolean sendPacket(String channel, byte[] bytes) {
if(channel.startsWith("minecraft:")) {
if (channel.startsWith("minecraft:")) {
return MinecraftCustomPayload.sendCustomPayload(player, channel, bytes);
} else {
player.sendPluginMessage(AdvancedPortalsPlugin.getInstance(), channel, bytes);

View File

@ -3,6 +3,7 @@ package com.sekwah.advancedportals.spigot.metrics;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
@ -10,7 +11,6 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -21,24 +21,39 @@ import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.HttpsURLConnection;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*
* <p>Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
if (System.getProperty("bstats.relocatecheck") == null
|| !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little
// "trick" ... :D
final String defaultPackage =
new String(
new byte[] {
'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u',
'k', 'k', 'i', 't'
});
final String examplePackage =
new String(
new byte[] {
'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'
});
// We want to make sure nobody just copy & pastes the example and use the wrong package
// names
if (Metrics.class.getPackage().getName().equals(defaultPackage)
|| Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException(
"bStats Metrics class has not been relocated correctly!");
}
}
}
@ -101,15 +116,18 @@ public class Metrics {
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
config.options()
.header(
"bStats collects some data for plugin authors like how many servers are"
+ " using their plugins.\n"
+ "To honor their work, you should not disable it.\n"
+ "This has nearly no effect on the server performance!\n"
+ "Check out https://bStats.org/ to learn more :)")
.copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
} catch (IOException ignored) {
}
}
// Load the data
@ -127,10 +145,12 @@ public class Metrics {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
} catch (NoSuchFieldException ignored) {
}
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
Bukkit.getServicesManager()
.register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
@ -159,31 +179,37 @@ public class Metrics {
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
/** Starts the Scheduler which submits our data every 30 minutes. */
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
final Timer timer =
new Timer(
true); // We use a timer cause the Bukkit scheduler is affected by server
// lags
timer.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we
// have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only
// the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
},
1000 * 60 * 5,
1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough
// time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
* Gets the plugin specific data. This method is called using Reflection.
*
* @return The plugin specific data.
*/
@ -219,13 +245,19 @@ public class Metrics {
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
// This fixes java.lang.NoSuchMethodError:
// org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod =
Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount =
onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer()))
.size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
playerAmount =
Bukkit.getOnlinePlayers()
.size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
@ -256,9 +288,7 @@ public class Metrics {
return data;
}
/**
* Collects the data and sends it afterwards.
*/
/** Collects the data and sends it afterwards. */
private void submitData() {
final JsonObject data = getServerData();
@ -268,51 +298,75 @@ public class Metrics {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
for (RegisteredServiceProvider<?> provider :
Bukkit.getServicesManager().getRegistrations(service)) {
try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
Object plugin =
provider.getService()
.getMethod("getPluginData")
.invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
Class<?> jsonObjectJsonSimple =
Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
Method jsonStringGetter =
jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
JsonObject object =
new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
this.plugin
.getLogger()
.log(
Level.SEVERE,
"Encountered unexpected exception",
e);
}
continue; // continue looping since we cannot do any other thing.
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
} catch (NullPointerException
| NoSuchMethodException
| IllegalAccessException
| InvocationTargetException ignored) {
}
}
} catch (NoSuchFieldException ignored) { }
} catch (NoSuchFieldException ignored) {
}
}
data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
new Thread(
new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger()
.log(
Level.WARNING,
"Could not submit plugin stats of "
+ plugin.getName(),
e);
}
}
}
})
.start();
}
/**
@ -327,7 +381,8 @@ public class Metrics {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
throw new IllegalAccessException(
"This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data.toString());
@ -343,7 +398,8 @@ public class Metrics {
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty(
"Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
@ -363,7 +419,8 @@ public class Metrics {
}
bufferedReader.close();
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
plugin.getLogger()
.info("Sent data to bStats and received response: " + builder.toString());
}
}
@ -385,10 +442,8 @@ public class Metrics {
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
/** Represents a custom chart. */
public abstract static class CustomChart {
// The id of the chart
final String chartId;
@ -417,7 +472,11 @@ public class Metrics {
chart.add("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
Bukkit.getLogger()
.log(
Level.WARNING,
"Failed to get data for custom chart with id " + chartId,
t);
}
return null;
}
@ -425,12 +484,9 @@ public class Metrics {
}
protected abstract JsonObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
/** Represents a custom simple pie. */
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
@ -459,9 +515,7 @@ public class Metrics {
}
}
/**
* Represents a custom advanced pie.
*/
/** Represents a custom advanced pie. */
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
@ -503,9 +557,7 @@ public class Metrics {
}
}
/**
* Represents a custom drilldown pie.
*/
/** Represents a custom drilldown pie. */
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
@ -534,7 +586,8 @@ public class Metrics {
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObject value = new JsonObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
for (Map.Entry<String, Integer> valueEntry :
map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
@ -552,9 +605,7 @@ public class Metrics {
}
}
/**
* Represents a custom single line chart.
*/
/** Represents a custom single line chart. */
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
@ -581,12 +632,9 @@ public class Metrics {
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
/** Represents a custom multi line chart. */
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
@ -626,12 +674,9 @@ public class Metrics {
data.add("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
/** Represents a custom simple bar chart. */
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
@ -664,12 +709,9 @@ public class Metrics {
data.add("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
/** Represents a custom advanced bar chart. */
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
@ -714,5 +756,4 @@ public class Metrics {
return data;
}
}
}

View File

@ -8,8 +8,8 @@ import java.lang.reflect.Method;
/**
* Just a util class to force spigot to allow us to have fun with the minecraft: channel category
*
* Atm at least this is just designed to be able to access debug/ for showing visuals of the portals and such
*
* <p>Atm at least this is just designed to be able to access debug/ for showing visuals of the
* portals and such
*/
public class MinecraftCustomPayload {
@ -23,7 +23,10 @@ public class MinecraftCustomPayload {
Object minecraftKey = minecraftKeyConstructor.newInstance(channel);
// Access the sendCustomPayload method in the CraftPlayer class
Method sendCustomPayloadMethod = player.getClass().getDeclaredMethod("sendCustomPayload", minecraftKeyClass, byte[].class);
Method sendCustomPayloadMethod =
player.getClass()
.getDeclaredMethod(
"sendCustomPayload", minecraftKeyClass, byte[].class);
// Make the private method accessible
sendCustomPayloadMethod.setAccessible(true);

View File

@ -2,17 +2,23 @@ package com.sekwah.advancedportals.spigot.utils;
import com.sekwah.advancedportals.core.serializeddata.BlockLocation;
import com.sekwah.advancedportals.core.serializeddata.PlayerLocation;
import org.bukkit.Location;
public class ContainerHelpers {
public static PlayerLocation toPlayerLocation(Location loc) {
return new PlayerLocation(loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch());
return new PlayerLocation(
loc.getWorld().getName(),
loc.getX(),
loc.getY(),
loc.getZ(),
loc.getYaw(),
loc.getPitch());
}
public static BlockLocation toBlockLocation(Location loc) {
return new BlockLocation(loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
return new BlockLocation(
loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
}

View File

@ -1,17 +1,14 @@
package com.sekwah.advancedportals.spigot.warpeffects;
import com.sekwah.advancedportals.core.effect.WarpEffect;
import com.sekwah.advancedportals.core.registry.WarpEffectRegistry;
import javax.inject.Inject;
public class SpigotWarpEffects {
@Inject
private WarpEffectRegistry warpEffectRegistry;
@Inject private WarpEffectRegistry warpEffectRegistry;
public void registerEffects() {
warpEffectRegistry.registerEffect("ender", new EnderWarpEffect());
}
}