diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a4335df --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Keep CRLF for *.bat files which are for Windows. +# Ref: https://stackoverflow.com/questions/21822650 +*.bat -crlf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..0581c91 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,68 @@ +name: release +on: + push: + tags: + - "**" +jobs: + publish: + runs-on: ubuntu-18.04 + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + # Fetch all history + fetch-depth: 0 + - name: Maven Publish + id: maven_publish + env: + MAVEN_USERNAME: ${{ secrets.TEACON_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.TEACON_PASSWORD }} + run: ./gradlew publishReleasePublicationToArchiveRepository githubActionOutput + - name: Generate Changelog + id: changelog + shell: bash + env: + CURRENT: ${{ github.ref }} + # Special thanks to this post on Stack Overflow regarding change set between two tags: + # https://stackoverflow.com/questions/12082981 + # Do note that actions/checkout will enter detach mode by default, so you won't have + # access to HEAD ref. Use GitHub-Action-supplied `github.ref` instead. + # Special thanks to this issue ticket regarding escaping newline: + # https://github.com/actions/create-release/issues/25 + # We use Bash parameter expansion to do find-and-replace. + # https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html + # Also we cannot use git rev-list because it always prepend "commit " + # See https://stackoverflow.com/questions/36927089/ + run: | + current_tag=${CURRENT/refs\/tags\//} + last_tag=`git describe --tags --abbrev=0 "$current_tag"^ 2>/dev/null || echo` + if [ last_tag ]; then + changelog=`git log --pretty="format:%H: %s" ${last_tag}..$current_tag` + else + changelog=`git log --pretty="format:%H: %s"` + fi + changelog="${changelog//'%'/'%25'}" + changelog="${changelog//$'\n'/' %0A'}" + echo "::set-output name=value::Change set since ${last_tag:-the beginning}: %0A%0A$changelog" + - name: GitHub Release + id: create_release + uses: actions/create-release@v1.1.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + draft: false + prerelease: false + body: | + ${{ steps.changelog.outputs.value }} + - name: GitHub Release Artifact + uses: actions/upload-release-asset@v1.0.2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ${{ steps.maven_publish.outputs.artifact_path }} + asset_name: ${{ steps.maven_publish.outputs.artifact_name }} + # https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types + asset_content_type: "application/java-archive" diff --git a/.github/workflows/test-build.yml b/.github/workflows/test-build.yml new file mode 100644 index 0000000..22e3407 --- /dev/null +++ b/.github/workflows/test-build.yml @@ -0,0 +1,14 @@ +name: test-build +on: + push: + paths: + - "src/**" + - "build.gradle" +jobs: + build: + runs-on: ubuntu-18.04 + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Build + run: ./gradlew build --stacktrace diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..757f761 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea +out +*.ipr +*.iws +*.iml +.idea + +# vscode +.vscode + +# gradle +build +.gradle + +# other +eclipse +run +*.txt + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b67a13d --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2020, TeaConMC members and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the TeaConMC nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL TEACONMC MEMBERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..692ef01 --- /dev/null +++ b/build.gradle @@ -0,0 +1,149 @@ +import java.time.Instant +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit + +buildscript { + repositories { + maven { url = 'https://files.minecraftforge.net/maven' } + jcenter() + mavenCentral() + } + dependencies { + classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true + } +} +apply plugin: 'net.minecraftforge.gradle' +apply plugin: 'eclipse' +apply plugin: 'maven-publish' + +version = '0.1.0' +group = 'org.teacon' +archivesBaseName = 'AreaControl-Forge-1.15' + +sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' + +minecraft { + mappings channel: 'snapshot', version: '20200513-1.15.1' + + runs { + client { + workingDirectory project.file('run') + property 'forge.logging.console.level', 'info' + mods { + area_control { + source sourceSets.main + } + } + } + + server { + workingDirectory project.file('run_server') + property 'forge.logging.console.level', 'info' + mods { + area_control { + source sourceSets.main + } + } + } + + data { + workingDirectory project.file('run') + property 'forge.logging.console.level', 'info' + args '--mod', 'area_control', '--all', '--output', file('src/generated/resources/') + mods { + area_control { + source sourceSets.main + } + } + } + } +} + +dependencies { + minecraft 'net.minecraftforge:forge:1.15.2-31.2.4' +} + +jar { + manifest { + attributes([ + "Specification-Title": "Area-Control", + "Specification-Vendor": "TeaConMC", + "Specification-Version": "1", + "Implementation-Title": project.name, + "Implementation-Version": "${version}", + "Implementation-Vendor": "TeaConMC", + "Implementation-Timestamp": DateTimeFormatter.ISO_INSTANT.format(Instant.now().truncatedTo(ChronoUnit.SECONDS)) + ]) + } +} + +def reobfFile = file("$buildDir/reobfJar/output.jar") +def reobfArtifact = artifacts.add('default', reobfFile) { + type 'jar' + builtBy 'reobfJar' +} +publishing { + publications { + release(MavenPublication) { + groupId = "org.teacon" + artifactId = "AreaControl-Forge-1.15" + + artifact reobfArtifact + pom { + name = 'AreaControl for Minecraft 1.15' + description = 'Comprehensive (maybe) plot management mod' + url = 'https://github.com/teaconmc/AreaControl' + licenses { + license { + name = 'BSD-3-Clause' + url = 'https://github.com/teaconmc/AreaControl/blob/1.15-forge/LICENSE' + } + } + developers { + developer { + id = '3TUSK' + name = '3TUSK' + } + } + issueManagement { + system = 'GitHub Issues' + url = 'https://github.com/teaconmc/AreaControl/issues' + } + scm { + url = 'https://github.com/teaconmc/AreaControl' + connection = 'scm:git:git://github.com/teaconmc/AreaControl.git' + developerConnection = 'scm:git:git@github.com:teaconmc/AreaControl.git' + } + } + } + } + repositories { + maven { + name = "archive" + url = "https://maven.hub.tritusk.info/releases" + credentials { + username = System.env.MAVEN_USERNAME + password = System.env.MAVEN_PASSWORD + } + } + } +} + +tasks.withType(PublishToMavenRepository) { + onlyIf { + System.env.MAVEN_USERNAME && System.env.MAVEN_PASSWORD + } +} + +/** + * A simple task to pass down the artifact name and path to other GitHub actions. + */ +task("githubActionOutput") { + onlyIf { + System.env.GITHUB_ACTIONS + } + doLast { + println "::set-output name=artifact_path::$buildDir/reobfJar/output.jar" + println "::set-output name=artifact_name::$archivesBaseName-${version}.jar" + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..c4f1c9e --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +# Ensure enough heap space during deployment +org.gradle.jvmargs=-Xmx3G +# It is said that daemon often brings more issues, so we disable it. +org.gradle.daemon=false diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7a3265e Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..949819d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + 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" + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@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=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/org/teacon/areacontrol/AreaControl.java b/src/main/java/org/teacon/areacontrol/AreaControl.java new file mode 100644 index 0000000..014e118 --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/AreaControl.java @@ -0,0 +1,68 @@ +package org.teacon.areacontrol; + +import java.nio.file.Files; +import java.nio.file.Path; + +import org.apache.commons.lang3.tuple.Pair; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import net.minecraft.server.MinecraftServer; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.ExtensionPoint; +import net.minecraftforge.fml.ModLoadingContext; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.server.FMLServerStartingEvent; +import net.minecraftforge.fml.event.server.FMLServerStoppingEvent; +import net.minecraftforge.fml.network.FMLNetworkConstants; + +@Mod("area_control") +@Mod.EventBusSubscriber(modid = "area_control") +public final class AreaControl { + + private static final Logger LOGGER = LogManager.getLogger("AreaControl"); + + public AreaControl() { + ModLoadingContext context = ModLoadingContext.get(); + context.registerExtensionPoint(ExtensionPoint.DISPLAYTEST, + () -> Pair.of(() -> FMLNetworkConstants.IGNORESERVERONLY, (serverVer, isDedi) -> true)); + } + + @SubscribeEvent + public static void onServerStart(FMLServerStartingEvent event) { + // Remember, when update Forge, make sure to use the command register event + // PR-ed by jaredlll08 + new AreaControlCommand(event.getCommandDispatcher()); + + final MinecraftServer server = event.getServer(); + final Path dataDir = server.getActiveAnvilConverter().getFile(server.getFolderName(), "serverconfig").toPath() + .resolve("area_control"); + if (Files.isDirectory(dataDir)) { + try { + AreaManager.INSTANCE.loadFrom(dataDir); + } catch (Exception e) { + LOGGER.error("Failed to read claims data, details: {}", e); + } + } else { + try { + Files.createDirectories(dataDir); + } catch (Exception e) { + LOGGER.warn("Failed to create data directory. Details: {}", e); + } + } + } + + @SubscribeEvent + public static void onServerStop(FMLServerStoppingEvent event) { + final MinecraftServer server = event.getServer(); + final Path dataDir = server.getActiveAnvilConverter().getFile(server.getFolderName(), "serverconfig").toPath() + .resolve("area_control"); + if (Files.isDirectory(dataDir)) { + try { + AreaManager.INSTANCE.saveTo(dataDir); + } catch (Exception e) { + LOGGER.warn("Failed to create data directory. Details: {}", e); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/teacon/areacontrol/AreaControlClaimHandler.java b/src/main/java/org/teacon/areacontrol/AreaControlClaimHandler.java new file mode 100644 index 0000000..1d21aa0 --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/AreaControlClaimHandler.java @@ -0,0 +1,39 @@ +package org.teacon.areacontrol; + +import java.util.ArrayDeque; +import java.util.WeakHashMap; + +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.item.Item; +import net.minecraft.item.Items; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.StringTextComponent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.LogicalSide; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.server.permission.PermissionAPI; + +@Mod.EventBusSubscriber(modid = "area_control") +public final class AreaControlClaimHandler { + + static Item userClaimTool = Items.STICK; + static Item adminTool = Items.TRIDENT; + + static WeakHashMap> recordPos = new WeakHashMap<>(); + + @SubscribeEvent(priority = EventPriority.LOWEST) + public static void onRightClick(PlayerInteractEvent.RightClickBlock event) { + if (event.getSide() == LogicalSide.SERVER) { + final PlayerEntity player = event.getPlayer(); + if (event.getItemStack().getItem() == adminTool && PermissionAPI.hasPermission(player, "area_control.admin.inspect")) { + player.sendStatusMessage(new StringTextComponent("AreaControl: Welcome back, administrator"), true); + } else if (event.getItemStack().getItem() == userClaimTool) { + final BlockPos clicked; + recordPos.computeIfAbsent(player, p -> new ArrayDeque<>()).offerLast(clicked = event.getPos().toImmutable()); + player.sendStatusMessage(new StringTextComponent(String.format("AreaControl: Marked position x=%d, y=%d, z=%d ", clicked.getX(), clicked.getY(), clicked.getZ())), true); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/teacon/areacontrol/AreaControlCommand.java b/src/main/java/org/teacon/areacontrol/AreaControlCommand.java new file mode 100644 index 0000000..986976e --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/AreaControlCommand.java @@ -0,0 +1,90 @@ +package org.teacon.areacontrol; + +import java.util.ArrayDeque; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; + +import org.teacon.areacontrol.api.Area; + +import net.minecraft.command.CommandSource; +import net.minecraft.command.Commands; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.StringTextComponent; + +public final class AreaControlCommand { + + public AreaControlCommand(CommandDispatcher dispatcher) { + dispatcher.register(Commands.literal("ac") + .redirect(dispatcher.register(Commands.literal("areacontrol") + .then(Commands.literal("about").executes(AreaControlCommand::about)) + .then(Commands.literal("admin").executes(AreaControlCommand::admin)) + .then(Commands.literal("claim").executes(AreaControlCommand::claim)) + .then(Commands.literal("list").executes(AreaControlCommand::list)) + .then(Commands.literal("set").then( + Commands.argument("property", StringArgumentType.string()).then( + Commands.argument("value", StringArgumentType.greedyString()) + .executes(AreaControlCommand::setProperty) + ))) + ) + ) + ); + } + + private static int about(CommandContext context) { + context.getSource().sendFeedback(new StringTextComponent("AreaControl 0.1.0"), false); + return Command.SINGLE_SUCCESS; + } + + private static int admin(CommandContext context) { + context.getSource().sendFeedback(new StringTextComponent("WIP"), false); + return Command.SINGLE_SUCCESS; + } + + private static int claim(CommandContext context) throws CommandSyntaxException { + final CommandSource src = context.getSource(); + final ArrayDeque recordPos = AreaControlClaimHandler.recordPos.get(src.asPlayer()); + if (recordPos != null && recordPos.size() >= 2) { + final Area area = Util.createArea("Unnamed area " + Util.nextRandomString(), new AxisAlignedBB(recordPos.pop(), recordPos.pop())); + recordPos.clear(); + if (AreaManager.INSTANCE.add(area)) { + src.sendFeedback(new StringTextComponent(String.format("Claim '%s' has been created from [%d, %d, %d] to [%d, %d, %d]", area.name, area.minX, area.minY, area.minZ, area.maxX, area.maxY, area.maxZ)), true); + return Command.SINGLE_SUCCESS; + } else { + src.sendFeedback(new StringTextComponent("Cannot claim the selected area because it overlaps another claimed area. Perhaps try somewhere else?"), false); + return -2; + } + } else { + src.sendFeedback(new StringTextComponent("Cannot determine what area you want to claim. Did you forget to select an area?"), false); + return -1; + } + + } + + private static int list(CommandContext context) throws CommandSyntaxException { + final CommandSource src = context.getSource(); + src.sendFeedback(new StringTextComponent("Currently known areas: "), false); + for (Area a : AreaManager.INSTANCE.getKnownAreas()) { + src.sendFeedback(new StringTextComponent(String.format(" - %s (from [%d, %d, %d] to [%d, %d, %d])", a.name, a.minX, a.minY, a.minZ, a.maxX, a.maxY, a.maxZ)), false); + } + return Command.SINGLE_SUCCESS; + } + + private static int setProperty(CommandContext context) throws CommandSyntaxException { + final Area area = AreaManager.INSTANCE.findBy(new BlockPos(context.getSource().getPos())); + if (area != AreaManager.INSTANCE.wildness) { + final String prop = context.getArgument("property", String.class); + final String value = context.getArgument("value", String.class); + area.properties.put(prop, value); + context.getSource().sendFeedback(new StringTextComponent(String.format("Area '%s''s property '%s' has been updated to '%s'", area.name, prop, value)), true); + return Command.SINGLE_SUCCESS; + } else { + context.getSource().sendErrorMessage(new StringTextComponent("You are in the wildness. What were you thinking?")); + return -1; + } + } +} \ No newline at end of file diff --git a/src/main/java/org/teacon/areacontrol/AreaControlEventHandlers.java b/src/main/java/org/teacon/areacontrol/AreaControlEventHandlers.java new file mode 100644 index 0000000..0cf30d6 --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/AreaControlEventHandlers.java @@ -0,0 +1,97 @@ +package org.teacon.areacontrol; + +import org.teacon.areacontrol.api.Area; +import org.teacon.areacontrol.api.AreaProperties; + +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.event.entity.living.LivingSpawnEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.event.world.BlockEvent; +import net.minecraftforge.event.world.ExplosionEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.fml.common.Mod; + +@Mod.EventBusSubscriber(modid = "area_control") +public final class AreaControlEventHandlers { + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onCheckSpawn(LivingSpawnEvent.CheckSpawn event) { + final BlockPos spawnPos = new BlockPos(event.getX(), event.getY(), event.getZ()); + final Area targetArea = AreaManager.INSTANCE.findBy(spawnPos); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_spawn")) { + event.setResult(Event.Result.DENY); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onSpecialSpawn(LivingSpawnEvent.SpecialSpawn event) { + final BlockPos spawnPos = new BlockPos(event.getX(), event.getY(), event.getZ()); + final Area targetArea = AreaManager.INSTANCE.findBy(spawnPos); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_special_spawn")) { + event.setCanceled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onBreakBlock(BlockEvent.BreakEvent event) { + final Area targetArea = AreaManager.INSTANCE.findBy(event.getPos()); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_break_block")) { + event.setCanceled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onClickBlock(PlayerInteractEvent.LeftClickBlock event) { + final Area targetArea = AreaManager.INSTANCE.findBy(event.getPos()); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_click_block")) { + event.setCanceled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onActivateBlock(PlayerInteractEvent.RightClickBlock event) { + final Area targetArea = AreaManager.INSTANCE.findBy(event.getPos()); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_activate_block")) { + event.setCanceled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onUseItem(PlayerInteractEvent.RightClickItem event) { + final Area targetArea = AreaManager.INSTANCE.findBy(event.getPos()); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_use_item")) { + event.setCanceled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onPlaceBlock(BlockEvent.EntityPlaceEvent event) { + final Area targetArea = AreaManager.INSTANCE.findBy(event.getPos()); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_place_block")) { + // TODO Does this consume the item? + event.setCanceled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void beforeExplosion(ExplosionEvent.Start event) { + final Area targetArea = AreaManager.INSTANCE.findBy(new BlockPos(event.getExplosion().getPosition())); + if (targetArea != null && !AreaProperties.getBool(targetArea, "area.allow_explosion")) { + event.setCanceled(true); + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void afterExplosion(ExplosionEvent.Detonate event) { + final Area targetArea = AreaManager.INSTANCE.findBy(new BlockPos(event.getExplosion().getPosition())); + if (targetArea != null) { + if (!AreaProperties.getBool(targetArea, "area.allow_explosion_affect_blocks")) { + event.getAffectedBlocks().clear(); + } + if (!AreaProperties.getBool(targetArea, "area.allow_explosion_affect_entities")) { + event.getAffectedEntities().clear(); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/org/teacon/areacontrol/AreaManager.java b/src/main/java/org/teacon/areacontrol/AreaManager.java new file mode 100644 index 0000000..9ceee73 --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/AreaManager.java @@ -0,0 +1,128 @@ +package org.teacon.areacontrol; + +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import org.teacon.areacontrol.api.Area; + +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; + +public final class AreaManager { + + public static final AreaManager INSTANCE = new AreaManager(); + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + final Area wildness = new Area(); + + private final HashMap areasByName = new HashMap<>(); + /** + * All known instances of {@link Area}, indexed by chunk positions covered by this area. + * Used for faster lookup of {@link Area}. + */ + private final HashMap> areasByChunk = new HashMap<>(); + + { + wildness.name = "wildness"; + wildness.minX = Integer.MIN_VALUE; + wildness.minY = Integer.MIN_VALUE; + wildness.minZ = Integer.MIN_VALUE; + wildness.maxX = Integer.MAX_VALUE; + wildness.maxY = Integer.MAX_VALUE; + wildness.maxZ = Integer.MAX_VALUE; + wildness.properties.put("area.allow_click_block", true); + wildness.properties.put("area.allow_activate_block", true); + wildness.properties.put("area.allow_use_item", true); + } + + private void buildCacheFor(Area area) { + ChunkPos.getAllInBox(new ChunkPos(area.minX >> 4, area.minZ >> 4), new ChunkPos(area.maxX >> 4, area.maxZ >> 4)) + .map(cp -> this.areasByChunk.computeIfAbsent(cp, _cp -> new ArrayList<>())) + .forEach(list -> list.add(area)); + } + + void loadFrom(Path dataDirRoot) throws Exception { + Path userDefinedAreas = dataDirRoot.resolve("claims.json"); + if (Files.isRegularFile(userDefinedAreas)) { + try (Reader reader = Files.newBufferedReader(userDefinedAreas)) { + for (Area a : GSON.fromJson(reader, Area[].class)) { + areasByName.put(a.name, a); + } + } + } + Path wildnessArea = dataDirRoot.resolve("wildness.json"); + if (Files.isRegularFile(wildnessArea)) { + try (Reader reader = Files.newBufferedReader(userDefinedAreas)) { + Area a = GSON.fromJson(reader, Area.class); + this.wildness.properties.putAll(a.properties); + } + } + } + + void saveTo(Path dataDirRoot) throws Exception { + Path userDefinedAreas = dataDirRoot.resolve("claims.json"); + Files.write(userDefinedAreas, GSON.toJson(this.areasByName.values()).getBytes(StandardCharsets.UTF_8)); + Path wildnessArea = dataDirRoot.resolve("wildness.json"); + Files.write(wildnessArea, GSON.toJson(this.wildness).getBytes(StandardCharsets.UTF_8)); + } + + /** + * @param area The Area instance to be recorded + * @return true if and only if the area is successfully recorded by this AreaManager; false otherwise. + */ + public boolean add(Area area) { + // First we filter out cases where at least one defining coordinate falls in an existing area + if (findBy(new BlockPos(area.minX, 0, area.minZ)) == this.wildness && findBy(new BlockPos(area.maxX, 0, area.maxZ)) == this.wildness) { + // Second we filter out cases where the area to define is enclosing another area. + boolean noEnclosing = true; + for (Area a : areasByName.values()) { + if (area.minX < a.minX && a.maxX < area.maxX) { + if (area.minY < a.minY && a.maxY < area.maxY) { + if (area.minZ < a.minZ && a.maxZ < area.maxZ) { + noEnclosing = false; + break; + } + } + } + } + if (noEnclosing) { + areasByName.computeIfAbsent(area.name, name -> area); + this.buildCacheFor(area); + return true; + } + } + return false; + } + + public Area findBy(BlockPos pos) { + for (Area area : this.areasByChunk.getOrDefault(new ChunkPos(pos), Collections.emptyList())) { + if (area.minX <= pos.getX() && pos.getX() <= area.maxX) { + if (area.minY <= pos.getY() && pos.getY() <= area.maxY) { + if (area.minZ <= pos.getZ() && pos.getZ() <= area.maxZ) { + return area; + } + } + } + } + return wildness; + } + + public Area findBy(String name) { + return areasByName.get(name); + } + + public Collection getKnownAreas() { + return Collections.unmodifiableCollection(this.areasByName.values()); + } +} \ No newline at end of file diff --git a/src/main/java/org/teacon/areacontrol/Util.java b/src/main/java/org/teacon/areacontrol/Util.java new file mode 100644 index 0000000..69f6be2 --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/Util.java @@ -0,0 +1,36 @@ +package org.teacon.areacontrol; + +import java.util.Random; + +import org.teacon.areacontrol.api.Area; + +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.AxisAlignedBB; + +public final class Util { + + private static final Random RAND = new Random(); + + public static String nextRandomString() { + // https://stackoverflow.com/questions/14622622/generating-a-random-hex-string-of-length-50-in-java-me-j2me#comment100639373_14623245 + // tldr: formatting to 8 digits of hexadecimal number, padding zeros at beginning + return String.format("%08x", RAND.nextInt()); + } + + public static boolean isOpInServer(PlayerEntity player, MinecraftServer server) { + return server.getPlayerList().getOppedPlayers().getEntry(player.getGameProfile()) != null; + } + + public static Area createArea(String name, AxisAlignedBB box) { + final Area a = new Area(); + a.name = name; + a.minX = (int) box.minX; + a.minY = (int) box.minY; + a.minZ = (int) box.minZ; + a.maxX = (int) box.maxX; + a.maxY = (int) box.maxY; + a.maxZ = (int) box.maxZ; + return a; + } +} \ No newline at end of file diff --git a/src/main/java/org/teacon/areacontrol/api/Area.java b/src/main/java/org/teacon/areacontrol/api/Area.java new file mode 100644 index 0000000..1b16c90 --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/api/Area.java @@ -0,0 +1,16 @@ +package org.teacon.areacontrol.api; + +import java.util.HashMap; +import java.util.Map; + +/** + * A cuboid area defined by min. coordinate and max. coordinate. + */ +public final class Area { + + public String name; + + public int minX, minY, minZ, maxX, maxY, maxZ; + + public final Map properties = new HashMap<>(); +} \ No newline at end of file diff --git a/src/main/java/org/teacon/areacontrol/api/AreaProperties.java b/src/main/java/org/teacon/areacontrol/api/AreaProperties.java new file mode 100644 index 0000000..5c6c79c --- /dev/null +++ b/src/main/java/org/teacon/areacontrol/api/AreaProperties.java @@ -0,0 +1,44 @@ +package org.teacon.areacontrol.api; + +public final class AreaProperties { + private AreaProperties() {} + + public static boolean getBool(Area area, String key) { + Object o = area.properties.get(key); + if (o == null) { + return false; + } else if (o instanceof Boolean) { + return (Boolean) o; + } else if (o instanceof Number) { + return ((Number) o).intValue() != 0; + } else { + return "true".equals(o) || "t".equals(o) || Character.valueOf('t').equals(o); + } + } + + public static int getInt(Area area, String key) { + Object o = area.properties.get(key); + if (o == null) { + return 0; + } else if (o instanceof Number) { + return ((Number) o).intValue(); + } else { + return o instanceof Boolean ? (Boolean) o ? 1 : 0 : 0; + } + } + + public static double getDouble(Area area, String key) { + Object o = area.properties.get(key); + if (o == null) { + return 0.0; + } else if (o instanceof Number) { + return ((Number) o).doubleValue(); + } else { + return o instanceof Boolean ? (Boolean) o ? 1.0 : 0.0 : 0.0; + } + } + + public static String getString(Area area, String key) { + return area.properties.getOrDefault(key, "").toString(); + } +} \ No newline at end of file diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..e042a8e --- /dev/null +++ b/src/main/resources/META-INF/mods.toml @@ -0,0 +1,15 @@ +modLoader="javafml" + +loaderVersion="[31,)" + +[[mods]] +modId="area_control" +version="${file.jarVersion}" +displayName="Area Control" + +# We will come back later. +credits="" + +authors="3TUSK" + +description="A comprehensive (maybe) plot management mod under Forge framework." \ No newline at end of file diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..dbabbba --- /dev/null +++ b/src/main/resources/pack.mcmeta @@ -0,0 +1 @@ +{"pack":{"pack_format":5,"description":"Things used by AreaControl mod"}} \ No newline at end of file