commit d0f069bc36cd84b937b2257aa41c78325dfedc3b Author: yourfriendoss Date: Fri Oct 3 19:14:01 2025 +0300 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c37caf --- /dev/null +++ b/.gitignore @@ -0,0 +1,118 @@ +# User-specific stuff +.idea/ + +*.iml +*.ipr +*.iws + +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +**/build/ + +# Common working directory +run/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a0e67c5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2023 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bf2ef6a --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# OPaC BlueMap + +This mod will show land claims from the [Open Parties and Claims](https://modrinth.com/mod/open-parties-and-claims) mod in the maps from the [BlueMap](https://modrinth.com/mod/bluemap) mod. This has currently only been tested on 1.19.2, but may work on newer versions. + +## Usage + +Simply install both the Open Parties and Claims mod as well as the BlueMap mod (and this mod), and you should be all set! diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..f218163 --- /dev/null +++ b/build.gradle @@ -0,0 +1,116 @@ +plugins { + id 'fabric-loom' version '1.11-SNAPSHOT' + id 'io.github.juuxel.loom-quiltflower' version '1.8.0' + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +repositories { + maven { + name = "ParchmentMC" + url = "https://maven.parchmentmc.org" + } + + maven { + name = "Fuzs Mod Resources" + url = "https://raw.githubusercontent.com/Fuzss/modresources/main/maven/" + } + + maven { url = "https://maven.quiltmc.org/repository/release" } + + exclusiveContent { + forRepository { + maven { + name = "Modrinth" + url = "https://api.modrinth.com/maven" + } + } + filter { + includeGroup "maven.modrinth" + } + } + + maven { url = "https://jitpack.io" } +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings(loom.layered { + officialMojangMappings() + parchment("org.parchmentmc.data:parchment-1.21.8:2025.09.14@zip") + }) + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API. This is technically optional, but you probably want it anyway. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + modImplementation("maven.modrinth:open-parties-and-claims:fabric-1.21.1-0.25.5") + modRuntimeOnly("fuzs.forgeconfigapiport:forgeconfigapiport-fabric:5.0.6") { + exclude(group: "net.fabricmc") + exclude(group: "net.fabricmc.fabric-api") + } + + implementation("com.github.BlueMap-Minecraft:BlueMapAPI:2.7.0") + modRuntimeOnly("maven.modrinth:bluemap:3.13-fabric-1.19") + + include(implementation("org.quiltmc.qup:json:0.2.0")) +} + +processResources { + inputs.property "version", project.version + filteringCharset "UTF-8" + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +def targetJavaVersion = 21 +tasks.withType(JavaCompile).configureEach { + // ensure that the encoding is set to UTF-8, no matter what the system default is + // this fixes some edge cases with special characters not displaying correctly + // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html + // If Javadoc is generated, this must be specified in that task too. + it.options.encoding = "UTF-8" + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + it.options.release = targetJavaVersion + } +} + +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } + archivesBaseName = project.archives_base_name + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() +} + +jar { + from("LICENSE") { + rename { "${it}_${project.archivesBaseName}"} + } +} + +// configure the maven publication +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..e50b4c4 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,16 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G + +# Fabric Properties + # check these on https://modmuss50.me/fabric.html + minecraft_version=1.21.8 + loader_version=0.17.2 + +# Mod Properties + mod_version = 1.1.0 + maven_group = io.github.gaming32 + archives_base_name = opac-bluemap-integration + +# Dependencies + # check this on https://modmuss50.me/fabric.html + fabric_version=0.133.4+1.21.8 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c1962a7 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..3c44eb1 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..aeb74cb --- /dev/null +++ b/gradlew @@ -0,0 +1,245 @@ +#!/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##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && 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 + 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" && ! "$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=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=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, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..f91a4fe --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/src/main/java/io/github/gaming32/opacbluemapintegration/ChunkPosDirection.java b/src/main/java/io/github/gaming32/opacbluemapintegration/ChunkPosDirection.java new file mode 100644 index 0000000..5c07290 --- /dev/null +++ b/src/main/java/io/github/gaming32/opacbluemapintegration/ChunkPosDirection.java @@ -0,0 +1,58 @@ +package io.github.gaming32.opacbluemapintegration; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.ChunkPos; + +public enum ChunkPosDirection { + LEFT(-1, 0), + FORWARD(0, 1), + RIGHT(1, 0), + BACKWARD(0, -1); + + public final int x, z; + public final ChunkPos value; + + ChunkPosDirection(int x, int z) { + this.x = x; + this.z = z; + this.value = new ChunkPos(x, z); + } + + public ChunkPosDirection getLeft() { + return rotate(-1); + } + + public ChunkPosDirection getRight() { + return rotate(1); + } + + public ChunkPosDirection getOpposite() { + return rotate(2); + } + + public ChunkPosDirection rotate(int clockwiseDistance) { + return values()[(ordinal() + clockwiseDistance) & 3]; + } + + public ChunkPos add(ChunkPos pos) { + return new ChunkPos(pos.x + x, pos.z + z); + } + + public int getEdge(ChunkPos pos) { + return switch (this) { + case LEFT -> pos.getMinBlockX(); + case FORWARD -> pos.getMaxBlockZ() + 1; + case RIGHT -> pos.getMaxBlockX() + 1; + case BACKWARD -> pos.getMinBlockZ(); + }; + } + + public static BlockPos getCorner(ChunkPos pos, ChunkPosDirection a, ChunkPosDirection b) { + if (a == b || a.getOpposite() == b) { + throw new IllegalArgumentException("Corner can't be accessed with opposite directions"); + } + return a.x != 0 + ? new BlockPos(a.getEdge(pos), 0, b.getEdge(pos)) + : new BlockPos(b.getEdge(pos), 0, a.getEdge(pos)); + } +} diff --git a/src/main/java/io/github/gaming32/opacbluemapintegration/OpacBluemapConfig.java b/src/main/java/io/github/gaming32/opacbluemapintegration/OpacBluemapConfig.java new file mode 100644 index 0000000..7ba4102 --- /dev/null +++ b/src/main/java/io/github/gaming32/opacbluemapintegration/OpacBluemapConfig.java @@ -0,0 +1,70 @@ +package io.github.gaming32.opacbluemapintegration; + +import org.quiltmc.qup.json.JsonReader; +import org.quiltmc.qup.json.JsonWriter; + +import java.io.IOException; + +public class OpacBluemapConfig { + private int updateInterval = 12000; // Every 10 minutes + private float markerMinY = 75f; + private float markerMaxY = 75f; + private boolean depthTest = false; + + public void read(JsonReader reader) throws IOException { + reader.beginObject(); + while (reader.hasNext()) { + final String key; + switch (key = reader.nextName()) { + case "updateInterval" -> updateInterval = reader.nextInt(); + case "markerMinY" -> markerMinY = reader.nextNumber().floatValue(); + case "markerMaxY" -> markerMaxY = reader.nextNumber().floatValue(); + case "depthTest" -> depthTest = reader.nextBoolean(); + default -> { + OpacBluemapIntegration.LOGGER.warn("Unknown OPaC BlueMap config key {}. Skipping.", key); + reader.skipValue(); + } + } + } + reader.endObject(); + } + + public void write(JsonWriter writer) throws IOException { + writer.beginObject(); + + writer.comment("How often, in ticks, the markers should be refreshed. Set to 0 to disable automatic refreshing."); + writer.comment("Default is 10 minutes (12000 ticks)."); + writer.name("updateInterval").value(updateInterval); + + writer.comment("The min and max Y for the markers. If these are the same, the marker will be drawn as a flat plane."); + writer.comment("Default is 75 to 75."); + writer.name("markerMinY").value(markerMinY); + writer.name("markerMaxY").value(markerMaxY); + + writer.comment("If set to false, the markers won't be covered up by objects in front of it."); + writer.comment("Default is false."); + writer.name("depthTest").value(depthTest); + + writer.endObject(); + } + + public int getUpdateInterval() { + return updateInterval; + } + + public void setUpdateInterval(int updateInterval) { + this.updateInterval = updateInterval; + } + + public float getMarkerMinY() { + return markerMinY; + } + + public float getMarkerMaxY() { + return markerMaxY; + } + + public boolean isDepthTest() { + return depthTest; + } +} diff --git a/src/main/java/io/github/gaming32/opacbluemapintegration/OpacBluemapIntegration.java b/src/main/java/io/github/gaming32/opacbluemapintegration/OpacBluemapIntegration.java new file mode 100644 index 0000000..40ce4c6 --- /dev/null +++ b/src/main/java/io/github/gaming32/opacbluemapintegration/OpacBluemapIntegration.java @@ -0,0 +1,284 @@ +package io.github.gaming32.opacbluemapintegration; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.logging.LogUtils; +import de.bluecolored.bluemap.api.BlueMapAPI; +import de.bluecolored.bluemap.api.BlueMapWorld; +import de.bluecolored.bluemap.api.markers.ExtrudeMarker; +import de.bluecolored.bluemap.api.markers.Marker; +import de.bluecolored.bluemap.api.markers.MarkerSet; +import de.bluecolored.bluemap.api.markers.ShapeMarker; +import de.bluecolored.bluemap.api.math.Color; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.ChatFormatting; +import net.minecraft.commands.arguments.TimeArgument; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.Mth; +import net.minecraft.world.level.ChunkPos; +import org.apache.commons.lang3.StringUtils; +import org.quiltmc.qup.json.JsonReader; +import org.quiltmc.qup.json.JsonWriter; +import org.slf4j.Logger; +import xaero.pac.common.claims.player.api.IPlayerClaimPosListAPI; +import xaero.pac.common.server.api.OpenPACServerAPI; + +import java.nio.file.Path; +import java.util.*; +import java.util.stream.Collectors; + +import static net.minecraft.commands.Commands.argument; +import static net.minecraft.commands.Commands.literal; + +public class OpacBluemapIntegration implements ModInitializer { + public static final Logger LOGGER = LogUtils.getLogger(); + + private static final String MARKER_SET_KEY = "opac-bluemap-integration"; + private static final Path CONFIG_FILE = FabricLoader.getInstance().getConfigDir().resolve("opac-bluemap.json5"); + + public static final OpacBluemapConfig CONFIG = new OpacBluemapConfig(); + + private static MinecraftServer minecraftServer; + + private static int updateIn; + + @Override + public void onInitialize() { + loadConfig(); + BlueMapAPI.onEnable(OpacBluemapIntegration::updateClaims); + ServerLifecycleEvents.SERVER_STARTING.register(server -> minecraftServer = server); + ServerLifecycleEvents.SERVER_STOPPED.register(server -> minecraftServer = null); + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(literal("opac-bluemap") + .requires(s -> s.hasPermission(2)) + .then(literal("refresh-now") + .requires(s -> BlueMapAPI.getInstance().isPresent()) + .executes(ctx -> { + final BlueMapAPI api = BlueMapAPI.getInstance().orElse(null); + if (api == null) { + ctx.getSource().sendFailure(Component.literal("BlueMap not loaded").withStyle(ChatFormatting.RED)); + return 0; + } + updateClaims(api); + ctx.getSource().sendSuccess( + () -> Component.literal("BlueMap OPaC claims refreshed").withStyle(ChatFormatting.GREEN), + true + ); + return Command.SINGLE_SUCCESS; + }) + ) + .then(literal("refresh-in") + .executes(ctx -> { + ctx.getSource().sendSuccess( + () -> Component.literal("OPaC BlueMap will refresh in ").append( + Component.literal((updateIn / 20) + "s").withStyle(ChatFormatting.GREEN) + ), + true + ); + return Command.SINGLE_SUCCESS; + }) + .then(argument("time", TimeArgument.time()) + .executes(ctx -> { + updateIn = IntegerArgumentType.getInteger(ctx, "time"); + ctx.getSource().sendSuccess( + () -> Component.literal("OPaC BlueMap will refresh in ").append( + Component.literal((updateIn / 20) + "s").withStyle(ChatFormatting.GREEN) + ), + true + ); + return Command.SINGLE_SUCCESS; + }) + ) + ) + .then(literal("refresh-every") + .executes(ctx -> { + ctx.getSource().sendSuccess( + () -> Component.literal("OPaC BlueMap auto refreshes every ").append( + Component.literal((CONFIG.getUpdateInterval() / 20) + "s").withStyle(ChatFormatting.GREEN) + ), + true + ); + return Command.SINGLE_SUCCESS; + }) + .then(argument("interval", TimeArgument.time()) + .executes(ctx -> { + final int interval = IntegerArgumentType.getInteger(ctx, "interval"); + CONFIG.setUpdateInterval(interval); + if (interval < updateIn) { + updateIn = interval; + } + saveConfig(); + ctx.getSource().sendSuccess( + () -> Component.literal("OPaC BlueMap will auto refresh every ").append( + Component.literal((interval / 20) + "s").withStyle(ChatFormatting.GREEN) + ), + true + ); + return Command.SINGLE_SUCCESS; + }) + ) + ) + .then(literal("reload") + .executes(ctx -> { + loadConfig(); + if (CONFIG.getUpdateInterval() < updateIn) { + updateIn = CONFIG.getUpdateInterval(); + } + ctx.getSource().sendSuccess( + () -> Component.literal("Reloaded OPaC BlueMap config").withStyle(ChatFormatting.GREEN), + true + ); + return Command.SINGLE_SUCCESS; + }) + ) + ); + }); + ServerTickEvents.END_SERVER_TICK.register(server -> { + if (updateIn <= 0) return; + if (--updateIn <= 0) { + BlueMapAPI.getInstance().ifPresent(OpacBluemapIntegration::updateClaims); + } + }); + } + + public static void loadConfig() { + try (JsonReader reader = JsonReader.json5(CONFIG_FILE)) { + CONFIG.read(reader); + } catch (Exception e) { + LOGGER.warn("Failed to read {}.", CONFIG_FILE, e); + } + saveConfig(); + } + + public static void saveConfig() { + try (JsonWriter writer = JsonWriter.json5(CONFIG_FILE)) { + CONFIG.write(writer); + } catch (Exception e) { + LOGGER.error("Failed to write {}.", CONFIG_FILE, e); + } + LOGGER.info("Saved OPaC BlueMap config"); + } + + public static void updateClaims(BlueMapAPI blueMap) { + if (minecraftServer == null) { + LOGGER.warn("updateClaims called with minecraftServer == null!"); + return; + } + LOGGER.info("Refreshing OPaC BlueMap markers"); + OpenPACServerAPI.get(minecraftServer) + .getServerClaimsManager() + .getPlayerInfoStream() + .forEach(playerClaimInfo -> { + String name = playerClaimInfo.getClaimsName(); + final String idName; + if (StringUtils.isBlank(name)) { + idName = name = playerClaimInfo.getPlayerUsername(); + if (name.length() > 2 && name.charAt(0) == '"' && name.charAt(name.length() - 1) == '"') { + name = name.substring(1, name.length() - 1) + " claim"; + } else { + name += "'s claim"; + } + } else { + idName = name; + } + final String displayName = name; + playerClaimInfo.getStream().forEach(entry -> { + final BlueMapWorld world = blueMap.getWorld(ResourceKey.create(Registries.DIMENSION, entry.getKey())).orElse(null); + if (world == null) return; + final List shapes = createShapes( + entry.getValue() + .getStream() + .flatMap(IPlayerClaimPosListAPI::getStream) + .collect(Collectors.toSet()) + ); + world.getMaps().forEach(map -> { + final Map markers = map + .getMarkerSets() + .computeIfAbsent(MARKER_SET_KEY, k -> + MarkerSet.builder() + .toggleable(true) + .label("Open Parties and Claims") + .build() + ) + .getMarkers(); + final float minY = CONFIG.getMarkerMinY(); + final float maxY = CONFIG.getMarkerMaxY(); + //noinspection SuspiciousNameCombination + final boolean flatPlane = Mth.equal(minY, maxY); + markers.keySet().removeIf(k -> k.startsWith(idName + "---")); + for (int i = 0; i < shapes.size(); i++) { + final ShapeHolder shape = shapes.get(i); + markers.put(idName + "---" + i, + // Yes these builders are the same. No they don't share a superclass (except for label). + flatPlane + ? ShapeMarker.builder() + .label(displayName) + .fillColor(new Color(playerClaimInfo.getClaimsColor(), 150)) + .lineColor(new Color(playerClaimInfo.getClaimsColor(), 255)) + .shape(shape.baseShape(), minY) + .holes(shape.holes()) + .depthTestEnabled(CONFIG.isDepthTest()) + .build() + : ExtrudeMarker.builder() + .label(displayName) + .fillColor(new Color(playerClaimInfo.getClaimsColor(), 150)) + .lineColor(new Color(playerClaimInfo.getClaimsColor(), 255)) + .shape(shape.baseShape(), minY, maxY) + .holes(shape.holes()) + .depthTestEnabled(CONFIG.isDepthTest()) + .build() + ); + } + }); + }); + }); + LOGGER.info("Refreshed OPaC BlueMap markers"); + updateIn = CONFIG.getUpdateInterval(); + } + + public static List createShapes(Set chunks) { + return createChunkGroups(chunks) + .stream() + .map(ShapeHolder::create) + .toList(); + } + + public static List> createChunkGroups(Set chunks) { + final List> result = new ArrayList<>(); + final Set visited = new HashSet<>(); + for (final ChunkPos chunk : chunks) { + if (visited.contains(chunk)) continue; + final Set neighbors = findNeighbors(chunk, chunks); + result.add(neighbors); + visited.addAll(neighbors); + } + return result; + } + + public static Set findNeighbors(ChunkPos chunk, Set chunks) { + if (!chunks.contains(chunk)) { + throw new IllegalArgumentException("chunks must contain chunk to find neighbors!"); + } + final Set visited = new HashSet<>(); + final Queue toVisit = new ArrayDeque<>(); + visited.add(chunk); + toVisit.add(chunk); + while (!toVisit.isEmpty()) { + final ChunkPos visiting = toVisit.remove(); + for (final ChunkPosDirection dir : ChunkPosDirection.values()) { + final ChunkPos offsetPos = dir.add(visiting); + if (!chunks.contains(offsetPos) || !visited.add(offsetPos)) continue; + toVisit.add(offsetPos); + } + } + return visited; + } +} diff --git a/src/main/java/io/github/gaming32/opacbluemapintegration/ShapeHolder.java b/src/main/java/io/github/gaming32/opacbluemapintegration/ShapeHolder.java new file mode 100644 index 0000000..045a6c7 --- /dev/null +++ b/src/main/java/io/github/gaming32/opacbluemapintegration/ShapeHolder.java @@ -0,0 +1,131 @@ +package io.github.gaming32.opacbluemapintegration; + +import com.flowpowered.math.vector.Vector2d; +import de.bluecolored.bluemap.api.math.Shape; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.ChunkPos; + +import java.util.*; +import java.util.stream.Collectors; + +public record ShapeHolder(Shape baseShape, Shape... holes) { + public static ShapeHolder create(Set chunks) { + return new ShapeHolder( + createBaseShape(chunks), + OpacBluemapIntegration.createChunkGroups(cutoutChunks(chunks)) + .stream() + .map(ShapeHolder::createBaseShape) + .toArray(Shape[]::new) + ); + } + + private static Shape createBaseShape(Set chunks) { + ChunkPos firstChunk = getBound(chunks, Math::min); + while (!chunks.contains(firstChunk)) { + // Step right until we hit a real chunk + firstChunk = ChunkPosDirection.RIGHT.add(firstChunk); + } + final List points = new ArrayList<>(); + points.add(new Vector2d(firstChunk.getMinBlockX(), firstChunk.getMinBlockZ())); + + ChunkPos current = firstChunk; + ChunkPosDirection direction = ChunkPosDirection.RIGHT; + do { + points.add(vector(ChunkPosDirection.getCorner(current, direction, direction.getRight()))); + final ChunkPos next = direction.add(current); + if (chunks.contains(next)) { + final ChunkPos right = direction.getRight().add(next); + if (chunks.contains(right)) { + current = right; + direction = direction.getRight(); + } else { + current = next; + } + } else { + direction = direction.getLeft(); + } + } while (!current.equals(firstChunk) || direction != ChunkPosDirection.RIGHT); + + return new Shape(simplifyPoints(points)); + } + + private static Set cutoutChunks(Set chunks) { + final ChunkPos minChunk = getBound(chunks, Math::min); + final ChunkPos maxChunk = getBound(chunks, Math::max); + + final Queue toVisit = new ArrayDeque<>(); + for (int x = minChunk.x; x <= maxChunk.x; x++) { + for (int z = minChunk.z; z <= maxChunk.z; z++) { + if (x > minChunk.x && x < maxChunk.x && z > minChunk.z && z < maxChunk.z) continue; + final ChunkPos chunk = new ChunkPos(x, z); + if (chunks.contains(chunk)) continue; + toVisit.add(chunk); + } + } + + final Set outsideChunks = new HashSet<>(toVisit); + while (!toVisit.isEmpty()) { + final ChunkPos chunk = toVisit.remove(); + for (final ChunkPosDirection dir : ChunkPosDirection.values()) { + final ChunkPos offsetPos = dir.add(chunk); + if ( + offsetPos.x < minChunk.x || offsetPos.x > maxChunk.x || + offsetPos.z < minChunk.z || offsetPos.z > maxChunk.z || + chunks.contains(offsetPos) || !outsideChunks.add(offsetPos) + ) continue; + toVisit.add(offsetPos); + } + } + + return ChunkPos.rangeClosed(minChunk, maxChunk) + .filter(c -> !chunks.contains(c) && !outsideChunks.contains(c)) + .collect(Collectors.toSet()); + } + + private static Vector2d vector(BlockPos pos) { + return new Vector2d(pos.getX(), pos.getZ()); + } + + private static List simplifyPoints(List points) { + if (points.size() < 4) { + return points; + } + + final List result = new ArrayList<>(); + result.add(points.get(0)); + + for (int i = 1; i < points.size() - 1; i++) { + final Vector2d last = points.get(i - 1); + final Vector2d point = points.get(i); + final Vector2d next = points.get(i + 1); + if (!point.sub(last).normalize().equals(next.sub(point).normalize())) { + result.add(point); + } + } + + final Vector2d lastPoint = points.get(points.size() - 1); + if (!lastPoint.equals(points.get(0))) { + result.add(lastPoint); + } + + return result; + } + + private static ChunkPos getBound(Iterable chunks, IntSelector selector) { + final Iterator iterator = chunks.iterator(); + final ChunkPos first = iterator.next(); + int x = first.x; + int z = first.z; + while (iterator.hasNext()) { + final ChunkPos pos = iterator.next(); + x = selector.select(x, pos.x); + z = selector.select(z, pos.z); + } + return new ChunkPos(x, z); + } + + @FunctionalInterface + private interface IntSelector { + int select(int a, int b); + } +} diff --git a/src/main/resources/assets/opac-bluemap-integration/icon.png b/src/main/resources/assets/opac-bluemap-integration/icon.png new file mode 100644 index 0000000..dcc960c Binary files /dev/null and b/src/main/resources/assets/opac-bluemap-integration/icon.png differ diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..23a93fe --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,31 @@ +{ + "schemaVersion": 1, + "id": "opac-bluemap-integration", + "version": "${version}", + "name": "OPaC BlueMap", + "description": "Syncs your Open Parties and Claims land claims to your BlueMap maps", + "authors": [ + "Gaming32" + ], + "contact": { + "repo": "https://github.com/Gaming32/opac-bluemap-integration" + }, + "license": "MIT", + "icon": "assets/opac-bluemap-integration/icon.png", + "environment": "*", + "entrypoints": { + "main": [ + "io.github.gaming32.opacbluemapintegration.OpacBluemapIntegration" + ] + }, + "mixins": [ + "opac-bluemap-integration.mixins.json" + ], + "depends": { + "fabricloader": ">=0.14.0", + "fabric": "*", + "minecraft": ">=1.19.2", + "bluemap": ">=3.13", + "openpartiesandclaims": ">=0.17.6" + } +} diff --git a/src/main/resources/opac-bluemap-integration.mixins.json b/src/main/resources/opac-bluemap-integration.mixins.json new file mode 100644 index 0000000..e48bc22 --- /dev/null +++ b/src/main/resources/opac-bluemap-integration.mixins.json @@ -0,0 +1,13 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "io.github.gaming32.opacbluemapintegration.mixin", + "compatibilityLevel": "JAVA_17", + "mixins": [ + ], + "client": [ + ], + "injectors": { + "defaultRequire": 1 + } +}