Compare commits

...

8 Commits

Author SHA1 Message Date
MineTec 1566419f85 Added HANGAR.md documentation, including overview, crafting, commands, configuration, and requirements. Included related screenshots. 2026-07-24 16:15:54 +02:00
MineTec ef2352d381 Added localization support with translatable components, centralized translations, and replaced hardcoded strings across commands and messages. 2026-07-24 16:06:20 +02:00
MineTec cf9326c2a5 Updated game rules to match latest Paper API changes, upgraded dependencies, and configured Gradle for modern plugin development. Added run-paper for testing, updated Gradle wrapper, and included executable scripts for compatibility. 2026-07-24 15:53:02 +02:00
MineTec b73352fe5b updated README with detailed plugin overview, usage, commands, and configuration documentation 2026-07-24 15:30:40 +02:00
MineTec 0aa098ae8f simplified code: shared entity tagging, world name scheme, less boilerplate
New EntityTagUtil replaces the three copies of the tag/find/remove
logic for display and interaction entities. The pixel world naming
scheme (build, parse, recognize) now lives in one place in
PixelBlockWorld with a cached base path instead of allocating on every
event. getPixels works with int arithmetic instead of two Location
allocations per cell, setBuildingPlatform lost its copy-pasted loops
and rebuilds the flower list only once, SubCommand is an abstract base
class instead of an interface with 12 trivial getters, and dead
methods were removed.
2026-07-23 22:59:00 +02:00
MineTec a024e42b80 fixed NPE and shutdown issues, cleaned up listeners and build config
Blocks destroyed before ever being entered no longer NPE on the null
entry location (new getReturnLocation fallback), destroy no longer
mutates the stored block location, placing an item whose block UUID
already exists cancels the event with a message instead of eating the
item, and pending task chains are flushed on shutdown. Failed block
initialization now propagates instead of leaving half-built blocks
registered. Listener null checks replaced requireNonNull, listener and
method name typos fixed, and the test-server copy path in build.gradle
is now a gradle property instead of a hardcoded home directory.
2026-07-23 22:58:47 +02:00
MineTec 76ddfc95af replaced single commands with /pixelblocks root command and permissions
New /pixelblocks (alias /pb) with create, give, exit and destroyall
subcommands, each gated by a permission (exit defaults to true, the
rest to op). Fixes the args[0] crash and missing UUID validation in
give, and the offline-owner NPE plus concurrent-modification risk in
destroyall (destroy now takes a force flag that skips the ownership
check for admins). Also centralizes the item id tag in
PixelBlockItem.setBlockId and drops the overridden itemName leftover.
2026-07-23 22:57:48 +02:00
MineTec bc43519077 moved database access to a dedicated single-thread executor
SQLite I/O no longer runs on the main server thread and the shared
PreparedStatements are confined to one thread. savePixelBlock captures
a snapshot of the block data on the calling thread. Main.pixelBlocks is
now a CopyOnWriteArrayList and list mutations moved out of async chains.
Blocks that fail to initialize on startup are skipped with a proper
error log instead of being registered half-built.
2026-07-23 22:57:22 +02:00
44 changed files with 1185 additions and 396 deletions
+3
View File
@@ -168,3 +168,6 @@ gradle-app.setting
*.hprof *.hprof
# End of https://www.toptal.com/developers/gitignore/api/java,intellij,gradle # End of https://www.toptal.com/developers/gitignore/api/java,intellij,gradle
### run-paper test server ###
run/
+77
View File
@@ -1,2 +1,79 @@
# PixelBlocks # PixelBlocks
**Design and build your own custom Minecraft blocks. In Minecraft.**
*No resource packs. No client mods. 100% server-side.*
PixelBlocks is a Paper plugin that lets players create their own blocks: place a pixel block, walk inside it, and build its appearance pixel by pixel in a dedicated building dimension. Every block placed inside becomes one pixel of the custom block (16×16×16 by default), just like a Minecraft block texture, but in 3D and made of real blocks. Since everything is rendered with vanilla display entities, custom blocks are visible to every player instantly: nothing to install, nothing to download.
## Why PixelBlocks?
- **Custom blocks without mods or resource packs:** everything is rendered with vanilla display entities; clients need nothing installed.
- **Portable builds:** break a pixel block and it drops as an item, contents included. Place it somewhere else, give it away, or collect them.
- **Real block feel:** the design is rendered in the world with real block models, including correct rotations and orientations, scaled down to a single block.
- **Ownership built in:** the first player to place an empty pixel block becomes its owner; editing and breaking can be restricted to owners via config.
- **Made for vanilla, survival and SMP servers:** pixel blocks are earned in-game through a late-game crafting recipe that players discover naturally, no commands or admin intervention needed. Ownership protection keeps builds safe on multiplayer servers, and nothing about vanilla gameplay changes for players who don't use the feature.
## How it works
1. Craft a pixel block and place it anywhere in the world.
2. Right-click it to enter its building dimension: a floating grass platform with a marked build area and an exit portal.
3. Build the block's look inside the marked area, pixel by pixel. Leave through the portal (or `/pixelblocks exit`) and the placed block now shows your design.
4. Break the block to pick it up. Item and design travel together.
The building dimensions are fully protected: no mob spawns, no explosions, no redstone contraptions escaping the build area, no liquids flowing out, and players cannot open containers that don't belong there.
## Crafting
The recipe unlocks for a player as soon as they click a Heart of the Sea or an End Crystal in their inventory.
| | | |
|---|---|---|
| Glass | End Crystal | Glass |
| Diamond Block | Heart of the Sea | Diamond Block |
| Grass Block | Grass Block | Grass Block |
## Requirements & installation
- Paper 1.21+
- Java 21
Drop `PixelBlocks-<version>-all.jar` into your server's `plugins/` folder and start the server. Config and storage are created on first start.
## Commands
Root command: `/pixelblocks` (alias `/pb`), players only.
| Command | Description | Permission | Default |
|---|---|---|---|
| `/pixelblocks create` | Creates a pixel block at your position | `pixelblocks.command.create` | op |
| `/pixelblocks give [uuid]` | Gives a pixel block item, optionally with a fixed UUID (e.g. to restore a lost item for an existing block) | `pixelblocks.command.give` | op |
| `/pixelblocks exit` | Leaves the pixel block you are currently in | `pixelblocks.command.exit` | everyone |
| `/pixelblocks destroyall` | Destroys **all** pixel blocks on the server (bypasses ownership) | `pixelblocks.command.destroyall` | op |
## Configuration
`plugins/PixelBlocks/config.yml`:
| Key | Default | Meaning |
|---|---|---|
| `pixelsPerBlock` | `16` | Edge length of the build area in blocks (= resolution of the miniature) |
| `onlyBreakableByOwners` | `false` | Only the owner may break a pixel block |
| `onlyEditableByOwners` | `true` | Only the owner may enter and edit a pixel block |
**Note:** don't change `pixelsPerBlock` once pixel blocks exist, because existing build dimensions and the miniature scale would no longer match.
## Data & backups
- `plugins/PixelBlocks/blocks.db`: SQLite database with pixel block metadata (owner, position, orientation).
- `plugins/PixelBlocks/worlds/<block-uuid>/`: one world per pixel block containing its build contents.
Back up both to preserve all pixel blocks.
## Building from source
```bash
gradle build
```
The plugin jar ends up in `build/libs/` as `PixelBlocks-<version>-all.jar`. To copy it to a local test server automatically, set `testServerPluginsDir=/path/to/server/plugins` in `gradle.properties` and run `gradle copyJarToTestServer`.
+14 -11
View File
@@ -1,6 +1,7 @@
plugins { plugins {
id 'java' id 'java'
id 'com.gradleup.shadow' version '8.3.1' id 'com.gradleup.shadow' version '9.6.1'
id 'xyz.jpenilla.run-paper' version '3.0.2'
} }
group = 'eu.mhsl.minecraft' group = 'eu.mhsl.minecraft'
@@ -22,36 +23,38 @@ repositories {
} }
dependencies { dependencies {
compileOnly "io.papermc.paper:paper-api:1.21.10-R0.1-SNAPSHOT" compileOnly "io.papermc.paper:paper-api:26.2.build.65-beta"
implementation "co.aikar:taskchain-bukkit:3.7.2" implementation "co.aikar:taskchain-bukkit:3.7.2"
} }
def targetJavaVersion = 21
java { java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion) toolchain.languageVersion = JavaLanguageVersion.of(25)
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
} }
processResources { processResources {
def props = [version: version] def props = [version: version]
inputs.properties props inputs.properties props
filteringCharset 'UTF-8' filteringCharset = 'UTF-8'
filesMatching('plugin.yml') { filesMatching('plugin.yml') {
expand props expand props
} }
} }
// Zielverzeichnis über testServerPluginsDir in gradle.properties oder -PtestServerPluginsDir=... setzen
tasks.register('copyJarToTestServer', Exec) { tasks.register('copyJarToTestServer', Exec) {
commandLine 'cp', 'build/libs/PixelBlocks-1.0-SNAPSHOT-all.jar', '/home/lars/Documents/Minecraft/Server/pixelblocks/plugins/PixelBlocks-1.0-SNAPSHOT-all.jar' def pluginsDir = providers.gradleProperty('testServerPluginsDir').getOrNull()
onlyIf { pluginsDir != null }
commandLine 'cp', "build/libs/PixelBlocks-${version}-all.jar", "${pluginsDir}/PixelBlocks-${version}-all.jar"
} }
shadowJar { shadowJar {
relocate 'co.aikar.taskchain', 'eu.mhsl.minecraft.pixelblocks.taskchain' relocate 'co.aikar.taskchain', 'eu.mhsl.minecraft.pixelblocks.taskchain'
} }
runServer {
minecraftVersion '26.2'
systemProperty 'com.mojang.eula.agree', 'true'
}
jar.dependsOn shadowJar jar.dependsOn shadowJar
copyJarToTestServer.dependsOn jar copyJarToTestServer.dependsOn jar
+70
View File
@@ -0,0 +1,70 @@
# PixelBlocks
**Design and build your own custom Minecraft blocks. In Minecraft.**
*No resource packs. No client mods. 100% server-side.*
![A tiny hut with a grass base, built as a single custom pixel block](https://mhsl.eu/gitea/Minecraft/PixelBlocks/raw/branch/main/docs/screenshots/pixelblock-hut.png)
PixelBlocks lets your players create their own blocks: place a pixel block, walk inside it, and build its appearance pixel by pixel in a dedicated building dimension. Every block placed inside becomes one pixel of the custom block (16×16×16 by default), just like a Minecraft block texture, but in 3D and made of real blocks.
Since everything is rendered with vanilla display entities, custom blocks are visible to every player instantly: nothing to install, nothing to download.
## ✨ Why PixelBlocks?
- **Custom blocks without mods or resource packs:** everything is rendered with vanilla display entities; clients need nothing installed.
- **Portable builds:** break a pixel block and it drops as an item, contents included. Place it somewhere else, give it away, or collect them.
- **Real block feel:** the design is rendered in the world with real block models, including correct rotations and orientations, scaled down to a single block.
- **Ownership built in:** the first player to place an empty pixel block becomes its owner; editing and breaking can be restricted to owners via config.
- **Made for vanilla, survival and SMP servers:** pixel blocks are earned in-game through a late-game crafting recipe that players discover naturally, no commands or admin intervention needed.
- **Localized:** English and German out of the box, following each player's client language.
## 🧭 How it works
1. Craft a pixel block and place it anywhere in the world.
2. Right-click it to enter its building dimension: a floating grass platform with a marked build area and an exit portal.
3. Build the block's look inside the marked area, pixel by pixel. Leave through the portal (or `/pixelblocks exit`) and the placed block now shows your design.
4. Break the block to pick it up. Item and design travel together.
The building dimensions are fully protected: no mob spawns, no explosions, no redstone contraptions escaping the build area, no liquids flowing out, and players cannot open containers that don't belong there.
## 🛠️ Crafting
The recipe unlocks for a player as soon as they click a Heart of the Sea or an End Crystal in their inventory.
![Crafting recipe: glass, end crystal and glass on top, diamond block, heart of the sea and diamond block in the middle, grass blocks at the bottom](https://mhsl.eu/gitea/Minecraft/PixelBlocks/raw/branch/main/docs/screenshots/crafting-recipe.png)
| | | |
|---|---|---|
| Glass | End Crystal | Glass |
| Diamond Block | Heart of the Sea | Diamond Block |
| Grass Block | Grass Block | Grass Block |
## ⌨️ Commands & permissions
Root command: `/pixelblocks` (alias `/pb`)
| Command | Description | Permission | Default |
|---|---|---|---|
| `/pixelblocks create` | Creates a pixel block at your position | `pixelblocks.command.create` | op |
| `/pixelblocks give [uuid]` | Gives a pixel block item | `pixelblocks.command.give` | op |
| `/pixelblocks exit` | Leaves the current pixel block | `pixelblocks.command.exit` | everyone |
| `/pixelblocks destroyall` | Destroys all pixel blocks | `pixelblocks.command.destroyall` | op |
## ⚙️ Configuration
```yaml
pixelsPerBlock: 16 # resolution of the miniature (don't change once blocks exist)
onlyBreakableByOwners: false # only the owner may break a pixel block
onlyEditableByOwners: true # only the owner may enter and edit a pixel block
```
## 📦 Requirements
- Paper 1.21 or newer (built against the latest release)
- Java 21+ (Java 25 for current Paper versions)
## 🔗 Links
- [Source code](https://mhsl.eu/gitea/Minecraft/PixelBlocks)
- Found a bug or have an idea? Open an issue in the repository!
Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.
+7 -1
View File
@@ -1 +1,7 @@
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+249
View File
@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -3,10 +3,8 @@ package eu.mhsl.minecraft.pixelblocks;
import co.aikar.taskchain.BukkitTaskChainFactory; import co.aikar.taskchain.BukkitTaskChainFactory;
import co.aikar.taskchain.TaskChain; import co.aikar.taskchain.TaskChain;
import co.aikar.taskchain.TaskChainFactory; import co.aikar.taskchain.TaskChainFactory;
import eu.mhsl.minecraft.pixelblocks.commands.CreatePixelBlockCommand; import eu.mhsl.minecraft.pixelblocks.commands.PixelBlocksCommand;
import eu.mhsl.minecraft.pixelblocks.commands.DestroyPixelBlocksCommand; import org.bukkit.command.PluginCommand;
import eu.mhsl.minecraft.pixelblocks.commands.ExitWorldCommand;
import eu.mhsl.minecraft.pixelblocks.commands.GivePixelBlockCommand;
import eu.mhsl.minecraft.pixelblocks.listeners.*; import eu.mhsl.minecraft.pixelblocks.listeners.*;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock; import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -15,10 +13,10 @@ import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.io.File; import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
public final class Main extends JavaPlugin { public final class Main extends JavaPlugin {
@@ -28,7 +26,7 @@ public final class Main extends JavaPlugin {
private static TaskChainFactory taskFactory; private static TaskChainFactory taskFactory;
public final static List<PixelBlock> pixelBlocks = new ArrayList<>(); public final static List<PixelBlock> pixelBlocks = new CopyOnWriteArrayList<>();
public static <T> TaskChain<T> sharedChain(String name) { public static <T> TaskChain<T> sharedChain(String name) {
return taskFactory.newSharedChain(name); return taskFactory.newSharedChain(name);
@@ -54,6 +52,7 @@ public final class Main extends JavaPlugin {
@Override @Override
public void onEnable() { public void onEnable() {
Translations.register();
Main.taskFactory = BukkitTaskChainFactory.create(this); Main.taskFactory = BukkitTaskChainFactory.create(this);
getLogger().info("Start constructing blocks from Database..."); getLogger().info("Start constructing blocks from Database...");
database.loadPixelBlocks(); database.loadPixelBlocks();
@@ -64,7 +63,7 @@ public final class Main extends JavaPlugin {
new FallOutOfPixelBlockListener(), new FallOutOfPixelBlockListener(),
new BreakPixelListener(), new BreakPixelListener(),
new PlacePixelBlockListener(), new PlacePixelBlockListener(),
new PreventInventorysListener(), new PreventInventoriesListener(),
new ExitPixelWorldListener(), new ExitPixelWorldListener(),
new PreventIllegalBlocksListener(), new PreventIllegalBlocksListener(),
new BreakPixelBlockListener(), new BreakPixelBlockListener(),
@@ -83,10 +82,10 @@ public final class Main extends JavaPlugin {
getServer().getPluginManager().registerEvents(listener, plugin); getServer().getPluginManager().registerEvents(listener, plugin);
} }
Objects.requireNonNull(getCommand("createpixelblock")).setExecutor(new CreatePixelBlockCommand()); PixelBlocksCommand pixelBlocksCommand = new PixelBlocksCommand();
Objects.requireNonNull(getCommand("givepixelblock")).setExecutor(new GivePixelBlockCommand()); PluginCommand rootCommand = Objects.requireNonNull(getCommand("pixelblocks"));
Objects.requireNonNull(getCommand("exitworld")).setExecutor(new ExitWorldCommand()); rootCommand.setExecutor(pixelBlocksCommand);
Objects.requireNonNull(getCommand("destroypixelblocks")).setExecutor(new DestroyPixelBlocksCommand()); rootCommand.setTabCompleter(pixelBlocksCommand);
Bukkit.addRecipe(PixelBlockItem.getRecipe()); Bukkit.addRecipe(PixelBlockItem.getRecipe());
} }
@@ -94,11 +93,9 @@ public final class Main extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
Bukkit.getOnlinePlayers().forEach(QuitWhileInPixelBlockListener::kickPlayerOutOfWorld); Bukkit.getOnlinePlayers().forEach(QuitWhileInPixelBlockListener::kickPlayerOutOfWorld);
try { taskFactory.shutdown(5, TimeUnit.SECONDS);
database.close(); database.close();
} catch(SQLException e) { Translations.unregister();
throw new RuntimeException("Failed disabling", e);
}
} }
public static Main plugin() { public static Main plugin() {
@@ -9,9 +9,9 @@ public record PixelBlockConfiguration(
boolean onlyEditableByOwner boolean onlyEditableByOwner
) { ) {
public static void setDefaults(FileConfiguration config) { public static void setDefaults(FileConfiguration config) {
config.addDefault(Keys.PixelsPerBlock.key, 16); config.addDefault(Keys.PixelsPerBlock.getKey(), 16);
config.addDefault(Keys.OnlyBreakableByOwners.key, false); config.addDefault(Keys.OnlyBreakableByOwners.getKey(), false);
config.addDefault(Keys.OnlyEditableByOwners.key, true); config.addDefault(Keys.OnlyEditableByOwners.getKey(), true);
config.options().copyDefaults(true); config.options().copyDefaults(true);
} }
@@ -7,14 +7,38 @@ import org.bukkit.Location;
import java.sql.*; import java.sql.*;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public class PixelBlockDatabase { public class PixelBlockDatabase {
private final Connection db; private final Connection db;
// Alle Statement-Zugriffe nach dem Startup laufen ausschließlich auf diesem Thread,
// da die geteilten PreparedStatements nicht threadsicher sind.
private final ExecutorService executor =
Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "PixelBlocks-Database"));
private final PreparedStatement getAllPixelBlocks; private final PreparedStatement getAllPixelBlocks;
private final PreparedStatement deletePixelBlock; private final PreparedStatement deletePixelBlock;
private final PreparedStatement insertOrReplacePixelBlock; private final PreparedStatement insertOrReplacePixelBlock;
private record PixelBlockRow(
String uuid,
String owner,
String worldName,
double x,
double y,
double z,
String entryWorldName,
double entryX,
double entryY,
double entryZ,
String direction
) {
}
public PixelBlockDatabase(String url) { public PixelBlockDatabase(String url) {
try { try {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
@@ -50,52 +74,78 @@ public class PixelBlockDatabase {
} }
} }
public void close() throws SQLException { public void close() {
deletePixelBlock.close(); this.executor.shutdown();
getAllPixelBlocks.close(); try {
insertOrReplacePixelBlock.close(); if(!this.executor.awaitTermination(10, TimeUnit.SECONDS)) {
db.close(); Main.logger().warning("Database executor did not terminate in time, forcing shutdown");
this.executor.shutdownNow();
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
this.executor.shutdownNow();
}
try {
this.deletePixelBlock.close();
this.getAllPixelBlocks.close();
this.insertOrReplacePixelBlock.close();
this.db.close();
} catch(SQLException e) {
Main.logger().log(Level.SEVERE, "Failed closing the database", e);
}
} }
public void deletePixelBlock(PixelBlock pixelBlock) { public void deletePixelBlock(PixelBlock pixelBlock) {
Bukkit.getScheduler().runTaskAsynchronously(Main.plugin(), () -> { String uuid = pixelBlock.getBlockUUID().toString();
this.executor.execute(() -> {
try { try {
this.deletePixelBlock.setString(1, pixelBlock.getBlockUUID().toString()); this.deletePixelBlock.setString(1, uuid);
this.deletePixelBlock.executeUpdate(); this.deletePixelBlock.executeUpdate();
} catch(SQLException e) { } catch(SQLException e) {
throw new RuntimeException("Failed to delete PixelBlock from the database", e); Main.logger().log(Level.SEVERE, String.format("Failed to delete PixelBlock '%s' from the database", uuid), e);
} }
}); });
} }
public void savePixelBlock(PixelBlock pixelBlock) { public void savePixelBlock(PixelBlock pixelBlock) {
Bukkit.getScheduler().runTask(Main.plugin(), () -> { Location blockLocation = pixelBlock.getPixelBlockLocation();
Location entryLocation = pixelBlock.hasLastEntryLocation() ? pixelBlock.getLastEntryLocation() : blockLocation;
PixelBlockRow row = new PixelBlockRow(
pixelBlock.getBlockUUID().toString(),
pixelBlock.getOwnerUUID().toString(),
blockLocation.getWorld().getName(),
blockLocation.getX(),
blockLocation.getY(),
blockLocation.getZ(),
entryLocation.getWorld().getName(),
entryLocation.getX(),
entryLocation.getY(),
entryLocation.getZ(),
pixelBlock.getFacingDirection().toString()
);
this.executor.execute(() -> {
try { try {
this.insertOrReplacePixelBlock.setString(1, pixelBlock.getBlockUUID().toString()); this.insertOrReplacePixelBlock.setString(1, row.uuid());
this.insertOrReplacePixelBlock.setString(2, pixelBlock.getOwnerUUID().toString()); this.insertOrReplacePixelBlock.setString(2, row.owner());
this.insertOrReplacePixelBlock.setString(3, pixelBlock.getPixelBlockLocation().getWorld().getName()); this.insertOrReplacePixelBlock.setString(3, row.worldName());
this.insertOrReplacePixelBlock.setDouble(4, pixelBlock.getPixelBlockLocation().getX()); this.insertOrReplacePixelBlock.setDouble(4, row.x());
this.insertOrReplacePixelBlock.setDouble(5, pixelBlock.getPixelBlockLocation().getY()); this.insertOrReplacePixelBlock.setDouble(5, row.y());
this.insertOrReplacePixelBlock.setDouble(6, pixelBlock.getPixelBlockLocation().getZ()); this.insertOrReplacePixelBlock.setDouble(6, row.z());
if(pixelBlock.hasLastEntryLocation()) { this.insertOrReplacePixelBlock.setString(7, row.entryWorldName());
this.insertOrReplacePixelBlock.setString(7, pixelBlock.getLastEntryLocation().getWorld().getName()); this.insertOrReplacePixelBlock.setDouble(8, row.entryX());
this.insertOrReplacePixelBlock.setDouble(8, pixelBlock.getLastEntryLocation().getX()); this.insertOrReplacePixelBlock.setDouble(9, row.entryY());
this.insertOrReplacePixelBlock.setDouble(9, pixelBlock.getLastEntryLocation().getY()); this.insertOrReplacePixelBlock.setDouble(10, row.entryZ());
this.insertOrReplacePixelBlock.setDouble(10, pixelBlock.getLastEntryLocation().getZ());
} else {
this.insertOrReplacePixelBlock.setString(7, pixelBlock.getPixelBlockLocation().getWorld().getName());
this.insertOrReplacePixelBlock.setDouble(8, pixelBlock.getPixelBlockLocation().getX());
this.insertOrReplacePixelBlock.setDouble(9, pixelBlock.getPixelBlockLocation().getY());
this.insertOrReplacePixelBlock.setDouble(10, pixelBlock.getPixelBlockLocation().getZ());
}
this.insertOrReplacePixelBlock.setString(11, pixelBlock.getFacingDirection().toString()); this.insertOrReplacePixelBlock.setString(11, row.direction());
this.insertOrReplacePixelBlock.executeUpdate(); this.insertOrReplacePixelBlock.executeUpdate();
} catch(SQLException e) { } catch(SQLException e) {
throw new RuntimeException("Failed to create or update PixelBlock in the database", e); Main.logger().log(Level.SEVERE, String.format("Failed to create or update PixelBlock '%s' in the database", row.uuid()), e);
} }
}); });
} }
@@ -105,6 +155,8 @@ public class PixelBlockDatabase {
ResultSet allPixelBlocks = this.getAllPixelBlocks.executeQuery(); ResultSet allPixelBlocks = this.getAllPixelBlocks.executeQuery();
while(allPixelBlocks.next()) { while(allPixelBlocks.next()) {
String uuid = allPixelBlocks.getString("uuid");
try {
Location blockLocation = new Location( Location blockLocation = new Location(
Bukkit.getWorld(allPixelBlocks.getString("locationWorldName")), Bukkit.getWorld(allPixelBlocks.getString("locationWorldName")),
allPixelBlocks.getDouble("locationX"), allPixelBlocks.getDouble("locationX"),
@@ -120,12 +172,15 @@ public class PixelBlockDatabase {
); );
Main.pixelBlocks.add(PixelBlock.fromExisting( Main.pixelBlocks.add(PixelBlock.fromExisting(
UUID.fromString(allPixelBlocks.getString("uuid")), UUID.fromString(uuid),
UUID.fromString(allPixelBlocks.getString("owner")), UUID.fromString(allPixelBlocks.getString("owner")),
blockLocation, blockLocation,
Direction.valueOf(allPixelBlocks.getString("direction")), Direction.valueOf(allPixelBlocks.getString("direction")),
entryLocation entryLocation
)); ));
} catch(Exception e) {
Main.logger().log(Level.SEVERE, String.format("Failed initializing existing pixelblock '%s'", uuid), e);
}
} }
} catch(SQLException e) { } catch(SQLException e) {
throw new RuntimeException("Failed loading PixelBlocks from the database", e); throw new RuntimeException("Failed loading PixelBlocks from the database", e);
@@ -17,6 +17,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -36,6 +37,12 @@ public class PixelBlockItem {
} }
} }
public static void setBlockId(@NotNull ItemStack item, @NotNull UUID id) {
ItemMeta meta = item.getItemMeta();
meta.getPersistentDataContainer().set(idProperty, PersistentDataType.STRING, id.toString());
item.setItemMeta(meta);
}
public static @Nullable BlockInfo getBlockInfo(ItemStack item) { public static @Nullable BlockInfo getBlockInfo(ItemStack item) {
PersistentDataContainer container = item.getItemMeta().getPersistentDataContainer(); PersistentDataContainer container = item.getItemMeta().getPersistentDataContainer();
if(!container.has(idProperty)) return null; if(!container.has(idProperty)) return null;
@@ -46,7 +53,7 @@ public class PixelBlockItem {
return new BlockInfo(blockId, ownerId); return new BlockInfo(blockId, ownerId);
} }
public static @NotNull ItemStack getBlockAsItem(@NotNull PixelBlock block) { public static @NotNull ItemStack getBlockAsItem(@NotNull PixelBlock block, @NotNull Locale locale) {
String ownerName = Optional.ofNullable(Bukkit.getOfflinePlayer(block.getOwnerUUID()).getName()).orElseGet(() -> block.getOwnerUUID().toString()); String ownerName = Optional.ofNullable(Bukkit.getOfflinePlayer(block.getOwnerUUID()).getName()).orElseGet(() -> block.getOwnerUUID().toString());
ItemStack itemStack = HeadUtil.getCustomTextureHead(itemTexture); ItemStack itemStack = HeadUtil.getCustomTextureHead(itemTexture);
@@ -54,10 +61,10 @@ public class PixelBlockItem {
meta.setMaxStackSize(1); meta.setMaxStackSize(1);
meta.getPersistentDataContainer().set(idProperty, PersistentDataType.STRING, block.getBlockUUID().toString()); meta.getPersistentDataContainer().set(idProperty, PersistentDataType.STRING, block.getBlockUUID().toString());
meta.getPersistentDataContainer().set(ownerProperty, PersistentDataType.STRING, block.getOwnerUUID().toString()); meta.getPersistentDataContainer().set(ownerProperty, PersistentDataType.STRING, block.getOwnerUUID().toString());
meta.displayName(Component.text("Pixelblock von " + ownerName)); meta.displayName(Translations.render(Component.translatable("pixelblocks.item.name.owned", Component.text(ownerName)), locale));
meta.lore(List.of( meta.lore(List.of(
Component.text(ownerName + " ist der Besitzer dieses Blocks."), Translations.render(Component.translatable("pixelblocks.item.lore.owner", Component.text(ownerName)), locale),
Component.text("Klicke auf den gesetzten Block, um diesen zu bearbeiten!"), Translations.render(Component.translatable("pixelblocks.item.lore.edit-hint"), locale),
Component.text(block.getBlockUUID().toString()).color(NamedTextColor.DARK_GRAY) Component.text(block.getBlockUUID().toString()).color(NamedTextColor.DARK_GRAY)
)); ));
itemStack.setItemMeta(meta); itemStack.setItemMeta(meta);
@@ -66,14 +73,17 @@ public class PixelBlockItem {
} }
public static @NotNull ItemStack getEmptyPixelBlock() { public static @NotNull ItemStack getEmptyPixelBlock() {
return getEmptyPixelBlock(Translations.defaultLocale);
}
public static @NotNull ItemStack getEmptyPixelBlock(@NotNull Locale locale) {
ItemStack item = HeadUtil.getCustomTextureHead(itemTexture); ItemStack item = HeadUtil.getCustomTextureHead(itemTexture);
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setMaxStackSize(1); meta.setMaxStackSize(1);
meta.itemName(Component.text(emptyBlockUUID.toString())); meta.displayName(Translations.render(Component.translatable("pixelblocks.item.name.empty"), locale));
meta.displayName(Component.text("Leerer Pixelblock"));
meta.lore(List.of( meta.lore(List.of(
Component.text("Der erste Spieler, der den Block platziert wird zum Besitzer des Blocks."), Translations.render(Component.translatable("pixelblocks.item.lore.first-placer"), locale),
Component.text("Klicke auf den gesetzten Block, um diesen zu bearbeiten!") Translations.render(Component.translatable("pixelblocks.item.lore.edit-hint"), locale)
)); ));
meta.getPersistentDataContainer().set(idProperty, PersistentDataType.STRING, emptyBlockUUID.toString()); meta.getPersistentDataContainer().set(idProperty, PersistentDataType.STRING, emptyBlockUUID.toString());
item.setItemMeta(meta); item.setItemMeta(meta);
@@ -0,0 +1,39 @@
package eu.mhsl.minecraft.pixelblocks;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.translation.GlobalTranslator;
import net.kyori.adventure.translation.TranslationStore;
import org.jetbrains.annotations.NotNull;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class Translations {
public static final Locale defaultLocale = Locale.ENGLISH;
private static final List<Locale> supportedLocales = List.of(Locale.ENGLISH, Locale.GERMAN);
private static TranslationStore.StringBased<MessageFormat> store;
public static void register() {
store = TranslationStore.messageFormat(Key.key("pixelblocks", "translations"));
store.defaultLocale(defaultLocale);
for(Locale locale : supportedLocales) {
ResourceBundle bundle = ResourceBundle.getBundle("i18n.messages", locale, Translations.class.getClassLoader());
store.registerAll(locale, bundle, true);
}
GlobalTranslator.translator().addSource(store);
}
public static void unregister() {
if(store != null) GlobalTranslator.translator().removeSource(store);
}
// Für Texte, die persistiert werden (z. B. Item-Namen) und daher nicht
// automatisch pro Empfänger übersetzt werden können
public static @NotNull Component render(@NotNull Component component, @NotNull Locale locale) {
return GlobalTranslator.render(component, locale);
}
}
@@ -1,36 +0,0 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlockWorld;
import eu.mhsl.minecraft.pixelblocks.utils.Direction;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class CreatePixelBlockCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(sender instanceof Player p) {
World playerWorld = p.getWorld();
if(PixelBlockWorld.getPixelBlockWorlds().contains(playerWorld)) {
p.sendMessage("Pixelblöcke können nicht innerhalb anderen Pixelblöcken erstellt werden.");
return true;
}
Location playerLocation = p.getLocation();
PixelBlock.createPixelBlock(
UUID.randomUUID(),
p.getUniqueId(),
playerLocation.toBlockLocation(),
Direction.south
);
}
return true;
}
}
@@ -0,0 +1,32 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlockWorld;
import eu.mhsl.minecraft.pixelblocks.utils.Direction;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public class CreateSubCommand extends SubCommand {
public CreateSubCommand() {
super("create", "pixelblocks.command.create", "pixelblocks.command.create.description");
}
@Override
public void execute(@NotNull Player player, @NotNull String[] args) {
if(PixelBlockWorld.isPixelWorld(player.getWorld())) {
player.sendMessage(Component.translatable("pixelblocks.error.create-inside").color(NamedTextColor.RED));
return;
}
PixelBlock.createPixelBlock(
UUID.randomUUID(),
player.getUniqueId(),
player.getLocation().toBlockLocation(),
Direction.south
);
}
}
@@ -0,0 +1,23 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.Main;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class DestroyAllSubCommand extends SubCommand {
public DestroyAllSubCommand() {
super("destroyall", "pixelblocks.command.destroyall", "pixelblocks.command.destroyall.description");
}
@Override
public void execute(@NotNull Player player, @NotNull String[] args) {
List<PixelBlock> blocksToDestroy = List.copyOf(Main.pixelBlocks);
blocksToDestroy.forEach(pixelBlock -> pixelBlock.destroy(player, true));
player.sendMessage(Component.translatable("pixelblocks.command.destroyall.success", Component.text(blocksToDestroy.size())).color(NamedTextColor.GREEN));
}
}
@@ -1,19 +0,0 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.Main;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class DestroyPixelBlocksCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(sender instanceof Player p) {
Main.pixelBlocks.forEach(pixelBlock -> pixelBlock.destroy(Bukkit.getPlayer(pixelBlock.getOwnerUUID())));
}
return true;
}
}
@@ -0,0 +1,30 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlockWorld;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class ExitSubCommand extends SubCommand {
public ExitSubCommand() {
super("exit", "pixelblocks.command.exit", "pixelblocks.command.exit.description");
}
@Override
public void execute(@NotNull Player player, @NotNull String[] args) {
if(!PixelBlockWorld.isPixelWorld(player.getWorld())) {
player.sendMessage(Component.translatable("pixelblocks.error.not-in-pixelblock").color(NamedTextColor.RED));
return;
}
PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(player.getWorld());
if(pixelBlock == null) {
player.sendMessage(Component.translatable("pixelblocks.error.block-not-found").color(NamedTextColor.RED));
return;
}
pixelBlock.exitBlock(player);
}
}
@@ -1,30 +0,0 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlockWorld;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
public class ExitWorldCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(sender instanceof Player p) {
World playerWorld = p.getWorld();
if(PixelBlockWorld.getOtherWorlds().contains(playerWorld)) {
p.sendMessage("Du kannst nur Pixelblöcke verlassen.");
return true;
}
PixelBlock currentPixelBlock = PixelBlock.getPixelBlockFromBlockWorld(playerWorld);
Objects.requireNonNull(currentPixelBlock);
currentPixelBlock.exitBlock(p);
}
return true;
}
}
@@ -1,40 +0,0 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.PixelBlockItem;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import java.util.UUID;
import static eu.mhsl.minecraft.pixelblocks.PixelBlockItem.getEmptyPixelBlock;
public class GivePixelBlockCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(sender instanceof Player p) {
ItemStack result = getEmptyPixelBlock();
ItemMeta itemMeta = result.getItemMeta();
PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer();
if(!dataContainer.has(PixelBlockItem.idProperty)) return false;
String currentId = dataContainer.get(PixelBlockItem.idProperty, PersistentDataType.STRING);
Objects.requireNonNull(currentId);
if(!UUID.fromString(currentId).equals(PixelBlockItem.emptyBlockUUID)) return false;
dataContainer.set(PixelBlockItem.idProperty, PersistentDataType.STRING, args[0]);
result.setItemMeta(itemMeta);
p.getInventory().addItem(result);
}
return true;
}
}
@@ -0,0 +1,44 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import eu.mhsl.minecraft.pixelblocks.PixelBlockItem;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.UUID;
public class GiveSubCommand extends SubCommand {
public GiveSubCommand() {
super("give", "pixelblocks.command.give", "pixelblocks.command.give.description");
}
@Override
public void execute(@NotNull Player player, @NotNull String[] args) {
UUID blockId;
if(args.length == 0) {
blockId = UUID.randomUUID();
} else {
try {
blockId = UUID.fromString(args[0]);
} catch(IllegalArgumentException e) {
player.sendMessage(Component.translatable("pixelblocks.error.invalid-uuid", Component.text(args[0])).color(NamedTextColor.RED));
return;
}
}
ItemStack item = PixelBlockItem.getEmptyPixelBlock(player.locale());
PixelBlockItem.setBlockId(item, blockId);
player.getInventory().addItem(item);
player.sendMessage(Component.translatable("pixelblocks.command.give.success", Component.text(blockId.toString())).color(NamedTextColor.GREEN));
}
@Override
public @NotNull List<String> tabComplete(@NotNull Player player, @NotNull String[] args) {
if(args.length == 1) return List.of("<uuid>");
return List.of();
}
}
@@ -0,0 +1,80 @@
package eu.mhsl.minecraft.pixelblocks.commands;
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.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class PixelBlocksCommand implements CommandExecutor, TabCompleter {
private final List<SubCommand> subCommands = List.of(
new CreateSubCommand(),
new GiveSubCommand(),
new ExitSubCommand(),
new DestroyAllSubCommand()
);
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(!(sender instanceof Player player)) {
sender.sendMessage(Component.translatable("pixelblocks.command.players-only").color(NamedTextColor.RED));
return true;
}
Optional<SubCommand> subCommand = args.length == 0
? Optional.empty()
: this.subCommands.stream().filter(sub -> sub.name().equalsIgnoreCase(args[0])).findFirst();
if(subCommand.isEmpty()) {
this.sendUsage(player);
return true;
}
if(!player.hasPermission(subCommand.get().permission())) {
player.sendMessage(Component.translatable("pixelblocks.command.no-permission").color(NamedTextColor.RED));
return true;
}
subCommand.get().execute(player, Arrays.copyOfRange(args, 1, args.length));
return true;
}
@Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if(!(sender instanceof Player player)) return List.of();
if(args.length == 1) {
return this.subCommands.stream()
.filter(sub -> player.hasPermission(sub.permission()))
.map(SubCommand::name)
.filter(name -> name.startsWith(args[0].toLowerCase()))
.toList();
}
return this.subCommands.stream()
.filter(sub -> sub.name().equalsIgnoreCase(args[0]))
.filter(sub -> player.hasPermission(sub.permission()))
.findFirst()
.map(sub -> sub.tabComplete(player, Arrays.copyOfRange(args, 1, args.length)))
.orElse(List.of());
}
private void sendUsage(@NotNull Player player) {
player.sendMessage(Component.translatable("pixelblocks.command.usage.header").color(NamedTextColor.GOLD));
this.subCommands.stream()
.filter(sub -> player.hasPermission(sub.permission()))
.forEach(sub -> player.sendMessage(Component.text()
.append(Component.text("/pixelblocks " + sub.name(), NamedTextColor.YELLOW))
.append(Component.text(" - ", NamedTextColor.GRAY))
.append(Component.translatable(sub.descriptionKey()).color(NamedTextColor.GRAY))
.build()));
}
}
@@ -0,0 +1,36 @@
package eu.mhsl.minecraft.pixelblocks.commands;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public abstract class SubCommand {
private final String name;
private final String permission;
private final String descriptionKey;
protected SubCommand(@NotNull String name, @NotNull String permission, @NotNull String descriptionKey) {
this.name = name;
this.permission = permission;
this.descriptionKey = descriptionKey;
}
public final @NotNull String name() {
return name;
}
public final @NotNull String permission() {
return permission;
}
public final @NotNull String descriptionKey() {
return descriptionKey;
}
public abstract void execute(@NotNull Player player, @NotNull String[] args);
public @NotNull List<String> tabComplete(@NotNull Player player, @NotNull String[] args) {
return List.of();
}
}
@@ -15,6 +15,6 @@ public class BreakPixelBlockListener implements Listener {
Location blockLocation = event.getAttacked().getLocation().toBlockLocation(); Location blockLocation = event.getAttacked().getLocation().toBlockLocation();
PixelBlock pixelBlock = PixelBlock.getPixelBlockFromPlacedLocation(blockLocation); PixelBlock pixelBlock = PixelBlock.getPixelBlockFromPlacedLocation(blockLocation);
if(pixelBlock == null) return; if(pixelBlock == null) return;
pixelBlock.destroy(event.getPlayer()); pixelBlock.destroy(event.getPlayer(), false);
} }
} }
@@ -1,15 +1,14 @@
package eu.mhsl.minecraft.pixelblocks.listeners; package eu.mhsl.minecraft.pixelblocks.listeners;
import eu.mhsl.minecraft.pixelblocks.PixelBlockItem; import eu.mhsl.minecraft.pixelblocks.PixelBlockItem;
import eu.mhsl.minecraft.pixelblocks.Translations;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import java.util.Objects; import java.util.Locale;
import java.util.UUID; import java.util.UUID;
public class CraftPixelBlockListener implements Listener { public class CraftPixelBlockListener implements Listener {
@@ -17,14 +16,13 @@ public class CraftPixelBlockListener implements Listener {
public void onCraft(CraftItemEvent event) { public void onCraft(CraftItemEvent event) {
ItemStack result = event.getInventory().getResult(); ItemStack result = event.getInventory().getResult();
if(result == null) return; if(result == null) return;
ItemMeta itemMeta = result.getItemMeta();
PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer();
if(!dataContainer.has(PixelBlockItem.idProperty)) return;
String currentId = dataContainer.get(PixelBlockItem.idProperty, PersistentDataType.STRING);
Objects.requireNonNull(currentId);
if(!UUID.fromString(currentId).equals(PixelBlockItem.emptyBlockUUID)) return;
dataContainer.set(PixelBlockItem.idProperty, PersistentDataType.STRING, UUID.randomUUID().toString()); PixelBlockItem.BlockInfo info = PixelBlockItem.getBlockInfo(result);
result.setItemMeta(itemMeta); if(info == null || !info.id().equals(PixelBlockItem.emptyBlockUUID)) return;
Locale locale = event.getWhoClicked() instanceof Player player ? player.locale() : Translations.defaultLocale;
ItemStack localizedResult = PixelBlockItem.getEmptyPixelBlock(locale);
PixelBlockItem.setBlockId(localizedResult, UUID.randomUUID());
event.getInventory().setResult(localizedResult);
} }
} }
@@ -20,7 +20,7 @@ public class DiscoverRecipesListener implements Listener {
if(!(event.getWhoClicked() instanceof Player player)) return; if(!(event.getWhoClicked() instanceof Player player)) return;
if(!List.of(Material.HEART_OF_THE_SEA, Material.END_CRYSTAL).contains(clickedItem.getType())) return; if(!List.of(Material.HEART_OF_THE_SEA, Material.END_CRYSTAL).contains(clickedItem.getType())) return;
if(player.hasDiscoveredRecipe(PixelBlockItem.recipeKey)) return; if(player.hasDiscoveredRecipe(PixelBlockItem.recipeKey)) return;
Main.logger().log(Level.INFO, String.format("%s unlocked tne PixelBlock recipe!", player.getName())); Main.logger().log(Level.INFO, String.format("%s unlocked the PixelBlock recipe!", player.getName()));
player.discoverRecipe(PixelBlockItem.recipeKey); player.discoverRecipe(PixelBlockItem.recipeKey);
} }
} }
@@ -1,5 +1,6 @@
package eu.mhsl.minecraft.pixelblocks.listeners; package eu.mhsl.minecraft.pixelblocks.listeners;
import eu.mhsl.minecraft.pixelblocks.Main;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock; import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlockWorld; import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlockWorld;
import org.bukkit.World; import org.bukkit.World;
@@ -8,7 +9,6 @@ import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.player.PlayerPortalEvent; import org.bukkit.event.player.PlayerPortalEvent;
import java.util.Objects;
public class ExitPixelWorldListener implements Listener { public class ExitPixelWorldListener implements Listener {
@EventHandler @EventHandler
@@ -18,7 +18,10 @@ public class ExitPixelWorldListener implements Listener {
event.setCancelled(true); event.setCancelled(true);
PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(pixelBlockWorld); PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(pixelBlockWorld);
Objects.requireNonNull(pixelBlock); if(pixelBlock == null) {
Main.logger().warning("Player used a portal in an unknown pixel world: " + pixelBlockWorld.getName());
return;
}
pixelBlock.exitBlock(event.getPlayer()); pixelBlock.exitBlock(event.getPlayer());
} }
@@ -7,7 +7,6 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
import java.util.Objects;
public class FallOutOfPixelBlockListener implements Listener { public class FallOutOfPixelBlockListener implements Listener {
@EventHandler @EventHandler
@@ -17,7 +16,7 @@ public class FallOutOfPixelBlockListener implements Listener {
if(!PixelBlockWorld.isPixelWorld(player.getWorld())) return; if(!PixelBlockWorld.isPixelWorld(player.getWorld())) return;
PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(player.getWorld()); PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(player.getWorld());
Objects.requireNonNull(pixelBlock); if(pixelBlock == null) return;
player.teleport(pixelBlock.getPixelWorld().getSpawnLocation()); player.teleport(pixelBlock.getPixelWorld().getSpawnLocation());
} }
} }
@@ -24,7 +24,13 @@ public class PlacePixelBlockListener implements Listener {
World playerWorld = event.getPlayer().getWorld(); World playerWorld = event.getPlayer().getWorld();
if(PixelBlockWorld.isPixelWorld(playerWorld)) { if(PixelBlockWorld.isPixelWorld(playerWorld)) {
event.getPlayer().sendMessage(Component.text("In Pixelblöcken kann kein Pixelblock platziert werden.", NamedTextColor.RED)); event.getPlayer().sendMessage(Component.translatable("pixelblocks.error.place-inside").color(NamedTextColor.RED));
event.setCancelled(true);
return;
}
if(PixelBlock.exists(info.id())) {
event.getPlayer().sendMessage(Component.translatable("pixelblocks.error.already-exists").color(NamedTextColor.RED));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@@ -17,7 +17,7 @@ public class PlacePixelListener implements Listener {
} }
@EventHandler @EventHandler
public void onBuketEmpty(PlayerBucketEmptyEvent event) { public void onBucketEmpty(PlayerBucketEmptyEvent event) {
EventCanceling.shouldCancelInPixelBlock( EventCanceling.shouldCancelInPixelBlock(
event, event,
event.getBlock().getWorld(), event.getBlock().getWorld(),
@@ -10,7 +10,7 @@ import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
public class PreventInventorysListener implements Listener { public class PreventInventoriesListener implements Listener {
@EventHandler @EventHandler
public void onInventoryOpen(InventoryOpenEvent event) { public void onInventoryOpen(InventoryOpenEvent event) {
EventCanceling.shouldCancelInPixelBlock( EventCanceling.shouldCancelInPixelBlock(
@@ -8,7 +8,6 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import java.util.Objects;
public class QuitWhileInPixelBlockListener implements Listener { public class QuitWhileInPixelBlockListener implements Listener {
@EventHandler @EventHandler
@@ -20,7 +19,7 @@ public class QuitWhileInPixelBlockListener implements Listener {
World pixelBlockWorld = player.getLocation().getWorld(); World pixelBlockWorld = player.getLocation().getWorld();
if(!PixelBlockWorld.isPixelWorld(pixelBlockWorld)) return; if(!PixelBlockWorld.isPixelWorld(pixelBlockWorld)) return;
PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(pixelBlockWorld); PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(pixelBlockWorld);
Objects.requireNonNull(pixelBlock); if(pixelBlock == null) return;
pixelBlock.exitBlock(player); pixelBlock.exitBlock(player);
} }
} }
@@ -14,8 +14,8 @@ import org.bukkit.entity.Item;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nullable;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -38,18 +38,16 @@ public class PixelBlock {
private final UUID blockUUID; private final UUID blockUUID;
public static @Nullable PixelBlock getPixelBlockFromBlockWorld(World world) { public static @Nullable PixelBlock getPixelBlockFromBlockWorld(World world) {
UUID worldUUID = PixelBlockWorld.getUUIDFromWorld(world);
if(worldUUID == null) return null;
return Main.pixelBlocks.stream() return Main.pixelBlocks.stream()
.filter(block -> block.blockUUID.equals(getUUIDFromWorld(world))) .filter(block -> block.blockUUID.equals(worldUUID))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
} }
public static @Nullable UUID getUUIDFromWorld(@NotNull World world) { public static boolean exists(@NotNull UUID blockUUID) {
try { return Main.pixelBlocks.stream().anyMatch(pixelBlock -> pixelBlock.blockUUID.equals(blockUUID));
return UUID.fromString(List.of(world.getName().split("/")).getLast());
} catch(IllegalArgumentException e) {
return null;
}
} }
public static @Nullable PixelBlock getPixelBlockFromPlacedLocation(@NotNull Location placedLocation) { public static @Nullable PixelBlock getPixelBlockFromPlacedLocation(@NotNull Location placedLocation) {
@@ -76,7 +74,6 @@ public class PixelBlock {
this.facingDirection = direction; this.facingDirection = direction;
this.lastEntryLocation = lastEntryLocation; this.lastEntryLocation = lastEntryLocation;
try {
this.pixelWorld = new PixelBlockWorld(this); this.pixelWorld = new PixelBlockWorld(this);
this.pixelData = this.pixelWorld.getPixels(this.facingDirection); this.pixelData = this.pixelWorld.getPixels(this.facingDirection);
this.pixels = new Pixels(this); this.pixels = new Pixels(this);
@@ -86,9 +83,6 @@ public class PixelBlock {
this.getBlockTaskChain().sync(() -> this.isAccessible = true).execute(); this.getBlockTaskChain().sync(() -> this.isAccessible = true).execute();
Main.logger().info(String.format("Loaded existing pixelblock '%s'", this.blockUUID)); Main.logger().info(String.format("Loaded existing pixelblock '%s'", this.blockUUID));
} catch(Exception e) {
Main.logger().info(String.format("Failed initializing existing pixelblock '%s': %s", this.blockUUID, e.getMessage()));
}
} }
public static PixelBlock createPixelBlock(UUID blockUUID, UUID ownerUUID, Location pixelBlockLocation, Direction direction) { public static PixelBlock createPixelBlock(UUID blockUUID, UUID ownerUUID, Location pixelBlockLocation, Direction direction) {
@@ -96,8 +90,8 @@ public class PixelBlock {
} }
private PixelBlock(UUID blockUUID, UUID ownerUUID, Location pixelBlockLocation, Direction direction) { private PixelBlock(UUID blockUUID, UUID ownerUUID, Location pixelBlockLocation, Direction direction) {
if(Main.pixelBlocks.stream().anyMatch(pixelBlock -> pixelBlock.getBlockUUID().equals(blockUUID))) if(exists(blockUUID))
throw new IllegalStateException(String.format("PixelBlock '%s' ist bereits in der Welt vorhanden!", blockUUID)); throw new IllegalStateException(String.format("PixelBlock '%s' already exists in the world!", blockUUID));
this.blockUUID = blockUUID; this.blockUUID = blockUUID;
this.ownerUUID = ownerUUID; this.ownerUUID = ownerUUID;
@@ -118,12 +112,8 @@ public class PixelBlock {
this.scheduleEntityUpdate(); this.scheduleEntityUpdate();
this.getBlockTaskChain()
.async(() -> {
Main.database().savePixelBlock(this); Main.database().savePixelBlock(this);
Main.pixelBlocks.add(this); Main.pixelBlocks.add(this);
})
.execute();
this.getBlockTaskChain().sync(() -> this.isAccessible = true).execute(); this.getBlockTaskChain().sync(() -> this.isAccessible = true).execute();
} }
@@ -134,14 +124,14 @@ public class PixelBlock {
public void enterBlock(@NotNull Player player) { public void enterBlock(@NotNull Player player) {
if(Main.configuration().onlyEditableByOwner() && !player.getUniqueId().equals(ownerUUID)) { if(Main.configuration().onlyEditableByOwner() && !player.getUniqueId().equals(ownerUUID)) {
player.sendMessage(Component.text("Dieser Pixelblock gehört nicht dir!", NamedTextColor.RED)); player.sendMessage(Component.translatable("pixelblocks.error.not-owner").color(NamedTextColor.RED));
return; return;
} }
this.lastEntryLocation = player.getLocation(); this.lastEntryLocation = player.getLocation();
Main.database().savePixelBlock(this);
getBlockTaskChain() getBlockTaskChain()
.async(() -> Main.database().savePixelBlock(this))
.sync(() -> { .sync(() -> {
if(!this.isAccessible) return; if(!this.isAccessible) return;
player.teleport(this.pixelWorld.getSpawnLocation()); player.teleport(this.pixelWorld.getSpawnLocation());
@@ -153,7 +143,7 @@ public class PixelBlock {
public void exitBlock(@NotNull Player player) { public void exitBlock(@NotNull Player player) {
this.getBlockTaskChain() this.getBlockTaskChain()
.sync(() -> player.teleport(this.lastEntryLocation != null ? this.lastEntryLocation : this.pixelBlockLocation)) .sync(() -> player.teleport(this.getReturnLocation()))
.sync(() -> this.pixelData = this.pixelWorld.getPixels(this.facingDirection)) .sync(() -> this.pixelData = this.pixelWorld.getPixels(this.facingDirection))
.current(() -> Main.logger().info(String.format("%s exited PixelBlock", player.getName()))) .current(() -> Main.logger().info(String.format("%s exited PixelBlock", player.getName())))
.delay(1) .delay(1)
@@ -178,16 +168,17 @@ public class PixelBlock {
.execute(); .execute();
} }
public void destroy(Player destroyedBy) { public void destroy(Player destroyedBy, boolean force) {
if(!this.isAccessible) return; if(!this.isAccessible) return;
if(Main.configuration().onlyBreakableByOwner() && !destroyedBy.getUniqueId().equals(ownerUUID)) { if(!force && Main.configuration().onlyBreakableByOwner() && !destroyedBy.getUniqueId().equals(ownerUUID)) {
destroyedBy.sendMessage("Dieser Pixelblock gehört nicht dir!"); destroyedBy.sendMessage(Component.translatable("pixelblocks.error.not-owner").color(NamedTextColor.RED));
return; return;
} }
Location returnLocation = this.getReturnLocation();
this.pixelWorld.getPlayersInWorld().forEach(p -> { this.pixelWorld.getPlayersInWorld().forEach(p -> {
p.sendMessage(Component.text("Der Pixelblock wurde von einem anderen Spieler abgebaut!", NamedTextColor.RED)); p.sendMessage(Component.translatable("pixelblocks.info.destroyed-by-other").color(NamedTextColor.RED));
p.teleport(this.lastEntryLocation); p.teleport(returnLocation);
}); });
Main.logger().info(String.format("Destroying PixelBlock '%s' at %s", this.blockUUID, pixelBlockLocation)); Main.logger().info(String.format("Destroying PixelBlock '%s' at %s", this.blockUUID, pixelBlockLocation));
@@ -195,20 +186,19 @@ public class PixelBlock {
this.pixelWorld.getEntitiesInWorld().stream() this.pixelWorld.getEntitiesInWorld().stream()
.filter(entity -> entity instanceof Item) .filter(entity -> entity instanceof Item)
.forEach(entity -> entity.teleport(this.lastEntryLocation)); .forEach(entity -> entity.teleport(returnLocation));
this.getBlockTaskChain() this.getBlockTaskChain()
.sync(() -> { .sync(() -> {
this.removeEntities(); this.removeEntities();
World world = this.pixelBlockLocation.getWorld(); World world = this.pixelBlockLocation.getWorld();
world.playSound(this.pixelBlockLocation, Sound.BLOCK_COPPER_BULB_BREAK, 1.0F, 30); world.playSound(this.pixelBlockLocation, Sound.BLOCK_COPPER_BULB_BREAK, 1.0F, 2.0F);
world.dropItem(this.pixelBlockLocation.add(new Vector(0.5, 0.5, 0.5)), PixelBlockItem.getBlockAsItem(this)); world.dropItem(this.getPixelBlockLocation().add(new Vector(0.5, 0.5, 0.5)), PixelBlockItem.getBlockAsItem(this, destroyedBy.locale()));
})
.async(() -> {
Main.database().deletePixelBlock(this);
Main.pixelBlocks.remove(this);
}) })
.execute(); .execute();
Main.database().deletePixelBlock(this);
Main.pixelBlocks.remove(this);
} }
private void removeEntities() { private void removeEntities() {
@@ -243,6 +233,12 @@ public class PixelBlock {
return this.lastEntryLocation != null; return this.lastEntryLocation != null;
} }
private @NotNull Location getReturnLocation() {
return this.hasLastEntryLocation()
? this.lastEntryLocation.clone()
: this.getPixelBlockLocation().add(0.5, 0, 0.5);
}
public List<PixelBlockWorld.PixelData> getPixelData() { public List<PixelBlockWorld.PixelData> getPixelData() {
return pixelData; return pixelData;
} }
@@ -1,16 +1,14 @@
package eu.mhsl.minecraft.pixelblocks.pixelblock; package eu.mhsl.minecraft.pixelblocks.pixelblock;
import eu.mhsl.minecraft.pixelblocks.Main; import eu.mhsl.minecraft.pixelblocks.Main;
import eu.mhsl.minecraft.pixelblocks.utils.EntityTagUtil;
import eu.mhsl.minecraft.pixelblocks.utils.MinMaxUtil; import eu.mhsl.minecraft.pixelblocks.utils.MinMaxUtil;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Interaction; import org.bukkit.entity.Interaction;
import org.bukkit.persistence.PersistentDataType;
import java.util.List; import java.util.List;
import java.util.Objects;
public class PixelBlockHitbox { public class PixelBlockHitbox {
private static final NamespacedKey hitboxOfTag = new NamespacedKey(Main.plugin(), "hitbox_of"); private static final NamespacedKey hitboxOfTag = new NamespacedKey(Main.plugin(), "hitbox_of");
@@ -29,7 +27,7 @@ public class PixelBlockHitbox {
Interaction interaction; Interaction interaction;
if (pixels.size() <= 5) { if (pixels.size() <= 5) {
interaction = (Interaction) absoluteLocation.getWorld().spawnEntity( interaction = (Interaction) absoluteLocation.getWorld().spawnEntity(
absoluteLocation.clone().add(0.5, -0, 0.5), absoluteLocation.clone().add(0.5, 0, 0.5),
EntityType.INTERACTION EntityType.INTERACTION
); );
interaction.setInteractionHeight(1); interaction.setInteractionHeight(1);
@@ -45,7 +43,7 @@ public class PixelBlockHitbox {
Location spawnLocation = absoluteLocation.clone().add( Location spawnLocation = absoluteLocation.clone().add(
((startingX+endingX)/2+0.5)/pixelsPerBlock, ((startingX+endingX)/2+0.5)/pixelsPerBlock,
(startingY/pixelsPerBlock)-0, startingY/pixelsPerBlock,
((startingZ+endingZ)/2+0.5)/pixelsPerBlock ((startingZ+endingZ)/2+0.5)/pixelsPerBlock
); );
@@ -81,19 +79,10 @@ public class PixelBlockHitbox {
interaction.setInteractionWidth(width); interaction.setInteractionWidth(width);
} }
interaction.getPersistentDataContainer() EntityTagUtil.tag(interaction, hitboxOfTag, this.parentBlock.getBlockUUID());
.set(hitboxOfTag, PersistentDataType.STRING, this.parentBlock.getBlockUUID().toString());
} }
public void destroy() { public void destroy() {
this.parentBlock.getPixelBlockLocation().getNearbyEntitiesByType(Interaction.class, 1) EntityTagUtil.removeTagged(this.parentBlock.getPixelBlockLocation(), Interaction.class, hitboxOfTag, this.parentBlock.getBlockUUID());
.stream()
.filter(interaction -> interaction.getPersistentDataContainer().has(hitboxOfTag))
.filter(interaction -> Objects.equals(
interaction.getPersistentDataContainer().get(hitboxOfTag, PersistentDataType.STRING),
parentBlock.getBlockUUID().toString()
))
.forEach(Entity::remove);
} }
} }
@@ -1,21 +1,18 @@
package eu.mhsl.minecraft.pixelblocks.pixelblock; package eu.mhsl.minecraft.pixelblocks.pixelblock;
import eu.mhsl.minecraft.pixelblocks.Main; import eu.mhsl.minecraft.pixelblocks.Main;
import eu.mhsl.minecraft.pixelblocks.utils.EntityTagUtil;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemDisplay; import org.bukkit.entity.ItemDisplay;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataHolder;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.util.Transformation; import org.bukkit.util.Transformation;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.UUID; import java.util.UUID;
public class PixelBlockPlaceholder { public class PixelBlockPlaceholder {
@@ -67,20 +64,10 @@ public class PixelBlockPlaceholder {
displayContainer.setItemStack(ItemStack.of(Material.WHITE_STAINED_GLASS)); displayContainer.setItemStack(ItemStack.of(Material.WHITE_STAINED_GLASS));
placeholders.add(displayContainer); placeholders.add(displayContainer);
placeholders.stream() placeholders.forEach(placeholder -> EntityTagUtil.tag(placeholder, placeholderOfTag, parentBlockUUID));
.map(PersistentDataHolder::getPersistentDataContainer)
.forEach(container -> container.set(placeholderOfTag, PersistentDataType.STRING, parentBlockUUID.toString()));
} }
public void destroy() { public void destroy() {
this.parentBlock.getPixelBlockLocation() EntityTagUtil.removeTagged(this.parentBlock.getPixelBlockLocation(), ItemDisplay.class, placeholderOfTag, this.parentBlock.getBlockUUID());
.getNearbyEntitiesByType(ItemDisplay.class, 1)
.stream()
.filter(itemDisplay -> itemDisplay.getPersistentDataContainer().has(placeholderOfTag))
.filter(itemDisplay -> Objects.equals(
itemDisplay.getPersistentDataContainer().get(placeholderOfTag, PersistentDataType.STRING),
parentBlock.getBlockUUID().toString()
))
.forEach(Entity::remove);
} }
} }
@@ -4,6 +4,7 @@ import eu.mhsl.minecraft.pixelblocks.Main;
import eu.mhsl.minecraft.pixelblocks.utils.Direction; import eu.mhsl.minecraft.pixelblocks.utils.Direction;
import eu.mhsl.minecraft.pixelblocks.utils.LocationUtil; import eu.mhsl.minecraft.pixelblocks.utils.LocationUtil;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData; import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional; import org.bukkit.block.data.Directional;
@@ -20,6 +21,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Random; import java.util.Random;
import java.util.UUID;
public class PixelBlockWorld { public class PixelBlockWorld {
private final PixelBlock parentPixelBlock; private final PixelBlock parentPixelBlock;
@@ -28,16 +30,28 @@ public class PixelBlockWorld {
int worldGrassBorderWidth = 10; int worldGrassBorderWidth = 10;
int pixelsPerBlock = Main.configuration().pixelsPerBlock(); int pixelsPerBlock = Main.configuration().pixelsPerBlock();
// Kapselt das Namensschema der Pixelwelten: <dataFolder>/worlds/<blockUUID>
private static String worldsBasePath;
private static @NotNull String getWorldsBasePath() {
if(worldsBasePath == null) {
worldsBasePath = Main.plugin().getDataFolder().getPath() + File.separator + "worlds";
}
return worldsBasePath;
}
public static boolean isPixelWorld(@NotNull World world) { public static boolean isPixelWorld(@NotNull World world) {
return world.getName().startsWith(Main.plugin().getDataFolder().getPath()); return world.getName().startsWith(getWorldsBasePath());
} }
public static @NotNull List<World> getOtherWorlds() { public static @Nullable UUID getUUIDFromWorld(@NotNull World world) {
return Bukkit.getWorlds().stream().filter(w -> !PixelBlockWorld.isPixelWorld(w)).toList(); if(!isPixelWorld(world)) return null;
String worldName = world.getName();
try {
return UUID.fromString(worldName.substring(worldName.lastIndexOf(File.separatorChar) + 1));
} catch(IllegalArgumentException e) {
return null;
} }
public static @NotNull List<World> getPixelBlockWorlds() {
return Bukkit.getWorlds().stream().filter(PixelBlockWorld::isPixelWorld).toList();
} }
public PixelBlockWorld(PixelBlock parentPixelBlock) { public PixelBlockWorld(PixelBlock parentPixelBlock) {
@@ -55,7 +69,7 @@ public class PixelBlockWorld {
} }
public @NotNull String getWorldPathName() { public @NotNull String getWorldPathName() {
return Main.plugin().getDataFolder().getPath() + File.separator + "worlds" + File.separator + this.parentPixelBlock.getBlockUUID(); return getWorldsBasePath() + File.separator + this.parentPixelBlock.getBlockUUID();
} }
public @NotNull Location getSpawnLocation() { public @NotNull Location getSpawnLocation() {
@@ -78,10 +92,6 @@ public class PixelBlockWorld {
return new Location(this.world, 0, -60, 0); return new Location(this.world, 0, -60, 0);
} }
public @NotNull Location getBuildOriginEnd() {
return getBuildOrigin().add(pixelsPerBlock, pixelsPerBlock, pixelsPerBlock);
}
public @NotNull Location getBorderOrigin() { public @NotNull Location getBorderOrigin() {
return getBuildOrigin().subtract(1, 1, 1); return getBuildOrigin().subtract(1, 1, 1);
} }
@@ -99,31 +109,32 @@ public class PixelBlockWorld {
public List<PixelData> getPixels(Direction direction) { public List<PixelData> getPixels(Direction direction) {
List<PixelData> pixelData = new ArrayList<>(); List<PixelData> pixelData = new ArrayList<>();
Location origin = this.getBuildOrigin();
int max = pixelsPerBlock - 1;
for(int x = 0; x < pixelsPerBlock; x++) { for(int x = 0; x < pixelsPerBlock; x++) {
for(int y = 0; y < pixelsPerBlock; y++) { for(int y = 0; y < pixelsPerBlock; y++) {
for(int z = 0; z < pixelsPerBlock; z++) { for(int z = 0; z < pixelsPerBlock; z++) {
Location relativeLocation = new Location(world, x, y, z); int blockX = switch(direction) {
case south -> x;
case north -> max - x;
case east -> max - z;
case west -> z;
};
int blockZ = switch(direction) {
case south -> z;
case north -> max - z;
case east -> x;
case west -> max - x;
};
Block block = this.world.getBlockAt(origin.getBlockX() + blockX, origin.getBlockY() + y, origin.getBlockZ() + blockZ);
BlockData blockData = block.getBlockData();
if(blockData.getMaterial().isAir()) continue;
Location blockLocation = this.getBuildOrigin();
switch(direction) {
case south ->
blockLocation.add(relativeLocation.x(), relativeLocation.y(), relativeLocation.z());
case north ->
blockLocation.add((pixelsPerBlock - 1) - relativeLocation.x(), relativeLocation.y(), (pixelsPerBlock - 1) - relativeLocation.z());
case east ->
blockLocation.add((pixelsPerBlock - 1) - relativeLocation.z(), relativeLocation.y(), relativeLocation.x());
case west ->
blockLocation.add(relativeLocation.z(), relativeLocation.y(), (pixelsPerBlock - 1) - relativeLocation.x());
}
BlockData blockData = blockLocation.getBlock().getBlockData();
@Nullable Directional directional = blockData instanceof Directional face ? face : null; @Nullable Directional directional = blockData instanceof Directional face ? face : null;
@Nullable Rotatable rotatable = blockData instanceof Rotatable rotation ? rotation : null; @Nullable Rotatable rotatable = blockData instanceof Rotatable rotation ? rotation : null;
BlockState state = blockLocation.getBlock().getState(); pixelData.add(new PixelData(new Vector(x, y, z), blockData, directional, rotatable, block.getState(), (double) 1 / pixelsPerBlock));
if(!blockData.getMaterial().isAir()) {
pixelData.add(new PixelData(relativeLocation.toVector(), blockData, directional, rotatable, state, (double) 1 / pixelsPerBlock));
}
} }
} }
} }
@@ -141,12 +152,12 @@ public class PixelBlockWorld {
World world = Bukkit.createWorld(worldCreator); World world = Bukkit.createWorld(worldCreator);
Objects.requireNonNull(world); Objects.requireNonNull(world);
world.setGameRule(GameRule.RANDOM_TICK_SPEED, 0); world.setGameRule(GameRules.RANDOM_TICK_SPEED, 0);
world.setGameRule(GameRule.DO_FIRE_TICK, false); world.setGameRule(GameRules.FIRE_SPREAD_RADIUS_AROUND_PLAYER, 0);
world.setGameRule(GameRule.DO_MOB_SPAWNING, false); world.setGameRule(GameRules.SPAWN_MOBS, false);
world.setGameRule(GameRule.DO_WEATHER_CYCLE, false); world.setGameRule(GameRules.ADVANCE_WEATHER, false);
world.setGameRule(GameRule.DO_VINES_SPREAD, false); world.setGameRule(GameRules.SPREAD_VINES, false);
world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false); world.setGameRule(GameRules.ADVANCE_TIME, false);
WorldBorder worldBorder = world.getWorldBorder(); WorldBorder worldBorder = world.getWorldBorder();
worldBorder.setCenter(getBuildOrigin().add((double) pixelsPerBlock / 2, 0, (double) pixelsPerBlock / 2)); worldBorder.setCenter(getBuildOrigin().add((double) pixelsPerBlock / 2, 0, (double) pixelsPerBlock / 2));
@@ -156,37 +167,7 @@ public class PixelBlockWorld {
return world; return world;
} }
private void setBuildingPlatform() { private static final List<Material> FLOWERS = List.of(
Bukkit.getScheduler().runTask(Main.plugin(), () -> {
for(int x = 0; x < (pixelsPerBlock + 2) + 2 * worldGrassBorderWidth; x++) {
for(int z = 0; z < (pixelsPerBlock + 2) + 2 * worldGrassBorderWidth; z++) {
getPlatformOrigin().add(x, 0, z).getBlock().setType(Material.GRASS_BLOCK);
}
}
for(int x = 0; x < (pixelsPerBlock + 2) + 2 * worldGrassBorderWidth; x++) {
for(int z = 0; z < (pixelsPerBlock + 2) + 2 * worldGrassBorderWidth; z++) {
getPlatformOrigin().add(x, -1, z).getBlock().setType(Material.DIRT);
}
}
for(int x = 0; x < (pixelsPerBlock + 2); x++) {
for(int z = 0; z < (pixelsPerBlock + 2); z++) {
Location currentLocation = getBorderOrigin().add(x, 0, z);
if(currentLocation.x() == getBorderOrigin().x() || currentLocation.z() == getBorderOrigin().z()) {
currentLocation.getBlock().setType(Material.RED_CONCRETE);
} else if(currentLocation.x() == getBorderOrigin().x() + (pixelsPerBlock + 1) || currentLocation.z() == getBorderOrigin().z() + (pixelsPerBlock + 1)) {
currentLocation.getBlock().setType(Material.RED_CONCRETE);
}
}
}
Random random = new Random();
LocationUtil.iterateBlocks(getPlatformOrigin().add(1, 1, 1), getPlatformOriginEnd().add(0, 1, 0), location -> {
if(allowPlacements(location)) return;
if(!location.clone().subtract(0, 1, 0).getBlock().getType().equals(Material.GRASS_BLOCK)) return;
List<Material> flowers = List.of(
Material.DANDELION, Material.DANDELION,
Material.POPPY, Material.POPPY,
Material.BLUE_ORCHID, Material.BLUE_ORCHID,
@@ -200,23 +181,50 @@ public class PixelBlockWorld {
Material.SHORT_GRASS, Material.SHORT_GRASS,
Material.TALL_GRASS Material.TALL_GRASS
); );
if(flowers.contains(location.getBlock().getType())) location.getBlock().setType(Material.AIR);
private void setBuildingPlatform() {
Bukkit.getScheduler().runTask(Main.plugin(), () -> {
int platformSize = (pixelsPerBlock + 2) + 2 * worldGrassBorderWidth;
Location platformOrigin = this.getPlatformOrigin();
for(int x = 0; x < platformSize; x++) {
for(int z = 0; z < platformSize; z++) {
platformOrigin.clone().add(x, 0, z).getBlock().setType(Material.GRASS_BLOCK);
platformOrigin.clone().add(x, -1, z).getBlock().setType(Material.DIRT);
}
}
int borderSize = pixelsPerBlock + 2;
Location borderOrigin = this.getBorderOrigin();
for(int x = 0; x < borderSize; x++) {
for(int z = 0; z < borderSize; z++) {
if(x == 0 || z == 0 || x == borderSize - 1 || z == borderSize - 1) {
borderOrigin.clone().add(x, 0, z).getBlock().setType(Material.RED_CONCRETE);
}
}
}
Random random = new Random();
LocationUtil.iterateBlocks(getPlatformOrigin().add(1, 1, 1), getPlatformOriginEnd().add(0, 1, 0), location -> {
if(allowPlacements(location)) return;
if(!location.clone().subtract(0, 1, 0).getBlock().getType().equals(Material.GRASS_BLOCK)) return;
if(FLOWERS.contains(location.getBlock().getType())) location.getBlock().setType(Material.AIR);
if(!location.getBlock().getType().equals(Material.AIR)) return; if(!location.getBlock().getType().equals(Material.AIR)) return;
if(random.nextInt(30) == 0) { if(random.nextInt(30) == 0) {
Material randomFlower = flowers.get(random.nextInt(flowers.size())); location.getBlock().setType(FLOWERS.get(random.nextInt(FLOWERS.size())));
location.getBlock().setType(randomFlower);
} }
}); });
Location portalLocation = this.getPortalLocation();
for(int x = 0; x < 4; x++) { for(int x = 0; x < 4; x++) {
for(int y = 0; y < 5; y++) { for(int y = 0; y < 5; y++) {
getPortalLocation().add(x, y, 0).getBlock().setType(Material.OBSIDIAN); portalLocation.clone().add(x, y, 0).getBlock().setType(Material.OBSIDIAN);
} }
} }
for(int x = 1; x < 3; x++) { for(int x = 1; x < 3; x++) {
for(int y = 1; y < 4; y++) { for(int y = 1; y < 4; y++) {
getPortalLocation().add(x, y, 0).getBlock().setType(Material.NETHER_PORTAL); portalLocation.clone().add(x, y, 0).getBlock().setType(Material.NETHER_PORTAL);
} }
} }
}); });
@@ -2,6 +2,7 @@ package eu.mhsl.minecraft.pixelblocks.pixelblock;
import eu.mhsl.minecraft.pixelblocks.Main; import eu.mhsl.minecraft.pixelblocks.Main;
import eu.mhsl.minecraft.pixelblocks.utils.Direction; import eu.mhsl.minecraft.pixelblocks.utils.Direction;
import eu.mhsl.minecraft.pixelblocks.utils.EntityTagUtil;
import eu.mhsl.minecraft.pixelblocks.utils.ListUtil; import eu.mhsl.minecraft.pixelblocks.utils.ListUtil;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
@@ -16,7 +17,6 @@ import org.bukkit.block.data.type.EnderChest;
import org.bukkit.entity.BlockDisplay; import org.bukkit.entity.BlockDisplay;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.util.Transformation; import org.bukkit.util.Transformation;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -24,7 +24,6 @@ import org.jetbrains.annotations.Nullable;
import org.joml.Vector3d; import org.joml.Vector3d;
import java.util.List; import java.util.List;
import java.util.Objects;
public class Pixels { public class Pixels {
private static final NamespacedKey pixelOfTag = new NamespacedKey(Main.plugin(), "pixel_of"); private static final NamespacedKey pixelOfTag = new NamespacedKey(Main.plugin(), "pixel_of");
@@ -61,18 +60,16 @@ public class Pixels {
transform.getTranslation().set(centerOffset.mul(-1)); transform.getTranslation().set(centerOffset.mul(-1));
entity.setTransformation(transform); entity.setTransformation(transform);
entity.getPersistentDataContainer().set(pixelOfTag, PersistentDataType.STRING, this.parentBlock.getBlockUUID().toString()); EntityTagUtil.tag(entity, pixelOfTag, this.parentBlock.getBlockUUID());
} }
public void destroy() { public void destroy() {
List<BlockDisplay> entities = parentBlock.getPixelBlockLocation().getNearbyEntitiesByType(BlockDisplay.class, 1) List<BlockDisplay> entities = EntityTagUtil.findTagged(
.stream() this.parentBlock.getPixelBlockLocation(),
.filter(blockDisplay -> blockDisplay.getPersistentDataContainer().has(pixelOfTag)) BlockDisplay.class,
.filter(blockDisplay -> Objects.equals( pixelOfTag,
blockDisplay.getPersistentDataContainer().get(pixelOfTag, PersistentDataType.STRING), this.parentBlock.getBlockUUID()
parentBlock.getBlockUUID().toString() );
))
.toList();
ListUtil.splitListInParts(10, entities) ListUtil.splitListInParts(10, entities)
.forEach(pixels -> parentBlock.getBlockTaskChain() .forEach(pixels -> parentBlock.getBlockTaskChain()
@@ -0,0 +1,29 @@
package eu.mhsl.minecraft.pixelblocks.utils;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Entity;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
public class EntityTagUtil {
public static void tag(@NotNull Entity entity, @NotNull NamespacedKey key, @NotNull UUID id) {
entity.getPersistentDataContainer().set(key, PersistentDataType.STRING, id.toString());
}
public static <T extends Entity> @NotNull List<T> findTagged(@NotNull Location center, @NotNull Class<T> type, @NotNull NamespacedKey key, @NotNull UUID id) {
String idString = id.toString();
return center.getNearbyEntitiesByType(type, 1)
.stream()
.filter(entity -> Objects.equals(entity.getPersistentDataContainer().get(key, PersistentDataType.STRING), idString))
.toList();
}
public static <T extends Entity> void removeTagged(@NotNull Location center, @NotNull Class<T> type, @NotNull NamespacedKey key, @NotNull UUID id) {
findTagged(center, type, key, id).forEach(Entity::remove);
}
}
@@ -14,7 +14,7 @@ public class EventCanceling {
if(!PixelBlockWorld.isPixelWorld(world)) return; if(!PixelBlockWorld.isPixelWorld(world)) return;
@Nullable PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(world); @Nullable PixelBlock pixelBlock = PixelBlock.getPixelBlockFromBlockWorld(world);
if(pixelBlock == null) { if(pixelBlock == null) {
Main.logger().warning("Cancelling place event because PixelBlock could not be found: " + world.getName()); Main.logger().warning("Cancelling %s event because PixelBlock '%s' could not be found!".formatted(event.getClass().getSimpleName(), world.getName()));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@@ -0,0 +1,22 @@
pixelblocks.command.players-only=Dieser Befehl kann nur von Spielern ausgeführt werden.
pixelblocks.command.no-permission=Dazu hast du keine Berechtigung.
pixelblocks.command.usage.header=PixelBlocks-Befehle:
pixelblocks.command.create.description=Erstellt einen neuen Pixelblock an deiner Position.
pixelblocks.command.give.description=Gibt dir ein Pixelblock-Item, optional mit fester UUID.
pixelblocks.command.give.success=Pixelblock '{0}' erhalten.
pixelblocks.command.exit.description=Verlässt den Pixelblock, in dem du dich befindest.
pixelblocks.command.destroyall.description=Zerstört alle Pixelblöcke auf dem Server.
pixelblocks.command.destroyall.success={0} Pixelblöcke werden zerstört.
pixelblocks.error.not-owner=Dieser Pixelblock gehört nicht dir!
pixelblocks.error.create-inside=Pixelblöcke können nicht innerhalb anderer Pixelblöcke erstellt werden.
pixelblocks.error.place-inside=In Pixelblöcken kann kein Pixelblock platziert werden.
pixelblocks.error.already-exists=Dieser Pixelblock existiert bereits in der Welt!
pixelblocks.error.invalid-uuid='{0}' ist keine gültige UUID.
pixelblocks.error.not-in-pixelblock=Du befindest dich nicht in einem Pixelblock.
pixelblocks.error.block-not-found=Dieser Pixelblock konnte nicht gefunden werden.
pixelblocks.info.destroyed-by-other=Der Pixelblock wurde von einem anderen Spieler abgebaut!
pixelblocks.item.name.owned=Pixelblock von {0}
pixelblocks.item.name.empty=Leerer Pixelblock
pixelblocks.item.lore.owner={0} ist der Besitzer dieses Blocks.
pixelblocks.item.lore.edit-hint=Klicke auf den gesetzten Block, um diesen zu bearbeiten!
pixelblocks.item.lore.first-placer=Der erste Spieler, der den Block platziert, wird zum Besitzer des Blocks.
@@ -0,0 +1,22 @@
pixelblocks.command.players-only=This command can only be used by players.
pixelblocks.command.no-permission=You don't have permission to do that.
pixelblocks.command.usage.header=PixelBlocks commands:
pixelblocks.command.create.description=Creates a new pixel block at your position.
pixelblocks.command.give.description=Gives you a pixel block item, optionally with a fixed UUID.
pixelblocks.command.give.success=Received pixel block '{0}'.
pixelblocks.command.exit.description=Leaves the pixel block you are currently in.
pixelblocks.command.destroyall.description=Destroys all pixel blocks on the server.
pixelblocks.command.destroyall.success={0} pixel blocks are being destroyed.
pixelblocks.error.not-owner=This pixel block does not belong to you!
pixelblocks.error.create-inside=Pixel blocks cannot be created inside other pixel blocks.
pixelblocks.error.place-inside=Pixel blocks cannot be placed inside pixel blocks.
pixelblocks.error.already-exists=This pixel block already exists in the world!
pixelblocks.error.invalid-uuid='{0}' is not a valid UUID.
pixelblocks.error.not-in-pixelblock=You are not inside a pixel block.
pixelblocks.error.block-not-found=This pixel block could not be found.
pixelblocks.info.destroyed-by-other=The pixel block was destroyed by another player!
pixelblocks.item.name.owned=Pixel block of {0}
pixelblocks.item.name.empty=Empty pixel block
pixelblocks.item.lore.owner={0} is the owner of this block.
pixelblocks.item.lore.edit-hint=Click the placed block to edit it!
pixelblocks.item.lore.first-placer=The first player to place this block becomes its owner.
+17 -4
View File
@@ -3,7 +3,20 @@ version: '${version}'
main: eu.mhsl.minecraft.pixelblocks.Main main: eu.mhsl.minecraft.pixelblocks.Main
api-version: '1.21' api-version: '1.21'
commands: commands:
createpixelblock: pixelblocks:
exitworld: description: Verwaltung von Pixelblöcken
givepixelblock: usage: /pixelblocks <create|give|exit|destroyall>
destroypixelblocks: aliases: [pb]
permissions:
pixelblocks.command.create:
description: Erlaubt das Erstellen eines Pixelblocks per Befehl
default: op
pixelblocks.command.give:
description: Erlaubt das Geben von Pixelblock-Items
default: op
pixelblocks.command.exit:
description: Erlaubt das Verlassen eines Pixelblocks per Befehl
default: true
pixelblocks.command.destroyall:
description: Erlaubt das Zerstören aller Pixelblöcke
default: op