commit dcff9c656d2f66f10c11d4e1e7a33adce56ef9f4 Author: Adrian Victor Date: Sat May 30 20:35:24 2026 -0300 initial diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a87d264 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9e4b940 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# MacOS DS_Store files +.DS_Store + +# Gradle cache folder +.gradle + +# Gradle build folder +build + +# IntelliJ +out/ +.idea +*.iml +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Common working directory +run diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..2eecf08 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,34 @@ +plugins { + id("java-library") + id("xyz.jpenilla.run-paper") version "3.0.2" +} + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") +} + +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.11-R0.1-SNAPSHOT") +} + +java { + toolchain.languageVersion = JavaLanguageVersion.of(21) +} + +tasks { + runServer { + // Configure the Minecraft version for our task. + // This is the only required configuration besides applying the plugin. + // Your plugin's jar (or shadowJar if present) will be used automatically. + minecraftVersion("1.21.11") + jvmArgs("-Xms2G", "-Xmx2G") + } + + processResources { + val props = mapOf("version" to version, "description" to project.description) + filesMatching("plugin.yml") { + expand(props) + } + } +} diff --git a/gitignroe b/gitignroe new file mode 100644 index 0000000..f0201c9 --- /dev/null +++ b/gitignroe @@ -0,0 +1,16 @@ +bin/ +libs/ +.idea/ +.gradle/ +build/ +out/ + +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +run/ + +*.log diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..844b80e --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +group=org.adrianvictor +version=1.0-SNAPSHOT +description=Take your players to the dreamland when sleeping! +org.gradle.configuration-cache=true +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc 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..5dd3c01 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..0262dcb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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 + + + +# 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" ) + + 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 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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.kts b/settings.gradle.kts new file mode 100644 index 0000000..e8f8129 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "SweetDreams" diff --git a/src/main/java/org/adrianvictor/sweetdreams/Configuration.java b/src/main/java/org/adrianvictor/sweetdreams/Configuration.java new file mode 100644 index 0000000..2a52b89 --- /dev/null +++ b/src/main/java/org/adrianvictor/sweetdreams/Configuration.java @@ -0,0 +1,46 @@ +package org.adrianvictor.sweetdreams; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; + +public class Configuration { + private final YamlConfiguration playerStorage = new YamlConfiguration(); + private final File playerStorageFile; + private final YamlConfiguration pluginConfig = new YamlConfiguration(); + private final File pluginConfigFile = new File(""); + private final SweetDreams plugin; + + public Configuration() { + plugin = SweetDreams.getPlugin(); + playerStorageFile = new File(plugin.getDataFolder(), "playerstorage.yml"); + + if (playerStorageFile.exists()) { + try { + playerStorage.load(playerStorageFile); + } catch (IOException | InvalidConfigurationException e) { + plugin.getLogger().severe("Error loading player storage: " + e.getMessage()); + throw new RuntimeException(e); + } + } + } + + public void savePlayerStorage() { + try { + playerStorage.save(playerStorageFile); + } catch (IOException e) { + plugin.getLogger().severe("Could not save to player storage: " + e.getMessage()); + throw new RuntimeException(e); + } + } + + public YamlConfiguration getPlayerStorage() { + return playerStorage; + } + + public YamlConfiguration getPluginConfig() { + return pluginConfig; + } +} diff --git a/src/main/java/org/adrianvictor/sweetdreams/EventListener.java b/src/main/java/org/adrianvictor/sweetdreams/EventListener.java new file mode 100644 index 0000000..be2f9ac --- /dev/null +++ b/src/main/java/org/adrianvictor/sweetdreams/EventListener.java @@ -0,0 +1,122 @@ +package org.adrianvictor.sweetdreams; + +import com.destroystokyo.paper.event.player.PlayerSetSpawnEvent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityPortalEnterEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.util.Vector; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; + +public class EventListener implements Listener { + private final PlayerStorage storage; + private final Set teleporting = new HashSet<>(); + + public EventListener() { + this.storage = SweetDreams.getPlugin().getStorage(); + } + + @EventHandler + public void onPlayerBedEnterEvent(PlayerBedEnterEvent event) { + if (event.getPlayer().getWorld() == SweetDreams.getPlugin().getWorld()) { + storage.savePlayerSpawnPoint(event.getPlayer()); + event.getPlayer().sendMessage("Respawn point set."); + event.setCancelled(true); + return; + } + + Long time = event.getPlayer().getWorld().getTime(); + + if (!(time >= 13000 && time <= 23000)) { + event.setCancelled(true); + return; + } + + teleport(event.getPlayer()); + + event.setCancelled(true); + } + + @EventHandler + public void onPlayerSetSpawn(PlayerSetSpawnEvent event) { + if (event.getPlayer().getWorld() != SweetDreams.getPlugin().getWorld()) + return; + + // TODO save player spawn point on dreamlands + + event.setCancelled(true); + } + + @EventHandler + public void onPortalEnter(EntityPortalEnterEvent event) { + if (event.getEntity().getWorld() == SweetDreams.getPlugin().getWorld()) + event.setCancelled(true); + } + + @EventHandler + public void onEntityDamage(EntityDamageEvent event) { + if (event.getEntity().getWorld() != SweetDreams.getPlugin().getWorld()) return; + if (event.getEntity() instanceof Player player) { + if (event.getCause() == EntityDamageEvent.DamageCause.VOID) { + teleport(player); + + player.setVelocity(new Vector(0, 0, 0)); + player.setFallDistance(0); + } + } + } + + @EventHandler + public void onPlayerDeath(PlayerDeathEvent event) { + if (event.getEntity().getWorld() != SweetDreams.getPlugin().getWorld()) return; + Player player = event.getPlayer(); + + teleport(player); + event.setCancelled(true); + } + + private void teleport(Player player) { + UUID uuid = player.getUniqueId(); + if (!teleporting.add(uuid)) return; + + Bukkit.getScheduler().runTask(SweetDreams.getPlugin(), () -> { + try { + World playerWorld = player.getWorld(); + + if (playerWorld == SweetDreams.getPlugin().getWorld()) { + storage.savePlayer(player, PlayerStorage.StorageWorldType.SKYLANDS); + + player.teleport(Objects.requireNonNullElse( + player.getRespawnLocation(), + Bukkit.getWorld("world").getSpawnLocation() + )); + player.getInventory().clear(); + + storage.loadPlayer(player, PlayerStorage.StorageWorldType.OVERWORLD); + + player.sendMessage("You woke up from a bad dream..."); + player.playSound(player.getLocation(), Sound.ENTITY_ENDER_DRAGON_DEATH, 1.0f, 1.0f); + } else { + World world = SweetDreams.getPlugin().getWorld(); + + storage.savePlayer(player, PlayerStorage.StorageWorldType.OVERWORLD); + player.getInventory().clear(); + player.teleport(storage.loadPlayer(player, PlayerStorage.StorageWorldType.SKYLANDS)); + } + } finally { + teleporting.remove(uuid); + } + }); + } +} diff --git a/src/main/java/org/adrianvictor/sweetdreams/PlayerStorage.java b/src/main/java/org/adrianvictor/sweetdreams/PlayerStorage.java new file mode 100644 index 0000000..fdcd206 --- /dev/null +++ b/src/main/java/org/adrianvictor/sweetdreams/PlayerStorage.java @@ -0,0 +1,140 @@ +package org.adrianvictor.sweetdreams; + +import org.bukkit.Location; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +public class PlayerStorage { + private final Configuration config; + private final YamlConfiguration storage; +// Map inventories = new HashMap<>(); + + public enum StorageWorldType { + OVERWORLD("overworld"), + SKYLANDS("skylands"); + + private final String key; + + StorageWorldType(String key) { + this.key = key; + } + + public String getKey() { + return key; + } + } + + public PlayerStorage(Configuration config) { + this.config = config; + this.storage = config.getPlayerStorage(); + } + + public void savePlayer(Player player, StorageWorldType type) { + UUID uuid = player.getUniqueId(); + String base = "players." + uuid + "." + type.getKey(); + + ItemStack[] inv = player.getInventory().getContents(); + storage.set(base + ".inventory", null); + for (int i = 0; i < inv.length; i++) { + storage.set(base + ".inventory." + i, inv[i]); + } + + ItemStack[] armor = player.getInventory().getArmorContents(); + storage.set(base + ".armor", null); + for (int i = 0; i < armor.length; i++) { + storage.set(base + ".armor." + i, armor[i]); + } + + storage.set(base + ".offhand", player.getInventory().getItemInOffHand()); + + ItemStack[] ender = player.getEnderChest().getContents(); + storage.set(base + ".enderchest", null); + for (int i = 0; i < ender.length; i++) { + storage.set(base + ".enderchest." + i, ender[i]); + } + + storage.set(base + ".xp.level", player.getLevel()); + storage.set(base + ".xp.exp", player.getExp()); + storage.set(base + ".xp.total", player.getTotalExperience()); + + storage.set(base + ".stats.health", player.getHealth()); + storage.set(base + ".stats.food", player.getFoodLevel()); + storage.set(base + ".stats.saturation", player.getSaturation()); + + config.savePlayerStorage(); + } + + public Location loadPlayer(Player player, StorageWorldType type) { + UUID uuid = player.getUniqueId(); + String base = "players." + uuid + "." + type.getKey(); + + ItemStack[] inv = new ItemStack[36]; + var invSec = storage.getConfigurationSection(base + ".inventory"); + if (invSec != null) { + for (String key : invSec.getKeys(false)) { + try { + int slot = Integer.parseInt(key); + if (slot >= 0 && slot < inv.length) { + inv[slot] = storage.getItemStack(base + ".inventory." + key); + } + } catch (Exception ignored) {} + } + } + player.getInventory().setContents(inv); + + ItemStack[] armor = new ItemStack[4]; + var armorSec = storage.getConfigurationSection(base + ".armor"); + if (armorSec != null) { + for (String key : armorSec.getKeys(false)) { + try { + int slot = Integer.parseInt(key); + if (slot >= 0 && slot < armor.length) { + armor[slot] = storage.getItemStack(base + ".armor." + key); + } + } catch (Exception ignored) {} + } + } + player.getInventory().setArmorContents(armor); + + ItemStack offhand = storage.getItemStack(base + ".offhand"); + player.getInventory().setItemInOffHand(offhand); + + ItemStack[] ender = new ItemStack[27]; + var enderSec = storage.getConfigurationSection(base + ".enderchest"); + if (enderSec != null) { + for (String key : enderSec.getKeys(false)) { + try { + int slot = Integer.parseInt(key); + if (slot >= 0 && slot < ender.length) { + ender[slot] = storage.getItemStack(base + ".enderchest." + key); + } + } catch (Exception ignored) {} + } + } + player.getEnderChest().setContents(ender); + + player.setTotalExperience(storage.getInt(base + ".xp.total", 0)); + player.setLevel(storage.getInt(base + ".xp.level", 0)); + player.setExp((float) storage.getDouble(base + ".xp.exp", 0.0)); + + player.setHealth(Math.min(storage.getDouble(base + ".stats.health", 20.0), player.getMaxHealth())); + player.setFoodLevel(storage.getInt(base + ".stats.food", 20)); + player.setSaturation((float) storage.getDouble(base + ".stats.saturation", 5.0)); + + Object rawSpawn = storage.get(base + ".spawn"); + if (rawSpawn instanceof Location spawn) { + return spawn; + } else { + return SweetDreams.getPlugin().getWorld().getSpawnLocation(); + } + } + + public void savePlayerSpawnPoint(Player player) { + UUID uuid = player.getUniqueId(); + String base = "players." + uuid + ".skylands"; + storage.set(base + ".spawn", player.getLocation()); + } +} diff --git a/src/main/java/org/adrianvictor/sweetdreams/SkyIslandsGenerator.java b/src/main/java/org/adrianvictor/sweetdreams/SkyIslandsGenerator.java new file mode 100644 index 0000000..c9b3efe --- /dev/null +++ b/src/main/java/org/adrianvictor/sweetdreams/SkyIslandsGenerator.java @@ -0,0 +1,398 @@ +package org.adrianvictor.sweetdreams; + +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.generator.WorldInfo; +import org.jspecify.annotations.NonNull; + +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; + +public class SkyIslandsGenerator extends ChunkGenerator { + + private enum IslandType { + ROUND, + LONG, + ARCHIPELAGO, + SPIKY + } + + private static final IslandType[] TYPES = IslandType.values(); + + private record Blob(double x, double y, double z, double rx, double ry, double rz) {} + + private static final int CELL_SIZE = 30; + + private static final int MIN_RADIUS = 6; + private static final int MAX_RADIUS = 16; + + private static final int MIN_Y = 80; + private static final int MAX_Y = 180; + + private record LeafOffset(int dx, int dy, int dz) {} + + private static final LeafOffset[] LEAF_OFFSETS; + + static { + java.util.List offsets = new java.util.ArrayList<>(); + + for (int dx = -2; dx <= 2; dx++) { + for (int dz = -2; dz <= 2; dz++) { + for (int dy = -2; dy <= 0; dy++) { + + if (Math.abs(dx) + Math.abs(dz) <= 3) { + offsets.add(new LeafOffset(dx, dy, dz)); + } + } + } + } + + LEAF_OFFSETS = offsets.toArray(LeafOffset[]::new); + } + + @Override + public @NonNull List getDefaultPopulators(@NonNull World world) { + return Collections.singletonList(new SkylandsBlockPopulator()); + } + + @Override + public void generateSurface(WorldInfo worldInfo, @NonNull Random random, int chunkX, int chunkZ, @NonNull ChunkData chunkData) { + + long seed = worldInfo.getSeed(); + + int chunkWorldX = chunkX * 16; + int chunkWorldZ = chunkZ * 16; + + int cellX = Math.floorDiv(chunkWorldX, CELL_SIZE); + int cellZ = Math.floorDiv(chunkWorldZ, CELL_SIZE); + + short[][] highestY = new short[16][16]; + + AtomicBoolean hasTerrain = new AtomicBoolean(false); + + for (int x = 0; x < 16; x++) { + Arrays.fill(highestY[x], Short.MIN_VALUE); + } + + for (int gx = cellX - 2; gx <= cellX + 2; gx++) { + for (int gz = cellZ - 2; gz <= cellZ + 2; gz++) { + + SplittableRandom r = new SplittableRandom(hash(seed, gx, gz)); + if (r.nextDouble() > 0.8) { + continue; + } + + generateIslandGeometry( + gx, + gz, + r, + blob -> hasTerrain.set(hasTerrain.get() | carveBlob( + chunkData, + chunkX, + chunkZ, + blob, + highestY + )) + ); + + } + } + + if (!hasTerrain.get()) { + return; + } + + decorateTerrain(chunkData, random, highestY); + } + + private boolean carveBlob(ChunkData chunkData, int chunkX, int chunkZ, Blob blob, short[][] highestY) { + boolean touched = false; + + int minHeight = chunkData.getMinHeight(); + int maxHeight = chunkData.getMaxHeight() - 1; + + double invRx = 1.0 / blob.rx(); + double invRy = 1.0 / blob.ry(); + double invRz = 1.0 / blob.rz(); + + int baseX = chunkX * 16; + int baseZ = chunkZ * 16; + + int blobMinX = (int)Math.floor(blob.x() - blob.rx()); + int blobMaxX = (int)Math.ceil(blob.x() + blob.rx()); + + int blobMinZ = (int)Math.floor(blob.z() - blob.rz()); + int blobMaxZ = (int)Math.ceil(blob.z() + blob.rz()); + + int minLocalX = Math.max(0, blobMinX - baseX); + int maxLocalX = Math.min(15, blobMaxX - baseX); + + int minLocalZ = Math.max(0, blobMinZ - baseZ); + int maxLocalZ = Math.min(15, blobMaxZ - baseZ); + + for (int localX = minLocalX; localX <= maxLocalX; localX++) { + for (int localZ = minLocalZ; localZ <= maxLocalZ; localZ++) { + + int worldX = baseX + localX; + int worldZ = baseZ + localZ; + +// int minY = Math.max(chunkData.getMinHeight(), (int)Math.floor(blob.y() - blob.ry())); +// int maxY = Math.min(chunkData.getMaxHeight() -1, (int)Math.ceil(blob.y() + blob.ry())); + + double nx = (worldX - blob.x()) * invRx; + double nz = (worldZ - blob.z()) * invRz; + + double horizontal = nx * nx + nz * nz; + + if (horizontal > 1.0) + continue; + + double remaining = 1.0 - horizontal; + + if (remaining <= 0) + continue; + + double yRadius = Math.sqrt(remaining) * blob.ry(); + + int startY = Math.max( + minHeight, + (int)Math.ceil(blob.y() - yRadius) + ); + + int endY = Math.min( + maxHeight, + (int)Math.floor(blob.y() + yRadius) + ); + + for (int y = startY; y <= endY; y++) { + chunkData.setBlock(localX, y, localZ, Material.STONE); + touched = true; + } + + highestY[localX][localZ] = (short) Math.max(highestY[localX][localZ], endY); + } + } + + return touched; + } + + private void decorateTerrain(ChunkData chunkData, Random random, short[][] highestY) { + generateSurfaceLayers(chunkData, highestY); + generateOres(chunkData, random); + generateTrees(chunkData, random, highestY); + } + + private void generateSurfaceLayers(ChunkData chunkData, short[][] highestY) { + int minHeight = chunkData.getMinHeight(); + int maxHeight = chunkData.getMaxHeight() - 1; + + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + + int highest = highestY[x][z]; + + if (highest == Short.MIN_VALUE) + continue; + + chunkData.setBlock(x, highest, z, Material.GRASS_BLOCK); + + for (int y = highest - 1; y >= highest - 3; y--) { + if (y >= minHeight) { + chunkData.setBlock(x, y, z, Material.DIRT); + } + } + } + } + } + + private void generateOres(ChunkData chunkData, Random random) { + generateOreVeins(chunkData, random, Material.COAL_ORE, 25, 10); + generateOreVeins(chunkData, random, Material.IRON_ORE, 15, 8); + generateOreVeins(chunkData, random, Material.GOLD_ORE, 6, 6); + generateOreVeins(chunkData, random, Material.DIAMOND_ORE, 2, 4); + } + + private void generateOreVeins(ChunkData chunkData, Random random, Material ore, int veins, int size) { + + for (int i = 0; i < veins; i++) { + + int startX = random.nextInt(16); + int startY = chunkData.getMinHeight() + random.nextInt(chunkData.getMaxHeight() - chunkData.getMinHeight()); + + int startZ = random.nextInt(16); + + for (int j = 0; j < size; j++) { + + int x = startX + random.nextInt(5) - 2; + int y = startY + random.nextInt(5) - 2; + int z = startZ + random.nextInt(5) - 2; + + if (x < 0 || x >= 16) continue; + if (z < 0 || z >= 16) continue; + if (y < chunkData.getMinHeight()) continue; + if (y >= chunkData.getMaxHeight()) continue; + + if (chunkData.getType(x, y, z) == Material.STONE) { + chunkData.setBlock(x, y, z, ore); + } + } + } + } + + private void generateTrees(ChunkData chunkData, Random random, short[][] highestY) { + for (int x = 2; x < 14; x++) { + for (int z = 2; z < 14; z++) { + + if (random.nextInt(500) != 0) { + continue; + } + + int y = highestY[x][z]; + + if (y == Short.MIN_VALUE) { + continue; + } + + if (chunkData.getType(x, y, z) != Material.GRASS_BLOCK) { + continue; + } + + placeTree(chunkData, x, y + 1, z, random); + } + } + } + + private void placeTree(ChunkData chunkData, int x, int y, int z, Random random) { + int height = 4 + random.nextInt(3); + + for (int dy = 0; dy < height; dy++) { + chunkData.setBlock(x, y + dy, z, Material.OAK_LOG); + } + + int top = y + height; + + for (LeafOffset o : LEAF_OFFSETS) { + chunkData.setBlock( + x + o.dx(), + top + o.dy(), + z + o.dz(), + Material.OAK_LEAVES + ); + } + + chunkData.setBlock(x, top + 1, z, Material.OAK_LEAVES); + } + + private void generateIslandGeometry( + int cellX, + int cellZ, + SplittableRandom random, + java.util.function.Consumer consumer + ) { + + int centerX = cellX * CELL_SIZE + random.nextInt(CELL_SIZE); + int centerZ = cellZ * CELL_SIZE + random.nextInt(CELL_SIZE); + int centerY = MIN_Y + random.nextInt(MAX_Y - MIN_Y); + + IslandType type = + TYPES[random.nextInt(TYPES.length)]; + + switch (type) { + + case ROUND -> { + + consumer.accept( + new Blob( + centerX, + centerY, + centerZ, + 12 + random.nextInt(10), + 6 + random.nextInt(5), + 12 + random.nextInt(10) + ) + ); + } + + case LONG -> { + + double angle = random.nextDouble() * Math.PI * 2; + + int segments = 3 + random.nextInt(5); + + for (int i = 0; i < segments; i++) { + + consumer.accept( + new Blob( + centerX + Math.cos(angle) * i * 10, + centerY + random.nextInt(5) - 2, + centerZ + Math.sin(angle) * i * 10, + 8 + random.nextInt(4), + 5 + random.nextInt(2), + 8 + random.nextInt(4) + ) + ); + } + } + + case ARCHIPELAGO -> { + + int count = 3 + random.nextInt(5); + + for (int i = 0; i < count; i++) { + + consumer.accept( + new Blob( + centerX + random.nextInt(60) - 30, + centerY, + centerZ + random.nextInt(60) - 30, + 7 + random.nextInt(5), + 4 + random.nextInt(3), + 7 + random.nextInt(5) + ) + ); + } + } + + case SPIKY -> { + + consumer.accept( + new Blob(centerX, centerY, centerZ, 16, 8, 16) + ); + + for (int i = 0; i < 6; i++) { + + consumer.accept( + new Blob( + centerX + random.nextInt(20) - 10, + centerY - random.nextInt(12), + centerZ + random.nextInt(20) - 10, + 2, + 10 + random.nextInt(8), + 2 + ) + ); + } + } + } + } + + private static long hash(long seed, int x, int z) { + long h = seed; + + h ^= (long) x * 0x9E3779B97F4A7C15L; + h ^= (long) z * 0xC2B2AE3D27D4EB4FL; + + h ^= h >>> 30; + h *= 0xBF58476D1CE4E5B9L; + + h ^= h >>> 27; + h *= 0x94D049BB133111EBL; + + h ^= h >>> 31; + + return h; + } + +} \ No newline at end of file diff --git a/src/main/java/org/adrianvictor/sweetdreams/SkylandsBlockPopulator.java b/src/main/java/org/adrianvictor/sweetdreams/SkylandsBlockPopulator.java new file mode 100644 index 0000000..f893c5c --- /dev/null +++ b/src/main/java/org/adrianvictor/sweetdreams/SkylandsBlockPopulator.java @@ -0,0 +1,22 @@ +package org.adrianvictor.sweetdreams; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.LimitedRegion; +import org.bukkit.generator.WorldInfo; +import org.jspecify.annotations.NonNull; + +import java.util.Random; + +public class SkylandsBlockPopulator extends BlockPopulator { + @Override + public void populate( + @NonNull WorldInfo worldInfo, + @NonNull Random random, + int chunkX, + int chunkZ, + @NonNull LimitedRegion region + ) { + } +} diff --git a/src/main/java/org/adrianvictor/sweetdreams/SweetDreams.java b/src/main/java/org/adrianvictor/sweetdreams/SweetDreams.java new file mode 100644 index 0000000..5c95735 --- /dev/null +++ b/src/main/java/org/adrianvictor/sweetdreams/SweetDreams.java @@ -0,0 +1,86 @@ +package org.adrianvictor.sweetdreams; + +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.WorldCreator; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; + +public final class SweetDreams extends JavaPlugin { + private World world; + private static SweetDreams plugin; + private Configuration configuration; + private PlayerStorage storage; + + @Override + public void onEnable() { + plugin = this; + configuration = new Configuration(); + storage = new PlayerStorage(configuration); + + boolean generated = false; + + for (World world: getServer().getWorlds()) { + if (world.getName().equals("world_sweetdreams")) { + Bukkit.unloadWorld(world, true); + File worldFolder = new File(Bukkit.getWorldContainer(), "world_sweetdreams"); + if (worldFolder.exists()) { + deleteFolder(worldFolder); + } +// this.world = world; +// generated = true; + } + } + + if (!generated) { + world = createSkylandsWorld("world_sweetdreams"); + } + + getServer().getPluginManager().registerEvents(new EventListener(), this); + } + + private void deleteFolder(File folder) { + if (folder.isDirectory()) { + File[] files = folder.listFiles(); + if (files != null) { + for (File file : files) { + deleteFolder(file); + } + } + } + folder.delete(); + } + + @Override + public void onDisable() { + // Plugin shutdown logic + } + + public World getWorld() { + return world; + } + + public static SweetDreams getPlugin() { + return plugin; + } + + public World createSkylandsWorld(String worldName) { + WorldCreator creator = new WorldCreator(worldName); + creator.generator(new SkyIslandsGenerator()); + creator.environment(World.Environment.NORMAL); + + World world = creator.createWorld(); + world.setSpawnFlags(true, true); + + return world; + } + + public Configuration getConfiguration() { + return configuration; + } + + public PlayerStorage getStorage() { + return storage; + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/playerstorage.yml b/src/main/resources/playerstorage.yml new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..1e4f95a --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,11 @@ +name: SweetDreams +description: $description +prefix: SweetDreams +version: '${version}' + +main: org.adrianvictor.sweetdreams.SweetDreams +api-version: '1.21.11' +load: POSTWORLD + +authors: [ tenkuma ] +website: https://adrianvic.github.io