AsminWirelessRedstone 1.0.0: wireless transmitters/receivers for Paper 1.20.4
Build Plugin / build-and-release (push) Failing after 1m58s
Build Plugin / build-and-release (push) Failing after 1m58s
This commit is contained in:
commit
f7fae9df31
27 files changed
+2514
No files matched your search
@@ -0,0 +1,117 @@
|
||||
name: Build Plugin
|
||||
run-name: Build AsminWirelessRedstone
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: asmin-wireless-redstone-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: docker-builder
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Java 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
|
||||
- name: Calculate next version
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
latest="$(git tag --list 'v[0-9]*' --sort=-version:refname | head -n 1)"
|
||||
if [[ -z "$latest" ]]; then
|
||||
version="1.0.0"
|
||||
else
|
||||
current="${latest#v}"
|
||||
IFS='.' read -r major minor patch <<< "$current"
|
||||
if (( patch >= 9 )); then
|
||||
version="$major.$((minor + 1)).0"
|
||||
else
|
||||
version="$major.$minor.$((patch + 1))"
|
||||
fi
|
||||
fi
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build plugin
|
||||
run: mvn --batch-mode clean verify -Drevision=${{ steps.version.outputs.version }}
|
||||
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
latest="$(git tag --list 'v[0-9]*' --sort=-version:refname | head -n 1 || true)"
|
||||
if [[ -n "$latest" ]]; then
|
||||
changes="$(git log --no-merges --pretty=format:'- %s' "$latest..HEAD")"
|
||||
else
|
||||
changes="$(git log --no-merges --pretty=format:'- %s' -n 10)"
|
||||
fi
|
||||
if [[ -z "$changes" ]]; then
|
||||
changes="$(awk '/^## \[/{if(seen) exit; seen=1; next} seen && NF {print}' CHANGELOG.md | head -n 12)"
|
||||
fi
|
||||
{
|
||||
echo "Prosty plugin do bezprzewodowego sterowania blokami redstone."
|
||||
echo
|
||||
echo "Zmiany w wersji ${VERSION}:"
|
||||
printf '%s\n' "$changes"
|
||||
echo
|
||||
echo "Kompatybilność: Minecraft 1.20.4, Paper/Purpur."
|
||||
echo "Wymagana Java 17."
|
||||
} > release-body.md
|
||||
|
||||
- name: Create Gitea release and upload plugin
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -z "$GITEA_TOKEN" ]]; then
|
||||
echo "Dodaj token z prawem zapisu do repo jako sekret GITEA_TOKEN."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
jar="AsminWirelessRedstone.jar"
|
||||
test -f "target/$jar"
|
||||
api="$GITEA_SERVER_URL/api/v1/repos/$GITEA_REPOSITORY"
|
||||
|
||||
python3 - "$VERSION" "$TAG" <<'PY' > release.json
|
||||
import json, sys
|
||||
version, tag = sys.argv[1], sys.argv[2]
|
||||
with open("release-body.md", encoding="utf-8") as handle:
|
||||
body = handle.read()
|
||||
print(json.dumps({
|
||||
"tag_name": tag,
|
||||
"name": f"AsminWirelessRedstone {version}",
|
||||
"body": body,
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
}, ensure_ascii=False))
|
||||
PY
|
||||
|
||||
release="$(curl --fail-with-body -sS -X POST "$api/releases" \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data-binary @release.json)"
|
||||
|
||||
release_id="$(python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])' <<< "$release")"
|
||||
curl --fail-with-body -sS -X POST "$api/releases/$release_id/assets?name=$jar" \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-F "attachment=@target/$jar;filename=$jar"
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
target/
|
||||
.idea/
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
.DS_Store
|
||||
*.log
|
||||
|
||||
# Materiały źródłowe dostarczone do analizy
|
||||
_src/
|
||||
Wireless-Redstone-1.5.0.jar
|
||||
Wireless-Redstone-Plugin-main.zip
|
||||
@@ -0,0 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## [1.0.0]
|
||||
|
||||
- Przeniesienie pluginu na Minecraft 1.20.4, Paper/Purpur i Java 17 (zamiast 1.21/Java 21).
|
||||
- Nowy system nadajników: dźwignie, przyciski, płyty naciskowe, blok redstone i haki linki.
|
||||
- Nowy system odbiorników: lampy redstone, proszek redstone z rzeczywistym poziomem sygnału, szyny, drzwi, klapy i bramy.
|
||||
- Synchronizacja oparta na zdarzeniach Bukkit bez cyklicznego skanowania bloków i bez okresowego zadania synchronizującego.
|
||||
- Zasilanie sąsiednich elementów redstone przez bezprzewodowy proszek redstone.
|
||||
- Grupy z własnymi nazwami, kategorią `Kategoria/Nazwa`, właścicielem i connector tool do dodawania/usuwania bloków.
|
||||
- Bezpieczny zapis grup do `groups.yml` z kopią zapasową i odtwarzanie stanu przy ładowaniu chunków.
|
||||
- Czyszczenie nieaktualnych lokalizacji przy niszczeniu, wybuchach, przepływie cieczy i ruchu tłoków.
|
||||
- Testy jednostkowe modelu oraz workflow Gitea Actions budujący i publikujący release.
|
||||
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Wireless Redstone Contributors
|
||||
Modifications Copyright (c) 2026 Asmin_
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,57 @@
|
||||
# AsminWirelessRedstone
|
||||
|
||||
Prosty plugin do Minecrafta umożliwiający bezprzewodowe sterowanie blokami redstone. Pozwala łączyć nadajniki, takie jak dźwignie, przyciski i płyty naciskowe, z odbiornikami, takimi jak lampy i proszek redstone. Wszystko działa bez fizycznego połączenia redstone i bez ograniczenia odległości.
|
||||
|
||||
Plugin obsługuje grupy urządzeń, zapisuje ich konfigurację i przywraca ją po restarcie serwera.
|
||||
|
||||
## Wymagania
|
||||
|
||||
- Minecraft Java Edition 1.20.4.
|
||||
- Paper lub Purpur 1.20.4.
|
||||
- Java 17.
|
||||
- Brak dodatkowych zależności.
|
||||
|
||||
## Kompatybilność
|
||||
|
||||
Plugin jest zbudowany przeciwko API Paper 1.20.4 (`api-version: 1.20`) i działa na Paperze oraz Purpurze w wersji 1.20.4 bez dodatkowych modyfikacji. Nie używa API dostępnego dopiero w 1.21+.
|
||||
|
||||
## Korzystanie
|
||||
|
||||
1. Umieść `AsminWirelessRedstone.jar` w folderze `plugins/` serwera i zrestartuj serwer.
|
||||
2. Nadaj uprawnienie `asminwireless.use` graczom, którzy mają tworzyć grupy. Domyślnie mają je operatorzy.
|
||||
3. Użyj `/wireless create <nazwa>` — otrzymasz `Wireless Connector`.
|
||||
4. Prawym przyciskiem myszy klikaj bloki, które mają należeć do grupy:
|
||||
- nadajniki: dźwignia, przyciski, płyty naciskowe, blok redstone, haki linki,
|
||||
- odbiorniki: lampa redstone, proszek redstone, szyny zasilane/aktywujące/detekcyjne, drzwi, klapy i bramy.
|
||||
5. Lewym przyciskiem myszy z connectora usuń blok z grupy. Zmiana stanu nadajnika natychmiast aktualizuje odbiorniki w grupie. Proszek redstone otrzymuje rzeczywisty poziom sygnału i zasila kolejne elementy redstone w standardowy sposób.
|
||||
|
||||
Jeden nadajnik może sterować wieloma odbiornikami. Nie ma limitu odległości. Domyślny limit to 256 bloków na grupę i można go zmienić w `config.yml`. Dane grup są zapisywane w `plugins/AsminWirelessRedstone/groups.yml` (z kopią zapasową `.bak`).
|
||||
|
||||
## Komendy
|
||||
|
||||
- `/wireless create <nazwa>` — daje connector tworzący nową grupę przy pierwszym kliknięciu.
|
||||
- `/wireless tool <grupa>` — daje connector do istniejącej grupy.
|
||||
- `/wireless list [--all]` — lista grup (`--all` dla administratora).
|
||||
- `/wireless info <grupa>` — szczegóły grupy.
|
||||
- `/wireless rename <grupa> <nowa-nazwa>` (alias: `/wireless modify name ...`) — zmiana nazwy.
|
||||
- `/wireless delete <grupa>` — usunięcie grupy.
|
||||
- `/wireless reload` — przeładowanie konfiguracji i danych.
|
||||
- `/wireless cleanup` — usunięcie nieaktualnych lokalizacji w załadowanych chunkach.
|
||||
- `/wireless help` — pomoc.
|
||||
|
||||
Aliasy komendy: `/wr`, `/awr`. Nazwy mogą mieć formę `Kategoria/Nazwa` (bez spacji).
|
||||
|
||||
## Uprawnienia
|
||||
|
||||
- `asminwireless.use` — tworzenie grup i obsługa własnych grup (domyślnie: op).
|
||||
- `asminwireless.admin` — zarządzanie wszystkimi grupami, `reload` i `cleanup` (domyślnie: op).
|
||||
|
||||
## Podziękowania
|
||||
|
||||
Bazuje na kodzie projektu Wireless Redstone Cobbleworks / Wireless Redstone Contributors (licencja MIT). Zachowano ich autorstwo w `LICENSE`.
|
||||
|
||||
Plugin zrobiłem dla siebie. Nie wiem, czy jest stabilny, więc używasz go na własną odpowiedzialność. Jeśli chcesz go przetestować, z chęcią przyjmę uwagi na adresie [hello@asmin.me](mailto:hello@asmin.me).
|
||||
|
||||
Możesz edytować kod. Jeśli opublikujesz własną wersję, dodaj moje autorstwo w creditsach.
|
||||
|
||||
**Autor:** [Asmin_](https://asmin.me)
|
||||
@@ -0,0 +1,80 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>me.asmin</groupId>
|
||||
<artifactId>AsminWirelessRedstone</artifactId>
|
||||
<version>${revision}</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>AsminWirelessRedstone</name>
|
||||
<description>Wireless redstone groups for Paper/Purpur 1.20.4</description>
|
||||
|
||||
<properties>
|
||||
<revision>1.0.0</revision>
|
||||
<java.version>17</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<paper.version>1.20.4-R0.1-SNAPSHOT</paper.version>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>${paper.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>AsminWirelessRedstone</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>${java.version}</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.2.5</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>me.asmin.wirelessredstone.AsminWirelessRedstone</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,86 @@
|
||||
package me.asmin.wirelessredstone;
|
||||
|
||||
import me.asmin.wirelessredstone.command.WirelessCommand;
|
||||
import me.asmin.wirelessredstone.listener.BlockLifecycleListener;
|
||||
import me.asmin.wirelessredstone.listener.ConnectorToolListener;
|
||||
import me.asmin.wirelessredstone.listener.RedstoneListener;
|
||||
import me.asmin.wirelessredstone.manager.GroupManager;
|
||||
import me.asmin.wirelessredstone.tool.ConnectorTool;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
public final class AsminWirelessRedstone extends JavaPlugin {
|
||||
|
||||
private GroupManager groupManager;
|
||||
private ConnectorTool connectorTool;
|
||||
private BukkitTask saveTask;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
saveDefaultConfig();
|
||||
|
||||
groupManager = new GroupManager(this);
|
||||
groupManager.load();
|
||||
connectorTool = new ConnectorTool(this);
|
||||
|
||||
registerCommand();
|
||||
getServer().getPluginManager().registerEvents(new RedstoneListener(this, groupManager), this);
|
||||
getServer().getPluginManager().registerEvents(new BlockLifecycleListener(this, groupManager), this);
|
||||
getServer().getPluginManager().registerEvents(new ConnectorToolListener(this, groupManager, connectorTool), this);
|
||||
|
||||
// Apply persisted group state to already loaded chunks. ChunkLoadEvent
|
||||
// handles everything that is loaded later.
|
||||
getServer().getScheduler().runTask(this, groupManager::refreshAllLoaded);
|
||||
getLogger().info("AsminWirelessRedstone enabled (Paper/Purpur 1.20.4).");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (saveTask != null) {
|
||||
saveTask.cancel();
|
||||
saveTask = null;
|
||||
}
|
||||
if (groupManager != null) {
|
||||
groupManager.saveNow();
|
||||
}
|
||||
getLogger().info("AsminWirelessRedstone disabled.");
|
||||
}
|
||||
|
||||
public void scheduleSave() {
|
||||
if (saveTask != null && !saveTask.isCancelled()) return;
|
||||
long delay = Math.max(1L, getConfig().getLong("save-debounce-ticks", 40L));
|
||||
saveTask = getServer().getScheduler().runTaskLater(this, () -> {
|
||||
saveTask = null;
|
||||
if (groupManager != null) groupManager.saveNow();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
public void reloadPluginData() {
|
||||
reloadConfig();
|
||||
groupManager.reload();
|
||||
}
|
||||
|
||||
private void registerCommand() {
|
||||
PluginCommand command = getCommand("wireless");
|
||||
if (command == null) {
|
||||
getLogger().severe("Command 'wireless' is missing from plugin.yml.");
|
||||
return;
|
||||
}
|
||||
WirelessCommand executor = new WirelessCommand(this, groupManager);
|
||||
command.setExecutor(executor);
|
||||
command.setTabCompleter(executor);
|
||||
}
|
||||
|
||||
public GroupManager getGroupManager() {
|
||||
return groupManager;
|
||||
}
|
||||
|
||||
public ConnectorTool getConnectorTool() {
|
||||
return connectorTool;
|
||||
}
|
||||
|
||||
public boolean actionBarFeedback() {
|
||||
return getConfig().getBoolean("action-bar-feedback", true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package me.asmin.wirelessredstone.command;
|
||||
|
||||
import me.asmin.wirelessredstone.AsminWirelessRedstone;
|
||||
import me.asmin.wirelessredstone.manager.GroupManager;
|
||||
import me.asmin.wirelessredstone.model.GroupName;
|
||||
import me.asmin.wirelessredstone.model.WirelessGroup;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class WirelessCommand implements CommandExecutor, TabCompleter {
|
||||
|
||||
private static final String USE = "asminwireless.use";
|
||||
private static final String ADMIN = "asminwireless.admin";
|
||||
|
||||
private final AsminWirelessRedstone plugin;
|
||||
private final GroupManager groups;
|
||||
|
||||
public WirelessCommand(AsminWirelessRedstone plugin, GroupManager groups) {
|
||||
this.plugin = plugin;
|
||||
this.groups = groups;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (!(sender instanceof Player player)) {
|
||||
sender.sendMessage(Component.text("This command can only be used by a player.", NamedTextColor.RED));
|
||||
return true;
|
||||
}
|
||||
if (!player.hasPermission(USE)) {
|
||||
player.sendMessage(Component.text("You do not have permission to use this command.", NamedTextColor.RED));
|
||||
return true;
|
||||
}
|
||||
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
|
||||
help(player);
|
||||
return true;
|
||||
}
|
||||
|
||||
String sub = args[0].toLowerCase(Locale.ROOT);
|
||||
switch (sub) {
|
||||
case "create" -> create(player, args);
|
||||
case "tool", "edit" -> tool(player, args);
|
||||
case "list" -> list(player, args);
|
||||
case "info" -> info(player, args);
|
||||
case "delete", "remove" -> delete(player, args);
|
||||
case "rename" -> rename(player, args);
|
||||
case "modify" -> modify(player, args);
|
||||
case "reload" -> reload(player);
|
||||
case "cleanup" -> cleanup(player);
|
||||
default -> {
|
||||
player.sendMessage(Component.text("Unknown subcommand. Use /wireless help.", NamedTextColor.RED));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void create(Player player, String[] args) {
|
||||
if (args.length < 2) {
|
||||
player.sendMessage(Component.text("Usage: /wireless create <name>", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
GroupName name;
|
||||
try {
|
||||
name = GroupName.parse(args[1]);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
player.sendMessage(Component.text(ex.getMessage(), NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
if (groups.nameExists(name)) {
|
||||
player.sendMessage(Component.text("A group with that name already exists.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
ItemStack item = plugin.getConnectorTool().creationTool(name.displayName());
|
||||
plugin.getConnectorTool().give(player, item);
|
||||
player.sendMessage(Component.text("Connector received. Right-click a supported block to create group ", NamedTextColor.GREEN)
|
||||
.append(Component.text(name.displayName(), NamedTextColor.YELLOW))
|
||||
.append(Component.text(".", NamedTextColor.GREEN)));
|
||||
}
|
||||
|
||||
private void tool(Player player, String[] args) {
|
||||
if (args.length < 2) {
|
||||
player.sendMessage(Component.text("Usage: /wireless tool <group>", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
WirelessGroup group = find(player, args[1]).orElse(null);
|
||||
if (group == null) {
|
||||
player.sendMessage(Component.text("No such group.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
if (!canManage(player, group)) {
|
||||
player.sendMessage(Component.text("You can only edit your own groups.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
ItemStack item = plugin.getConnectorTool().boundTool(group.id(), group.displayName());
|
||||
plugin.getConnectorTool().give(player, item);
|
||||
player.sendMessage(Component.text("Connector for ", NamedTextColor.GREEN)
|
||||
.append(Component.text(group.displayName(), NamedTextColor.YELLOW))
|
||||
.append(Component.text(" received.", NamedTextColor.GREEN)));
|
||||
}
|
||||
|
||||
private void list(Player player, String[] args) {
|
||||
boolean all = args.length >= 2 && args[1].equalsIgnoreCase("--all");
|
||||
if (all && !player.hasPermission(ADMIN)) {
|
||||
player.sendMessage(Component.text("You do not have permission to list all groups.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
List<WirelessGroup> result = new ArrayList<>(groups.accessible(player.getUniqueId(), all));
|
||||
if (result.isEmpty()) {
|
||||
player.sendMessage(Component.text("No wireless groups.", NamedTextColor.GRAY));
|
||||
return;
|
||||
}
|
||||
result.sort(Comparator.comparing(WirelessGroup::displayName, String.CASE_INSENSITIVE_ORDER));
|
||||
player.sendMessage(Component.text("Wireless groups (" + result.size() + "):", NamedTextColor.GOLD));
|
||||
for (WirelessGroup group : result) {
|
||||
String owner = all ? " owner=" + group.owner().toString().substring(0, 8) : "";
|
||||
player.sendMessage(Component.text(" - ", NamedTextColor.GRAY)
|
||||
.append(Component.text(group.displayName(), NamedTextColor.YELLOW))
|
||||
.append(Component.text(" tx=" + group.transmitters().size()
|
||||
+ " rx=" + group.receivers().size()
|
||||
+ " signal=" + group.signal() + owner, NamedTextColor.DARK_GRAY)));
|
||||
}
|
||||
}
|
||||
|
||||
private void info(Player player, String[] args) {
|
||||
if (args.length < 2) {
|
||||
player.sendMessage(Component.text("Usage: /wireless info <group>", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
WirelessGroup group = find(player, args[1]).orElse(null);
|
||||
if (group == null) {
|
||||
player.sendMessage(Component.text("No such group.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
player.sendMessage(Component.text("Group: ", NamedTextColor.GOLD)
|
||||
.append(Component.text(group.displayName(), NamedTextColor.YELLOW)));
|
||||
player.sendMessage(Component.text("ID: " + group.id(), NamedTextColor.DARK_GRAY));
|
||||
player.sendMessage(Component.text("Owner: " + group.owner(), NamedTextColor.GRAY));
|
||||
player.sendMessage(Component.text("Transmitters: " + group.transmitters().size()
|
||||
+ ", receivers: " + group.receivers().size()
|
||||
+ ", signal: " + group.signal(), NamedTextColor.GRAY));
|
||||
group.transmitters().stream().limit(8).forEach(key ->
|
||||
player.sendMessage(Component.text(" TX ", NamedTextColor.RED)
|
||||
.append(Component.text(key.toString(), NamedTextColor.DARK_GRAY))));
|
||||
group.receivers().stream().limit(8).forEach(key ->
|
||||
player.sendMessage(Component.text(" RX ", NamedTextColor.GREEN)
|
||||
.append(Component.text(key.toString(), NamedTextColor.DARK_GRAY))));
|
||||
int hidden = group.size() - Math.min(8, group.transmitters().size())
|
||||
- Math.min(8, group.receivers().size());
|
||||
if (hidden > 0) {
|
||||
player.sendMessage(Component.text(" ... and " + hidden + " more", NamedTextColor.DARK_GRAY));
|
||||
}
|
||||
}
|
||||
|
||||
private void delete(Player player, String[] args) {
|
||||
if (args.length < 2) {
|
||||
player.sendMessage(Component.text("Usage: /wireless delete <group>", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
WirelessGroup group = find(player, args[1]).orElse(null);
|
||||
if (group == null) {
|
||||
player.sendMessage(Component.text("No such group.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
if (!canManage(player, group)) {
|
||||
player.sendMessage(Component.text("You can only edit your own groups.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
groups.delete(group);
|
||||
player.sendMessage(Component.text("Deleted group " + group.displayName() + ".", NamedTextColor.GREEN));
|
||||
}
|
||||
|
||||
private void rename(Player player, String[] args) {
|
||||
if (args.length < 3) {
|
||||
player.sendMessage(Component.text("Usage: /wireless rename <group> <newName>", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
WirelessGroup group = find(player, args[1]).orElse(null);
|
||||
if (group == null) {
|
||||
player.sendMessage(Component.text("No such group.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
if (!canManage(player, group)) {
|
||||
player.sendMessage(Component.text("You can only edit your own groups.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
GroupName newName;
|
||||
try {
|
||||
newName = GroupName.parse(args[2]);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
player.sendMessage(Component.text(ex.getMessage(), NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
if (!groups.rename(group, newName)) {
|
||||
player.sendMessage(Component.text("A group with that name already exists.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
player.sendMessage(Component.text("Group renamed to " + group.displayName() + ".", NamedTextColor.GREEN));
|
||||
}
|
||||
|
||||
private void modify(Player player, String[] args) {
|
||||
if (args.length >= 4 && args[1].equalsIgnoreCase("name")) {
|
||||
rename(player, new String[]{"rename", args[2], args[3]});
|
||||
} else {
|
||||
player.sendMessage(Component.text("Usage: /wireless modify name <group> <newName>", NamedTextColor.RED));
|
||||
}
|
||||
}
|
||||
|
||||
private void reload(Player player) {
|
||||
if (!player.hasPermission(ADMIN)) {
|
||||
player.sendMessage(Component.text("You do not have permission to reload the plugin.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
plugin.reloadPluginData();
|
||||
player.sendMessage(Component.text("Configuration and groups reloaded.", NamedTextColor.GREEN));
|
||||
}
|
||||
|
||||
private void cleanup(Player player) {
|
||||
if (!player.hasPermission(ADMIN)) {
|
||||
player.sendMessage(Component.text("You do not have permission to clean up groups.", NamedTextColor.RED));
|
||||
return;
|
||||
}
|
||||
int removed = groups.cleanupLoaded();
|
||||
player.sendMessage(Component.text("Removed " + removed + " stale loaded block location(s).", NamedTextColor.GREEN));
|
||||
}
|
||||
|
||||
private Optional<WirelessGroup> find(Player player, String query) {
|
||||
return groups.find(player.getUniqueId(), player.hasPermission(ADMIN), query);
|
||||
}
|
||||
|
||||
private boolean canManage(Player player, WirelessGroup group) {
|
||||
return groups.canManage(player.getUniqueId(), player.hasPermission(ADMIN), group);
|
||||
}
|
||||
|
||||
private void help(Player player) {
|
||||
player.sendMessage(Component.text("AsminWirelessRedstone commands:", NamedTextColor.GOLD));
|
||||
player.sendMessage(Component.text("/wireless create <name>", NamedTextColor.YELLOW)
|
||||
.append(Component.text(" - receive a connector tool", NamedTextColor.GRAY)));
|
||||
player.sendMessage(Component.text("/wireless tool <group>", NamedTextColor.YELLOW)
|
||||
.append(Component.text(" - receive a connector for a group", NamedTextColor.GRAY)));
|
||||
player.sendMessage(Component.text("/wireless list [--all] / info <group>", NamedTextColor.YELLOW)
|
||||
.append(Component.text(" - inspect groups", NamedTextColor.GRAY)));
|
||||
player.sendMessage(Component.text("/wireless rename <group> <new> / delete <group>", NamedTextColor.YELLOW));
|
||||
player.sendMessage(Component.text("/wireless reload / cleanup", NamedTextColor.YELLOW)
|
||||
.append(Component.text(" - admin maintenance", NamedTextColor.GRAY)));
|
||||
player.sendMessage(Component.text("Connector: right-click to add, left-click to remove.", NamedTextColor.GRAY));
|
||||
player.sendMessage(Component.text("Supported: " + me.asmin.wirelessredstone.util.BlockTypes.supportedNames(),
|
||||
NamedTextColor.DARK_GRAY));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
if (!(sender instanceof Player player) || !player.hasPermission(USE)) return List.of();
|
||||
if (args.length == 1) {
|
||||
return filter(List.of("create", "tool", "list", "info", "delete", "rename", "reload", "cleanup", "help"),
|
||||
args[0]);
|
||||
}
|
||||
if (args.length == 2) {
|
||||
String sub = args[0].toLowerCase(Locale.ROOT);
|
||||
if (sub.equals("list")) return filter(List.of("--all"), args[1]);
|
||||
if (sub.equals("info") || sub.equals("delete") || sub.equals("tool")
|
||||
|| sub.equals("rename") || sub.equals("edit")) {
|
||||
boolean admin = player.hasPermission(ADMIN);
|
||||
return filter(groups.accessible(player.getUniqueId(), admin).stream()
|
||||
.map(WirelessGroup::displayName)
|
||||
.sorted(String.CASE_INSENSITIVE_ORDER)
|
||||
.collect(Collectors.toList()), args[1]);
|
||||
}
|
||||
}
|
||||
if (args.length == 3 && args[0].equalsIgnoreCase("rename")) {
|
||||
return filter(List.of("new_name"), args[2]);
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private List<String> filter(List<String> options, String prefix) {
|
||||
String value = prefix == null ? "" : prefix.toLowerCase(Locale.ROOT);
|
||||
return options.stream()
|
||||
.filter(option -> option.toLowerCase(Locale.ROOT).startsWith(value))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package me.asmin.wirelessredstone.listener;
|
||||
|
||||
import me.asmin.wirelessredstone.AsminWirelessRedstone;
|
||||
import me.asmin.wirelessredstone.manager.GroupManager;
|
||||
import me.asmin.wirelessredstone.util.BlockKeys;
|
||||
import me.asmin.wirelessredstone.util.BlockTypes;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockBurnEvent;
|
||||
import org.bukkit.event.block.BlockExplodeEvent;
|
||||
import org.bukkit.event.block.BlockFadeEvent;
|
||||
import org.bukkit.event.block.BlockFormEvent;
|
||||
import org.bukkit.event.block.BlockFromToEvent;
|
||||
import org.bukkit.event.block.BlockPistonExtendEvent;
|
||||
import org.bukkit.event.block.BlockPistonRetractEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.block.BlockSpreadEvent;
|
||||
import org.bukkit.event.entity.EntityChangeBlockEvent;
|
||||
import org.bukkit.event.entity.EntityExplodeEvent;
|
||||
import org.bukkit.event.world.ChunkLoadEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/** Keeps the group index free of stale block locations. */
|
||||
public final class BlockLifecycleListener implements Listener {
|
||||
|
||||
private final AsminWirelessRedstone plugin;
|
||||
private final GroupManager groups;
|
||||
|
||||
public BlockLifecycleListener(AsminWirelessRedstone plugin, GroupManager groups) {
|
||||
this.plugin = plugin;
|
||||
this.groups = groups;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onBreak(BlockBreakEvent event) {
|
||||
groups.remove(BlockKeys.of(event.getBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlace(BlockPlaceEvent event) {
|
||||
if (isConnector(event.getItemInHand())) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
groups.remove(BlockKeys.of(event.getBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onChunkLoad(ChunkLoadEvent event) {
|
||||
groups.handleChunkLoad(event.getChunk());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onEntityExplode(EntityExplodeEvent event) {
|
||||
for (Block block : event.blockList()) {
|
||||
groups.remove(BlockKeys.of(block));
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onBlockExplode(BlockExplodeEvent event) {
|
||||
for (Block block : event.blockList()) {
|
||||
groups.remove(BlockKeys.of(block));
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onBurn(BlockBurnEvent event) {
|
||||
groups.remove(BlockKeys.of(event.getBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onFade(BlockFadeEvent event) {
|
||||
groups.remove(BlockKeys.of(event.getBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onFromTo(BlockFromToEvent event) {
|
||||
groups.remove(BlockKeys.of(event.getToBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onSpread(BlockSpreadEvent event) {
|
||||
groups.remove(BlockKeys.of(event.getBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onForm(BlockFormEvent event) {
|
||||
groups.remove(BlockKeys.of(event.getBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
|
||||
groups.remove(BlockKeys.of(event.getBlock()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPistonExtend(BlockPistonExtendEvent event) {
|
||||
for (Block block : event.getBlocks()) {
|
||||
groups.remove(BlockKeys.of(block));
|
||||
groups.remove(BlockKeys.of(block.getRelative(event.getDirection())));
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPistonRetract(BlockPistonRetractEvent event) {
|
||||
for (Block block : event.getBlocks()) {
|
||||
groups.remove(BlockKeys.of(block));
|
||||
groups.remove(BlockKeys.of(block.getRelative(event.getDirection().getOppositeFace())));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isConnector(ItemStack item) {
|
||||
if (plugin.getConnectorTool() != null && plugin.getConnectorTool().isTool(item)) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package me.asmin.wirelessredstone.listener;
|
||||
|
||||
import me.asmin.wirelessredstone.AsminWirelessRedstone;
|
||||
import me.asmin.wirelessredstone.manager.GroupManager;
|
||||
import me.asmin.wirelessredstone.model.BlockKey;
|
||||
import me.asmin.wirelessredstone.model.BlockRole;
|
||||
import me.asmin.wirelessredstone.model.GroupName;
|
||||
import me.asmin.wirelessredstone.model.WirelessGroup;
|
||||
import me.asmin.wirelessredstone.tool.ConnectorTool;
|
||||
import me.asmin.wirelessredstone.util.BlockKeys;
|
||||
import me.asmin.wirelessredstone.util.BlockTypes;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.block.BlockDamageEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class ConnectorToolListener implements Listener {
|
||||
|
||||
private final AsminWirelessRedstone plugin;
|
||||
private final GroupManager groups;
|
||||
private final ConnectorTool tool;
|
||||
|
||||
public ConnectorToolListener(AsminWirelessRedstone plugin, GroupManager groups, ConnectorTool tool) {
|
||||
this.plugin = plugin;
|
||||
this.groups = groups;
|
||||
this.tool = tool;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInteract(PlayerInteractEvent event) {
|
||||
ItemStack item = event.getItem();
|
||||
if (!tool.isTool(item)) return;
|
||||
|
||||
event.setCancelled(true);
|
||||
Player player = event.getPlayer();
|
||||
EquipmentSlot hand = event.getHand();
|
||||
|
||||
// Paper fires one event per hand. Do not process the same tool twice.
|
||||
if (hand == EquipmentSlot.OFF_HAND
|
||||
&& tool.isTool(player.getInventory().getItemInMainHand())) {
|
||||
return;
|
||||
}
|
||||
if (!player.hasPermission("asminwireless.use")) {
|
||||
message(player, "You do not have permission to manage wireless groups.", NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
|
||||
Block block = event.getClickedBlock();
|
||||
if (block == null) return;
|
||||
|
||||
if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
|
||||
handleRemove(player, block);
|
||||
} else if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
|
||||
handleAdd(player, block, item, hand);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleAdd(Player player, Block block, ItemStack item, EquipmentSlot hand) {
|
||||
BlockRole role = BlockTypes.roleOf(block.getType());
|
||||
if (role == null) {
|
||||
message(player, "Unsupported block. Supported: " + BlockTypes.supportedNames(), NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
|
||||
BlockKey key = BlockKeys.of(block);
|
||||
if (groups.isManaged(key)) {
|
||||
message(player, "That block already belongs to a wireless group.", NamedTextColor.YELLOW);
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<UUID> boundId = tool.groupId(item);
|
||||
WirelessGroup group;
|
||||
if (boundId.isPresent()) {
|
||||
group = groups.byId(boundId.get()).orElse(null);
|
||||
if (group == null) {
|
||||
message(player, "That group no longer exists.", NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
String rawName = tool.creationName(item).orElse(null);
|
||||
if (rawName == null) {
|
||||
message(player, "This connector has no group. Use /wireless tool <group>.", NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
GroupName name;
|
||||
try {
|
||||
name = GroupName.parse(rawName);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
message(player, ex.getMessage(), NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
if (groups.nameExists(name)) {
|
||||
message(player, "A group with that name already exists.", NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
group = groups.create(player.getUniqueId(), name);
|
||||
ItemStack updated = tool.bind(item, group.id(), group.displayName());
|
||||
setItem(player, hand, updated);
|
||||
}
|
||||
|
||||
if (!groups.canManage(player.getUniqueId(), player.hasPermission("asminwireless.admin"), group)) {
|
||||
message(player, "You can only edit your own groups.", NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
|
||||
GroupManager.AddResult result = groups.add(group, key, role);
|
||||
switch (result) {
|
||||
case OK -> {
|
||||
String text = (role == BlockRole.TRANSMITTER ? "Transmitter" : "Receiver")
|
||||
+ " added to " + group.displayName()
|
||||
+ " (" + group.size() + "/" + groups.maxBlocks() + ")";
|
||||
feedback(player, text, NamedTextColor.GREEN);
|
||||
}
|
||||
case FULL -> message(player, "This group is full.", NamedTextColor.RED);
|
||||
case ALREADY_MANAGED -> message(player, "That block already belongs to a group.", NamedTextColor.YELLOW);
|
||||
case GROUP_MISSING -> message(player, "That group no longer exists.", NamedTextColor.RED);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleRemove(Player player, Block block) {
|
||||
BlockKey key = BlockKeys.of(block);
|
||||
Optional<WirelessGroup> optional = groups.at(key);
|
||||
if (optional.isEmpty()) {
|
||||
message(player, "That block is not part of a wireless group.", NamedTextColor.YELLOW);
|
||||
return;
|
||||
}
|
||||
WirelessGroup group = optional.get();
|
||||
if (!groups.canManage(player.getUniqueId(), player.hasPermission("asminwireless.admin"), group)) {
|
||||
message(player, "You can only edit your own groups.", NamedTextColor.RED);
|
||||
return;
|
||||
}
|
||||
GroupManager.RemoveResult result = groups.remove(key);
|
||||
if (result == null) return;
|
||||
|
||||
String text = result.groupRemoved()
|
||||
? "Removed from " + result.group().displayName() + " (group is now empty)"
|
||||
: "Removed from " + result.group().displayName()
|
||||
+ " (" + result.group().size() + "/" + groups.maxBlocks() + ")";
|
||||
feedback(player, text, NamedTextColor.YELLOW);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockDamage(BlockDamageEvent event) {
|
||||
if (tool.isTool(event.getPlayer().getInventory().getItemInMainHand())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlace(BlockPlaceEvent event) {
|
||||
if (tool.isTool(event.getItemInHand())
|
||||
|| tool.isTool(event.getPlayer().getInventory().getItemInOffHand())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void setItem(Player player, EquipmentSlot hand, ItemStack item) {
|
||||
if (hand == EquipmentSlot.OFF_HAND) {
|
||||
player.getInventory().setItemInOffHand(item);
|
||||
} else {
|
||||
player.getInventory().setItemInMainHand(item);
|
||||
}
|
||||
}
|
||||
|
||||
private void message(Player player, String text, NamedTextColor color) {
|
||||
player.sendMessage(Component.text(text, color));
|
||||
}
|
||||
|
||||
private void feedback(Player player, String text, NamedTextColor color) {
|
||||
Component component = Component.text(text, color);
|
||||
if (plugin.actionBarFeedback()) {
|
||||
player.sendActionBar(component);
|
||||
} else {
|
||||
player.sendMessage(component);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package me.asmin.wirelessredstone.listener;
|
||||
|
||||
import me.asmin.wirelessredstone.AsminWirelessRedstone;
|
||||
import me.asmin.wirelessredstone.manager.GroupManager;
|
||||
import me.asmin.wirelessredstone.model.BlockKey;
|
||||
import me.asmin.wirelessredstone.model.BlockRole;
|
||||
import me.asmin.wirelessredstone.model.WirelessGroup;
|
||||
import me.asmin.wirelessredstone.util.BlockKeys;
|
||||
import me.asmin.wirelessredstone.util.BlockTypes;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.block.BlockPhysicsEvent;
|
||||
import org.bukkit.event.block.BlockRedstoneEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
|
||||
/**
|
||||
* Event-driven synchronization. No polling task is used: transmitter changes
|
||||
* are coalesced and processed once on the next server tick.
|
||||
*/
|
||||
public final class RedstoneListener implements Listener {
|
||||
|
||||
private final AsminWirelessRedstone plugin;
|
||||
private final GroupManager groups;
|
||||
|
||||
public RedstoneListener(AsminWirelessRedstone plugin, GroupManager groups) {
|
||||
this.plugin = plugin;
|
||||
this.groups = groups;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onTransmitterRedstone(BlockRedstoneEvent event) {
|
||||
Block block = event.getBlock();
|
||||
if (!BlockTypes.isTransmitter(block.getType())) return;
|
||||
BlockKey key = BlockKeys.of(block);
|
||||
if (groups.roleAt(key) == BlockRole.TRANSMITTER) {
|
||||
groups.scheduleTransmitter(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a wirelessly powered dust block from being recalculated to a lower
|
||||
* vanilla value while the group signal is active. The actual value is
|
||||
* written by BlockSignals.
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onReceiverWire(BlockRedstoneEvent event) {
|
||||
if (event.getBlock().getType() != Material.REDSTONE_WIRE) return;
|
||||
BlockKey key = BlockKeys.of(event.getBlock());
|
||||
if (groups.roleAt(key) != BlockRole.RECEIVER) return;
|
||||
WirelessGroup group = groups.at(key).orElse(null);
|
||||
if (group != null && group.signal() > event.getNewCurrent()) {
|
||||
event.setNewCurrent(group.signal());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onTransmitterPhysics(BlockPhysicsEvent event) {
|
||||
Block block = event.getBlock();
|
||||
if (!BlockTypes.isTransmitter(block.getType())) return;
|
||||
BlockKey key = BlockKeys.of(block);
|
||||
if (groups.roleAt(key) == BlockRole.TRANSMITTER) {
|
||||
groups.scheduleTransmitter(key);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onTransmitterInteract(PlayerInteractEvent event) {
|
||||
if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) return;
|
||||
Block block = event.getClickedBlock();
|
||||
if (block == null || !BlockTypes.isTransmitter(block.getType())) return;
|
||||
BlockKey key = BlockKeys.of(block);
|
||||
if (groups.roleAt(key) == BlockRole.TRANSMITTER) {
|
||||
// Levers/buttons are toggled by the server after this event, so
|
||||
// read their state on the next tick.
|
||||
groups.scheduleTransmitter(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
package me.asmin.wirelessredstone.manager;
|
||||
|
||||
import me.asmin.wirelessredstone.AsminWirelessRedstone;
|
||||
import me.asmin.wirelessredstone.model.BlockKey;
|
||||
import me.asmin.wirelessredstone.model.BlockRole;
|
||||
import me.asmin.wirelessredstone.model.ChunkKey;
|
||||
import me.asmin.wirelessredstone.model.GroupName;
|
||||
import me.asmin.wirelessredstone.model.WirelessGroup;
|
||||
import me.asmin.wirelessredstone.util.BlockKeys;
|
||||
import me.asmin.wirelessredstone.util.BlockSignals;
|
||||
import me.asmin.wirelessredstone.util.BlockTypes;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Owns the group registry, location index and chunk index. All methods are
|
||||
* main-thread only, except the cheap read-only getters used by commands.
|
||||
*/
|
||||
public final class GroupManager {
|
||||
|
||||
public enum AddResult { OK, FULL, ALREADY_MANAGED, GROUP_MISSING }
|
||||
|
||||
public record RemoveResult(WirelessGroup group, BlockRole role, boolean groupRemoved) {
|
||||
}
|
||||
|
||||
private final AsminWirelessRedstone plugin;
|
||||
private final GroupStorage storage;
|
||||
private final Map<UUID, WirelessGroup> groups = new LinkedHashMap<>();
|
||||
private final Map<BlockKey, UUID> locationIndex = new HashMap<>();
|
||||
private final Map<ChunkKey, Set<BlockKey>> chunkIndex = new HashMap<>();
|
||||
private final Set<BlockKey> pendingTransmitters = new HashSet<>();
|
||||
private boolean flushScheduled;
|
||||
private int maxBlocks;
|
||||
|
||||
public GroupManager(AsminWirelessRedstone plugin) {
|
||||
this.plugin = plugin;
|
||||
this.storage = new GroupStorage(plugin);
|
||||
this.maxBlocks = plugin.getConfig().getInt("max-blocks-per-group", 256);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Loading and saving
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
public void load() {
|
||||
groups.clear();
|
||||
locationIndex.clear();
|
||||
chunkIndex.clear();
|
||||
pendingTransmitters.clear();
|
||||
maxBlocks = Math.max(2, plugin.getConfig().getInt("max-blocks-per-group", 256));
|
||||
|
||||
for (WirelessGroup group : storage.load()) {
|
||||
if (groups.containsKey(group.id())) {
|
||||
plugin.getLogger().warning("Duplicate group id " + group.id() + " was ignored.");
|
||||
continue;
|
||||
}
|
||||
for (BlockKey key : new ArrayList<>(group.transmitters())) {
|
||||
if (locationIndex.putIfAbsent(key, group.id()) != null) {
|
||||
group.remove(key);
|
||||
} else {
|
||||
addToChunkIndex(key);
|
||||
}
|
||||
}
|
||||
for (BlockKey key : new ArrayList<>(group.receivers())) {
|
||||
if (locationIndex.putIfAbsent(key, group.id()) != null) {
|
||||
group.remove(key);
|
||||
} else {
|
||||
addToChunkIndex(key);
|
||||
}
|
||||
}
|
||||
if (!group.isEmpty()) {
|
||||
groups.put(group.id(), group);
|
||||
}
|
||||
}
|
||||
plugin.getLogger().info("Loaded " + groups.size() + " wireless group(s).");
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
load();
|
||||
refreshAllLoaded();
|
||||
}
|
||||
|
||||
public void saveNow() {
|
||||
try {
|
||||
storage.save(groups.values());
|
||||
} catch (IOException ex) {
|
||||
plugin.getLogger().severe("Could not save groups.yml: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void scheduleSave() {
|
||||
plugin.scheduleSave();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Group lookup / management
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
public Optional<WirelessGroup> byId(UUID id) {
|
||||
return Optional.ofNullable(groups.get(id));
|
||||
}
|
||||
|
||||
public Optional<WirelessGroup> at(BlockKey key) {
|
||||
UUID id = locationIndex.get(key);
|
||||
return id == null ? Optional.empty() : byId(id);
|
||||
}
|
||||
|
||||
public BlockRole roleAt(BlockKey key) {
|
||||
UUID id = locationIndex.get(key);
|
||||
if (id == null) return null;
|
||||
WirelessGroup group = groups.get(id);
|
||||
return group == null ? null : group.roleOf(key);
|
||||
}
|
||||
|
||||
public boolean isManaged(BlockKey key) {
|
||||
return locationIndex.containsKey(key);
|
||||
}
|
||||
|
||||
public Collection<WirelessGroup> all() {
|
||||
return Collections.unmodifiableCollection(groups.values());
|
||||
}
|
||||
|
||||
public List<WirelessGroup> accessible(UUID playerId, boolean admin) {
|
||||
List<WirelessGroup> result = new ArrayList<>();
|
||||
for (WirelessGroup group : groups.values()) {
|
||||
if (admin || group.owner().equals(playerId)) result.add(group);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean canManage(UUID playerId, boolean admin, WirelessGroup group) {
|
||||
return admin || group.owner().equals(playerId);
|
||||
}
|
||||
|
||||
public Optional<WirelessGroup> find(UUID playerId, boolean admin, String query) {
|
||||
if (query == null || query.isBlank()) return Optional.empty();
|
||||
String value = query.trim().toLowerCase(Locale.ROOT);
|
||||
List<WirelessGroup> allowed = accessible(playerId, admin);
|
||||
|
||||
for (WirelessGroup group : allowed) {
|
||||
if (group.displayName().toLowerCase(Locale.ROOT).equals(value)) return Optional.of(group);
|
||||
}
|
||||
for (WirelessGroup group : allowed) {
|
||||
if (group.groupName().name().toLowerCase(Locale.ROOT).equals(value)) return Optional.of(group);
|
||||
}
|
||||
for (WirelessGroup group : allowed) {
|
||||
if (group.id().toString().toLowerCase(Locale.ROOT).startsWith(value)) return Optional.of(group);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public boolean nameExists(GroupName name) {
|
||||
for (WirelessGroup group : groups.values()) {
|
||||
if (group.displayName().equalsIgnoreCase(name.displayName())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public WirelessGroup create(UUID owner, GroupName name) {
|
||||
WirelessGroup group = new WirelessGroup(UUID.randomUUID(), owner, name);
|
||||
groups.put(group.id(), group);
|
||||
scheduleSave();
|
||||
return group;
|
||||
}
|
||||
|
||||
public boolean rename(WirelessGroup group, GroupName newName) {
|
||||
if (!group.displayName().equalsIgnoreCase(newName.displayName()) && nameExists(newName)) {
|
||||
return false;
|
||||
}
|
||||
group.setGroupName(newName);
|
||||
scheduleSave();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void delete(WirelessGroup group) {
|
||||
groups.remove(group.id());
|
||||
for (BlockKey key : new ArrayList<>(group.allLocations())) {
|
||||
locationIndex.remove(key);
|
||||
removeFromChunkIndex(key);
|
||||
}
|
||||
scheduleSave();
|
||||
}
|
||||
|
||||
public int maxBlocks() {
|
||||
return maxBlocks;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Block assignment
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
public AddResult add(WirelessGroup group, BlockKey key, BlockRole role) {
|
||||
if (groups.get(group.id()) != group) return AddResult.GROUP_MISSING;
|
||||
if (locationIndex.containsKey(key)) return AddResult.ALREADY_MANAGED;
|
||||
if (group.size() >= maxBlocks) return AddResult.FULL;
|
||||
|
||||
boolean added = role == BlockRole.TRANSMITTER
|
||||
? group.addTransmitter(key)
|
||||
: group.addReceiver(key);
|
||||
if (!added) return AddResult.ALREADY_MANAGED;
|
||||
|
||||
locationIndex.put(key, group.id());
|
||||
addToChunkIndex(key);
|
||||
scheduleSave();
|
||||
|
||||
if (role == BlockRole.TRANSMITTER) {
|
||||
refresh(group, true);
|
||||
} else {
|
||||
applyKey(group, key, true);
|
||||
}
|
||||
return AddResult.OK;
|
||||
}
|
||||
|
||||
/** Removes a block from its group. Returns null when the location was not managed. */
|
||||
public RemoveResult remove(BlockKey key) {
|
||||
UUID groupId = locationIndex.get(key);
|
||||
if (groupId == null) return null;
|
||||
WirelessGroup group = groups.get(groupId);
|
||||
if (group == null) {
|
||||
locationIndex.remove(key);
|
||||
removeFromChunkIndex(key);
|
||||
return null;
|
||||
}
|
||||
|
||||
BlockRole role = detach(key);
|
||||
if (role == null) return null;
|
||||
boolean removedGroup = !groups.containsKey(groupId);
|
||||
if (!removedGroup && role == BlockRole.TRANSMITTER) {
|
||||
refresh(group, false);
|
||||
}
|
||||
scheduleSave();
|
||||
return new RemoveResult(group, role, removedGroup);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Chunk loading, validation, state restoration
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
public void handleChunkLoad(Chunk chunk) {
|
||||
ChunkKey chunkKey = new ChunkKey(chunk.getWorld().getUID(), chunk.getX(), chunk.getZ());
|
||||
Set<BlockKey> keys = chunkIndex.get(chunkKey);
|
||||
if (keys == null || keys.isEmpty()) return;
|
||||
|
||||
Set<UUID> transmitterGroups = new HashSet<>();
|
||||
Map<UUID, Set<BlockKey>> receiverGroups = new HashMap<>();
|
||||
for (BlockKey key : new ArrayList<>(keys)) {
|
||||
UUID groupId = locationIndex.get(key);
|
||||
if (groupId == null) {
|
||||
keys.remove(key);
|
||||
continue;
|
||||
}
|
||||
WirelessGroup group = groups.get(groupId);
|
||||
if (group == null) {
|
||||
locationIndex.remove(key);
|
||||
keys.remove(key);
|
||||
continue;
|
||||
}
|
||||
BlockRole role = group.roleOf(key);
|
||||
Block block = BlockKeys.block(key);
|
||||
if (role == null || block == null) {
|
||||
detach(key);
|
||||
scheduleSave();
|
||||
continue;
|
||||
}
|
||||
boolean valid = role == BlockRole.TRANSMITTER
|
||||
? BlockTypes.isTransmitter(block.getType())
|
||||
: BlockTypes.isReceiver(block.getType());
|
||||
if (!valid) {
|
||||
detach(key);
|
||||
scheduleSave();
|
||||
continue;
|
||||
}
|
||||
if (role == BlockRole.TRANSMITTER) {
|
||||
transmitterGroups.add(groupId);
|
||||
} else {
|
||||
receiverGroups.computeIfAbsent(groupId, ignored -> new HashSet<>()).add(key);
|
||||
}
|
||||
}
|
||||
|
||||
Set<UUID> touched = new HashSet<>(transmitterGroups);
|
||||
touched.addAll(receiverGroups.keySet());
|
||||
for (UUID id : touched) {
|
||||
WirelessGroup group = groups.get(id);
|
||||
if (group == null) continue;
|
||||
if (transmitterGroups.contains(id)) {
|
||||
// A transmitter chunk can change the group state; refresh all
|
||||
// currently loaded receivers once.
|
||||
refresh(group, true);
|
||||
} else {
|
||||
// Only the receivers in this chunk need their state restored.
|
||||
for (BlockKey key : receiverGroups.getOrDefault(id, Set.of())) {
|
||||
applyKey(group, key, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void refreshAllLoaded() {
|
||||
for (WirelessGroup group : new ArrayList<>(groups.values())) {
|
||||
refresh(group, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recomputes the group signal from all loaded transmitters, then applies it
|
||||
* to receivers. If no transmitter is loaded the previous signal is kept,
|
||||
* and restored when a transmitter chunk loads.
|
||||
*/
|
||||
public void refresh(WirelessGroup group, boolean forceApply) {
|
||||
if (groups.get(group.id()) != group) return;
|
||||
|
||||
List<BlockKey> invalid = new ArrayList<>();
|
||||
boolean anyLoaded = false;
|
||||
boolean allLoaded = true;
|
||||
int highest = 0;
|
||||
|
||||
for (BlockKey key : new ArrayList<>(group.transmitters())) {
|
||||
Block block = BlockKeys.block(key);
|
||||
if (block == null || !block.getWorld().isChunkLoaded(key.x() >> 4, key.z() >> 4)) {
|
||||
allLoaded = false;
|
||||
continue;
|
||||
}
|
||||
if (!BlockTypes.isTransmitter(block.getType())) {
|
||||
invalid.add(key);
|
||||
continue;
|
||||
}
|
||||
anyLoaded = true;
|
||||
highest = Math.max(highest, BlockSignals.read(block));
|
||||
}
|
||||
|
||||
if (!invalid.isEmpty()) {
|
||||
for (BlockKey key : invalid) detach(key);
|
||||
scheduleSave();
|
||||
if (!groups.containsKey(group.id())) return;
|
||||
refresh(group, forceApply);
|
||||
return;
|
||||
}
|
||||
|
||||
int target;
|
||||
if (group.transmitters().isEmpty()) {
|
||||
target = 0;
|
||||
} else if (!anyLoaded) {
|
||||
// No transmitter is loaded; keep the last known state until a
|
||||
// transmitter chunk loads.
|
||||
target = group.signal();
|
||||
} else if (highest > 0 || allLoaded) {
|
||||
target = highest;
|
||||
} else {
|
||||
// At least one transmitter is in an unloaded chunk. Do not turn
|
||||
// the group off based only on loaded transmitters.
|
||||
target = group.signal();
|
||||
}
|
||||
|
||||
boolean changed = group.setSignal(target);
|
||||
if (changed || forceApply) apply(group, forceApply);
|
||||
}
|
||||
|
||||
public void apply(WirelessGroup group, boolean force) {
|
||||
List<BlockKey> invalid = new ArrayList<>();
|
||||
for (BlockKey key : new ArrayList<>(group.receivers())) {
|
||||
if (!applyKey(group, key, force, invalid)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!invalid.isEmpty()) {
|
||||
for (BlockKey key : invalid) detach(key);
|
||||
scheduleSave();
|
||||
}
|
||||
}
|
||||
|
||||
private void applyKey(WirelessGroup group, BlockKey key, boolean force) {
|
||||
List<BlockKey> invalid = new ArrayList<>();
|
||||
applyKey(group, key, force, invalid);
|
||||
if (!invalid.isEmpty()) {
|
||||
for (BlockKey blockKey : invalid) detach(blockKey);
|
||||
scheduleSave();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean applyKey(WirelessGroup group, BlockKey key, boolean force, List<BlockKey> invalid) {
|
||||
if (groups.get(group.id()) != group) return false;
|
||||
Block block = BlockKeys.block(key);
|
||||
if (block == null) return true;
|
||||
World world = block.getWorld();
|
||||
if (!world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) return true;
|
||||
if (!BlockTypes.isReceiver(block.getType())) {
|
||||
invalid.add(key);
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
BlockSignals.apply(block, group.signal(), force);
|
||||
} catch (RuntimeException ex) {
|
||||
plugin.getLogger().warning("Could not update receiver at " + key + ": " + ex.getMessage());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Event entry points
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
public void scheduleTransmitter(BlockKey key) {
|
||||
if (roleAt(key) != BlockRole.TRANSMITTER) return;
|
||||
pendingTransmitters.add(key);
|
||||
if (flushScheduled) return;
|
||||
flushScheduled = true;
|
||||
plugin.getServer().getScheduler().runTask(plugin, this::flushTransmitters);
|
||||
}
|
||||
|
||||
private void flushTransmitters() {
|
||||
flushScheduled = false;
|
||||
if (pendingTransmitters.isEmpty()) return;
|
||||
|
||||
Set<UUID> groupIds = new HashSet<>();
|
||||
for (BlockKey key : pendingTransmitters) {
|
||||
if (roleAt(key) == BlockRole.TRANSMITTER) {
|
||||
UUID id = locationIndex.get(key);
|
||||
if (id != null) groupIds.add(id);
|
||||
}
|
||||
}
|
||||
pendingTransmitters.clear();
|
||||
|
||||
for (UUID id : groupIds) {
|
||||
WirelessGroup group = groups.get(id);
|
||||
if (group != null) refresh(group, false);
|
||||
}
|
||||
|
||||
if (!pendingTransmitters.isEmpty() && !flushScheduled) {
|
||||
flushScheduled = true;
|
||||
plugin.getServer().getScheduler().runTask(plugin, this::flushTransmitters);
|
||||
}
|
||||
}
|
||||
|
||||
public int cleanupLoaded() {
|
||||
int removed = 0;
|
||||
for (WirelessGroup group : new ArrayList<>(groups.values())) {
|
||||
for (BlockKey key : new ArrayList<>(group.allLocations())) {
|
||||
Block block = BlockKeys.block(key);
|
||||
if (block == null || !block.getWorld().isChunkLoaded(key.x() >> 4, key.z() >> 4)) {
|
||||
continue;
|
||||
}
|
||||
BlockRole role = group.roleOf(key);
|
||||
boolean valid = role == BlockRole.TRANSMITTER
|
||||
? BlockTypes.isTransmitter(block.getType())
|
||||
: BlockTypes.isReceiver(block.getType());
|
||||
if (!valid) {
|
||||
detach(key);
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (removed > 0) {
|
||||
scheduleSave();
|
||||
refreshAllLoaded();
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Internal indexes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private BlockRole detach(BlockKey key) {
|
||||
UUID groupId = locationIndex.remove(key);
|
||||
removeFromChunkIndex(key);
|
||||
if (groupId == null) return null;
|
||||
WirelessGroup group = groups.get(groupId);
|
||||
if (group == null) return null;
|
||||
BlockRole role = group.remove(key);
|
||||
if (group.isEmpty()) groups.remove(groupId);
|
||||
return role;
|
||||
}
|
||||
|
||||
private void addToChunkIndex(BlockKey key) {
|
||||
chunkIndex.computeIfAbsent(key.chunkKey(), ignored -> new HashSet<>()).add(key);
|
||||
}
|
||||
|
||||
private void removeFromChunkIndex(BlockKey key) {
|
||||
ChunkKey chunkKey = key.chunkKey();
|
||||
Set<BlockKey> keys = chunkIndex.get(chunkKey);
|
||||
if (keys == null) return;
|
||||
keys.remove(key);
|
||||
if (keys.isEmpty()) chunkIndex.remove(chunkKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package me.asmin.wirelessredstone.manager;
|
||||
|
||||
import me.asmin.wirelessredstone.AsminWirelessRedstone;
|
||||
import me.asmin.wirelessredstone.model.BlockKey;
|
||||
import me.asmin.wirelessredstone.model.GroupName;
|
||||
import me.asmin.wirelessredstone.model.WirelessGroup;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Atomic YAML persistence for groups. */
|
||||
final class GroupStorage {
|
||||
|
||||
private final AsminWirelessRedstone plugin;
|
||||
private final File file;
|
||||
private final File backup;
|
||||
private final File temp;
|
||||
|
||||
GroupStorage(AsminWirelessRedstone plugin) {
|
||||
this.plugin = plugin;
|
||||
File folder = plugin.getDataFolder();
|
||||
this.file = new File(folder, "groups.yml");
|
||||
this.backup = new File(folder, "groups.yml.bak");
|
||||
this.temp = new File(folder, "groups.yml.tmp");
|
||||
}
|
||||
|
||||
synchronized List<WirelessGroup> load() {
|
||||
LoadResult primary = file.isFile() ? read(file) : new LoadResult(List.of(), false);
|
||||
if (primary.valid()) return primary.groups();
|
||||
if (backup.isFile()) {
|
||||
plugin.getLogger().warning("Primary group file is missing or unreadable; trying backup.");
|
||||
return read(backup).groups();
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private record LoadResult(List<WirelessGroup> groups, boolean valid) {
|
||||
}
|
||||
|
||||
private LoadResult read(File source) {
|
||||
List<WirelessGroup> groups = new ArrayList<>();
|
||||
try {
|
||||
YamlConfiguration yaml = YamlConfiguration.loadConfiguration(source);
|
||||
ConfigurationSection root = yaml.getConfigurationSection("groups");
|
||||
boolean valid = yaml.contains("version") || root != null;
|
||||
if (root == null) return new LoadResult(groups, valid);
|
||||
|
||||
for (String key : root.getKeys(false)) {
|
||||
String base = "groups." + key;
|
||||
try {
|
||||
String idValue = yaml.getString(base + ".id");
|
||||
String ownerValue = yaml.getString(base + ".owner");
|
||||
String name = yaml.getString(base + ".name");
|
||||
if (idValue == null || ownerValue == null || name == null) continue;
|
||||
|
||||
String category = yaml.getString(base + ".category");
|
||||
GroupName groupName = GroupName.parse(category == null ? name : category + "/" + name);
|
||||
WirelessGroup group = new WirelessGroup(
|
||||
UUID.fromString(idValue), UUID.fromString(ownerValue), groupName);
|
||||
|
||||
loadLocations(yaml, base + ".transmitters", true, group);
|
||||
loadLocations(yaml, base + ".receivers", false, group);
|
||||
groups.add(group);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
plugin.getLogger().warning("Skipping invalid group entry '" + key + "': " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
return new LoadResult(groups, true);
|
||||
} catch (RuntimeException ex) {
|
||||
plugin.getLogger().warning("Could not read " + source.getName() + ": " + ex.getMessage());
|
||||
return new LoadResult(groups, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadLocations(YamlConfiguration yaml, String path, boolean transmitter, WirelessGroup group) {
|
||||
for (Map<?, ?> map : yaml.getMapList(path)) {
|
||||
String worldName = string(map.get("world"));
|
||||
String worldIdValue = string(map.get("world-uuid"));
|
||||
UUID worldId = parseUuid(worldIdValue);
|
||||
World world = worldId == null ? null : Bukkit.getWorld(worldId);
|
||||
if (world == null && worldName != null) {
|
||||
world = Bukkit.getWorld(worldName);
|
||||
if (world != null) worldId = world.getUID();
|
||||
}
|
||||
if (world == null || worldId == null) {
|
||||
plugin.getLogger().warning("Dropping wireless block in missing world: " + worldName);
|
||||
continue;
|
||||
}
|
||||
int x = number(map.get("x"));
|
||||
int y = number(map.get("y"));
|
||||
int z = number(map.get("z"));
|
||||
BlockKey key = new BlockKey(worldId, world.getName(), x, y, z);
|
||||
if (transmitter) {
|
||||
group.addTransmitter(key);
|
||||
} else {
|
||||
group.addReceiver(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void save(Collection<WirelessGroup> groups) throws IOException {
|
||||
File folder = plugin.getDataFolder();
|
||||
if (!folder.isDirectory() && !folder.mkdirs()) {
|
||||
throw new IOException("Could not create plugin data folder");
|
||||
}
|
||||
|
||||
YamlConfiguration yaml = new YamlConfiguration();
|
||||
yaml.set("version", 1);
|
||||
int index = 0;
|
||||
for (WirelessGroup group : groups) {
|
||||
String base = "groups." + index++;
|
||||
yaml.set(base + ".id", group.id().toString());
|
||||
yaml.set(base + ".owner", group.owner().toString());
|
||||
yaml.set(base + ".name", group.groupName().name());
|
||||
if (group.groupName().category() != null) {
|
||||
yaml.set(base + ".category", group.groupName().category());
|
||||
}
|
||||
yaml.set(base + ".transmitters", serialize(group.transmitters()));
|
||||
yaml.set(base + ".receivers", serialize(group.receivers()));
|
||||
}
|
||||
|
||||
if (file.isFile()) {
|
||||
try {
|
||||
Files.copy(file.toPath(), backup.toPath(),
|
||||
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
|
||||
} catch (IOException ex) {
|
||||
plugin.getLogger().warning("Could not update groups.yml.bak: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
Files.writeString(temp.toPath(), yaml.saveToString(), StandardCharsets.UTF_8);
|
||||
moveAtomically(temp.toPath(), file.toPath());
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> serialize(Collection<BlockKey> keys) {
|
||||
List<Map<String, Object>> result = new ArrayList<>(keys.size());
|
||||
for (BlockKey key : keys) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("world", key.worldName());
|
||||
map.put("world-uuid", key.worldId().toString());
|
||||
map.put("x", key.x());
|
||||
map.put("y", key.y());
|
||||
map.put("z", key.z());
|
||||
result.add(map);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void moveAtomically(Path source, Path target) throws IOException {
|
||||
try {
|
||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
} catch (IOException atomicFailure) {
|
||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
private static String string(Object value) {
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
private static UUID parseUuid(String value) {
|
||||
if (value == null) return null;
|
||||
try {
|
||||
return UUID.fromString(value);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int number(Object value) {
|
||||
if (value instanceof Number number) return number.intValue();
|
||||
if (value == null) return 0;
|
||||
try {
|
||||
return Integer.parseInt(String.valueOf(value));
|
||||
} catch (NumberFormatException ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Immutable, Bukkit-independent block position. The world UUID is used for
|
||||
* identity, while the name is kept as a fallback for renamed worlds.
|
||||
*/
|
||||
public record BlockKey(UUID worldId, String worldName, int x, int y, int z) implements Comparable<BlockKey> {
|
||||
|
||||
public BlockKey {
|
||||
Objects.requireNonNull(worldId, "worldId");
|
||||
worldName = worldName == null ? "" : worldName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof BlockKey key)) return false;
|
||||
return x == key.x && y == key.y && z == key.z && worldId.equals(key.worldId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = worldId.hashCode();
|
||||
result = 31 * result + x;
|
||||
result = 31 * result + y;
|
||||
result = 31 * result + z;
|
||||
return result;
|
||||
}
|
||||
|
||||
public ChunkKey chunkKey() {
|
||||
return new ChunkKey(worldId, x >> 4, z >> 4);
|
||||
}
|
||||
|
||||
public String coords() {
|
||||
return x + ", " + y + ", " + z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(BlockKey other) {
|
||||
int result = worldId.compareTo(other.worldId);
|
||||
if (result != 0) return result;
|
||||
result = Integer.compare(x, other.x);
|
||||
if (result != 0) return result;
|
||||
result = Integer.compare(y, other.y);
|
||||
if (result != 0) return result;
|
||||
return Integer.compare(z, other.z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return worldName + " (" + coords() + ")";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
public enum BlockRole {
|
||||
TRANSMITTER,
|
||||
RECEIVER
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/** Chunk coordinates used to restore receiver state when a chunk loads. */
|
||||
public record ChunkKey(UUID worldId, int x, int z) {
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Validated group name. The optional "category/name" syntax is inherited from
|
||||
* the original plugin and is kept as a lightweight grouping aid.
|
||||
*/
|
||||
public record GroupName(String category, String name) {
|
||||
|
||||
private static final Pattern PART = Pattern.compile("[A-Za-z0-9_-]{1,32}");
|
||||
|
||||
public GroupName {
|
||||
Objects.requireNonNull(name, "name");
|
||||
}
|
||||
|
||||
public static GroupName parse(String raw) {
|
||||
if (raw == null) throw new IllegalArgumentException("Name is required");
|
||||
String value = raw.trim();
|
||||
if (value.isEmpty()) throw new IllegalArgumentException("Name is required");
|
||||
|
||||
String category = null;
|
||||
String name = value;
|
||||
int slash = value.indexOf('/');
|
||||
if (slash >= 0) {
|
||||
if (slash != value.lastIndexOf('/')) {
|
||||
throw new IllegalArgumentException("Only one category separator is allowed");
|
||||
}
|
||||
category = value.substring(0, slash).trim();
|
||||
name = value.substring(slash + 1).trim();
|
||||
if (!PART.matcher(category).matches()) {
|
||||
throw new IllegalArgumentException("Invalid category; use letters, numbers, '_' or '-'");
|
||||
}
|
||||
}
|
||||
if (!PART.matcher(name).matches()) {
|
||||
throw new IllegalArgumentException("Invalid name; use letters, numbers, '_' or '-'");
|
||||
}
|
||||
return new GroupName(category, name);
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return category == null ? name : category + "/" + name;
|
||||
}
|
||||
|
||||
public boolean matches(String input) {
|
||||
if (input == null) return false;
|
||||
String value = input.trim().toLowerCase(Locale.ROOT);
|
||||
return displayName().toLowerCase(Locale.ROOT).equals(value)
|
||||
|| name.toLowerCase(Locale.ROOT).equals(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/** A named set of wireless transmitters and receivers. */
|
||||
public final class WirelessGroup {
|
||||
|
||||
private final UUID id;
|
||||
private final UUID owner;
|
||||
private GroupName groupName;
|
||||
private final Set<BlockKey> transmitters = new LinkedHashSet<>();
|
||||
private final Set<BlockKey> receivers = new LinkedHashSet<>();
|
||||
private int signal;
|
||||
|
||||
public WirelessGroup(UUID id, UUID owner, GroupName groupName) {
|
||||
this.id = Objects.requireNonNull(id, "id");
|
||||
this.owner = Objects.requireNonNull(owner, "owner");
|
||||
this.groupName = Objects.requireNonNull(groupName, "groupName");
|
||||
}
|
||||
|
||||
public UUID id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public UUID owner() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
public GroupName groupName() {
|
||||
return groupName;
|
||||
}
|
||||
|
||||
public void setGroupName(GroupName groupName) {
|
||||
this.groupName = Objects.requireNonNull(groupName, "groupName");
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return groupName.displayName();
|
||||
}
|
||||
|
||||
public Set<BlockKey> transmitters() {
|
||||
return Collections.unmodifiableSet(transmitters);
|
||||
}
|
||||
|
||||
public Set<BlockKey> receivers() {
|
||||
return Collections.unmodifiableSet(receivers);
|
||||
}
|
||||
|
||||
public boolean addTransmitter(BlockKey key) {
|
||||
if (contains(key)) return false;
|
||||
return transmitters.add(key);
|
||||
}
|
||||
|
||||
public boolean addReceiver(BlockKey key) {
|
||||
if (contains(key)) return false;
|
||||
return receivers.add(key);
|
||||
}
|
||||
|
||||
public boolean contains(BlockKey key) {
|
||||
return transmitters.contains(key) || receivers.contains(key);
|
||||
}
|
||||
|
||||
public BlockRole roleOf(BlockKey key) {
|
||||
if (transmitters.contains(key)) return BlockRole.TRANSMITTER;
|
||||
if (receivers.contains(key)) return BlockRole.RECEIVER;
|
||||
return null;
|
||||
}
|
||||
|
||||
public BlockRole remove(BlockKey key) {
|
||||
if (transmitters.remove(key)) return BlockRole.TRANSMITTER;
|
||||
if (receivers.remove(key)) return BlockRole.RECEIVER;
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return transmitters.isEmpty() && receivers.isEmpty();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return transmitters.size() + receivers.size();
|
||||
}
|
||||
|
||||
public Collection<BlockKey> allLocations() {
|
||||
if (transmitters.isEmpty()) return receivers();
|
||||
if (receivers.isEmpty()) return transmitters();
|
||||
Set<BlockKey> all = new LinkedHashSet<>(transmitters);
|
||||
all.addAll(receivers);
|
||||
return Collections.unmodifiableSet(all);
|
||||
}
|
||||
|
||||
public int signal() {
|
||||
return signal;
|
||||
}
|
||||
|
||||
public boolean setSignal(int signal) {
|
||||
int clamped = Math.max(0, Math.min(15, signal));
|
||||
if (this.signal == clamped) return false;
|
||||
this.signal = clamped;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package me.asmin.wirelessredstone.tool;
|
||||
|
||||
import me.asmin.wirelessredstone.AsminWirelessRedstone;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** The connector tool used to add and remove blocks in a group. */
|
||||
public final class ConnectorTool {
|
||||
|
||||
private static final String TOOL_VALUE = "connector";
|
||||
|
||||
private final NamespacedKey toolKey;
|
||||
private final NamespacedKey groupKey;
|
||||
private final NamespacedKey nameKey;
|
||||
|
||||
public ConnectorTool(AsminWirelessRedstone plugin) {
|
||||
this.toolKey = new NamespacedKey(plugin, "connector");
|
||||
this.groupKey = new NamespacedKey(plugin, "group");
|
||||
this.nameKey = new NamespacedKey(plugin, "creation_name");
|
||||
}
|
||||
|
||||
public boolean isTool(ItemStack item) {
|
||||
if (item == null || item.getType() != Material.REDSTONE_TORCH || !item.hasItemMeta()) return false;
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
return meta != null && TOOL_VALUE.equals(
|
||||
meta.getPersistentDataContainer().get(toolKey, PersistentDataType.STRING));
|
||||
}
|
||||
|
||||
public Optional<UUID> groupId(ItemStack item) {
|
||||
if (!isTool(item)) return Optional.empty();
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return Optional.empty();
|
||||
String value = meta.getPersistentDataContainer().get(groupKey, PersistentDataType.STRING);
|
||||
if (value == null) return Optional.empty();
|
||||
try {
|
||||
return Optional.of(UUID.fromString(value));
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<String> creationName(ItemStack item) {
|
||||
if (!isTool(item)) return Optional.empty();
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return Optional.empty();
|
||||
return Optional.ofNullable(meta.getPersistentDataContainer().get(nameKey, PersistentDataType.STRING));
|
||||
}
|
||||
|
||||
public ItemStack creationTool(String groupName) {
|
||||
return build(null, groupName);
|
||||
}
|
||||
|
||||
public ItemStack boundTool(UUID groupId, String groupName) {
|
||||
return build(groupId, groupName);
|
||||
}
|
||||
|
||||
public ItemStack bind(ItemStack item, UUID groupId, String groupName) {
|
||||
if (!isTool(item)) return item;
|
||||
ItemStack result = item.clone();
|
||||
ItemMeta meta = result.getItemMeta();
|
||||
if (meta == null) return result;
|
||||
meta.getPersistentDataContainer().set(groupKey, PersistentDataType.STRING, groupId.toString());
|
||||
meta.getPersistentDataContainer().remove(nameKey);
|
||||
applyAppearance(meta, groupName);
|
||||
result.setItemMeta(meta);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void give(Player player, ItemStack item) {
|
||||
if (player.getInventory().firstEmpty() == -1) {
|
||||
player.getWorld().dropItemNaturally(player.getLocation(), item);
|
||||
} else {
|
||||
player.getInventory().addItem(item);
|
||||
}
|
||||
}
|
||||
|
||||
private ItemStack build(UUID groupId, String groupName) {
|
||||
ItemStack item = new ItemStack(Material.REDSTONE_TORCH);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null) return item;
|
||||
meta.getPersistentDataContainer().set(toolKey, PersistentDataType.STRING, TOOL_VALUE);
|
||||
if (groupId != null) {
|
||||
meta.getPersistentDataContainer().set(groupKey, PersistentDataType.STRING, groupId.toString());
|
||||
}
|
||||
if (groupName != null) {
|
||||
meta.getPersistentDataContainer().set(nameKey, PersistentDataType.STRING, groupName);
|
||||
}
|
||||
applyAppearance(meta, groupName);
|
||||
item.setItemMeta(meta);
|
||||
return item;
|
||||
}
|
||||
|
||||
private void applyAppearance(ItemMeta meta, String groupName) {
|
||||
meta.displayName(Component.text("Wireless Connector", NamedTextColor.RED)
|
||||
.decoration(TextDecoration.ITALIC, false)
|
||||
.decorate(TextDecoration.BOLD));
|
||||
|
||||
List<Component> lore = new ArrayList<>();
|
||||
lore.add(Component.text("Group: ", NamedTextColor.GRAY)
|
||||
.append(Component.text(groupName == null ? "?" : groupName, NamedTextColor.YELLOW))
|
||||
.decoration(TextDecoration.ITALIC, false));
|
||||
lore.add(Component.text("Right-click: add block", NamedTextColor.DARK_GRAY)
|
||||
.decoration(TextDecoration.ITALIC, false));
|
||||
lore.add(Component.text("Left-click: remove block", NamedTextColor.DARK_GRAY)
|
||||
.decoration(TextDecoration.ITALIC, false));
|
||||
meta.lore(lore);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package me.asmin.wirelessredstone.util;
|
||||
|
||||
import me.asmin.wirelessredstone.model.BlockKey;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public final class BlockKeys {
|
||||
|
||||
private BlockKeys() {
|
||||
}
|
||||
|
||||
public static BlockKey of(Block block) {
|
||||
World world = block.getWorld();
|
||||
return new BlockKey(world.getUID(), world.getName(),
|
||||
block.getX(), block.getY(), block.getZ());
|
||||
}
|
||||
|
||||
public static World world(BlockKey key) {
|
||||
World world = Bukkit.getWorld(key.worldId());
|
||||
if (world == null && !key.worldName().isEmpty()) {
|
||||
world = Bukkit.getWorld(key.worldName());
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
public static Block block(BlockKey key) {
|
||||
World world = world(key);
|
||||
return world == null ? null : world.getBlockAt(key.x(), key.y(), key.z());
|
||||
}
|
||||
|
||||
public static boolean isLoaded(BlockKey key) {
|
||||
World world = world(key);
|
||||
return world != null && world.isChunkLoaded(key.x() >> 4, key.z() >> 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package me.asmin.wirelessredstone.util;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.AnaloguePowerable;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.block.data.Lightable;
|
||||
import org.bukkit.block.data.Openable;
|
||||
import org.bukkit.block.data.Powerable;
|
||||
import org.bukkit.block.data.type.RedstoneWire;
|
||||
|
||||
/** Reads transmitter power and applies it to supported receivers. */
|
||||
public final class BlockSignals {
|
||||
|
||||
private BlockSignals() {
|
||||
}
|
||||
|
||||
public static int clamp(int signal) {
|
||||
return Math.max(0, Math.min(15, signal));
|
||||
}
|
||||
|
||||
/** Reads the current output of a transmitter. */
|
||||
public static int read(Block block) {
|
||||
Material type = block.getType();
|
||||
if (type == Material.REDSTONE_BLOCK) return 15;
|
||||
|
||||
BlockData data = block.getBlockData();
|
||||
if (data instanceof AnaloguePowerable analogue) {
|
||||
return clamp(analogue.getPower());
|
||||
}
|
||||
if (data instanceof Powerable powerable) {
|
||||
return powerable.isPowered() ? 15 : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a wireless signal to a receiver.
|
||||
*
|
||||
* Redstone dust gets a real power value and a physics update, so adjacent
|
||||
* vanilla redstone (more dust, lamps, rails, etc.) reacts normally. The
|
||||
* RedstoneListener protects the injected value from being recomputed to
|
||||
* zero while the group is still active.
|
||||
*/
|
||||
public static void apply(Block block, int signal, boolean force) {
|
||||
int power = clamp(signal);
|
||||
Material type = block.getType();
|
||||
|
||||
if (type == Material.REDSTONE_WIRE && block.getBlockData() instanceof RedstoneWire wire) {
|
||||
if (force || wire.getPower() != power) {
|
||||
wire.setPower(power);
|
||||
block.setBlockData(wire, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == Material.REDSTONE_LAMP && block.getBlockData() instanceof Lightable lightable) {
|
||||
boolean lit = power > 0;
|
||||
if (lightable.isLit() != lit) {
|
||||
lightable.setLit(lit);
|
||||
block.setBlockData(lightable, false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
BlockData data = block.getBlockData();
|
||||
boolean powered = power > 0;
|
||||
boolean changed = false;
|
||||
|
||||
if (data instanceof Powerable powerable) {
|
||||
changed = powerable.isPowered() != powered;
|
||||
powerable.setPowered(powered);
|
||||
}
|
||||
if (data instanceof Openable openable) {
|
||||
changed |= openable.isOpen() != powered;
|
||||
openable.setOpen(powered);
|
||||
}
|
||||
if (changed || force) {
|
||||
block.setBlockData(data, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package me.asmin.wirelessredstone.util;
|
||||
|
||||
import me.asmin.wirelessredstone.model.BlockRole;
|
||||
import org.bukkit.Material;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
|
||||
/** Explicit 1.20.4 block lists (tags are avoided on hot event paths). */
|
||||
public final class BlockTypes {
|
||||
|
||||
private static final Set<Material> TRANSMITTERS = EnumSet.noneOf(Material.class);
|
||||
private static final Set<Material> RECEIVERS = EnumSet.noneOf(Material.class);
|
||||
|
||||
static {
|
||||
Collections.addAll(TRANSMITTERS,
|
||||
Material.LEVER,
|
||||
Material.REDSTONE_BLOCK,
|
||||
Material.TRIPWIRE_HOOK,
|
||||
Material.STONE_BUTTON,
|
||||
Material.POLISHED_BLACKSTONE_BUTTON,
|
||||
Material.OAK_BUTTON,
|
||||
Material.SPRUCE_BUTTON,
|
||||
Material.BIRCH_BUTTON,
|
||||
Material.JUNGLE_BUTTON,
|
||||
Material.ACACIA_BUTTON,
|
||||
Material.DARK_OAK_BUTTON,
|
||||
Material.MANGROVE_BUTTON,
|
||||
Material.CHERRY_BUTTON,
|
||||
Material.BAMBOO_BUTTON,
|
||||
Material.CRIMSON_BUTTON,
|
||||
Material.WARPED_BUTTON,
|
||||
Material.STONE_PRESSURE_PLATE,
|
||||
Material.POLISHED_BLACKSTONE_PRESSURE_PLATE,
|
||||
Material.LIGHT_WEIGHTED_PRESSURE_PLATE,
|
||||
Material.HEAVY_WEIGHTED_PRESSURE_PLATE,
|
||||
Material.OAK_PRESSURE_PLATE,
|
||||
Material.SPRUCE_PRESSURE_PLATE,
|
||||
Material.BIRCH_PRESSURE_PLATE,
|
||||
Material.JUNGLE_PRESSURE_PLATE,
|
||||
Material.ACACIA_PRESSURE_PLATE,
|
||||
Material.DARK_OAK_PRESSURE_PLATE,
|
||||
Material.MANGROVE_PRESSURE_PLATE,
|
||||
Material.CHERRY_PRESSURE_PLATE,
|
||||
Material.BAMBOO_PRESSURE_PLATE,
|
||||
Material.CRIMSON_PRESSURE_PLATE,
|
||||
Material.WARPED_PRESSURE_PLATE);
|
||||
|
||||
Collections.addAll(RECEIVERS,
|
||||
Material.REDSTONE_LAMP,
|
||||
Material.REDSTONE_WIRE,
|
||||
Material.POWERED_RAIL,
|
||||
Material.ACTIVATOR_RAIL,
|
||||
Material.DETECTOR_RAIL,
|
||||
Material.IRON_DOOR,
|
||||
Material.IRON_TRAPDOOR,
|
||||
Material.OAK_DOOR,
|
||||
Material.SPRUCE_DOOR,
|
||||
Material.BIRCH_DOOR,
|
||||
Material.JUNGLE_DOOR,
|
||||
Material.ACACIA_DOOR,
|
||||
Material.DARK_OAK_DOOR,
|
||||
Material.MANGROVE_DOOR,
|
||||
Material.CHERRY_DOOR,
|
||||
Material.BAMBOO_DOOR,
|
||||
Material.CRIMSON_DOOR,
|
||||
Material.WARPED_DOOR,
|
||||
Material.OAK_TRAPDOOR,
|
||||
Material.SPRUCE_TRAPDOOR,
|
||||
Material.BIRCH_TRAPDOOR,
|
||||
Material.JUNGLE_TRAPDOOR,
|
||||
Material.ACACIA_TRAPDOOR,
|
||||
Material.DARK_OAK_TRAPDOOR,
|
||||
Material.MANGROVE_TRAPDOOR,
|
||||
Material.CHERRY_TRAPDOOR,
|
||||
Material.BAMBOO_TRAPDOOR,
|
||||
Material.CRIMSON_TRAPDOOR,
|
||||
Material.WARPED_TRAPDOOR,
|
||||
Material.OAK_FENCE_GATE,
|
||||
Material.SPRUCE_FENCE_GATE,
|
||||
Material.BIRCH_FENCE_GATE,
|
||||
Material.JUNGLE_FENCE_GATE,
|
||||
Material.ACACIA_FENCE_GATE,
|
||||
Material.DARK_OAK_FENCE_GATE,
|
||||
Material.MANGROVE_FENCE_GATE,
|
||||
Material.CHERRY_FENCE_GATE,
|
||||
Material.BAMBOO_FENCE_GATE,
|
||||
Material.CRIMSON_FENCE_GATE,
|
||||
Material.WARPED_FENCE_GATE);
|
||||
}
|
||||
|
||||
private BlockTypes() {
|
||||
}
|
||||
|
||||
public static BlockRole roleOf(Material material) {
|
||||
if (material == null || material.isAir()) return null;
|
||||
if (TRANSMITTERS.contains(material)) return BlockRole.TRANSMITTER;
|
||||
if (RECEIVERS.contains(material)) return BlockRole.RECEIVER;
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isTransmitter(Material material) {
|
||||
return material != null && TRANSMITTERS.contains(material);
|
||||
}
|
||||
|
||||
public static boolean isReceiver(Material material) {
|
||||
return material != null && RECEIVERS.contains(material);
|
||||
}
|
||||
|
||||
public static String supportedNames() {
|
||||
return "lever, buttons, pressure plates, redstone block, tripwire hook, "
|
||||
+ "redstone lamp, redstone dust, rails, doors, trapdoors, fence gates";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# AsminWirelessRedstone
|
||||
# Maximum number of transmitter + receiver blocks in a single group.
|
||||
# There is no distance limit between blocks.
|
||||
max-blocks-per-group: 256
|
||||
|
||||
# Group edits are saved after this many ticks. Redstone state changes are
|
||||
# never written to disk.
|
||||
save-debounce-ticks: 40
|
||||
|
||||
# Show action-bar feedback while using the connector tool.
|
||||
action-bar-feedback: true
|
||||
@@ -0,0 +1,20 @@
|
||||
name: AsminWirelessRedstone
|
||||
version: ${project.version}
|
||||
main: me.asmin.wirelessredstone.AsminWirelessRedstone
|
||||
api-version: "1.20"
|
||||
description: Wireless redstone transmitters and receivers connected in named groups.
|
||||
authors: [Asmin_, Cobbleworks]
|
||||
website: https://git.asmin.me/asminme/AsminWirelessRedstone
|
||||
commands:
|
||||
wireless:
|
||||
description: Manage wireless redstone groups.
|
||||
usage: /wireless help
|
||||
permission: asminwireless.use
|
||||
aliases: [wr, awr]
|
||||
permissions:
|
||||
asminwireless.use:
|
||||
description: Allows creating and managing own wireless groups.
|
||||
default: op
|
||||
asminwireless.admin:
|
||||
description: Allows managing all groups and reloading the plugin.
|
||||
default: op
|
||||
@@ -0,0 +1,33 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
class BlockKeyTest {
|
||||
|
||||
@Test
|
||||
void chunkKeyHandlesNegativeCoordinates() {
|
||||
UUID world = UUID.randomUUID();
|
||||
assertEquals(new ChunkKey(world, -1, -1),
|
||||
new BlockKey(world, "world", -1, 64, -1).chunkKey());
|
||||
assertEquals(new ChunkKey(world, -1, 0),
|
||||
new BlockKey(world, "world", -16, 64, 0).chunkKey());
|
||||
assertEquals(new ChunkKey(world, 0, 0),
|
||||
new BlockKey(world, "world", 15, 64, 15).chunkKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void identityUsesWorldUuidAndCoordinates() {
|
||||
UUID world = UUID.randomUUID();
|
||||
BlockKey first = new BlockKey(world, "world", 1, 2, 3);
|
||||
BlockKey same = new BlockKey(world, "renamed-world", 1, 2, 3);
|
||||
BlockKey other = new BlockKey(world, "world", 1, 2, 4);
|
||||
assertEquals(first, same);
|
||||
assertNotEquals(first, other);
|
||||
assertEquals("1, 2, 3", first.coords());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class GroupNameTest {
|
||||
|
||||
@Test
|
||||
void parsesPlainName() {
|
||||
GroupName name = GroupName.parse(" KitchenLights ");
|
||||
assertEquals("KitchenLights", name.name());
|
||||
assertEquals(null, name.category());
|
||||
assertEquals("KitchenLights", name.displayName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesCategory() {
|
||||
GroupName name = GroupName.parse("Factory/Line_1");
|
||||
assertEquals("Factory", name.category());
|
||||
assertEquals("Line_1", name.name());
|
||||
assertEquals("Factory/Line_1", name.displayName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidNames() {
|
||||
assertThrows(IllegalArgumentException.class, () -> GroupName.parse(""));
|
||||
assertThrows(IllegalArgumentException.class, () -> GroupName.parse("two/groups/x"));
|
||||
assertThrows(IllegalArgumentException.class, () -> GroupName.parse("bad name"));
|
||||
assertThrows(IllegalArgumentException.class, () -> GroupName.parse("bad/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesNameOrDisplayName() {
|
||||
GroupName name = GroupName.parse("Factory/Line");
|
||||
assertTrue(name.matches("Line"));
|
||||
assertTrue(name.matches("factory/line"));
|
||||
assertFalse(name.matches("Other"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package me.asmin.wirelessredstone.model;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class WirelessGroupTest {
|
||||
|
||||
private final UUID world = UUID.randomUUID();
|
||||
private final WirelessGroup group = new WirelessGroup(
|
||||
UUID.randomUUID(), UUID.randomUUID(), GroupName.parse("Test"));
|
||||
|
||||
@Test
|
||||
void addsTransmittersAndReceivers() {
|
||||
BlockKey transmitter = new BlockKey(world, "world", 0, 64, 0);
|
||||
BlockKey receiver = new BlockKey(world, "world", 10, 64, 10);
|
||||
|
||||
assertTrue(group.addTransmitter(transmitter));
|
||||
assertTrue(group.addReceiver(receiver));
|
||||
assertFalse(group.addTransmitter(transmitter));
|
||||
assertEquals(BlockRole.TRANSMITTER, group.roleOf(transmitter));
|
||||
assertEquals(BlockRole.RECEIVER, group.roleOf(receiver));
|
||||
assertEquals(2, group.size());
|
||||
assertFalse(group.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockCannotBeInBothRoles() {
|
||||
BlockKey key = new BlockKey(world, "world", 0, 64, 0);
|
||||
assertTrue(group.addTransmitter(key));
|
||||
assertFalse(group.addReceiver(key));
|
||||
assertEquals(1, group.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void removesAndDetectsEmptyGroups() {
|
||||
BlockKey key = new BlockKey(world, "world", 0, 64, 0);
|
||||
group.addReceiver(key);
|
||||
assertEquals(BlockRole.RECEIVER, group.remove(key));
|
||||
assertNull(group.remove(key));
|
||||
assertTrue(group.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void signalIsClamped() {
|
||||
assertFalse(group.setSignal(0));
|
||||
assertTrue(group.setSignal(99));
|
||||
assertEquals(15, group.signal());
|
||||
assertTrue(group.setSignal(-4));
|
||||
assertEquals(0, group.signal());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user