Skip to content

Commit

Permalink
very wip, not yet tested
Browse files Browse the repository at this point in the history
  • Loading branch information
MrSn0wy committed Dec 20, 2024
1 parent 01cb64f commit b601828
Show file tree
Hide file tree
Showing 9 changed files with 229 additions and 222 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### [W.I.P]
- Storage is loaded in memory instead of reading it again and again, Improves speed and IO usage
- Made it so the DeathLocation is only kept in memory (WIP)
- Improved the Storage classes and functions (I'm doing proper java, yipie)

### [v1.2.2]
- Handled a case where the client (geyser) will return the language as uppercase instead of lowercase.
- Fixed null-pointer exceptions being logged when a language file couldn't be found.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package dev.mrsnowy.teleport_commands;

import com.google.gson.*;
import com.mojang.datafixers.util.Pair;
import dev.mrsnowy.teleport_commands.storage.StorageManager;
import dev.mrsnowy.teleport_commands.commands.*;
import net.minecraft.commands.Commands;
import net.minecraft.core.BlockPos;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.storage.LevelResource;
Expand All @@ -17,8 +17,9 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import net.minecraft.core.BlockPos;

import static dev.mrsnowy.teleport_commands.utils.tools.DeathLocationUpdater;
import static dev.mrsnowy.teleport_commands.storage.StorageManager.*;

public class TeleportCommands {
public static final String MOD_ID = "teleport_commands";
Expand All @@ -42,7 +43,7 @@ public static void initializeMod(MinecraftServer server) {

SERVER = server;

cleanStorage();
StorageManager.STORAGE = storageValidator();

// initialize commands, also allows me to easily disable any when there is a config
Commands commandManager = server.getCommands();
Expand All @@ -53,27 +54,51 @@ public static void initializeMod(MinecraftServer server) {
worldspawn.register(commandManager);
}


// Runs when the playerDeath mixin calls it, updates the /back command position
public static void onPlayerDeath(ServerPlayer player) {
try {
// update /back command position
DeathLocationUpdater(new BlockPos(player.getBlockX(), player.getBlockY(), player.getBlockZ()), player.serverLevel(), player.getStringUUID());
BlockPos pos = new BlockPos(player.getBlockX(), player.getBlockY(), player.getBlockZ());

Pair<StorageManager.StorageClass, StorageManager.StorageClass.Player> storages = GetPlayerStorage(player.getStringUUID());

StorageManager.StorageClass.Player playerStorage = storages.getSecond();

playerStorage.deathLocation.x = pos.getX();
playerStorage.deathLocation.y = pos.getY();
playerStorage.deathLocation.z = pos.getZ();
playerStorage.deathLocation.world = player.serverLevel().dimension().location().toString();

StorageSaver();

} catch (Exception e) {
LOGGER.error(e.toString());
LOGGER.error("Error while saving the player death location! => ", e);
}
}

// cleans and updates Storage to the newest "version"
private static void cleanStorage() {
// private static StorageManager.StorageClass loadStorage() throws Exception {
// // double check that the storage file is intact
// StorageInit();
//
// String jsonContent = Files.readString(STORAGE_FILE);
// Gson gson = new GsonBuilder().create();
//
//}

// cleans and updates Storage to the newest "version". This is painful
private static StorageClass storageValidator() {
LOGGER.info("Cleaning and updating Storage!");

try {
StorageManager.StorageInit();
StorageInit();

long startFileSize = Files.size(StorageManager.STORAGE_FILE);

FileReader reader = new FileReader(StorageManager.STORAGE_FILE.toString());
JsonElement jsonElement = JsonParser.parseReader(reader);

if (jsonElement.isJsonObject()) {

JsonObject mainJsonObject = jsonElement.getAsJsonObject();
JsonArray newWarpsArray = new JsonArray();
JsonArray newPlayersArray = new JsonArray();
Expand All @@ -88,7 +113,6 @@ private static void cleanStorage() {
if (warpElement.isJsonObject()) {
JsonObject warp = warpElement.getAsJsonObject();


String warpName = warp.has("name") ? warp.get("name").getAsString() : "";
Integer warpX = warp.has("x") ? warp.get("x").getAsInt() : null;
Integer warpY = warp.has("y") ? warp.get("y").getAsInt() : null;
Expand All @@ -109,8 +133,6 @@ private static void cleanStorage() {
}
}
}


}


Expand Down Expand Up @@ -204,7 +226,7 @@ private static void cleanStorage() {

newPlayer.addProperty("UUID", UUID);
newPlayer.addProperty("DefaultHome", DefaultHome);
newPlayer.add("deathLocation", deathLocation);
newPlayer.add("deathLocationClass", deathLocation);
newPlayer.add("Homes", homes);

newPlayersArray.add(newPlayer);
Expand All @@ -225,12 +247,14 @@ private static void cleanStorage() {
byte[] json = gson.toJson(mainJsonObject).getBytes();
Files.write(StorageManager.STORAGE_FILE, json, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

long endFileSize = Files.size(StorageManager.STORAGE_FILE);

LOGGER.info("Success! Cleaned: {}B", Math.round((startFileSize - endFileSize)));
LOGGER.info("Success! Cleaned: {}B", Math.round(( startFileSize - Files.size(StorageManager.STORAGE_FILE) )));
return gson.fromJson(mainJsonObject, StorageManager.StorageClass.class);
}

} catch (IOException e) {
LOGGER.error("Error while cleaning the database!", e);
}
}

return null;
}
}
108 changes: 59 additions & 49 deletions common/src/main/java/dev/mrsnowy/teleport_commands/commands/back.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.datafixers.util.Pair;
import dev.mrsnowy.teleport_commands.TeleportCommands;
import dev.mrsnowy.teleport_commands.storage.StorageManager;

import java.util.*;

import dev.mrsnowy.teleport_commands.utils.tools;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.Commands;
import net.minecraft.core.BlockPos;
Expand All @@ -15,11 +15,24 @@
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.phys.Vec3;

import static dev.mrsnowy.teleport_commands.storage.StorageManager.GetPlayerStorage;
import static dev.mrsnowy.teleport_commands.utils.tools.*;
import static net.minecraft.commands.Commands.argument;

public class back {
public static final ArrayList<deathLocationClass> backList = new ArrayList<>();

public static class deathLocationClass {
final public String UUID;
final public BlockPos pos;
final public String world;

public deathLocationClass(String uuid, BlockPos pos, String world) {
this.UUID = uuid;
this.pos = pos;
this.world = world;
backList.add(this);
}
}

public static void register(Commands commandManager) {

Expand Down Expand Up @@ -58,69 +71,66 @@ public static void register(Commands commandManager) {
}


private static void ToDeathLocation(ServerPlayer player, boolean safetyDisabled) throws Exception {
StorageManager.StorageClass.Player playerStorage = GetPlayerStorage(player.getStringUUID()).getSecond();

// todo : fix... what do i need to fix LMAO

if (playerStorage.deathLocation == null) {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.noLocation", player).withStyle(ChatFormatting.RED), true);
} else {
final BlockPos pos = new BlockPos(playerStorage.deathLocation.x, playerStorage.deathLocation.y, playerStorage.deathLocation.z);
private static void ToDeathLocation(ServerPlayer player, boolean safetyDisabled) {

boolean found = false;
for (ServerLevel currentWorld : TeleportCommands.SERVER.getAllLevels()) {
Optional<deathLocationClass> OptionalDeathLocation = backList.stream()
.filter( deathLocation -> Objects.equals( deathLocation.UUID, player.getStringUUID() ))
.findFirst();

if (Objects.equals(currentWorld.dimension().location().toString(), playerStorage.deathLocation.world)) {
if (OptionalDeathLocation.isEmpty()) {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.noLocation", player).withStyle(ChatFormatting.RED), true);
return;
}

// check if the death location isn't safe and that safety isn't enabled
if (!safetyDisabled) {
deathLocationClass deathLocation = OptionalDeathLocation.get();

Pair<Integer, Optional<Vec3>> teleportData = teleportSafetyChecker(pos.getX(), pos.getY(), pos.getZ(), currentWorld, player);
Optional<ServerLevel> OptionalWorld = tools.getWorld( deathLocation.world );
if (OptionalWorld.isEmpty()) {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.noLocation", player).withStyle(ChatFormatting.RED), true);
return;
}

switch (teleportData.getFirst()) {
case 0: // safe location found!
if (teleportData.getSecond().isPresent()) {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.go", player), true);
Teleporter(player, currentWorld, teleportData.getSecond().get());
} else {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.error", player).withStyle(ChatFormatting.RED, ChatFormatting.BOLD), true);
}
ServerLevel world = OptionalWorld.get();

break;
case 1: // same
player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.same", player).withStyle(ChatFormatting.AQUA), true);
break;
case 2: // no safe location
// check if the death location isn't safe and that safety isn't enabled
if (!safetyDisabled) {

player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.noSafeLocation", player).withStyle(ChatFormatting.RED, ChatFormatting.BOLD), false);
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.safetyIsForLosers", player).withStyle(ChatFormatting.AQUA), false);
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.forceTeleport", player).withStyle(ChatFormatting.AQUA, ChatFormatting.BOLD)
.withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/back true"))),false);
break;
}
Pair<Integer, Optional<Vec3>> teleportData = teleportSafetyChecker(deathLocation.pos, world, player);

switch (teleportData.getFirst()) {
case 0: // safe location found!
if (teleportData.getSecond().isPresent()) {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.go", player), true);
Teleporter(player, world, teleportData.getSecond().get());
} else {
BlockPos playerBlockPos = new BlockPos(player.getBlockX(), player.getBlockY(), player.getBlockZ());
if (!playerBlockPos.equals(pos) || player.level() != currentWorld) {

player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.go", player), true);
Teleporter(player, currentWorld, new Vec3(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5));

} else {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.same", player).withStyle(ChatFormatting.AQUA), true);
}
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.error", player).withStyle(ChatFormatting.RED, ChatFormatting.BOLD), true);
}

break;
case 1: // same
player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.same", player).withStyle(ChatFormatting.AQUA), true);
break;
case 2: // no safe location

found = true;
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.noSafeLocation", player).withStyle(ChatFormatting.RED, ChatFormatting.BOLD), false);
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.safetyIsForLosers", player).withStyle(ChatFormatting.AQUA), false);
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.forceTeleport", player).withStyle(ChatFormatting.AQUA, ChatFormatting.BOLD)
.withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/back true"))),false);
break;
}
}

if (!found) {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.common.noLocation", player).withStyle(ChatFormatting.RED), true);
} else {
BlockPos playerBlockPos = new BlockPos(player.getBlockX(), player.getBlockY(), player.getBlockZ());

if (!playerBlockPos.equals(deathLocation.pos) || player.level() != world) {

player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.go", player), true);
Teleporter(player, world, new Vec3(deathLocation.pos.getX() + 0.5, deathLocation.pos.getY(), deathLocation.pos.getZ() + 0.5));

} else {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.back.same", player).withStyle(ChatFormatting.AQUA), true);
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -172,21 +172,15 @@ private static void SetHome(ServerPlayer player, String homeName) throws Excepti

if (homeNotFound) {
// Create a new NamedLocation
StorageManager.StorageClass.NamedLocation homeLocation = new StorageManager.StorageClass.NamedLocation();

homeLocation.name = homeName;
homeLocation.x = blockPos.getX();
homeLocation.y = blockPos.getY();
homeLocation.z = blockPos.getZ();
homeLocation.world = world.dimension().location().toString();
StorageManager.StorageClass.NamedLocation homeLocation = new StorageManager.StorageClass.NamedLocation(homeName, blockPos, world.dimension().location().toString());

playerStorage.Homes.add(homeLocation);

if (playerStorage.Homes.size() == 1) {
playerStorage.DefaultHome = homeName;
}

StorageSaver(storage);
StorageSaver();
player.displayClientMessage(getTranslatedText("commands.teleport_commands.home.set", player), true);
} else {
player.displayClientMessage(getTranslatedText("commands.teleport_commands.home.exists", player).withStyle(ChatFormatting.RED), true);
Expand Down Expand Up @@ -251,7 +245,7 @@ private static void DeleteHome(ServerPlayer player, String homeName) throws Exce
if (Objects.equals(currentHome.name, homeName)) {
// delete the home
playerStorage.Homes.remove(currentHome);
StorageSaver(storage);
StorageSaver();

deletedHome = true;
player.displayClientMessage(getTranslatedText("commands.teleport_commands.home.delete", player), true);
Expand Down Expand Up @@ -294,7 +288,7 @@ private static void RenameHome(ServerPlayer player, String homeName, String newH
}

currentHome.name = newHomeName;
StorageSaver(storage);
StorageSaver();

WarpRenamed = true;
player.displayClientMessage(getTranslatedText("commands.teleport_commands.home.rename", player), true);
Expand Down Expand Up @@ -332,7 +326,7 @@ private static void SetDefaultHome(ServerPlayer player, String homeName) throws
if (!Objects.equals(playerStorage.DefaultHome, homeName)) {

playerStorage.DefaultHome = homeName;
StorageSaver(storage);
StorageSaver();
player.displayClientMessage(getTranslatedText("commands.teleport_commands.home.default", player), true);

} else {
Expand Down
Loading

0 comments on commit b601828

Please sign in to comment.