mirror of
https://github.com/Cubicake/RaycastedAntiESP.git
synced 2026-11-17 06:26:04 -05:00
Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0823dc9a83 | ||
|
|
36a44c9e0d | ||
|
|
29f7ec211a | ||
|
|
38c39aecc5 | ||
|
|
70ec4c212f | ||
|
|
d5026d28d4 | ||
|
|
df5e9f6ca8 | ||
|
|
61831a813a | ||
|
|
9ca8b4ee3a | ||
|
|
635f407c3a | ||
|
|
c18b30da36 | ||
|
|
b524cfdf10 | ||
|
|
968c803106 | ||
|
|
77c5a18433 | ||
|
|
081e762c5c | ||
|
|
1733fd1884 | ||
|
|
773378e6cb | ||
|
|
ac67aa8786 | ||
|
|
40bbaeb5ff | ||
|
|
76f5816162 | ||
|
|
1201ff1370 | ||
|
|
11f1c6ecb7 | ||
|
|
0a6302674d | ||
|
|
4283dfd87b | ||
|
|
9d01af18f3 | ||
|
|
77dd9bb31a | ||
|
|
47f862323b | ||
|
|
c356ed0172 | ||
|
|
7e0725c538 | ||
|
|
6dc3f2f84e | ||
|
|
8e76557a88 | ||
|
|
f76e2bbcf7 | ||
|
|
87cd59b346 | ||
|
|
a151bdbeca | ||
|
|
6d288de95b | ||
|
|
aa0ebdbc93 | ||
|
|
af50b9c69c | ||
|
|
963fbbe9be | ||
|
|
02ef0c3343 | ||
|
|
1ac6e6b50b | ||
|
|
f1dfe64d67 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: cubicake
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
+3
-1
@@ -1,11 +1,13 @@
|
||||
# User-specific stuff
|
||||
.idea/
|
||||
|
||||
README.md
|
||||
*.md
|
||||
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
|
||||
README.md
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Latest version: v1.5.1
|
||||
Latest version: v1.6.0
|
||||
|
||||
The latest version can currently only be found on Modrinth https://modrinth.com/plugin/raycasted-entity-occlusions/
|
||||
|
||||
@@ -15,7 +15,10 @@ Use cases:
|
||||
- Massive megabases containing hundreds of armour stands, item frames, banners etc can cause performance issues on low-end devices unable to process so many entities. REO will cull those entities for the client, reducing the number of entities to process.
|
||||
- Hide nametags behind walls
|
||||
- Yes, this plugin is a bit overkill for doing that, yes you can do it anyways.
|
||||
|
||||
Dependencies:
|
||||
- Packetevents (soft depend)
|
||||
- Only needed if you are using the cull-players option and wish for the players to remain in the tablist
|
||||
|
||||
Known issues:
|
||||
- Due to the nature of the plugin, there will be a short delay once an entity should be visible before it appears, causing it to appear like it "popped" into view. This issue is partially resolved by turning engine-mode to 2
|
||||
- If cull-player is set to true any culled players will be removed from tablist. Potential solutions are being investigated, suggestions are welcome.
|
||||
- Due to the nature of the plugin, there will be a short delay once an entity should be visible before it appears, causing it to appear like it "popped" into view. This issue is partially resolved by turning engine-mode to 2, and is worse for players with higher ping.
|
||||
+18
-2
@@ -1,9 +1,10 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id("xyz.jpenilla.run-paper") version "2.3.1"
|
||||
}
|
||||
|
||||
group = 'games.cubi'
|
||||
version = '1.6.0-dev-1'
|
||||
version = '1.7.0-pre-alpha'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
@@ -21,7 +22,7 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
|
||||
compileOnly("com.github.retrooper:packetevents-spigot:2.8.0")
|
||||
}
|
||||
|
||||
@@ -50,4 +51,19 @@ processResources {
|
||||
filesMatching('plugin.yml') {
|
||||
expand props
|
||||
}
|
||||
}
|
||||
|
||||
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.8")
|
||||
}
|
||||
}
|
||||
|
||||
jar {
|
||||
manifest {
|
||||
attributes "paperweight-mappings-namespace": "mojang"
|
||||
}
|
||||
}
|
||||
+17
-15
@@ -1,4 +1,4 @@
|
||||
package games.cubi.raycastedEntityOcclusion;
|
||||
package games.cubi.raycastedAntiESP;
|
||||
|
||||
import com.mojang.brigadier.Command;
|
||||
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||
@@ -11,21 +11,23 @@ import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
|
||||
import games.cubi.raycastedAntiESP.config.ConfigManager;
|
||||
|
||||
|
||||
|
||||
public class CommandsManager {
|
||||
private final RaycastedEntityOcclusion plugin;
|
||||
private final RaycastedAntiESP plugin;
|
||||
private final ConfigManager cfg;
|
||||
|
||||
public CommandsManager(RaycastedEntityOcclusion plugin, ConfigManager cfg) {
|
||||
public CommandsManager(RaycastedAntiESP plugin, ConfigManager cfg) {
|
||||
this.plugin = plugin;
|
||||
this.cfg = cfg;
|
||||
}
|
||||
|
||||
public LiteralCommandNode<CommandSourceStack> registerCommand() {
|
||||
//run help command if no context provided
|
||||
LiteralCommandNode<CommandSourceStack> buildCommand = Commands.literal("raycastedentityocclusions")
|
||||
.requires(sender -> sender.getSender().hasPermission("raycastedentityocclusions.command"))
|
||||
LiteralCommandNode<CommandSourceStack> buildCommand = Commands.literal("raycastedantiesp")
|
||||
.requires(sender -> sender.getSender().hasPermission("raycastedantiesp.command"))
|
||||
.executes(context -> {
|
||||
helpCommand(context);
|
||||
return Command.SINGLE_SUCCESS;
|
||||
@@ -35,19 +37,19 @@ public class CommandsManager {
|
||||
.then(Commands.literal("reload")
|
||||
.executes(context -> {
|
||||
cfg.load();
|
||||
context.getSource().getSender().sendMessage("[EntityOcclusions] Config reloaded.");
|
||||
context.getSource().getSender().sendMessage("[RaycastedAntiESP] Config reloaded.");
|
||||
return Command.SINGLE_SUCCESS;
|
||||
}))
|
||||
.then(Commands.literal("config-values")
|
||||
.executes(context -> {
|
||||
CommandSender sender = context.getSource().getSender();
|
||||
//dynamic config values
|
||||
sender.sendMessage("[EntityOcclusions] Config values: ");
|
||||
sender.sendMessage("[RaycastedAntiESP] Config values: ");
|
||||
|
||||
ConfigurationSection root = cfg.cfg.getConfigurationSection("");
|
||||
ConfigurationSection root = cfg.getConfigFile().getConfigurationSection("");
|
||||
for (String path : root.getKeys(true)) {
|
||||
Object val = cfg.cfg.get(path);
|
||||
|
||||
Object val = cfg.getConfigFile().get(path);
|
||||
if (val instanceof ConfigurationSection) continue;
|
||||
sender.sendMessage(MiniMessage.miniMessage().deserialize("<green>" + path + "<gray> = <white>" + val));
|
||||
}
|
||||
return Command.SINGLE_SUCCESS;
|
||||
@@ -56,7 +58,7 @@ public class CommandsManager {
|
||||
.then(Commands.literal("set")
|
||||
.executes(context -> {
|
||||
CommandSender sender = context.getSource().getSender();
|
||||
sender.sendRichMessage("<red>Usage: /raycastedentityocclusions set <key> <value>");;
|
||||
sender.sendRichMessage("<red>Usage: /raycastedantiesp set <key> <value>");;
|
||||
return 0;
|
||||
})
|
||||
.then(Commands.argument("key", StringArgumentType.string())
|
||||
@@ -100,11 +102,11 @@ public class CommandsManager {
|
||||
|
||||
public int helpCommand(CommandContext<CommandSourceStack> context) {
|
||||
CommandSender sender = context.getSource().getSender();
|
||||
sender.sendRichMessage("<white>RaycastedEntityOcclusions <yellow>v" + plugin.getDescription().getVersion());
|
||||
sender.sendRichMessage("<white>RaycastedAntiESP <yellow>v" + plugin.getDescription().getVersion());
|
||||
sender.sendRichMessage("<white>Commands:");
|
||||
sender.sendRichMessage("<green>/raycastedentityocclusions reload <gray>- Reloads the config");
|
||||
sender.sendRichMessage("<green>/raycastedentityocclusions config-values <gray>- Shows all config values");
|
||||
sender.sendRichMessage("<green>/raycastedentityocclusions set <key> <value> <gray>- Sets a config value");
|
||||
sender.sendRichMessage("<green>/raycastedantiesp reload <gray>- Reloads the config");
|
||||
sender.sendRichMessage("<green>/raycastedantiesp config-values <gray>- Shows all config values");
|
||||
sender.sendRichMessage("<green>/raycastedantiesp set <key> <value> <gray>- Sets a config value");
|
||||
return Command.SINGLE_SUCCESS;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package games.cubi.raycastedAntiESP;
|
||||
|
||||
import com.destroystokyo.paper.event.server.ServerTickStartEvent;
|
||||
import games.cubi.raycastedAntiESP.packets.PacketProcessor;
|
||||
import games.cubi.raycastedAntiESP.snapshot.ChunkSnapshotManager;
|
||||
import games.cubi.raycastedAntiESP.data.DataHolder;
|
||||
import games.cubi.raycastedAntiESP.config.ConfigManager;
|
||||
import games.cubi.raycastedAntiESP.utils.Enums;
|
||||
import io.papermc.paper.event.entity.EntityMoveEvent;
|
||||
import io.papermc.paper.event.player.PlayerTrackEntityEvent;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockBurnEvent;
|
||||
import org.bukkit.event.block.BlockExplodeEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.world.ChunkLoadEvent;
|
||||
import org.bukkit.event.world.ChunkUnloadEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static games.cubi.raycastedAntiESP.UpdateChecker.checkForUpdates;
|
||||
|
||||
public class EventListener implements Listener {
|
||||
private final ChunkSnapshotManager manager;
|
||||
private final ConfigManager config;
|
||||
private PacketProcessor packetProcessor;
|
||||
private final RaycastedAntiESP plugin;
|
||||
|
||||
private static EventListener instance = null;
|
||||
|
||||
private EventListener(RaycastedAntiESP plugin, ChunkSnapshotManager mgr, ConfigManager cfg) {
|
||||
this.manager = mgr;
|
||||
this.config = cfg;
|
||||
this.plugin = plugin;
|
||||
//load packet processor after a tick in a bukkit runnable to ensure the plugin is fully loaded TODO: All schedulers should migrate to paper/folia scheduler, also this should be moved somewhere else, maybe when the config gets the update it passes it on?
|
||||
Bukkit.getScheduler().runTaskLater(plugin, () -> {
|
||||
if (DataHolder.isPacketEventsPresent()) {
|
||||
packetProcessor = RaycastedAntiESP.getPacketProcessor();
|
||||
} else {
|
||||
packetProcessor = null;
|
||||
}
|
||||
}, 1L);
|
||||
}
|
||||
|
||||
public static EventListener getInstance(RaycastedAntiESP plugin, ChunkSnapshotManager mgr, ConfigManager cfg) {
|
||||
if (instance == null) {
|
||||
instance = new EventListener(plugin, mgr, cfg);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
// Snapshot events
|
||||
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
|
||||
public void onChunkLoad(ChunkLoadEvent e) {
|
||||
manager.onChunkLoad(e.getChunk());
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
|
||||
public void onChunkUnload(ChunkUnloadEvent e) {
|
||||
manager.onChunkUnload(e.getChunk());
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
|
||||
public void onPlace(BlockPlaceEvent e) {
|
||||
manager.onBlockChange(e.getBlock().getLocation(), e.getBlock().getType(), Enums.BlockChangeType.BROKEN);
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
|
||||
public void onBreak(BlockBreakEvent e) {
|
||||
manager.onBlockChange(e.getBlock().getLocation(), Material.AIR, Enums.BlockChangeType.BROKEN);
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
|
||||
public void onBurn(BlockBurnEvent e) {
|
||||
manager.onBlockChange(e.getBlock().getLocation(), Material.AIR, Enums.BlockChangeType.BROKEN);
|
||||
}
|
||||
|
||||
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
|
||||
public void onExplode(BlockExplodeEvent e) {
|
||||
manager.onBlockChange(e.getBlock().getLocation(), e.getBlock().getType(), Enums.BlockChangeType.BROKEN);
|
||||
}
|
||||
// These events do not cover all cases, but I can't be bothered to figure out a better solution rn. Frequent snapshot refreshes is the solution. If anyone has a solution please let me know.
|
||||
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPlayerDisconnect(PlayerQuitEvent e) {
|
||||
if (DataHolder.isPacketEventsPresent() && packetProcessor != null) {
|
||||
UUID player = e.getPlayer().getUniqueId();
|
||||
packetProcessor.sendPlayerInfoRemovePacket(player);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if (player.hasPermission("raycastedentityocclusions.updatecheck")) {
|
||||
checkForUpdates(plugin, player);
|
||||
}
|
||||
DataHolder.players().registerPlayer(player.getUniqueId(), player.hasPermission("raycastedentityocclusions.bypass"));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST) //Runs first
|
||||
public void serverTickStartEvent(ServerTickStartEvent event) {
|
||||
DataHolder.incrementTick();
|
||||
//TODO: connect this to new engine
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR) //Runs last
|
||||
public void serverTickStopEvent(ServerTickStartEvent event) {
|
||||
DataHolder.incrementTick();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onEntityMove(EntityMoveEvent event) {
|
||||
DataHolder.entityLocation().queueEntityLocationUpdate(event.getEntity().getUniqueId(), event.getTo().add(0,event.getEntity().getHeight()/2,0));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlayerTrackEntity(PlayerTrackEntityEvent event) {
|
||||
UUID entityUUID = event.getEntity().getUniqueId();
|
||||
Player player = event.getPlayer();
|
||||
UUID playerUUID = player.getUniqueId();
|
||||
|
||||
if (DataHolder.entityVisibility().entityVisibilityShouldChange(entityUUID, playerUUID)) return; // The player is meant to see the entity, do nothing
|
||||
|
||||
event.setCancelled(true);
|
||||
DataHolder.entityVisibility().hideEntity(entityUUID, player);
|
||||
DataHolder.players().getPlayerData(playerUUID).addEntity(entityUUID);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlayerUntrackEntity(PlayerTrackEntityEvent event) {
|
||||
UUID entityUUID = event.getEntity().getUniqueId();
|
||||
Player player = event.getPlayer();
|
||||
UUID playerUUID = player.getUniqueId();
|
||||
|
||||
if (DataHolder.entityVisibility().entityVisibilityShouldChange(entityUUID, playerUUID)) return; // State change was triggered by us, do nothing
|
||||
|
||||
DataHolder.players().getPlayerData(playerUUID).removeEntity(entityUUID); // Remove entity from player's data as they are no longer tracking it, so no more raycasts are needed
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package games.cubi.raycastedAntiESP;
|
||||
|
||||
import games.cubi.raycastedAntiESP.config.DebugConfig;
|
||||
import games.cubi.raycastedAntiESP.utils.CheckPreviousLogForError;
|
||||
import org.jetbrains.annotations.Range;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class Logger {
|
||||
/*
|
||||
* Logging severity is from 0-10. If the configured severity is 0, no logs will be sent. If 1, only most important logs.
|
||||
*
|
||||
* Therefore, logs with level of 1 are most important and 10 least
|
||||
*
|
||||
* Note that by default the log levels are at 3, so any logs which should appear normally should be at 1-3. Additionally, loggers which fire every tick (or more often) should be at 10, and loggers firing frequently at 7-9
|
||||
* */
|
||||
private static final CheckPreviousLogForError earlyReturn = new CheckPreviousLogForError();
|
||||
|
||||
private enum Level {
|
||||
INFO,
|
||||
WARN,
|
||||
ERROR
|
||||
}
|
||||
|
||||
private static int getLevel(Level severity, DebugConfig debug) {
|
||||
return switch (severity) {
|
||||
case INFO -> debug.getInfoLevel();
|
||||
case WARN -> debug.getWarnLevel();
|
||||
case ERROR -> debug.getErrorLevel();
|
||||
default -> 1;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Logs a warning message and serves as an early return. Nothing called after this method will be executed.
|
||||
* @param throwable The throwable to log, used for the included stack trace. The message of the throwable will be used as the warning message
|
||||
* @throws CheckPreviousLogForError Always throws this to allow for early return from functions after logging an error
|
||||
* **/
|
||||
public static void warningAndReturn(Throwable throwable) {
|
||||
warning(processThrowable(throwable), 1);
|
||||
throw earlyReturn;
|
||||
}
|
||||
|
||||
public static void error(Throwable throwable) {
|
||||
error(processThrowable(throwable), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an error message including stack trace and serves as an early return. Nothing called after this method will be executed.
|
||||
* @param throwable The throwable to log, used for the included stack trace. The message of the throwable will be used as the error message
|
||||
* @throws CheckPreviousLogForError Always throws this to allow for early return from functions after logging an error
|
||||
* **/
|
||||
|
||||
public static void errorAndReturn(Throwable throwable) {
|
||||
error(processThrowable(throwable), 1);
|
||||
throw earlyReturn;
|
||||
}
|
||||
|
||||
private static String processThrowable(Throwable throwable) {
|
||||
StackTraceElement[] thrown = throwable.getStackTrace();
|
||||
StringBuilder message = new StringBuilder(throwable.getMessage() != null ? throwable.getMessage() : "No error message set");
|
||||
for (int i = 0; i < Math.min(3, thrown.length); i++) {
|
||||
StackTraceElement element = thrown[i];
|
||||
message.append(" at ").append(element.toString());
|
||||
|
||||
}
|
||||
return message.toString();
|
||||
}
|
||||
|
||||
public static void info(String message, @Range(from = 1, to = 10) int level) {
|
||||
forwardLog(message, Level.INFO, level);
|
||||
}
|
||||
|
||||
public static void warning(String message, @Range(from = 1, to = 10) int level) {
|
||||
forwardLog(message, Level.WARN, level);
|
||||
}
|
||||
|
||||
public static void error(String message, @Range(from = 1, to = 10) int level) {
|
||||
forwardLog(message, Level.ERROR, level);
|
||||
}
|
||||
|
||||
private static void forwardLog(String message, Level severity, int level) {
|
||||
DebugConfig debug = RaycastedAntiESP.getConfigManager().getDebugConfig();
|
||||
|
||||
if (debug.logToFile()) logToFile(message);
|
||||
|
||||
if (getLevel(severity, debug) < level) {
|
||||
return;
|
||||
}
|
||||
switch (severity) {
|
||||
case INFO:
|
||||
RaycastedAntiESP.logger().info(message);
|
||||
case WARN:
|
||||
RaycastedAntiESP.logger().warning(message);
|
||||
case ERROR:
|
||||
RaycastedAntiESP.logger().severe(message);
|
||||
default:
|
||||
RaycastedAntiESP.logger().severe(message + "| Additionally, severity " + severity + " is not supported by the logger.");
|
||||
}
|
||||
}
|
||||
|
||||
private static final AtomicReference<ConcurrentLinkedQueue<String>> logBuffer = new AtomicReference<>(new ConcurrentLinkedQueue<String>());
|
||||
private static final String logName = System.currentTimeMillis()+""; // Unique and new logs will have larger numbers
|
||||
private static final ReentrantLock flushLock = new ReentrantLock();
|
||||
|
||||
private static void logToFile(String line) {
|
||||
if (line == null) return;
|
||||
logBuffer.get().offer(line);
|
||||
}
|
||||
|
||||
public static void flush() {
|
||||
flushLock.lock();
|
||||
try {
|
||||
// Atomically swap buffers so producers can keep logging without blocking on I/O.
|
||||
ConcurrentLinkedQueue<String> toWrite = logBuffer.getAndSet(new ConcurrentLinkedQueue<>());
|
||||
|
||||
if (toWrite.isEmpty()) return;
|
||||
|
||||
try (BufferedWriter w = Files.newBufferedWriter(
|
||||
RaycastedAntiESP.get().getDataFolder().toPath().resolve("logs").resolve( logName +".log"),
|
||||
StandardCharsets.UTF_8,
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.WRITE,
|
||||
StandardOpenOption.APPEND)) {
|
||||
|
||||
String s;
|
||||
while ((s = toWrite.poll()) != null) {
|
||||
w.write(s);
|
||||
w.newLine(); // ensure each entry is on its own line
|
||||
}
|
||||
} catch (IOException e) {
|
||||
errorAndReturn(e);
|
||||
}
|
||||
} finally {
|
||||
flushLock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package games.cubi.raycastedAntiESP;
|
||||
|
||||
import com.mojang.brigadier.Command;
|
||||
import com.mojang.brigadier.tree.LiteralCommandNode;
|
||||
import games.cubi.raycastedAntiESP.engine.Engine;
|
||||
import games.cubi.raycastedAntiESP.packets.PacketProcessor;
|
||||
import games.cubi.raycastedAntiESP.packets.Registrar;
|
||||
import games.cubi.raycastedAntiESP.raycast.MovementTracker;
|
||||
import games.cubi.raycastedAntiESP.snapshot.ChunkSnapshotManager;
|
||||
import games.cubi.raycastedAntiESP.config.ConfigManager;
|
||||
import games.cubi.raycastedAntiESP.data.DataHolder;
|
||||
import io.papermc.paper.command.brigadier.CommandSourceStack;
|
||||
import io.papermc.paper.command.brigadier.Commands;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
import games.cubi.raycastedAntiESP.bStats.MetricsCollector;
|
||||
|
||||
public final class RaycastedAntiESP extends JavaPlugin implements CommandExecutor {
|
||||
private static ConfigManager cfg;
|
||||
private static ChunkSnapshotManager snapMgr;
|
||||
private static MovementTracker tracker;
|
||||
private static CommandsManager commands;
|
||||
private static Engine engine;
|
||||
private boolean packetEventsPresent = false; // Don't use this to check if PacketEvents is present, use DataHolder's packetevents field instead. This just checks if its present, not if its enabled/functional
|
||||
private static PacketProcessor packetProcessor = null;
|
||||
private static RaycastedAntiESP instance;
|
||||
private static java.util.logging.Logger logger;
|
||||
|
||||
public int tick = 0;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
logger = getLogger();
|
||||
Plugin packetEvents = Bukkit.getPluginManager().getPlugin("packetevents");
|
||||
if (packetEvents != null) {
|
||||
packetEventsPresent = true;
|
||||
getLogger().info("PacketEvents detected.");
|
||||
new Registrar(this);
|
||||
|
||||
} else {
|
||||
getLogger().info("PacketEvents not detected, disabling packet-based tablist modification. Don't worry, the plugin will still work without it.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
cfg = ConfigManager.initiateConfigManager(this);
|
||||
snapMgr = new ChunkSnapshotManager(this, cfg);
|
||||
tracker = new MovementTracker(this, cfg);
|
||||
commands = new CommandsManager(this, cfg);
|
||||
UpdateChecker.checkForUpdates(this, Bukkit.getConsoleSender());
|
||||
getServer().getPluginManager().registerEvents(EventListener.getInstance(this, snapMgr, cfg), this);
|
||||
//Brigadier API
|
||||
LiteralCommandNode<CommandSourceStack> buildCommand = commands.registerCommand();
|
||||
|
||||
this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> {
|
||||
commands.registrar().register(buildCommand);
|
||||
//alias "antiesp"
|
||||
commands.registrar().register(Commands.literal("antiesp")
|
||||
.requires(sender -> sender.getSender().hasPermission("raycastedantiesp.command"))
|
||||
.executes(context -> {
|
||||
new CommandsManager(this, cfg).helpCommand(context);
|
||||
return Command.SINGLE_SUCCESS;
|
||||
})
|
||||
.redirect(buildCommand).build());
|
||||
});
|
||||
|
||||
//bStats
|
||||
new MetricsCollector(this, cfg);
|
||||
|
||||
|
||||
// TODO: Move this somewhere else, the main class should be cleaner
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
tick++; /*
|
||||
EngineOld.runEngine(cfg, snapMgr, tracker, RaycastedEntityOcclusion.this);
|
||||
EngineOld.runTileEngine(cfg, snapMgr, tracker, RaycastedEntityOcclusion.this);*/
|
||||
}
|
||||
}.runTaskTimer(this, 0L, 1L);
|
||||
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (packetEventsPresent && Bukkit.getPluginManager().isPluginEnabled("packetevents")) {
|
||||
DataHolder.setPacketEventsPresent();
|
||||
packetProcessor = new PacketProcessor(RaycastedAntiESP.get());
|
||||
Logger.info("PacketEvents is enabled, enabling packet-based tablist modification.", 3);
|
||||
}
|
||||
}
|
||||
}.runTaskLater(this, 1L);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
Logger.flush();
|
||||
}
|
||||
|
||||
|
||||
public static ConfigManager getConfigManager() {
|
||||
return cfg;
|
||||
}
|
||||
public static ChunkSnapshotManager getChunkSnapshotManager() {
|
||||
return snapMgr;
|
||||
}
|
||||
public static MovementTracker getMovementTracker() {
|
||||
return tracker;
|
||||
}
|
||||
public static CommandsManager getCommandsManager() {
|
||||
return commands;
|
||||
}
|
||||
public static PacketProcessor getPacketProcessor() {
|
||||
return packetProcessor;
|
||||
}
|
||||
public static Engine getEngine() {
|
||||
return engine;
|
||||
}
|
||||
public static RaycastedAntiESP get() {
|
||||
return instance;
|
||||
}
|
||||
public static java.util.logging.Logger logger() {
|
||||
return logger;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package games.cubi.raycastedAntiESP;
|
||||
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URI;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
|
||||
public class UpdateChecker {
|
||||
private static CompletableFuture<String> fetchFeaturedVersion(RaycastedAntiESP plugin) {
|
||||
CompletableFuture<String> future = new CompletableFuture<>();
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
|
||||
|
||||
final String url = "https://api.modrinth.com/v2/project/bCjNZu0C/version?version_type=release";
|
||||
|
||||
try (final InputStreamReader reader = new InputStreamReader(new URI(url).toURL().openConnection().getInputStream())) {
|
||||
final JsonArray array = new JsonArray();
|
||||
array.add(new BufferedReader(reader).readLine());
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
stringBuilder.append(array.get(i).getAsString());
|
||||
}
|
||||
String apiData = stringBuilder.toString();
|
||||
JsonArray jsonArray = JsonParser.parseString(apiData).getAsJsonArray();
|
||||
JsonObject firstObject = jsonArray.get(0).getAsJsonObject();
|
||||
String versionNumber = firstObject.get("version_number").getAsString();
|
||||
|
||||
future.complete(versionNumber);
|
||||
|
||||
} catch (IOException | URISyntaxException e) {
|
||||
future.completeExceptionally(new IllegalStateException("Unable to fetch latest version", e));
|
||||
}
|
||||
});
|
||||
return future;
|
||||
}
|
||||
|
||||
private static final int INVALID_VERSION_FORMAT = -2; private static final int CURRENT_IS_OLDER = -1; private static final int VERSIONS_ARE_EQUAL = 0; private static final int CURRENT_IS_NEWER = 1;
|
||||
|
||||
private static int checkIfLaterThan(String currentVersion, String fetchedVersion) {
|
||||
String[] currentParts = currentVersion.replace("v", "").split("\\.");
|
||||
String[] fetchedParts = fetchedVersion.replace("v", "").split("\\.");
|
||||
|
||||
if (currentParts.length < 3 || fetchedParts.length < 3) {
|
||||
return INVALID_VERSION_FORMAT;
|
||||
}
|
||||
|
||||
int majorVersionDifference = Integer.parseInt(currentParts[0]) - Integer.parseInt(fetchedParts[0]);
|
||||
|
||||
if (majorVersionDifference == VERSIONS_ARE_EQUAL) {
|
||||
int minorVersionDifference = Integer.parseInt(currentParts[1]) - Integer.parseInt(fetchedParts[1]);
|
||||
|
||||
if (minorVersionDifference == VERSIONS_ARE_EQUAL) {
|
||||
int patchVersionDifference = Integer.parseInt(currentParts[2]) - Integer.parseInt(fetchedParts[2]);
|
||||
return patchVersionDifference;
|
||||
}
|
||||
return minorVersionDifference;
|
||||
}
|
||||
return majorVersionDifference;
|
||||
}
|
||||
|
||||
public static void checkForUpdates(RaycastedAntiESP plugin, CommandSender audience) {
|
||||
fetchFeaturedVersion(plugin).thenAccept(version -> {
|
||||
// This runs synchronously when the version is fetched
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
int versionCheck = checkIfLaterThan(plugin.getDescription().getVersion(), version);
|
||||
|
||||
if (versionCheck == VERSIONS_ARE_EQUAL) {
|
||||
audience.sendRichMessage("<green>You are using the latest version of Raycasted Entity Occlusions.");
|
||||
}
|
||||
|
||||
if (versionCheck == CURRENT_IS_OLDER) {
|
||||
audience.sendRichMessage("<red>You are not using the latest version of Raycasted Entity Occlusions. Please update to <green>v" + version+".");
|
||||
if (audience instanceof Player) audience.sendRichMessage("\n" + "<hover:show_text:'https://modrinth.com/project/bCjNZu0C/versions'><aqua><u><click:open_url:'https://modrinth.com/project/bCjNZu0C/versions'>Click here to download it.</click></u></aqua></hover>");
|
||||
}
|
||||
|
||||
if (versionCheck == CURRENT_IS_NEWER) {
|
||||
audience.sendRichMessage("<yellow>You are using a development build of Raycasted Entity Occlusions. The latest stable version is <green>v" + version + "<yellow>.");
|
||||
}
|
||||
|
||||
if (versionCheck == INVALID_VERSION_FORMAT) {
|
||||
audience.sendRichMessage("<red>Unable to check for updates, invalid version format.");
|
||||
}
|
||||
});
|
||||
}).exceptionally(ex -> {
|
||||
Logger.error(ex);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package games.cubi.raycastedEntityOcclusion.bStats;
|
||||
package games.cubi.raycastedAntiESP.bStats;
|
||||
/*
|
||||
* This Metrics class was auto-generated and can be copied into your project if you are
|
||||
* not using a build tool like Gradle or Maven for dependency management.
|
||||
+11
-11
@@ -1,31 +1,29 @@
|
||||
package games.cubi.raycastedEntityOcclusion.bStats;
|
||||
package games.cubi.raycastedAntiESP.bStats;
|
||||
|
||||
import games.cubi.raycastedEntityOcclusion.ConfigManager;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import games.cubi.raycastedAntiESP.config.ConfigManager;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class MetricsCollector {
|
||||
private final RaycastedEntityOcclusion plugin;
|
||||
private final RaycastedAntiESP plugin;
|
||||
private final Metrics metrics;
|
||||
private final ConfigManager config;
|
||||
|
||||
private List<Integer> playersOnline = new ArrayList<>();
|
||||
private List<Integer> entities = new ArrayList<>();
|
||||
|
||||
public MetricsCollector(RaycastedEntityOcclusion plugin, ConfigManager config) {
|
||||
public MetricsCollector(RaycastedAntiESP plugin, ConfigManager config) {
|
||||
this.plugin = plugin;
|
||||
int pluginId = 24553;
|
||||
metrics = new Metrics(plugin, pluginId);
|
||||
this.config = config;
|
||||
this.config = config;/*
|
||||
registerCustomMetrics();
|
||||
|
||||
plugin.getServer().getScheduler().runTaskTimer(plugin, this::collectMetrics, 0L, 6000L); // 6000 ticks = 5 minutes
|
||||
TODO: Re-enable metrics
|
||||
plugin.getServer().getScheduler().runTaskTimer(plugin, this::collectMetrics, 0L, 6000L); // 6000 ticks = 5 minutes*/
|
||||
}
|
||||
|
||||
/*
|
||||
public void registerCustomMetrics() {
|
||||
metrics.addCustomChart(new Metrics.SimplePie("max_occluding_count", () -> String.valueOf(config.maxOccludingCount)));
|
||||
|
||||
@@ -154,4 +152,6 @@ public class MetricsCollector {
|
||||
return "5000+";
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package games.cubi.raycastedAntiESP.config;
|
||||
|
||||
import games.cubi.raycastedAntiESP.Logger;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ConfigManager {
|
||||
private static ConfigManager instance;
|
||||
|
||||
private final RaycastedAntiESP plugin;
|
||||
private FileConfiguration config;
|
||||
|
||||
// Config objects
|
||||
private PlayerConfig playerConfig;
|
||||
private EntityConfig entityConfig;
|
||||
private TileEntityConfig tileEntityConfig;
|
||||
private SnapshotConfig snapshotConfig;
|
||||
private DebugConfig debugConfig;
|
||||
|
||||
// Default config objects TODO: Keep these here or move into individual config classes?
|
||||
private static final PlayerConfig DEFAULT_PLAYER_CONFIG = new PlayerConfig(1, 3, 16, 48, 50, true, true);
|
||||
private static final EntityConfig DEFAULT_ENTITY_CONFIG = new EntityConfig( 1, 3, 16, 48, 50, true);
|
||||
private static final TileEntityConfig DEFAULT_TILE_ENTITY_CONFIG = new TileEntityConfig(1, 3, 16, 48, 0, true, List.of(Material.BEACON));
|
||||
private static final SnapshotConfig DEFAULT_SNAPSHOT_CONFIG = new SnapshotConfig(60, 0, false);
|
||||
private static final DebugConfig DEFAULT_DEBUG_CONFIG = new DebugConfig(3, 3, 3, false, false, false);
|
||||
|
||||
private int maxEngineMode;
|
||||
|
||||
private ConfigManager(RaycastedAntiESP plugin) {
|
||||
this.plugin = plugin;
|
||||
load();
|
||||
}
|
||||
|
||||
public static ConfigManager initiateConfigManager(RaycastedAntiESP plugin) {
|
||||
if (instance == null) {
|
||||
if (isNotOnMainThread()) return null;
|
||||
instance = new ConfigManager(plugin);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
public static ConfigManager get() {
|
||||
if (instance == null) Logger.errorAndReturn(new RuntimeException("ConfigManager accessed before being initiated. Please report this to the plugin developer."));
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load or reload the configuration from file
|
||||
*/
|
||||
public void load() {
|
||||
//check that we are on the main bukkit thread to prevent concurrency issues
|
||||
if (isNotOnMainThread()) return;
|
||||
plugin.saveDefaultConfig();
|
||||
plugin.reloadConfig();
|
||||
config = plugin.getConfig();
|
||||
|
||||
// Set defaults if they don't exist
|
||||
setDefaults();
|
||||
|
||||
// Load config objects
|
||||
playerConfig = PlayerConfig.getFromConfig(config, getDefaultPlayerConfig());
|
||||
entityConfig = EntityConfig.getFromConfig(config, getDefaultEntityConfig());
|
||||
tileEntityConfig = TileEntityConfig.getFromConfig(config, getDefaultTileEntityConfig());
|
||||
snapshotConfig = SnapshotConfig.getFromConfig(config, getDefaultSnapshotConfig());
|
||||
debugConfig = DebugConfig.getFromConfig(config, getDefaultDebugConfig());
|
||||
|
||||
// Save any new defaults that were added
|
||||
plugin.saveConfig();
|
||||
|
||||
maxEngineMode = calculateMaxEngineMode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set default values in the configuration file if they don't exist
|
||||
*/
|
||||
private void setDefaults() {
|
||||
config.addDefault("config-version", "1.0");
|
||||
|
||||
PlayerConfig.setDefaults(config, getDefaultPlayerConfig());
|
||||
EntityConfig.setDefaults(config, getDefaultEntityConfig());
|
||||
TileEntityConfig.setDefaults(config, getDefaultTileEntityConfig());
|
||||
|
||||
SnapshotConfig.setDefaults(config, getDefaultSnapshotConfig());
|
||||
|
||||
DebugConfig.setDefaults(config, getDefaultDebugConfig());
|
||||
|
||||
config.options().copyDefaults(true);
|
||||
plugin.saveConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a single config value both in memory and in the file
|
||||
* @param path The config path (e.g., "player.enabled")
|
||||
* @param rawValue The raw string value to set
|
||||
* @return 1 for success, 0 for out of range, -1 for invalid input TODO: This is currently broken, and even if it worked it doesn't handle setting lists
|
||||
*/
|
||||
public int setConfigValue(String path, String rawValue) {
|
||||
if (!config.contains(path)) {
|
||||
return -1; // Path doesn't exist
|
||||
}
|
||||
|
||||
Object currentValue = config.get(path);
|
||||
Object parsedValue;
|
||||
|
||||
try {
|
||||
if (currentValue instanceof Boolean) {
|
||||
String lower = rawValue.toLowerCase();
|
||||
if (!lower.equals("true") && !lower.equals("false")) {
|
||||
return -1;
|
||||
}
|
||||
parsedValue = Boolean.parseBoolean(lower);
|
||||
} else if (currentValue instanceof Integer) {
|
||||
int intVal = Integer.parseInt(rawValue);
|
||||
if (intVal < 0 || intVal > 255) {
|
||||
return 0;
|
||||
}
|
||||
parsedValue = intVal;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Update the config file
|
||||
config.set(path, parsedValue);
|
||||
plugin.saveConfig();
|
||||
|
||||
// Reload to update the config objects
|
||||
load();
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private int calculateMaxEngineMode() {
|
||||
//return the highest engine mode listed
|
||||
int maxMode = 0;
|
||||
if (playerConfig.getEngineMode() > maxMode) maxMode = playerConfig.getEngineMode();
|
||||
if (entityConfig.getEngineMode() > maxMode) maxMode = entityConfig.getEngineMode();
|
||||
if (tileEntityConfig.getEngineMode() > maxMode) maxMode = tileEntityConfig.getEngineMode();
|
||||
return maxMode;
|
||||
}
|
||||
|
||||
private static boolean isNotOnMainThread() {
|
||||
if (RaycastedAntiESP.get().getServer().isPrimaryThread()) {
|
||||
return false;
|
||||
}
|
||||
Logger.error(new RuntimeException("ConfigManager attempted to be accessed off the main thread. Please report this to the plugin developer."));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static PlayerConfig getDefaultPlayerConfig() {
|
||||
return DEFAULT_PLAYER_CONFIG;
|
||||
}
|
||||
|
||||
public static EntityConfig getDefaultEntityConfig() {
|
||||
return DEFAULT_ENTITY_CONFIG;
|
||||
}
|
||||
|
||||
public static TileEntityConfig getDefaultTileEntityConfig() {
|
||||
return DEFAULT_TILE_ENTITY_CONFIG;
|
||||
}
|
||||
|
||||
public static SnapshotConfig getDefaultSnapshotConfig() {
|
||||
return DEFAULT_SNAPSHOT_CONFIG;
|
||||
}
|
||||
|
||||
public static DebugConfig getDefaultDebugConfig() {
|
||||
return DEFAULT_DEBUG_CONFIG;
|
||||
}
|
||||
|
||||
// Getters for current config objects
|
||||
public PlayerConfig getPlayerConfig() {
|
||||
return playerConfig;
|
||||
}
|
||||
|
||||
public EntityConfig getEntityConfig() {
|
||||
return entityConfig;
|
||||
}
|
||||
|
||||
public TileEntityConfig getTileEntityConfig() {
|
||||
return tileEntityConfig;
|
||||
}
|
||||
|
||||
public SnapshotConfig getSnapshotConfig() {
|
||||
return snapshotConfig;
|
||||
}
|
||||
|
||||
public DebugConfig getDebugConfig() {
|
||||
return debugConfig;
|
||||
}
|
||||
|
||||
public FileConfiguration getConfigFile() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public int getEngineMode() {
|
||||
return maxEngineMode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package games.cubi.raycastedAntiESP.config;
|
||||
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
public class DebugConfig {
|
||||
private static final String PATH = "debug";
|
||||
|
||||
private final byte infoLevel;
|
||||
private final byte warnLevel;
|
||||
private final byte errorLevel;
|
||||
private final boolean debugParticles;
|
||||
private final boolean timings;
|
||||
private final boolean logToFile;
|
||||
|
||||
public DebugConfig(byte infoLevel, byte warnLevel, byte errorLevel, boolean debugParticles, boolean timings, boolean logToFile) {
|
||||
this.infoLevel = infoLevel;
|
||||
this.warnLevel = warnLevel;
|
||||
this.errorLevel = errorLevel;
|
||||
this.debugParticles = debugParticles;
|
||||
this.timings = timings;
|
||||
this.logToFile = logToFile;
|
||||
}
|
||||
|
||||
public DebugConfig(int infoLevel, int warnLevel, int errorLevel, boolean debugParticles, boolean timings, boolean logToFile) {
|
||||
this.infoLevel = (byte) infoLevel;
|
||||
this.warnLevel = (byte) warnLevel;
|
||||
this.errorLevel = (byte) errorLevel;
|
||||
this.debugParticles = debugParticles;
|
||||
this.timings = timings;
|
||||
this.logToFile = logToFile;
|
||||
}
|
||||
|
||||
public byte getInfoLevel() {
|
||||
return infoLevel;
|
||||
}
|
||||
|
||||
public byte getWarnLevel() {
|
||||
return warnLevel;
|
||||
}
|
||||
|
||||
public byte getErrorLevel() {
|
||||
return errorLevel;
|
||||
}
|
||||
|
||||
public boolean showDebugParticles() {
|
||||
return debugParticles;
|
||||
}
|
||||
|
||||
public boolean recordTimings() {
|
||||
return timings;
|
||||
}
|
||||
|
||||
public boolean logToFile() {
|
||||
return logToFile;
|
||||
}
|
||||
|
||||
static DebugConfig getFromConfig(FileConfiguration config, DebugConfig defaults) {
|
||||
return new DebugConfig(
|
||||
(byte) config.getInt(PATH+".info-level", defaults.getInfoLevel()),
|
||||
(byte) config.getInt(PATH+".warn-level", defaults.getWarnLevel()),
|
||||
(byte) config.getInt(PATH+".error-level", defaults.getErrorLevel()),
|
||||
config.getBoolean(PATH+".particles", defaults.showDebugParticles()),
|
||||
config.getBoolean(PATH+".timings", defaults.recordTimings()),
|
||||
config.getBoolean(PATH+".log-to-file", defaults.logToFile())
|
||||
);
|
||||
}
|
||||
|
||||
static void setDefaults(FileConfiguration config, DebugConfig defaults) {
|
||||
config.addDefault(PATH+".info-level", defaults.getInfoLevel());
|
||||
config.addDefault(PATH+".warn-level", defaults.getWarnLevel());
|
||||
config.addDefault(PATH+".error-level", defaults.getErrorLevel());
|
||||
config.addDefault(PATH+".particles", defaults.showDebugParticles());
|
||||
config.addDefault(PATH+".timings", defaults.recordTimings());
|
||||
config.addDefault(PATH+".log-to-file", defaults.logToFile());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package games.cubi.raycastedAntiESP.config;
|
||||
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
public class EntityConfig extends RaycastConfig {
|
||||
public static final String PATH = "entity";
|
||||
|
||||
public EntityConfig(byte engineMode, byte maxOccludingCount, short alwaysShowRadius, short raycastRadius, short visibleRecheckInterval, boolean enabled) {
|
||||
super(engineMode, maxOccludingCount, alwaysShowRadius, raycastRadius, visibleRecheckInterval, enabled);
|
||||
}
|
||||
|
||||
public EntityConfig(int engineMode, int maxOccludingCount, int alwaysShowRadius, int raycastRadius, int visibleRecheckInterval, boolean enabled) {
|
||||
super(engineMode, maxOccludingCount, alwaysShowRadius, raycastRadius, visibleRecheckInterval, enabled);
|
||||
}
|
||||
|
||||
public EntityConfig(boolean enabled) {
|
||||
super(enabled);
|
||||
}
|
||||
|
||||
public EntityConfig(RaycastConfig superConfig) {
|
||||
super(superConfig);
|
||||
}
|
||||
|
||||
public static EntityConfig getFromConfig(FileConfiguration config, EntityConfig defaults) {
|
||||
return new EntityConfig(RaycastConfig.getFromConfig(config, PATH, defaults));
|
||||
}
|
||||
|
||||
public static void setDefaults(FileConfiguration config, EntityConfig defaults) {
|
||||
RaycastConfig.setDefaults(config, PATH, defaults);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package games.cubi.raycastedAntiESP.config;
|
||||
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
public class PlayerConfig extends RaycastConfig {
|
||||
public static final String PATH = "player";
|
||||
private final boolean onlyCullWhileSneaking;
|
||||
|
||||
public PlayerConfig(byte engineMode, byte maxOccludingCount, short alwaysShowRadius, short raycastRadius, short visibleRecheckInterval, boolean enabled, boolean onlyCullWhileSneaking) {
|
||||
super(engineMode, maxOccludingCount, alwaysShowRadius, raycastRadius, visibleRecheckInterval, enabled);
|
||||
this.onlyCullWhileSneaking = onlyCullWhileSneaking;
|
||||
}
|
||||
|
||||
public PlayerConfig(int engineMode, int maxOccludingCount, int alwaysShowRadius, int raycastRadius, int visibleRecheckInterval, boolean enabled, boolean onlyCullWhileSneaking) {
|
||||
super(engineMode, maxOccludingCount, alwaysShowRadius, raycastRadius, visibleRecheckInterval, enabled);
|
||||
this.onlyCullWhileSneaking = onlyCullWhileSneaking;
|
||||
}
|
||||
|
||||
public PlayerConfig(boolean enabled) {
|
||||
super(enabled);
|
||||
this.onlyCullWhileSneaking = false;
|
||||
}
|
||||
|
||||
public PlayerConfig(RaycastConfig superConfig, boolean onlyCullWhileSneaking) {
|
||||
super(superConfig);
|
||||
this.onlyCullWhileSneaking = onlyCullWhileSneaking;
|
||||
}
|
||||
|
||||
public boolean onlyCullWhileSneaking() {
|
||||
return onlyCullWhileSneaking;
|
||||
}
|
||||
|
||||
public static PlayerConfig getFromConfig(FileConfiguration config, PlayerConfig defaults) {
|
||||
return new PlayerConfig(RaycastConfig.getFromConfig(config, PATH, defaults), config.getBoolean(PATH+".only-cull-while-sneaking", defaults.onlyCullWhileSneaking()));
|
||||
}
|
||||
|
||||
public static void setDefaults(FileConfiguration config, PlayerConfig defaults) {
|
||||
RaycastConfig.setDefaults(config, PATH, defaults);
|
||||
config.addDefault(PATH+".only-cull-while-sneaking", defaults.onlyCullWhileSneaking());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package games.cubi.raycastedAntiESP.config;
|
||||
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
public class RaycastConfig {
|
||||
private final byte engineMode;
|
||||
private final byte maxOccludingCount;
|
||||
private final short alwaysShowRadius;
|
||||
private final short raycastRadius;
|
||||
private final short visibleRecheckInterval;
|
||||
private final boolean enabled;
|
||||
|
||||
public RaycastConfig(byte engineMode, byte maxOccludingCount, short alwaysShowRadius, short raycastRadius, short visibleRecheckInterval, boolean enabled) {
|
||||
this.engineMode = engineMode;
|
||||
this.maxOccludingCount = maxOccludingCount;
|
||||
this.alwaysShowRadius = alwaysShowRadius;
|
||||
this.raycastRadius = raycastRadius;
|
||||
this.visibleRecheckInterval = visibleRecheckInterval;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public RaycastConfig(int engineMode, int maxOccludingCount, int alwaysShowRadius, int raycastRadius, int visibleRecheckInterval, boolean enabled) {
|
||||
this.engineMode = (byte) engineMode;
|
||||
this.maxOccludingCount = (byte) maxOccludingCount;
|
||||
this.alwaysShowRadius = (short) alwaysShowRadius;
|
||||
this.raycastRadius = (short) raycastRadius;
|
||||
this.visibleRecheckInterval = (short) visibleRecheckInterval;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public RaycastConfig(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
if (enabled) throw new IllegalArgumentException("Abstract config created without parameters while enabled");
|
||||
engineMode = -1; maxOccludingCount = -1; alwaysShowRadius = 48; raycastRadius = -1; visibleRecheckInterval = -1;
|
||||
|
||||
}
|
||||
|
||||
public RaycastConfig(RaycastConfig other) {
|
||||
// This is unhinged but also the simplest way I can think of to do this
|
||||
this.engineMode = other.engineMode;
|
||||
this.maxOccludingCount = other.maxOccludingCount;
|
||||
this.alwaysShowRadius = other.alwaysShowRadius;
|
||||
this.raycastRadius = other.raycastRadius;
|
||||
this.visibleRecheckInterval = other.visibleRecheckInterval;
|
||||
this.enabled = other.enabled;
|
||||
}
|
||||
|
||||
|
||||
static RaycastConfig getFromConfig(FileConfiguration config, String path, RaycastConfig defaults) {
|
||||
return new RaycastConfig(
|
||||
config.getInt(path+".engine-mode", defaults.getEngineMode()),
|
||||
config.getInt(path+".max-occluding-count", defaults.getMaxOccludingCount()),
|
||||
config.getInt(path+".always-show-radius", defaults.getAlwaysShowRadius()),
|
||||
config.getInt(path+".raycast-radius", defaults.getRaycastRadius()),
|
||||
config.getInt(path+".visible-recheck-interval", defaults.getVisibleRecheckInterval()),
|
||||
config.getBoolean(path+".enabled", defaults.isEnabled())
|
||||
);
|
||||
}
|
||||
|
||||
static void setDefaults(FileConfiguration config, String path, RaycastConfig defaults) {
|
||||
config.addDefault(path+".enabled", defaults.isEnabled());
|
||||
config.addDefault(path+".engine-mode", defaults.getEngineMode());
|
||||
config.addDefault(path+".max-occluding-count", defaults.getMaxOccludingCount());
|
||||
config.addDefault(path+".always-show-radius", defaults.getAlwaysShowRadius());
|
||||
config.addDefault(path+".raycast-radius", defaults.getRaycastRadius());
|
||||
config.addDefault(path+".visible-recheck-interval", defaults.getVisibleRecheckInterval());
|
||||
}
|
||||
|
||||
public byte getEngineMode() {
|
||||
return engineMode;
|
||||
}
|
||||
|
||||
public byte getMaxOccludingCount() {
|
||||
return maxOccludingCount;
|
||||
}
|
||||
|
||||
public short getAlwaysShowRadius() {
|
||||
return alwaysShowRadius;
|
||||
}
|
||||
|
||||
public short getRaycastRadius() {
|
||||
return raycastRadius;
|
||||
}
|
||||
|
||||
public short getVisibleRecheckInterval() {
|
||||
return visibleRecheckInterval;
|
||||
}
|
||||
|
||||
public int getVisibleRecheckIntervalSeconds() {
|
||||
return (visibleRecheckInterval * 20);
|
||||
}
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package games.cubi.raycastedAntiESP.config;
|
||||
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
public class SnapshotConfig {
|
||||
private static final String PATH = "snapshot";
|
||||
private final short worldSnapshotRefreshInterval;
|
||||
private final int entityLocationRefreshInterval;
|
||||
private final boolean performUnsafeWorldSnapshots;
|
||||
|
||||
public SnapshotConfig(short worldRefresh, int entityRefresh, boolean doUnsafeWorldSnapshots) {
|
||||
worldSnapshotRefreshInterval = worldRefresh;
|
||||
entityLocationRefreshInterval = entityRefresh;
|
||||
performUnsafeWorldSnapshots = doUnsafeWorldSnapshots;
|
||||
}
|
||||
|
||||
public SnapshotConfig(int worldRefresh, int entityRefresh, boolean doUnsafeWorldSnapshots) {
|
||||
worldSnapshotRefreshInterval = (short) worldRefresh;
|
||||
entityLocationRefreshInterval = entityRefresh;
|
||||
performUnsafeWorldSnapshots = doUnsafeWorldSnapshots;
|
||||
}
|
||||
|
||||
public short getWorldSnapshotRefreshInterval() {
|
||||
return worldSnapshotRefreshInterval;
|
||||
}
|
||||
|
||||
public int getEntityLocationRefreshInterval() {
|
||||
return entityLocationRefreshInterval;
|
||||
}
|
||||
|
||||
public int getEntityLocationRefreshIntervalTicks() {
|
||||
return getEntityLocationRefreshInterval();
|
||||
}
|
||||
|
||||
public boolean performUnsafeWorldSnapshots() {
|
||||
return performUnsafeWorldSnapshots;
|
||||
}
|
||||
|
||||
static SnapshotConfig getFromConfig(FileConfiguration config, SnapshotConfig defaults) {
|
||||
return new SnapshotConfig(
|
||||
config.getInt(PATH+".world-refresh-interval", defaults.getWorldSnapshotRefreshInterval()),
|
||||
config.getInt(PATH+".entity-location-refresh-interval", defaults.getEntityLocationRefreshInterval()),
|
||||
config.getBoolean(PATH+".perform-unsafe-async-world-snapshots", defaults.performUnsafeWorldSnapshots())
|
||||
);
|
||||
}
|
||||
|
||||
static void setDefaults(FileConfiguration config, SnapshotConfig defaults) {
|
||||
config.addDefault(PATH+".world-refresh-interval", defaults.getWorldSnapshotRefreshInterval());
|
||||
config.addDefault(PATH+".entity-location-refresh-interval", defaults.getEntityLocationRefreshInterval());
|
||||
config.addDefault(PATH+".perform-unsafe-world-snapshots", defaults.performUnsafeWorldSnapshots());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package games.cubi.raycastedAntiESP.config;
|
||||
|
||||
import games.cubi.raycastedAntiESP.Logger;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class TileEntityConfig extends RaycastConfig {
|
||||
private static final String PATH = "tile-entity";
|
||||
private final List<Material> exemptedBlocks; // This list is immutable
|
||||
|
||||
public TileEntityConfig(byte engineMode, byte maxOccludingCount, short alwaysShowRadius, short raycastRadius, short visibleRecheckInterval, boolean enabled, List<Material> exemptedBlocks) {
|
||||
super(engineMode, maxOccludingCount, alwaysShowRadius, raycastRadius, visibleRecheckInterval, enabled);
|
||||
this.exemptedBlocks = List.copyOf(exemptedBlocks);
|
||||
}
|
||||
|
||||
public TileEntityConfig(int engineMode, int maxOccludingCount, int alwaysShowRadius, int raycastRadius, int visibleRecheckInterval, boolean enabled, List<Material> exemptedBlocks) {
|
||||
super(engineMode, maxOccludingCount, alwaysShowRadius, raycastRadius, visibleRecheckInterval, enabled);
|
||||
this.exemptedBlocks = List.copyOf(exemptedBlocks);
|
||||
}
|
||||
|
||||
public TileEntityConfig(boolean enabled, List<Material> exemptedBlocks) {
|
||||
super(enabled);
|
||||
this.exemptedBlocks = List.copyOf(exemptedBlocks);
|
||||
}
|
||||
|
||||
public TileEntityConfig(RaycastConfig superConfig,List<Material> exemptedBlocks) {
|
||||
super(superConfig);
|
||||
this.exemptedBlocks = List.copyOf(exemptedBlocks);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVisibleRecheckIntervalSeconds() {
|
||||
return super.getVisibleRecheckInterval();
|
||||
}
|
||||
|
||||
public List<Material> getExemptedBlocks() {
|
||||
return exemptedBlocks; // Immutable list
|
||||
}
|
||||
|
||||
public static TileEntityConfig getFromConfig(FileConfiguration config, TileEntityConfig defaults) {
|
||||
return new TileEntityConfig(RaycastConfig.getFromConfig(config, PATH, defaults), getMaterialList(config));
|
||||
}
|
||||
|
||||
private static List<Material> getMaterialList(FileConfiguration config) {
|
||||
List<String> materialNames = config.getStringList(PATH);
|
||||
|
||||
ArrayList<Material> materials = new ArrayList<>();
|
||||
|
||||
for (String name : materialNames) {
|
||||
if (name == null) continue;
|
||||
Material m = Material.matchMaterial(name);
|
||||
if (m != null) {
|
||||
materials.add(m);
|
||||
} else {
|
||||
Logger.error("Invalid material in config 'whitelisted-materials': " + name,1);
|
||||
}
|
||||
}
|
||||
return List.copyOf(materials);
|
||||
}
|
||||
|
||||
public static void setDefaults(FileConfiguration config, TileEntityConfig defaults) {
|
||||
RaycastConfig.setDefaults(config, PATH, defaults);
|
||||
config.addDefault(PATH+".exempted-blocks", defaults.getExemptedBlocks().stream().map(Material::name).toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package games.cubi.raycastedAntiESP.data;
|
||||
|
||||
public class DataHolder {
|
||||
|
||||
private static boolean packetEventsPresent;
|
||||
private static int tick = 0;
|
||||
|
||||
private static final EntityLocationService entityLocationService;
|
||||
private static final EntityVisibilityChangeCache entityVisibilityChangeCache;
|
||||
private static final PlayerRegistry playerRegistry;
|
||||
|
||||
static {
|
||||
entityLocationService = EntityLocationService.getInstance();
|
||||
entityVisibilityChangeCache = EntityVisibilityChangeCache.getInstance();
|
||||
playerRegistry = PlayerRegistry.getInstance();
|
||||
}
|
||||
|
||||
public static EntityLocationService entityLocation() {
|
||||
return entityLocationService;
|
||||
}
|
||||
public static EntityVisibilityChangeCache entityVisibility() {
|
||||
return entityVisibilityChangeCache;
|
||||
}
|
||||
public static PlayerRegistry players() {
|
||||
return playerRegistry;
|
||||
}
|
||||
|
||||
public static boolean isPacketEventsPresent() {
|
||||
return packetEventsPresent;
|
||||
}
|
||||
public static void setPacketEventsPresent() {
|
||||
packetEventsPresent = true;
|
||||
}
|
||||
/**
|
||||
* This counter increments twice per server tick, so a normal server will experience 40 TPS
|
||||
* **/
|
||||
public static int getTick() {
|
||||
return tick;
|
||||
}
|
||||
/**
|
||||
* This method should ONLY be called on the tick start and stop events
|
||||
* **/
|
||||
public static void incrementTick() {
|
||||
tick++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package games.cubi.raycastedAntiESP.data;
|
||||
|
||||
import games.cubi.raycastedAntiESP.utils.EntityLocationPair;
|
||||
import games.cubi.raycastedAntiESP.utils.ThreadSafeLoc;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class EntityLocationService {
|
||||
private static EntityLocationService instance;
|
||||
|
||||
private EntityLocationService() {}
|
||||
|
||||
public static EntityLocationService getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new EntityLocationService();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**UUID -> Entity UUID, QuantisedLocation -> Entity Location*/
|
||||
private final ConcurrentLinkedQueue<EntityLocationPair> entityLocProcessingQueue = new ConcurrentLinkedQueue<>();
|
||||
|
||||
public void queueEntityLocationUpdate(UUID entityUUID, Location location) {
|
||||
entityLocProcessingQueue.add(new EntityLocationPair(entityUUID, location));
|
||||
}
|
||||
|
||||
private volatile ConcurrentHashMap<UUID, ThreadSafeLoc> entityLocationMap = new ConcurrentHashMap<>();
|
||||
|
||||
public void updateEntireEntityLocationMap(HashMap<UUID, ThreadSafeLoc> newLocations) {
|
||||
entityLocationMap = new ConcurrentHashMap<>(newLocations);
|
||||
}
|
||||
|
||||
private void setOrUpdateEntityLocation(UUID entityUUID, Vector location, UUID world) {
|
||||
entityLocationMap.compute(entityUUID, (uuid, oldLoc) -> {
|
||||
if (oldLoc == null) return new ThreadSafeLoc(location, world);
|
||||
while (!oldLoc.update(location)) {
|
||||
Thread.onSpinWait(); //doesn't actually sleep the thread, just indicates that this thread should be deprioritized. Once the write lock is released it should write nearly immediately
|
||||
}
|
||||
return oldLoc;
|
||||
});
|
||||
}
|
||||
|
||||
private void setOrUpdateEntityLocation(UUID entityUUID, Location location) {
|
||||
setOrUpdateEntityLocation(entityUUID, location.toVector(), location.getWorld().getUID());
|
||||
}
|
||||
|
||||
// Run this async
|
||||
public void processEntityLocationQueue() {
|
||||
while (!entityLocProcessingQueue.isEmpty()) {
|
||||
EntityLocationPair entityLocationPair = entityLocProcessingQueue.poll();
|
||||
if (entityLocationPair == null) return;
|
||||
setOrUpdateEntityLocation(entityLocationPair.entity(), entityLocationPair.loc());
|
||||
}
|
||||
}
|
||||
|
||||
public ThreadSafeLoc getEntityLocation(UUID entityUUID) {
|
||||
return entityLocationMap.get(entityUUID);
|
||||
}
|
||||
|
||||
public HashMap<UUID, ThreadSafeLoc> getCopyOfEntityLocationMap() {
|
||||
return new HashMap<>(entityLocationMap);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package games.cubi.raycastedAntiESP.data;
|
||||
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class EntityVisibilityChangeCache {
|
||||
private static EntityVisibilityChangeCache instance;
|
||||
|
||||
private EntityVisibilityChangeCache() {}
|
||||
|
||||
public static EntityVisibilityChangeCache getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new EntityVisibilityChangeCache();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private record PlayerEntityPair(UUID playerUUID, UUID entityUUID) {}
|
||||
|
||||
private final HashMap<PlayerEntityPair, Long> visibilityStatusChange = new HashMap<>(); // Should only ever be accessed from main thread
|
||||
|
||||
private record ShowOrHideEntityToPlayer (UUID entityUUID, UUID playerUUID, boolean show) {}
|
||||
|
||||
private final ConcurrentLinkedQueue<ShowOrHideEntityToPlayer> entityVisibilityProcessingQueue = new ConcurrentLinkedQueue<>();
|
||||
|
||||
public void showEntity(UUID entityUUID, Player player) {
|
||||
Entity entity = Bukkit.getEntity(entityUUID);
|
||||
Objects.requireNonNull(entity);
|
||||
showEntity(entity, entityUUID, player);
|
||||
}
|
||||
public void showEntity(Entity entity, Player player) {
|
||||
showEntity(entity, entity.getUniqueId(), player);
|
||||
}
|
||||
|
||||
public void showEntity(Entity entity, UUID entityUUID, Player player) {
|
||||
addToVisibilityChangeCache(entityUUID, player.getUniqueId());
|
||||
player.showEntity(RaycastedAntiESP.get(), entity);
|
||||
}
|
||||
|
||||
public void showEntityAsync(UUID entityUUID, UUID playerUUID) {
|
||||
addToVisibilityChangeCache(entityUUID, playerUUID);
|
||||
addToEntityVisibilityProcessingQueue(entityUUID, playerUUID, true);
|
||||
}
|
||||
|
||||
public void hideEntityAsync(UUID entityUUID, UUID playerUUID) {
|
||||
addToVisibilityChangeCache(entityUUID, playerUUID);
|
||||
addToEntityVisibilityProcessingQueue(entityUUID, playerUUID, false);
|
||||
}
|
||||
|
||||
private void addToEntityVisibilityProcessingQueue(UUID entityUUID, UUID playerUUID, boolean show) {
|
||||
entityVisibilityProcessingQueue.add(new ShowOrHideEntityToPlayer(entityUUID, playerUUID, show));
|
||||
}
|
||||
|
||||
private void processEntityVisibilityProcessingQueue() {
|
||||
while (!entityVisibilityProcessingQueue.isEmpty()) {
|
||||
ShowOrHideEntityToPlayer task = entityVisibilityProcessingQueue.poll();
|
||||
if (task == null) return;
|
||||
Entity entity = Bukkit.getEntity(task.entityUUID());
|
||||
Player player = Bukkit.getPlayer(task.playerUUID());
|
||||
if (entity == null || player == null) continue; // Entity or player might have logged out or despawned
|
||||
if (task.show()) {
|
||||
player.showEntity(RaycastedAntiESP.get(), entity);
|
||||
} else {
|
||||
player.hideEntity(RaycastedAntiESP.get(), entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void hideEntity(UUID entityUUID, Player player) {
|
||||
Entity entity = Bukkit.getEntity(entityUUID);
|
||||
Objects.requireNonNull(entity);
|
||||
hideEntity(entity, entityUUID, player);
|
||||
}
|
||||
|
||||
public void hideEntity(Entity entity, Player player) {
|
||||
hideEntity(entity, entity.getUniqueId(), player);
|
||||
}
|
||||
|
||||
public void hideEntity(Entity entity, UUID entityUUID, Player player) {
|
||||
addToVisibilityChangeCache(entityUUID, player.getUniqueId());
|
||||
player.hideEntity(RaycastedAntiESP.get(), entity);
|
||||
}
|
||||
|
||||
private void addToVisibilityChangeCache(UUID entityUUID, UUID playerUUID) {
|
||||
synchronized (visibilityStatusChange) {
|
||||
visibilityStatusChange.put(new PlayerEntityPair(playerUUID, entityUUID), System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
public boolean entityVisibilityShouldChange(UUID entityUUID, UUID playerUUID) {
|
||||
synchronized (visibilityStatusChange) {
|
||||
return visibilityStatusChange.remove(new PlayerEntityPair(playerUUID, entityUUID)) != null;
|
||||
}
|
||||
}
|
||||
|
||||
public void cleanShouldShowEntityCache() {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
synchronized (visibilityStatusChange) {
|
||||
visibilityStatusChange.entrySet().removeIf(entry -> currentTime - entry.getValue() > 1000); // Remove entries older than 1 second
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package games.cubi.raycastedAntiESP.data;
|
||||
|
||||
import games.cubi.raycastedAntiESP.utils.PlayerData;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class PlayerRegistry {
|
||||
|
||||
private static PlayerRegistry instance;
|
||||
|
||||
private PlayerRegistry() {}
|
||||
|
||||
public static PlayerRegistry getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new PlayerRegistry();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private final ConcurrentHashMap<UUID, PlayerData> playerDataMap = new ConcurrentHashMap<>();
|
||||
|
||||
public void registerPlayer(UUID playerUUID, boolean bypass) {
|
||||
playerDataMap.putIfAbsent(playerUUID, new PlayerData(playerUUID, bypass));
|
||||
}
|
||||
|
||||
public PlayerData getPlayerData(UUID playerUUID) {
|
||||
return playerDataMap.get(playerUUID);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Live, mutable collection of all PlayerData instances.
|
||||
* **/
|
||||
public Collection<PlayerData> getAllPlayerData() {
|
||||
return playerDataMap.values();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package games.cubi.raycastedAntiESP.engine;
|
||||
|
||||
public class Engine {}
|
||||
/*
|
||||
import games.cubi.raycastedEntityOcclusion.ConfigManager;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
import games.cubi.raycastedEntityOcclusion.Utils.*;
|
||||
import io.papermc.paper.threadedregions.scheduler.AsyncScheduler;
|
||||
import io.papermc.paper.threadedregions.scheduler.EntityScheduler;
|
||||
import io.papermc.paper.threadedregions.scheduler.GlobalRegionScheduler;
|
||||
import io.papermc.paper.threadedregions.scheduler.ScheduledTask;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class Engine {
|
||||
//TODO: Maybe store the data somewhere else? Could rework chunk storage to be general data storage
|
||||
public ConcurrentHashMap<UUID, PlayerData> playerDataMap = new ConcurrentHashMap<>();
|
||||
private final AsyncScheduler asyncScheduler;
|
||||
@SuppressWarnings("FieldCanBeLocal")
|
||||
private final GlobalRegionScheduler globalScheduler; //TODO: Note that the use of the global scheduler here probs isn't actually done in a folia compat way
|
||||
|
||||
private final RaycastedEntityOcclusion plugin;
|
||||
private final ConfigManager config;
|
||||
|
||||
public Engine(RaycastedEntityOcclusion plugin, ConfigManager cfg) {
|
||||
this.plugin = plugin;
|
||||
this.config = cfg;
|
||||
asyncScheduler = plugin.getServer().getAsyncScheduler();
|
||||
globalScheduler = plugin.getServer().getGlobalRegionScheduler();
|
||||
|
||||
globalScheduler.runAtFixedRate(plugin, syncCollectDataFromBukkit(), 1, 1);
|
||||
}
|
||||
|
||||
public void registerPlayer(UUID playerUUID, boolean bypass) {
|
||||
playerDataMap.putIfAbsent(playerUUID, new PlayerData(playerUUID, bypass));
|
||||
}
|
||||
|
||||
|
||||
private Consumer<ScheduledTask> syncCollectDataFromBukkit() {
|
||||
// UUID:World UUID -> UUID:Entity UUID -> QuantisedLocation
|
||||
HashMap<UUID, HashMap<UUID, QuantisedLocation>> worldEntities = new HashMap<>();
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
HashMap<UUID, QuantisedLocation> entitiesInWorld = new HashMap<>();
|
||||
for (Entity entity : world.getEntities()) {
|
||||
if (entity instanceof Player) continue; // Skip players, they are handled separately
|
||||
entitiesInWorld.put(entity.getUniqueId(), new QuantisedLocation(entity.getLocation(), entity.getHeight()));
|
||||
}
|
||||
worldEntities.put(world.getUID(), entitiesInWorld);
|
||||
}
|
||||
HashMap<UUID, QuantisedLocation> players = new HashMap<>();
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
players.put(player.getUniqueId(), new QuantisedLocation(player.getLocation(), player.getEyeHeight()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//TODO: This is old
|
||||
HashMap<UUID, HashMap<UUID, Location>> gatheredData = new HashMap<>();
|
||||
|
||||
for (UUID playerUUID : playerDataMap.keySet()) {
|
||||
PlayerData data = playerDataMap.get(playerUUID);
|
||||
|
||||
if (data.hasBypassPermission()) continue;
|
||||
|
||||
Map<UUID, Boolean> entities = data.getEntityVisibilityMap();
|
||||
Map<BlockLocation, Long> tileEntities = data.getSeenTileEntitiesMap();
|
||||
|
||||
HashMap<UUID, Location> entitiesToCheck = new HashMap<>();
|
||||
|
||||
data.incrementTicksSinceVisibleEntityRecheck();
|
||||
if (data.getTicksSinceVisibleEntityRecheck() >= config.recheckInterval) {
|
||||
data.resetTicksSinceVisibleEntityRecheck();
|
||||
for (UUID entityUUID : entities.keySet()) {
|
||||
entitiesToCheck.putIfAbsent(entityUUID, Bukkit.getEntity(entityUUID).getLocation());
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (Map.Entry<UUID, Boolean> entry : entities.entrySet()) {
|
||||
if (!entry.getValue()) {
|
||||
UUID uuid = entry.getKey();
|
||||
entitiesToCheck.putIfAbsent(uuid, Bukkit.getEntity(uuid).getLocation());
|
||||
}
|
||||
}
|
||||
}
|
||||
entitiesToCheck.put(playerUUID, Bukkit.getPlayer(playerUUID).getLocation()); //used to pass in player location
|
||||
gatheredData.put(playerUUID, entitiesToCheck);
|
||||
}
|
||||
|
||||
asyncScheduler.runNow(plugin, processData(gatheredData));
|
||||
|
||||
return task -> {};
|
||||
}
|
||||
|
||||
private Consumer<ScheduledTask> processData(HashMap<UUID, HashMap<UUID, Location>> gatheredData) {
|
||||
|
||||
HashMap<LocationPair, Subscribers> raycastResultSubscription = new HashMap<>();
|
||||
|
||||
for (Map.Entry<UUID, HashMap<UUID, Location>> data : gatheredData.entrySet()) {
|
||||
UUID player = data.getKey();
|
||||
HashMap<UUID, Location> entityLocations = data.getValue();
|
||||
QuantisedLocation playerLoc = new QuantisedLocation(entityLocations.get(player));
|
||||
|
||||
for (Map.Entry<UUID, Location> entity : entityLocations.entrySet()) {
|
||||
|
||||
QuantisedLocation entityLoc = new QuantisedLocation(entity.getValue());
|
||||
|
||||
if (!playerLoc.isWithinRadius(entityLoc, config.raycastRadius)) continue;
|
||||
|
||||
LocationPair locationPair = LocationPair.of(playerLoc, entityLoc);
|
||||
|
||||
if (raycastResultSubscription.containsKey(locationPair)) {
|
||||
raycastResultSubscription.get(locationPair).addSubscriberWithEntity(player, entity.getKey());
|
||||
}
|
||||
else {
|
||||
raycastResultSubscription.put(locationPair, new Subscribers(player, entity.getKey()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return task -> {};
|
||||
}
|
||||
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,98 @@
|
||||
package games.cubi.raycastedAntiESP.engine;
|
||||
|
||||
import games.cubi.raycastedAntiESP.Logger;
|
||||
import games.cubi.raycastedAntiESP.config.*;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
import games.cubi.raycastedAntiESP.data.DataHolder;
|
||||
import games.cubi.raycastedAntiESP.utils.PlayerData;
|
||||
import games.cubi.raycastedAntiESP.utils.ThreadSafeLoc;
|
||||
import io.papermc.paper.threadedregions.scheduler.AsyncScheduler;
|
||||
import io.papermc.paper.threadedregions.scheduler.ScheduledTask;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class EngineNewer {
|
||||
private final AsyncScheduler asyncScheduler;
|
||||
private final BukkitScheduler bukkitScheduler;
|
||||
|
||||
private final RaycastedAntiESP plugin;
|
||||
private final ConfigManager config;
|
||||
|
||||
public EngineNewer(RaycastedAntiESP plugin, ConfigManager cfg) {
|
||||
this.plugin = plugin;
|
||||
this.config = cfg;
|
||||
asyncScheduler = plugin.getServer().getAsyncScheduler();
|
||||
bukkitScheduler = plugin.getServer().getScheduler();
|
||||
|
||||
forceEntityLocationUpdate();
|
||||
processEntityMovements(null); //first one will run on main thread but it shouldn't have to do much anyways
|
||||
clearOldCacheEntries();
|
||||
flushLogCache(null);
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
for (PlayerData playerData : DataHolder.players().getAllPlayerData()) {
|
||||
if (playerData.hasBypassPermission()) continue;
|
||||
ThreadSafeLoc playerLocation = DataHolder.entityLocation().getEntityLocation(playerData.getPlayerUUID());
|
||||
if (playerLocation == null) Logger.errorAndReturn(new RuntimeException("wtf"));
|
||||
}
|
||||
}
|
||||
|
||||
private void /*TODO: return the subscriber list*/ createSubscriberList() {
|
||||
for (PlayerData playerData : DataHolder.players().getAllPlayerData()) {
|
||||
if (playerData.hasBypassPermission()) continue;
|
||||
ThreadSafeLoc playerLocation = DataHolder.entityLocation().getEntityLocation(playerData.getPlayerUUID());
|
||||
|
||||
if (playerLocation == null) Logger.errorAndReturn(new RuntimeException("Player location missing for " + playerData.getPlayerUUID()));
|
||||
|
||||
boolean checkEntities = config.getEntityConfig().isEnabled();
|
||||
boolean checkBlocks = config.getTileEntityConfig().isEnabled();
|
||||
boolean checkPlayers = config.getPlayerConfig().isEnabled();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private void forceEntityLocationUpdate() {
|
||||
int recheckInterval = ConfigManager.get().getSnapshotConfig().getEntityLocationRefreshInterval();
|
||||
if (recheckInterval <= 0) {
|
||||
bukkitScheduler.runTaskLater(plugin, this::forceEntityLocationUpdate, 20 * 30); // Check again in 30 secs if config has changed
|
||||
return;
|
||||
}
|
||||
HashMap<UUID, ThreadSafeLoc> entities = new HashMap<>();
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
for (Entity entity : world.getEntities()) {
|
||||
entities.put(entity.getUniqueId(), new ThreadSafeLoc(entity.getLocation(), entity.getHeight()));
|
||||
}
|
||||
}
|
||||
DataHolder.entityLocation().updateEntireEntityLocationMap(entities);
|
||||
bukkitScheduler.runTaskLater(plugin, this::forceEntityLocationUpdate, recheckInterval);
|
||||
}
|
||||
|
||||
private void processEntityMovements(ScheduledTask scheduledTask) {
|
||||
DataHolder.entityLocation().processEntityLocationQueue();
|
||||
asyncScheduler.runDelayed(plugin, this::processEntityMovements, 15, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void clearOldCacheEntries() {
|
||||
DataHolder.entityVisibility().cleanShouldShowEntityCache();
|
||||
bukkitScheduler.runTaskLater(plugin, this::clearOldCacheEntries, 20 * 120);
|
||||
}
|
||||
|
||||
private void flushLogCache(ScheduledTask scheduledTask) {
|
||||
if (config.getDebugConfig().logToFile()) {
|
||||
Logger.flush();
|
||||
}
|
||||
asyncScheduler.runDelayed(plugin, this::flushLogCache, 2, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
+4
-7
@@ -1,10 +1,10 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Packets;
|
||||
package games.cubi.raycastedAntiESP.packets;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.manager.player.PlayerManager;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoRemove;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
@@ -12,12 +12,9 @@ import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public class PacketProcessor {
|
||||
private final RaycastedEntityOcclusion plugin;
|
||||
private final UUID key;
|
||||
private final UUID key = new UUID(0, 0); // Plugins can flag their packets with this UUID;
|
||||
|
||||
public PacketProcessor(RaycastedEntityOcclusion plugin) {
|
||||
this.plugin = plugin;
|
||||
key = UUID.randomUUID();
|
||||
public PacketProcessor(RaycastedAntiESP plugin) {
|
||||
}
|
||||
|
||||
public void processPlayerInfoRemovePacket(PacketSendEvent event) {
|
||||
+10
-8
@@ -1,14 +1,14 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Packets;
|
||||
package games.cubi.raycastedAntiESP.packets;
|
||||
|
||||
import com.github.retrooper.packetevents.event.PacketListener;
|
||||
import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
|
||||
public class PacketsListener implements PacketListener {
|
||||
private RaycastedEntityOcclusion plugin;
|
||||
private RaycastedAntiESP plugin;
|
||||
private PacketProcessor packetProcessor;
|
||||
public PacketsListener(RaycastedEntityOcclusion plugin) {
|
||||
public PacketsListener(RaycastedAntiESP plugin) {
|
||||
// This is run on load, not on enable.
|
||||
this.plugin = plugin;
|
||||
|
||||
@@ -16,13 +16,15 @@ public class PacketsListener implements PacketListener {
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_REMOVE) {
|
||||
if (packetProcessor == null) {
|
||||
// Initialize the PacketProcessor if it hasn't been initialized yet since the initialization of the PacketsListener is on load, not on enable.
|
||||
packetProcessor = plugin.getPacketProcessor();
|
||||
}
|
||||
initializePacketProcessor();
|
||||
packetProcessor.processPlayerInfoRemovePacket(event);
|
||||
}
|
||||
}
|
||||
|
||||
private void initializePacketProcessor() {
|
||||
if (packetProcessor == null) {
|
||||
packetProcessor = RaycastedAntiESP.getPacketProcessor();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -1,12 +1,13 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Packets;
|
||||
package games.cubi.raycastedAntiESP.packets;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerPriority;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
|
||||
// This only exists because you can't import packetevents api if it doesn't exist, and therefore the main class cant import it
|
||||
public class Registrar {
|
||||
|
||||
public Registrar(RaycastedEntityOcclusion plugin) {
|
||||
public Registrar(RaycastedAntiESP plugin) {
|
||||
// Register the packet listener
|
||||
PacketEvents.getAPI().getEventManager().registerListener(new PacketsListener(plugin), PacketListenerPriority.NORMAL);
|
||||
}
|
||||
+96
-83
@@ -1,28 +1,40 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Raycast;
|
||||
|
||||
package games.cubi.raycastedAntiESP.raycast;
|
||||
|
||||
public class EngineOld {}
|
||||
/*
|
||||
import games.cubi.raycastedEntityOcclusion.Logger;
|
||||
import games.cubi.raycastedEntityOcclusion.Snapshot.ChunkSnapshotManager;
|
||||
import games.cubi.raycastedEntityOcclusion.ConfigManager;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
|
||||
import games.cubi.raycastedEntityOcclusion.Snapshot.EntitySnapshotManager;
|
||||
import io.papermc.paper.threadedregions.scheduler.AsyncScheduler;
|
||||
import io.papermc.paper.threadedregions.scheduler.ScheduledTask;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.BlockState;
|
||||
import org.bukkit.block.TileState;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.Set;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class Engine {
|
||||
public class EngineOld {
|
||||
|
||||
public static ConcurrentHashMap<Location, Set<Player>> canSeeTileEntity = new ConcurrentHashMap<>();
|
||||
public static Set<Chunk> syncRecheck = ConcurrentHashMap.newKeySet();
|
||||
|
||||
private final static BlockData STONE = Material.STONE.createBlockData();
|
||||
private final static BlockData DEEPSLATE = Material.DEEPSLATE.createBlockData();
|
||||
|
||||
private static class RayJob {
|
||||
final Player player;
|
||||
@@ -49,30 +61,33 @@ public class Engine {
|
||||
visible = v;
|
||||
}
|
||||
}
|
||||
private static class PlayerInfo {
|
||||
private static class TileResult {
|
||||
final Player player;
|
||||
final Location location;
|
||||
final Location predLoc;
|
||||
final Location loc;
|
||||
final boolean visible;
|
||||
|
||||
PlayerInfo(Player p, Location loc, Location pred) {
|
||||
TileResult(Player p, Location location, boolean v) {
|
||||
player = p;
|
||||
location = loc;
|
||||
predLoc = pred;
|
||||
loc = location;
|
||||
visible = v;
|
||||
}
|
||||
}
|
||||
|
||||
private static Consumer<ScheduledTask> raycastEntitiesAroundPlayer(Player player, Location eye, Location predEye){
|
||||
|
||||
return task -> { /* This is needed for it to return, idk why*/ };
|
||||
}
|
||||
|
||||
Map<UUID, RayResult> results = new ConcurrentHashMap<>();
|
||||
|
||||
public static void runEngine(ConfigManager cfg, ChunkSnapshotManager snapMgr, MovementTracker tracker, EntitySnapshotManager entitySnapshotManager, RaycastedEntityOcclusion plugin) {
|
||||
public static void runEngine(ConfigManager cfg, ChunkSnapshotManager snapMgr, MovementTracker tracker, RaycastedEntityOcclusion plugin) {
|
||||
// ----- PHASE 1: SYNC GATHER -----
|
||||
List<PlayerInfo> info = new ArrayList<>();
|
||||
// TODO: Store players in EntitySnapshotManager and use that to avoid iterating through all players every tick
|
||||
AsyncScheduler asyncScheduler = plugin.getServer().getAsyncScheduler();
|
||||
|
||||
if (!syncRecheck.isEmpty()) {
|
||||
Logger.warning(syncRecheck.size() + " chunks failed to snapshot asynchronously, rechecking them now.");
|
||||
for (Chunk c : syncRecheck) {
|
||||
if (c.isLoaded()) {
|
||||
plugin.getChunkSnapshotManager().snapshotChunk(c);
|
||||
syncRecheck.remove(c);
|
||||
Logger.info("Successfully rechecked chunk " + c.getX() + ", " + c.getZ() + " in world " + c.getWorld().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<RayJob> jobs = new ArrayList<>();
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
if (p.hasPermission("raycastedentityocclusions.bypass")) continue;
|
||||
Location eye = p.getEyeLocation().clone();
|
||||
@@ -81,20 +96,12 @@ public class Engine {
|
||||
// getPredictedLocation returns null if insufficient data or too slow
|
||||
predEye = tracker.getPredictedLocation(p);
|
||||
}
|
||||
asyncScheduler.runNow(plugin, raycastEntitiesAroundPlayer(p, eye, predEye));
|
||||
}
|
||||
|
||||
// ----- PHASE 2: ASYNC RAYCASTS -----
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
|
||||
List<RayResult> results = new ArrayList<>();
|
||||
|
||||
|
||||
|
||||
for (Entity e : entitySnapshotManager.getBukkitEntitiesNear(eye, cfg.searchRadius, cfg.searchRadius, cfg.searchRadius)) {
|
||||
for (Entity e : p.getNearbyEntities(cfg.searchRadius, cfg.searchRadius, cfg.searchRadius)) {
|
||||
if (e == p) continue;
|
||||
// Cull-players logic
|
||||
if (e instanceof Player pl && (!cfg.cullPlayers || (cfg.onlyCullSneakingPlayers && !pl.isSneaking()))) {
|
||||
//TODO: Add to result that player should be shown
|
||||
p.showEntity(plugin, e);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -104,22 +111,16 @@ public class Engine {
|
||||
p.showEntity(plugin, e);
|
||||
} else if (dist > cfg.raycastRadius) {
|
||||
p.hideEntity(plugin, e);
|
||||
} else if (p.canSee(e) && plugin.tick % cfg.recheckInterval != 0) {
|
||||
// player can see entity, no need to raycast
|
||||
} else {
|
||||
} else if (!p.canSee(e) || plugin.tick % cfg.recheckInterval == 0) {
|
||||
// schedule for async raycast (with or without predEye)
|
||||
jobs.add(new RayJob(p, e, eye, predEye, target));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// ----- PHASE 2: ASYNC RAYCASTS -----
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
|
||||
List<RayResult> results = new ArrayList<>(jobs.size());
|
||||
for (RayJob job : jobs) {
|
||||
// if the player is not in the same world as the target, skip
|
||||
if (!job.player.getWorld().equals(job.target.getWorld())) {
|
||||
@@ -158,14 +159,17 @@ public class Engine {
|
||||
|
||||
}
|
||||
|
||||
private static ConcurrentLinkedQueue<TileResult> results = new ConcurrentLinkedQueue<>();
|
||||
|
||||
public static void runTileEngine(ConfigManager cfg, ChunkSnapshotManager snapMgr, MovementTracker tracker, RaycastedEntityOcclusion plugin) {
|
||||
if (cfg.checkTileEntities) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
if (p.hasPermission("raycastedentityocclusions.bypass")) continue;
|
||||
String world = p.getWorld().getName();
|
||||
World world = p.getWorld();
|
||||
//get player's chunk location
|
||||
int chunkX = p.getLocation().getBlockX() >> 4;
|
||||
int chunkZ = p.getLocation().getBlockZ() >> 4;
|
||||
|
||||
//async run with vars passed in
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
|
||||
int chunksRadius = (cfg.searchRadius + 15) / 16;
|
||||
@@ -186,26 +190,25 @@ public class Engine {
|
||||
|
||||
double distSquared = loc.distanceSquared(p.getLocation());
|
||||
if (distSquared > cfg.searchRadius * cfg.searchRadius) {
|
||||
hideTileEntity(p, loc);
|
||||
results.add(new TileResult(p, loc,false));
|
||||
continue;
|
||||
}
|
||||
if (distSquared < cfg.alwaysShowRadius * cfg.alwaysShowRadius) {
|
||||
showTileEntity(p, loc);
|
||||
results.add(new TileResult(p, loc,true));
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean result = RaycastUtil.raycast(p.getEyeLocation(), loc, cfg.maxOccludingCount, cfg.debugMode, snapMgr);
|
||||
if (cfg.engineMode == 2) {
|
||||
boolean visible = RaycastUtil.raycast(p.getEyeLocation(), loc, cfg.maxOccludingCount, cfg.debugMode, snapMgr);
|
||||
if (cfg.engineMode == 2 && !visible) {
|
||||
Location predEye = tracker.getPredictedLocation(p);
|
||||
if (predEye != null) {
|
||||
boolean result2 = RaycastUtil.raycast(predEye, loc, cfg.maxOccludingCount, cfg.debugMode, snapMgr);
|
||||
if (result2) {
|
||||
result = true;
|
||||
visible = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
syncToggleTileEntity(p, loc, result, plugin);
|
||||
if (result) {
|
||||
if (visible) {
|
||||
canSeeTileEntity.computeIfAbsent(loc, k -> ConcurrentHashMap.newKeySet()).add(p);
|
||||
} else {
|
||||
Set<Player> seenPlayers = canSeeTileEntity.get(loc);
|
||||
@@ -216,36 +219,46 @@ public class Engine {
|
||||
}
|
||||
}
|
||||
}
|
||||
results.add(new TileResult(p, loc, visible));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for (TileResult r : results) {
|
||||
Player p = r.player;
|
||||
Location loc = r.loc;
|
||||
boolean visible = r.visible;
|
||||
|
||||
public static void hideTileEntity(Player p, Location location) {
|
||||
if (p.hasPermission("raycastedentityocclusions.bypass")) return;
|
||||
BlockData fake;
|
||||
if (location.getBlockY() < 0) {
|
||||
fake = Material.DEEPSLATE.createBlockData();
|
||||
}
|
||||
else {
|
||||
fake = Material.STONE.createBlockData();
|
||||
}
|
||||
p.sendBlockChange(location, fake);
|
||||
}
|
||||
public static void showTileEntity(Player p, Location location) {
|
||||
Block block = location.getBlock();
|
||||
BlockData data = block.getBlockData();
|
||||
p.sendBlockChange(location, data);
|
||||
|
||||
}
|
||||
public static void syncToggleTileEntity(Player p, Location loc, boolean bool, RaycastedEntityOcclusion plugin) {
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
if (bool) {
|
||||
showTileEntity(p, loc);
|
||||
} else {
|
||||
hideTileEntity(p, loc);
|
||||
syncToggleTileEntity(p, loc, visible, plugin);
|
||||
results.remove(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void hideTileEntity(Player p, Location location, RaycastedEntityOcclusion plugin) {
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
if (p.hasPermission("raycastedentityocclusions.bypass")) return;
|
||||
if (location.getBlockY() < 0) p.sendBlockChange(location, DEEPSLATE);
|
||||
else p.sendBlockChange(location, STONE);
|
||||
});
|
||||
}
|
||||
}
|
||||
public static void showTileEntity(Player p, Location location, RaycastedEntityOcclusion plugin) {
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
Block block = location.getBlock();
|
||||
BlockState data = block.getState();
|
||||
if (data instanceof TileState tileData) {
|
||||
p.sendBlockChange(location, block.getBlockData());
|
||||
p.sendBlockUpdate(location, tileData);
|
||||
}
|
||||
else throw new RuntimeException("Attempting to show a block which isn't a tile entity");
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
public static void syncToggleTileEntity(Player p, Location loc, boolean show, RaycastedEntityOcclusion plugin) {
|
||||
if (show) {
|
||||
showTileEntity(p, loc, plugin);
|
||||
} else {
|
||||
hideTileEntity(p, loc, plugin);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
+18
-20
@@ -1,11 +1,10 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Raycast;
|
||||
package games.cubi.raycastedAntiESP.raycast;
|
||||
|
||||
import games.cubi.raycastedEntityOcclusion.ConfigManager;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
import games.cubi.raycastedAntiESP.config.ConfigManager;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
@@ -13,30 +12,29 @@ import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class MovementTracker {
|
||||
private final Map<Player, Deque<Location>> history = new ConcurrentHashMap<>();
|
||||
private final Map<Player, Deque<Location>> history = new ConcurrentHashMap<>(); //TODO: Queue makes more sense than deque, also this should be moved elsewhere
|
||||
|
||||
public MovementTracker(RaycastedEntityOcclusion plugin, ConfigManager config) {
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (config.engineMode == 2) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
history.computeIfAbsent(p, k -> new ArrayDeque<>(5));
|
||||
Deque<Location> dq = history.get(p);
|
||||
if (dq.size() >= 5) dq.removeFirst();
|
||||
public MovementTracker(RaycastedAntiESP plugin, ConfigManager config) {
|
||||
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, updateLocationHistory(config), 1L, 1L);
|
||||
}
|
||||
|
||||
dq.addLast(p.getEyeLocation());
|
||||
}
|
||||
}
|
||||
}
|
||||
}.runTaskTimer(plugin, 1L, 1L);
|
||||
private Runnable updateLocationHistory(ConfigManager config) {
|
||||
if (config.getEngineMode() != 2) return () -> {};
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
history.computeIfAbsent(p, k -> new ArrayDeque<>(5));
|
||||
Deque<Location> dq = history.get(p);
|
||||
|
||||
if (dq.size() >= 5) dq.removeFirst();
|
||||
|
||||
dq.addLast(p.getEyeLocation());
|
||||
}
|
||||
return () -> {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Predicts location 5 ticks ahead based on last 5 ticks. Returns null if insufficient or too slow.
|
||||
*/
|
||||
public Location getPredictedLocation(Player p) {
|
||||
//TODO: Make the predicted location incorporate ping
|
||||
Deque<Location> dq = history.get(p);
|
||||
if (dq == null || dq.size() < 5) return null;
|
||||
Location old = dq.peekFirst();
|
||||
@@ -0,0 +1,98 @@
|
||||
package games.cubi.raycastedAntiESP.raycast;
|
||||
|
||||
import games.cubi.raycastedAntiESP.snapshot.ChunkSnapshotManager;
|
||||
import games.cubi.raycastedAntiESP.utils.LocationPair;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
public class RaycastUtil {
|
||||
|
||||
public static boolean raycastLocationPair(LocationPair locationPair, int maxOccluding, boolean debug, ChunkSnapshotManager snap) {
|
||||
|
||||
//These locations do not need to be cloned because .toLocation creates a new location object. We can mutate it freely
|
||||
Location currentA = locationPair.first().toLocation();
|
||||
Location currentB = locationPair.second().toLocation();
|
||||
|
||||
Particle.DustOptions dustRed = null;
|
||||
Particle.DustOptions dustGreen = null;
|
||||
Particle.DustOptions dustBlue = null;
|
||||
if (debug) {
|
||||
dustRed = new Particle.DustOptions(Color.RED,1f);
|
||||
dustGreen = new Particle.DustOptions(Color.GREEN,1f);
|
||||
dustBlue = new Particle.DustOptions(Color.BLUE,1f);
|
||||
}
|
||||
|
||||
double total = currentA.distance(currentB);
|
||||
double traveledA = 0;
|
||||
double traveledB = 0;
|
||||
|
||||
Vector dirA = currentB.toVector().subtract(currentA.toVector()).normalize();
|
||||
Vector dirB = currentA.toVector().subtract(currentB.toVector()).normalize();
|
||||
|
||||
// Walk from each end until the cursors meet in the middle
|
||||
while (traveledA + traveledB < total) {
|
||||
|
||||
/* --- step from A ---> B --- */
|
||||
currentA.add(dirA);
|
||||
traveledA += 1;
|
||||
Material matA = snap.getMaterialAt(currentA);
|
||||
if (matA != null && matA.isOccluding()) {
|
||||
maxOccluding--;
|
||||
if (debug) currentA.getWorld().spawnParticle(Particle.DUST, currentA, 1, dustRed);
|
||||
} else if (debug) {
|
||||
currentA.getWorld().spawnParticle(Particle.DUST, currentA, 1, dustGreen);
|
||||
}
|
||||
if (maxOccluding < 1) return false;
|
||||
|
||||
/* --- step from B ---> A --- */
|
||||
if (traveledA + traveledB >= total) break; // already overlapped
|
||||
currentB.add(dirB);
|
||||
traveledB += 1;
|
||||
Material matB = snap.getMaterialAt(currentB);
|
||||
if (matB != null && matB.isOccluding()) {
|
||||
maxOccluding--;
|
||||
if (debug) currentB.getWorld().spawnParticle(Particle.DUST, currentB, 1, dustRed);
|
||||
} else if (debug) {
|
||||
currentB.getWorld().spawnParticle(Particle.DUST, currentB, 1, dustBlue);
|
||||
}
|
||||
if (maxOccluding < 1) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static boolean raycast(Location start, Location end, int maxOccluding, boolean debug, ChunkSnapshotManager snap) {
|
||||
Particle.DustOptions dustRed = null;
|
||||
Particle.DustOptions dustGreen = null;
|
||||
if (debug) {
|
||||
dustRed = new Particle.DustOptions(org.bukkit.Color.RED, 1f);
|
||||
dustGreen = new Particle.DustOptions(org.bukkit.Color.GREEN, 1f);
|
||||
}
|
||||
double total = start.distance(end);
|
||||
double traveled = 0;
|
||||
Location curr = start.clone();
|
||||
Vector dir = end.toVector().subtract(start.toVector()).normalize();
|
||||
while (traveled < total) {
|
||||
curr.add(dir);
|
||||
traveled += 1;
|
||||
Material mat = snap.getMaterialAt(curr);
|
||||
if (mat == null) {
|
||||
continue;
|
||||
}
|
||||
if (mat.isOccluding()) {
|
||||
maxOccluding--;
|
||||
if (debug) {
|
||||
start.getWorld().spawnParticle(Particle.DUST, curr, 1, dustRed);
|
||||
}
|
||||
if (maxOccluding < 1) return false;
|
||||
}
|
||||
else if (debug) {
|
||||
start.getWorld().spawnParticle(Particle.DUST, curr, 1, dustGreen);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package games.cubi.raycastedAntiESP.snapshot;
|
||||
|
||||
import games.cubi.raycastedAntiESP.config.ConfigManager;
|
||||
import games.cubi.raycastedAntiESP.Logger;
|
||||
import games.cubi.raycastedAntiESP.RaycastedAntiESP;
|
||||
|
||||
import games.cubi.raycastedAntiESP.utils.BlockLocation;
|
||||
import games.cubi.raycastedAntiESP.utils.Enums;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.ChunkSnapshot;
|
||||
import org.bukkit.block.BlockState;
|
||||
import org.bukkit.block.TileState;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.Map;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class ChunkSnapshotManager {
|
||||
private static class ChunkData {
|
||||
public final ChunkSnapshot snapshot;
|
||||
public final ConcurrentHashMap<BlockLocation, Material> delta = new ConcurrentHashMap<>();
|
||||
public final Set<BlockLocation> tileEntities = ConcurrentHashMap.newKeySet();
|
||||
public long lastRefresh;
|
||||
public int minHeight;
|
||||
public int maxHeight;
|
||||
|
||||
public ChunkData(ChunkSnapshot snapshot, long time) {
|
||||
this.snapshot = snapshot;
|
||||
this.lastRefresh = time;
|
||||
}
|
||||
}
|
||||
|
||||
private static final ConcurrentHashMap<String, ChunkData> dataMap = new ConcurrentHashMap<>();
|
||||
private final ConfigManager cfg;
|
||||
private final RaycastedAntiESP plugin;
|
||||
|
||||
public ChunkSnapshotManager(RaycastedAntiESP plugin, ConfigManager config) {
|
||||
cfg = config;
|
||||
this.plugin = plugin;
|
||||
//get loaded chunks and add them to dataMap
|
||||
for (World w : plugin.getServer().getWorlds()) {
|
||||
for (Chunk c : w.getLoadedChunks()) {
|
||||
snapshotChunk(c);
|
||||
}
|
||||
}
|
||||
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
long now = System.currentTimeMillis();
|
||||
int chunksRefreshed = 0;
|
||||
int chunksToRefreshMaximum = getNumberOfCachedChunks() / 3;
|
||||
for (Map.Entry<String, ChunkData> e : dataMap.entrySet()) {
|
||||
if (now - e.getValue().lastRefresh >= cfg.getSnapshotConfig().getWorldSnapshotRefreshInterval() * 1000L && chunksRefreshed < chunksToRefreshMaximum) {
|
||||
chunksRefreshed++;
|
||||
String key = e.getKey();
|
||||
snapshotChunk(key);
|
||||
}
|
||||
}
|
||||
Logger.info("ChunkSnapshotManager: Refreshed " + chunksRefreshed + " chunks out of " + chunksToRefreshMaximum + " maximum.", 10);
|
||||
}
|
||||
}.runTaskTimerAsynchronously(plugin, cfg.getSnapshotConfig().getWorldSnapshotRefreshInterval() * 2L, cfg.getSnapshotConfig().getWorldSnapshotRefreshInterval() * 2L /* This runs 10 times per refreshInterval, spreading out the refreshes */);
|
||||
}
|
||||
|
||||
public void onChunkLoad(Chunk c) {
|
||||
snapshotChunk(c);
|
||||
}
|
||||
|
||||
public void onChunkUnload(Chunk c) {
|
||||
removeChunkSnapshot(c);
|
||||
}
|
||||
|
||||
public void snapshotChunk(Chunk c) {
|
||||
Logger.info("ChunkSnapshotManager: Taking snapshot of chunk " + c.getWorld().getName() + ":" + c.getX() + ":" + c.getZ(),10);
|
||||
dataMap.put(key(c), takeSnapshot(c, System.currentTimeMillis()));
|
||||
}
|
||||
public void snapshotChunk(String key) {
|
||||
snapshotChunk(getKeyChunk(key));
|
||||
}
|
||||
public void removeChunkSnapshot(Chunk c) {
|
||||
Logger.info("ChunkSnapshotManager: Removing snapshot of chunk " + c.getWorld().getName() + ":" + c.getX() + ":" + c.getZ(), 9);
|
||||
dataMap.remove(key(c));
|
||||
}
|
||||
|
||||
// Used by EventListener to update the delta map when a block is placed or broken
|
||||
public void onBlockChange(Location loc, Material m, Enums.BlockChangeType type) {
|
||||
Logger.info("ChunkSnapshotManager: Block change at " + loc + " to " + m, 9);
|
||||
ChunkData d = dataMap.get(key(loc.getChunk()));
|
||||
if (d == null) {
|
||||
Logger.error("Data map value empty, ignoring block update!",2);
|
||||
return;
|
||||
}
|
||||
BlockLocation location = new BlockLocation(loc);
|
||||
d.delta.put(location, m);
|
||||
if (cfg.getTileEntityConfig().isEnabled()) {
|
||||
// Check if the block is a tile entity
|
||||
BlockState data = loc.getBlock().getState();
|
||||
loc = loc.clone().add(0.5, 0.5, 0.5);
|
||||
if (data instanceof TileState) {
|
||||
Logger.info("ChunkSnapshotManager: Tile entity at " + loc, 8);
|
||||
if (type == Enums.BlockChangeType.PLACED) {
|
||||
d.tileEntities.add(location);
|
||||
} else if (type == Enums.BlockChangeType.BROKEN) {
|
||||
d.tileEntities.remove(location);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {Logger.error("Data map value empty, ignoring block update!", 2);}
|
||||
}
|
||||
|
||||
private ChunkData takeSnapshot(Chunk c, long now) {
|
||||
World w = c.getWorld();
|
||||
ChunkData data = new ChunkData(c.getChunkSnapshot(), now);
|
||||
int chunkX = c.getX() * 16;
|
||||
int chunkZ = c.getZ() * 16;
|
||||
int minHeight = w.getMinHeight();
|
||||
int maxHeight = w.getMaxHeight();
|
||||
data.maxHeight = maxHeight;
|
||||
data.minHeight = minHeight;
|
||||
if (cfg.getTileEntityConfig().isEnabled()) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
for (int y = minHeight; y < maxHeight; y++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
BlockState bs = data.snapshot.getBlockData(x, y, z).createBlockState();
|
||||
|
||||
if (bs instanceof TileState) {
|
||||
data.tileEntities.add(new BlockLocation(w, x+ chunkX, y, z + chunkZ));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public String key(Chunk c) {
|
||||
return c.getWorld().getName() + ":" + c.getX() + ":" + c.getZ();
|
||||
}
|
||||
public String key(World world, int x, int z) {
|
||||
return world.getName() + ":" + x + ":" + z;
|
||||
}
|
||||
public int getKeyX(String key) {
|
||||
String[] parts = key.split(":");
|
||||
return Integer.parseInt(parts[1]);
|
||||
}
|
||||
public int getKeyZ(String key) {
|
||||
String[] parts = key.split(":");
|
||||
return Integer.parseInt(parts[2]);
|
||||
}
|
||||
public World getKeyWorld(String key) {
|
||||
String[] parts = key.split(":");
|
||||
return Bukkit.getWorld(parts[0]);
|
||||
}
|
||||
public Chunk getKeyChunk(String key) {
|
||||
return getKeyWorld(key).getChunkAt(getKeyX(key), getKeyZ(key));
|
||||
}
|
||||
|
||||
public Material getMaterialAt(Location loc) {
|
||||
Chunk chunk = loc.getChunk();
|
||||
ChunkData d = dataMap.get(key(chunk));
|
||||
if (d == null) {
|
||||
Chunk c = loc.getChunk();
|
||||
Logger.error("ChunkSnapshotManager: No snapshot for " + c+ " If this error persists, please report this on our discord (discord.cubi.games)", 3);
|
||||
//EngineOld.syncRecheck.add(chunk); TODO reenable
|
||||
return loc.getBlock().getType();
|
||||
}
|
||||
double yLevel = loc.getY();
|
||||
if (yLevel < d.minHeight || yLevel > d.maxHeight) {
|
||||
return null;
|
||||
}
|
||||
Material dm = d.delta.get(new BlockLocation(loc));
|
||||
if (dm != null) {
|
||||
Logger.info("Using delta", 9);
|
||||
return dm;
|
||||
}
|
||||
int x = loc.getBlockX() & 0xF;
|
||||
int y = loc.getBlockY();
|
||||
int z = loc.getBlockZ() & 0xF;
|
||||
|
||||
return d.snapshot.getBlockType(x, y, z);
|
||||
}
|
||||
|
||||
//get TileEntity Locations in chunk
|
||||
public Set<Location> getTileEntitiesInChunk(World world, int x, int z) {
|
||||
ChunkData d = dataMap.get(key(world, x, z));
|
||||
if (d == null) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return BlockLocation.toCentredLocations(d.tileEntities);
|
||||
}
|
||||
|
||||
public int getNumberOfCachedChunks() {
|
||||
return dataMap.size();
|
||||
//created to use in a info command maybe
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class BlockLocation {
|
||||
private final UUID world;
|
||||
private final int x;
|
||||
private final int y;
|
||||
private final int z;
|
||||
|
||||
public BlockLocation(World world, double x, double y, double z) {
|
||||
this.world = world.getUID();
|
||||
this.x = (int) Math.floor(x);
|
||||
this.y = (int) Math.floor(y);
|
||||
this.z = (int) Math.floor(z);
|
||||
}
|
||||
|
||||
public BlockLocation(Location loc) {
|
||||
this.world = loc.getWorld().getUID();
|
||||
this.x = (int) Math.floor(loc.getX());
|
||||
this.y = (int) Math.floor(loc.getY());
|
||||
this.z = (int) Math.floor(loc.getZ());
|
||||
}
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public int getZ() {
|
||||
return z;
|
||||
}
|
||||
|
||||
public Location toCentredLocation() {
|
||||
return new Location(Bukkit.getWorld(world), x + 0.5, y + 0.5, z + 0.5);
|
||||
}
|
||||
|
||||
public static Location toCentredLocation(BlockLocation blockLocation) {
|
||||
return new Location(Bukkit.getWorld(blockLocation.world), blockLocation.x + 0.5, blockLocation.y + 0.5, blockLocation.z + 0.5);
|
||||
}
|
||||
|
||||
public static Set<Location> toCentredLocations(Set<BlockLocation> blockLocations) {
|
||||
Set<Location> locations = new HashSet<>();
|
||||
for (BlockLocation bl : blockLocations) {
|
||||
locations.add(BlockLocation.toCentredLocation(bl));
|
||||
}
|
||||
return locations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof BlockLocation other)) return false;
|
||||
return x == other.x && y == other.y && z == other.z && world.equals(other.world);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(world, x, y, z);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
//Paper always prints the name of the exception being thrown, even if the message is empty. So, the name of this class will point the user to the actual error message
|
||||
public class CheckPreviousLogForError extends RuntimeException {
|
||||
public CheckPreviousLogForError() {
|
||||
super("",null, false, false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import java.util.UUID;
|
||||
|
||||
public record EntityLocationPair(UUID entity, Location loc) {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
public class Enums {
|
||||
public enum BlockChangeType {
|
||||
PLACED,
|
||||
BROKEN
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class LocationPair {
|
||||
private final QuantisedLocation loc1;
|
||||
private final QuantisedLocation loc2; // canonical ordering: loc1 ≤ loc2 by hash
|
||||
|
||||
private LocationPair(QuantisedLocation p, QuantisedLocation e) {
|
||||
this.loc1 = p;
|
||||
this.loc2 = e;
|
||||
}
|
||||
|
||||
public static LocationPair of(QuantisedLocation a, QuantisedLocation b) {
|
||||
if (!a.world().equals(b.world()))
|
||||
throw new IllegalArgumentException("Locations are in different worlds");
|
||||
// choose a deterministic order so (A,B)==(B,A) TODO: More perf optimal way than hashing? Or maybe just make sure this is ran async? Or is hashing fine perf wise?
|
||||
if (a.hashCode() <= b.hashCode()) {
|
||||
return new LocationPair(a, b);
|
||||
}
|
||||
else return new LocationPair(b, a);
|
||||
}
|
||||
|
||||
public QuantisedLocation first() {
|
||||
return loc1;
|
||||
}
|
||||
|
||||
public QuantisedLocation second() {
|
||||
return loc2;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof LocationPair lp)) return false;
|
||||
return loc1.equals(lp.loc1) && loc2.equals(lp.loc2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(loc1, loc2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
import games.cubi.raycastedAntiESP.data.DataHolder;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class PlayerData {
|
||||
|
||||
private record EntityVisibilityAndLastCheckTime(boolean visible, int lastChecked) {
|
||||
public EntityVisibilityAndLastCheckTime(boolean visible) {
|
||||
this(visible, DataHolder.getTick());
|
||||
}
|
||||
}
|
||||
|
||||
// Maps must be thread-safe as their values will be updated while async engine jobs are running, but UUID is probably fine.
|
||||
private final UUID playerUUID;
|
||||
private boolean hasBypassPermission;
|
||||
|
||||
// UUID = Entity UUID, Boolean = if it is visible to the player. False = hidden
|
||||
private final ConcurrentHashMap<UUID, EntityVisibilityAndLastCheckTime> entityVisibility = new ConcurrentHashMap<>();
|
||||
|
||||
// Location, time in millis TODO: Is it necessary to store the time as a long? Do we even need a recheck interval at all?
|
||||
private final ConcurrentHashMap<BlockLocation, Long> seenTileEntities = new ConcurrentHashMap<>();
|
||||
|
||||
public PlayerData(UUID playerUUID, boolean hasBypassPermission) {
|
||||
this.playerUUID = playerUUID;
|
||||
this.hasBypassPermission = hasBypassPermission;
|
||||
}
|
||||
|
||||
public PlayerData(Player player) {
|
||||
this.playerUUID = player.getUniqueId();
|
||||
this.hasBypassPermission = player.hasPermission("raycastedentityocclusions.bypass");
|
||||
}
|
||||
|
||||
public UUID getPlayerUUID() {
|
||||
return playerUUID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the provided set of entity UUIDs to the entity visibility map with a default visibility of false (not visible). If an entity UUID already exists in the map, it will not be modified.
|
||||
* **/
|
||||
public void addEntities(Set<UUID> entityUUIDs) {
|
||||
for (UUID entityUUID : entityUUIDs) {
|
||||
entityVisibility.putIfAbsent(entityUUID, new EntityVisibilityAndLastCheckTime(false));
|
||||
}
|
||||
}
|
||||
|
||||
public void addEntity(UUID entityUUID) {
|
||||
entityVisibility.putIfAbsent(entityUUID, new EntityVisibilityAndLastCheckTime(false)); // Default to hidden if not already present
|
||||
}
|
||||
|
||||
public void setEntityVisibility(UUID entityUUID, boolean visible) {
|
||||
entityVisibility.put(entityUUID, new EntityVisibilityAndLastCheckTime(visible)); // This can be used for both adding new entries and updating visibility
|
||||
}
|
||||
|
||||
public boolean isEntityVisible(UUID entityUUID) {
|
||||
return entityVisibility.getOrDefault(entityUUID, new EntityVisibilityAndLastCheckTime(true)).visible;
|
||||
//Default to true as entities are visible unless explicitly hidden
|
||||
}
|
||||
|
||||
public void removeEntity(UUID entityUUID) {
|
||||
entityVisibility.remove(entityUUID);
|
||||
}
|
||||
|
||||
public Map<BlockLocation, Long> getSeenTileEntitiesMap() {
|
||||
return new HashMap<>(seenTileEntities);
|
||||
}
|
||||
|
||||
public void addSeenTileEntity(BlockLocation tileEntityLocation) {
|
||||
seenTileEntities.put(tileEntityLocation, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void addSeenTileEntity(Location tileEntityLocation) {
|
||||
seenTileEntities.put(new BlockLocation(tileEntityLocation), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void removeSeenTileEntity(BlockLocation tileEntityLocation) {
|
||||
seenTileEntities.remove(tileEntityLocation); // This method should never actually be called, but it's here for completeness
|
||||
}
|
||||
|
||||
public void removeSeenTileEntity(Location tileEntityLocation) {
|
||||
seenTileEntities.remove(new BlockLocation(tileEntityLocation)); // This method should never actually be called, but it's here for completeness
|
||||
}
|
||||
|
||||
public boolean hasSeenTileEntity(BlockLocation tileEntityLocation) {
|
||||
return seenTileEntities.containsKey(tileEntityLocation);
|
||||
}
|
||||
|
||||
public boolean hasSeenTileEntity(Location tileEntityLocation) {
|
||||
return seenTileEntities.containsKey(new BlockLocation(tileEntityLocation));
|
||||
}
|
||||
|
||||
public boolean hasBypassPermission() {
|
||||
return hasBypassPermission;
|
||||
}
|
||||
|
||||
public void setBypassPermission(boolean hasBypassPermission) {
|
||||
this.hasBypassPermission = hasBypassPermission;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class QuantisedLocation {
|
||||
// One decimal place quantisation. This means that the coordinates are rounded to the nearest 0.1 block, and since integers are used this works up to 200m blocks away (integer limit/10)
|
||||
// Note that the last digit of the integer is the tenths place, so 123456789 represents 12345678.9 in real coordinates.
|
||||
private final int x;
|
||||
private final int y;
|
||||
private final int z;
|
||||
private final UUID world;
|
||||
|
||||
public QuantisedLocation(Location location) {
|
||||
this.x = (int) Math.floor(location.getX() * 10);
|
||||
this.y = (int) Math.floor(location.getY() * 10);
|
||||
this.z = (int) Math.floor(location.getZ() * 10);
|
||||
this.world = location.getWorld().getUID();
|
||||
}
|
||||
public QuantisedLocation(Location location, double height) {
|
||||
this.x = (int) Math.floor(location.getX() * 10);
|
||||
this.y = (int) Math.floor(location.getY()+(height/2) * 10);
|
||||
this.z = (int) Math.floor(location.getZ() * 10);
|
||||
this.world = location.getWorld().getUID();
|
||||
}
|
||||
|
||||
public Location toLocation() {
|
||||
return new Location(Bukkit.getWorld(world), (x / 10.0)+0.05, (y / 10.0)+0.05, (z / 10.0)+0.05);
|
||||
}
|
||||
|
||||
public ThreadSafeLoc toThreadSafeLoc() {
|
||||
return new ThreadSafeLoc(this);
|
||||
}
|
||||
|
||||
public Vector toNewVector() {
|
||||
return new Vector((x / 10.0)+0.05, (y / 10.0)+0.05, (z / 10.0)+0.05);
|
||||
}
|
||||
|
||||
public boolean isWithinRadius(QuantisedLocation other, double radius) {
|
||||
if (!this.world.equals(other.world)) {
|
||||
throw new IllegalArgumentException("Cannot calculate distance between different worlds.");
|
||||
}
|
||||
|
||||
int dx = this.x - other.x;
|
||||
int dy = this.y - other.y;
|
||||
int dz = this.z - other.z;
|
||||
|
||||
// Convert radius (in blocks) to squared distance in quantised units (tenths of blocks).
|
||||
double radiusSquared = radius * radius * 100; // (radius * 10)²
|
||||
int distanceSquared = dx * dx + dy * dy + dz * dz;
|
||||
|
||||
return distanceSquared <= radiusSquared;
|
||||
}
|
||||
|
||||
public double realX() {
|
||||
return (x / 10.0) + 0.05;
|
||||
}
|
||||
|
||||
public double realY() {
|
||||
return (y / 10.0) + 0.05;
|
||||
}
|
||||
|
||||
public double realZ() {
|
||||
return (z / 10.0) + 0.05;
|
||||
}
|
||||
|
||||
public UUID world() {
|
||||
return world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof QuantisedLocation other)) return false;
|
||||
return x == other.x && y == other.y && z == other.z && world.equals(other.world);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(world, x, y, z);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class Subscribers {
|
||||
//First UUID are the players, second uuid are the entities tied to their subscription
|
||||
private final HashMap<UUID, Set<UUID>> subscribers = new HashMap<>();
|
||||
|
||||
public Subscribers(UUID player, Set<UUID> entities) {
|
||||
subscribers.putIfAbsent(player, entities);
|
||||
}
|
||||
|
||||
public Subscribers(UUID player, UUID entity) {
|
||||
addSubscriberWithEntity(player, entity);
|
||||
}
|
||||
|
||||
public Subscribers() {}
|
||||
|
||||
public void addSubscriberWithEntity(UUID player, UUID entity) {
|
||||
// if 'player' is not already in the map, create a new HashSet<>()
|
||||
subscribers
|
||||
.computeIfAbsent(player, k -> new HashSet<>())
|
||||
.add(entity);
|
||||
}
|
||||
|
||||
public Set<UUID> getEntities(UUID player) {
|
||||
return subscribers.getOrDefault(player, Collections.emptySet());
|
||||
}
|
||||
|
||||
public Set<UUID> getPlayers() {
|
||||
return subscribers.keySet();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package games.cubi.raycastedAntiESP.utils;
|
||||
|
||||
import games.cubi.raycastedAntiESP.Logger;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public class ThreadSafeLoc //TBH I still don't even know if this is needed
|
||||
{
|
||||
private final UUID world;
|
||||
private final Vector vector1;
|
||||
private final Vector vector2;
|
||||
private volatile byte pointer = 1;
|
||||
private final AtomicBoolean writeLock = new AtomicBoolean(false);
|
||||
|
||||
|
||||
public ThreadSafeLoc(Vector vec, UUID world) {
|
||||
writeLock.set(true);
|
||||
this.world = world;
|
||||
vector1 = vec.clone(); //clone to ensure a new vector
|
||||
writeLock.set(false);
|
||||
vector2 = vector1.clone();
|
||||
}
|
||||
|
||||
public ThreadSafeLoc(Location loc) {
|
||||
this(loc.toVector(), loc.getWorld().getUID());
|
||||
}
|
||||
|
||||
public ThreadSafeLoc(Location loc, double height) {
|
||||
this(loc.add(0, height/2, 0).toVector(), loc.getWorld().getUID());
|
||||
}
|
||||
|
||||
public ThreadSafeLoc(QuantisedLocation loc) {
|
||||
this(new Vector(loc.realX(), loc.realY(), loc.realZ()), loc.world());
|
||||
}
|
||||
|
||||
/**This returns the actual vector, so make sure it is cloned before use*/
|
||||
private Vector getPointedVector() {
|
||||
if (pointer == 1) return vector1;
|
||||
return vector2;
|
||||
}
|
||||
|
||||
public Vector getPointedVectorClone() {
|
||||
return getPointedVector().clone();
|
||||
}
|
||||
|
||||
/**Returns a clone of the vector*/
|
||||
public Vector read() {
|
||||
return getPointedVector().clone();
|
||||
}
|
||||
/**Returns the X value of the vector*/
|
||||
public double readX() {
|
||||
return getPointedVector().getX();
|
||||
}
|
||||
/**Returns the Y value of the vector*/
|
||||
public double readY() {
|
||||
return getPointedVector().getY();
|
||||
}
|
||||
/**Returns the Z value of the vector*/
|
||||
public double readZ() {
|
||||
return getPointedVector().getZ();
|
||||
}
|
||||
public UUID readWorld() { return world; }
|
||||
|
||||
public boolean update(Vector newVec) {
|
||||
if (writeLock.compareAndSet(false, true)) {
|
||||
try {
|
||||
pointer = 2;
|
||||
overwriteVector(vector1, newVec);
|
||||
pointer = 1;
|
||||
overwriteVector(vector2, vector1);
|
||||
return true;
|
||||
} finally {
|
||||
boolean sanityCheck = writeLock.compareAndSet(true, false);
|
||||
if (!sanityCheck) Logger.errorAndReturn(new RuntimeException("ThreadSafeLoc lost thread lock during operation"));
|
||||
}
|
||||
}
|
||||
else return false;
|
||||
}
|
||||
|
||||
public boolean updateDelta(Vector delta) {
|
||||
if (writeLock.compareAndSet(false, true)) {
|
||||
try {
|
||||
pointer = 2;
|
||||
vector1.add(delta);
|
||||
pointer = 1;
|
||||
overwriteVector(vector2, vector1);
|
||||
return true;
|
||||
} finally {
|
||||
boolean sanityCheck = writeLock.compareAndSet(true, false);
|
||||
if (!sanityCheck) Logger.errorAndReturn(new RuntimeException("ThreadSafeLoc lost thread lock during operation"));
|
||||
}
|
||||
}
|
||||
else return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites the first object with the x,y,z values of the second object to avoid creating new vector objects
|
||||
@param object the vector being overwritten
|
||||
@param newVec the source of the x,y,z values
|
||||
@return the overwritten vector (same as object param)
|
||||
* **/
|
||||
@SuppressWarnings("UnusedReturnValue")
|
||||
private Vector overwriteVector(Vector object, Vector newVec) {
|
||||
object.setX(newVec.getX()).setY(newVec.getY()).setZ(newVec.getZ());
|
||||
return object;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof ThreadSafeLoc other)) return false;
|
||||
return world.equals(other.world) && this.getPointedVector().equals(other.getPointedVector());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(world, getPointedVector());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
package games.cubi.raycastedEntityOcclusion;
|
||||
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public class ConfigManager {
|
||||
private final JavaPlugin plugin;
|
||||
public int snapshotRefreshInterval;
|
||||
public int engineMode;
|
||||
public int maxOccludingCount;
|
||||
public boolean debugMode;
|
||||
public int alwaysShowRadius;
|
||||
public int raycastRadius;
|
||||
public int searchRadius;
|
||||
public boolean cullPlayers;
|
||||
public boolean onlyCullSneakingPlayers;
|
||||
public int recheckInterval;
|
||||
public boolean checkTileEntities;
|
||||
public int tileEntityRecheckInterval;
|
||||
public FileConfiguration cfg;
|
||||
public boolean packetEventsPresent = false;
|
||||
|
||||
public static final int SNAPSHOT_REFRESH_INTERVAL_DEFAULT = 60;
|
||||
public static final int ENGINE_MODE_DEFAULT = 1;
|
||||
public static final int MAX_OCCLUDING_COUNT_DEFAULT = 3;
|
||||
public static final boolean DEBUG_MODE_DEFAULT = false;
|
||||
public static final int ALWAYS_SHOW_RADIUS_DEFAULT = 16;
|
||||
public static final int RAYCAST_RADIUS_DEFAULT = 48;
|
||||
public static final int SEARCH_RADIUS_DEFAULT = 48;
|
||||
public static final boolean CULL_PLAYERS_DEFAULT = false;
|
||||
public static final boolean ONLY_CULL_SNEAKING_PLAYERS_DEFAULT = false;
|
||||
public static final int RECHECK_INTERVAL_DEFAULT = 50;
|
||||
public static final boolean CHECK_TILE_ENTITIES_DEFAULT = true;
|
||||
public static final int TILE_ENTITY_RECHECK_INTERVAL_DEFAULT = 0;
|
||||
|
||||
public ConfigManager(JavaPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
load();
|
||||
}
|
||||
|
||||
public void load() {
|
||||
plugin.saveDefaultConfig();
|
||||
plugin.reloadConfig();
|
||||
cfg = plugin.getConfig();
|
||||
|
||||
snapshotRefreshInterval = cfg.getInt("snapshot-refresh-interval", SNAPSHOT_REFRESH_INTERVAL_DEFAULT);
|
||||
engineMode = cfg.getInt("engine-mode", ENGINE_MODE_DEFAULT);
|
||||
maxOccludingCount = cfg.getInt("max-occluding-count", MAX_OCCLUDING_COUNT_DEFAULT);
|
||||
debugMode = cfg.getBoolean("debug-mode", DEBUG_MODE_DEFAULT);
|
||||
|
||||
alwaysShowRadius = cfg.getInt("always-show-radius", ALWAYS_SHOW_RADIUS_DEFAULT);
|
||||
raycastRadius = cfg.getInt("raycast-radius", RAYCAST_RADIUS_DEFAULT);
|
||||
searchRadius = cfg.getInt("search-radius", SEARCH_RADIUS_DEFAULT);
|
||||
cullPlayers = cfg.getBoolean("cull-players", CULL_PLAYERS_DEFAULT);
|
||||
onlyCullSneakingPlayers = cfg.getBoolean("only-cull-sneaking-players", ONLY_CULL_SNEAKING_PLAYERS_DEFAULT);
|
||||
recheckInterval = cfg.getInt("recheck-interval", RECHECK_INTERVAL_DEFAULT);
|
||||
|
||||
checkTileEntities = cfg.getBoolean("check-tile-entities", CHECK_TILE_ENTITIES_DEFAULT);
|
||||
tileEntityRecheckInterval = cfg.getInt("tile-entity-recheck-interval", TILE_ENTITY_RECHECK_INTERVAL_DEFAULT);
|
||||
|
||||
// Write defaults if missing
|
||||
cfg.addDefault("snapshot-refresh-interval", SNAPSHOT_REFRESH_INTERVAL_DEFAULT);
|
||||
cfg.addDefault("engine-mode", ENGINE_MODE_DEFAULT);
|
||||
cfg.addDefault("max-occluding-count", MAX_OCCLUDING_COUNT_DEFAULT);
|
||||
cfg.addDefault("debug-mode", DEBUG_MODE_DEFAULT);
|
||||
cfg.addDefault("always-show-radius", ALWAYS_SHOW_RADIUS_DEFAULT);
|
||||
cfg.addDefault("raycast-radius", RAYCAST_RADIUS_DEFAULT);
|
||||
cfg.addDefault("search-radius", SEARCH_RADIUS_DEFAULT);
|
||||
cfg.addDefault("cull-players", CULL_PLAYERS_DEFAULT);
|
||||
cfg.addDefault("only-cull-sneaking-players", ONLY_CULL_SNEAKING_PLAYERS_DEFAULT);
|
||||
cfg.addDefault("recheck-interval", RECHECK_INTERVAL_DEFAULT);
|
||||
cfg.addDefault("check-tile-entities", CHECK_TILE_ENTITIES_DEFAULT);
|
||||
cfg.addDefault("tile-entity-recheck-interval", TILE_ENTITY_RECHECK_INTERVAL_DEFAULT);
|
||||
cfg.options().copyDefaults(true);
|
||||
plugin.saveConfig();
|
||||
}
|
||||
|
||||
public int setConfigValue(String path, String rawValue) {
|
||||
if (!cfg.contains(path)) return -1;
|
||||
Object current = cfg.get(path);
|
||||
Object parsed;
|
||||
if (current instanceof Boolean) {
|
||||
String lower = rawValue.toLowerCase();
|
||||
if (!lower.equals("true") && !lower.equals("false")) return -1;
|
||||
parsed = Boolean.parseBoolean(lower);
|
||||
} else if (current instanceof Number) {
|
||||
int intVal;
|
||||
try {
|
||||
intVal = Integer.parseInt(rawValue);
|
||||
} catch (NumberFormatException e) {
|
||||
return -1;
|
||||
}
|
||||
if (intVal < 0 || intVal > 256) return 0;
|
||||
parsed = intVal;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
cfg.set(path, parsed);
|
||||
plugin.saveConfig();
|
||||
load();
|
||||
return 1;
|
||||
/*
|
||||
-1 = invalid input
|
||||
0 = out of range
|
||||
1 = success
|
||||
*/
|
||||
}
|
||||
public void setPacketEventsPresent(boolean present) {
|
||||
this.packetEventsPresent = present;
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package games.cubi.raycastedEntityOcclusion;
|
||||
|
||||
import games.cubi.raycastedEntityOcclusion.Packets.PacketProcessor;
|
||||
import games.cubi.raycastedEntityOcclusion.Snapshot.ChunkSnapshotManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockBurnEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.world.ChunkLoadEvent;
|
||||
import org.bukkit.event.world.ChunkUnloadEvent;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.UUID;
|
||||
|
||||
import static games.cubi.raycastedEntityOcclusion.UpdateChecker.checkForUpdates;
|
||||
|
||||
public class EventListener implements Listener {
|
||||
private final ChunkSnapshotManager manager;
|
||||
private final ConfigManager config;
|
||||
private PacketProcessor packetProcessor;
|
||||
private final RaycastedEntityOcclusion plugin;
|
||||
|
||||
public EventListener(RaycastedEntityOcclusion plugin, ChunkSnapshotManager mgr, ConfigManager cfg) {
|
||||
this.manager = mgr;
|
||||
this.config = cfg;
|
||||
this.plugin = plugin;
|
||||
//load packet processor after 2 ticks in a bukkit runnable to ensure the plugin is fully loaded
|
||||
Bukkit.getScheduler().runTaskLater(plugin, () -> {
|
||||
if (config.packetEventsPresent) {
|
||||
packetProcessor = plugin.getPacketProcessor();
|
||||
} else {
|
||||
packetProcessor = null;
|
||||
}
|
||||
}, 2L);
|
||||
}
|
||||
|
||||
// Snapshot events
|
||||
|
||||
@EventHandler
|
||||
public void onChunkLoad(ChunkLoadEvent e) {
|
||||
manager.onChunkLoad(e.getChunk());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onChunkUnload(ChunkUnloadEvent e) {
|
||||
manager.onChunkUnload(e.getChunk());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlace(BlockPlaceEvent e) {
|
||||
manager.onBlockChange(e.getBlock().getLocation(), e.getBlock().getType());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onBreak(BlockBreakEvent e) {
|
||||
manager.onBlockChange(e.getBlock().getLocation(), Material.AIR);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onBurn(BlockBurnEvent e) {
|
||||
manager.onBlockChange(e.getBlock().getLocation(), Material.AIR);
|
||||
}
|
||||
// These events do not cover all cases, but I can't be bothered to figure out a better solution rn. Frequent snapshot refreshes is the solution. If anyone has a solution please let me know.
|
||||
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerDisconnect(PlayerQuitEvent e) {
|
||||
if (config.packetEventsPresent && packetProcessor != null) {
|
||||
UUID player = e.getPlayer().getUniqueId();
|
||||
packetProcessor.sendPlayerInfoRemovePacket(player);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent event) {
|
||||
if (event.getPlayer().hasPermission("raycastedentityocclusions.updatecheck")) {
|
||||
Player sender = event.getPlayer();
|
||||
checkForUpdates(plugin, sender);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Raycast;
|
||||
|
||||
import games.cubi.raycastedEntityOcclusion.Snapshot.ChunkSnapshotManager;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
public class RaycastUtil {
|
||||
private static final Particle.DustOptions DUST_RED = new Particle.DustOptions(org.bukkit.Color.RED, 1f);
|
||||
private static final Particle.DustOptions DUST_GREEN = new Particle.DustOptions(org.bukkit.Color.GREEN, 1f);;
|
||||
|
||||
public static boolean raycast(Location start, Location end, int maxOccluding, boolean debug, ChunkSnapshotManager snap) {
|
||||
double total = start.distance(end);
|
||||
double traveled = 0;
|
||||
Location curr = start.clone();
|
||||
Vector dir = end.toVector().subtract(start.toVector()).normalize();
|
||||
while (traveled < total) {
|
||||
curr.add(dir);
|
||||
traveled += 1;
|
||||
Material mat = snap.getMaterialAt(curr);
|
||||
if (mat == null) {
|
||||
continue;
|
||||
}
|
||||
if (mat.isOccluding()) {
|
||||
maxOccluding--;
|
||||
if (debug) {
|
||||
start.getWorld().spawnParticle(Particle.DUST, curr, 1, DUST_RED);
|
||||
}
|
||||
if (maxOccluding < 1) return false;
|
||||
}
|
||||
else if (debug) {
|
||||
start.getWorld().spawnParticle(Particle.DUST, curr, 1, DUST_GREEN);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package games.cubi.raycastedEntityOcclusion;
|
||||
|
||||
import com.mojang.brigadier.Command;
|
||||
import com.mojang.brigadier.tree.LiteralCommandNode;
|
||||
import games.cubi.raycastedEntityOcclusion.Packets.PacketProcessor;
|
||||
import games.cubi.raycastedEntityOcclusion.Packets.Registrar;
|
||||
import games.cubi.raycastedEntityOcclusion.Raycast.Engine;
|
||||
import games.cubi.raycastedEntityOcclusion.Raycast.MovementTracker;
|
||||
import games.cubi.raycastedEntityOcclusion.Snapshot.ChunkSnapshotManager;
|
||||
import games.cubi.raycastedEntityOcclusion.Snapshot.EntitySnapshotManager;
|
||||
import io.papermc.paper.command.brigadier.CommandSourceStack;
|
||||
import io.papermc.paper.command.brigadier.Commands;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
import games.cubi.raycastedEntityOcclusion.bStats.MetricsCollector;
|
||||
|
||||
public class RaycastedEntityOcclusion extends JavaPlugin implements CommandExecutor {
|
||||
private ConfigManager cfg;
|
||||
private ChunkSnapshotManager snapMgr;
|
||||
private EntitySnapshotManager entitySnapshotManager;
|
||||
private MovementTracker tracker;
|
||||
private CommandsManager commands;
|
||||
private boolean packetEventsPresent = false;
|
||||
private PacketProcessor packetProcessor = null;
|
||||
private UpdateChecker updateChecker;
|
||||
|
||||
public int tick = 0;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
Plugin packetEvents = Bukkit.getPluginManager().getPlugin("packetevents");
|
||||
if (packetEvents != null) {
|
||||
packetEventsPresent = true;
|
||||
getLogger().info("PacketEvents detected.");
|
||||
new Registrar(this);
|
||||
|
||||
} else {
|
||||
getLogger().info("PacketEvents not detected, disabling packet-based tablist modification. Don't worry, the plugin will still work without it.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
cfg = new ConfigManager(this);
|
||||
snapMgr = new ChunkSnapshotManager(this);
|
||||
tracker = new MovementTracker(this, cfg);
|
||||
commands = new CommandsManager(this, cfg);
|
||||
updateChecker = new UpdateChecker(this);
|
||||
entitySnapshotManager = new EntitySnapshotManager();
|
||||
getServer().getPluginManager().registerEvents(new EventListener(this, snapMgr, cfg), this);
|
||||
//Brigadier API
|
||||
LiteralCommandNode<CommandSourceStack> buildCommand = commands.registerCommand();
|
||||
|
||||
this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, commands -> {
|
||||
commands.registrar().register(buildCommand);
|
||||
//alias "reo"
|
||||
commands.registrar().register(Commands.literal("reo")
|
||||
.requires(sender -> sender.getSender().hasPermission("raycastedentityocclusions.command"))
|
||||
.executes(context -> {
|
||||
new CommandsManager(this, cfg).helpCommand(context);
|
||||
return Command.SINGLE_SUCCESS;
|
||||
})
|
||||
.redirect(buildCommand).build());
|
||||
});
|
||||
|
||||
//bStats
|
||||
new MetricsCollector(this, cfg);
|
||||
|
||||
|
||||
// TODO: Move this somewhere else, the main class should be cleaner
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
tick++;
|
||||
Engine.runEngine(cfg, snapMgr, tracker, entitySnapshotManager, RaycastedEntityOcclusion.this);
|
||||
Engine.runTileEngine(cfg, snapMgr, tracker, RaycastedEntityOcclusion.this);
|
||||
}
|
||||
}.runTaskTimer(this, 0L, 1L);
|
||||
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (packetEventsPresent && Bukkit.getPluginManager().isPluginEnabled("packetevents")) {
|
||||
cfg.setPacketEventsPresent(true);
|
||||
packetProcessor = new PacketProcessor(RaycastedEntityOcclusion.this);
|
||||
getLogger().info("PacketEvents is enabled, enabling packet-based tablist modification.");
|
||||
}
|
||||
}
|
||||
}.runTaskLater(this, 1L);
|
||||
}
|
||||
|
||||
|
||||
public ConfigManager getConfigManager() {
|
||||
return cfg;
|
||||
}
|
||||
public ChunkSnapshotManager getChunkSnapshotManager() {
|
||||
return snapMgr;
|
||||
}
|
||||
public MovementTracker getMovementTracker() {
|
||||
return tracker;
|
||||
}
|
||||
public CommandsManager getCommandsManager() {
|
||||
return commands;
|
||||
}
|
||||
public PacketProcessor getPacketProcessor() {
|
||||
return packetProcessor;
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Snapshot;
|
||||
|
||||
import games.cubi.raycastedEntityOcclusion.ConfigManager;
|
||||
import games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.BlockState;
|
||||
import org.bukkit.block.TileState;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class ChunkSnapshotManager {
|
||||
public static class Data {
|
||||
public final ChunkSnapshot snapshot;
|
||||
public final Map<Location, Material> delta = new ConcurrentHashMap<>();
|
||||
public final Set<Location> tileEntities = ConcurrentHashMap.newKeySet();
|
||||
public long lastRefresh;
|
||||
public int minHeight;
|
||||
public int maxHeight;
|
||||
|
||||
public Data(ChunkSnapshot snapshot, long time) {
|
||||
this.snapshot = snapshot;
|
||||
this.lastRefresh = time;
|
||||
}
|
||||
}
|
||||
|
||||
private final Map<String, Data> dataMap = new ConcurrentHashMap<>();
|
||||
private final ConfigManager cfg;
|
||||
|
||||
public ChunkSnapshotManager(RaycastedEntityOcclusion plugin) {
|
||||
cfg = plugin.getConfigManager();
|
||||
//get loaded chunks and add them to dataMap
|
||||
for (World w : plugin.getServer().getWorlds()) {
|
||||
for (Chunk c : w.getLoadedChunks()) {
|
||||
dataMap.put(key(c), takeSnapshot(c, System.currentTimeMillis()));
|
||||
}
|
||||
}
|
||||
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
long now = System.currentTimeMillis();
|
||||
int chunksRefreshed = 0;
|
||||
int chunksToRefreshMaximum = getNumberOfCachedChunks() / 3;
|
||||
for (Map.Entry<String, Data> e : dataMap.entrySet()) {
|
||||
if (now - e.getValue().lastRefresh >= cfg.snapshotRefreshInterval * 1000L && chunksRefreshed < chunksToRefreshMaximum) {
|
||||
chunksRefreshed++;
|
||||
String key = e.getKey();
|
||||
String[] parts = key.split(":");
|
||||
World w = plugin.getServer().getWorld(parts[0]);
|
||||
if (w == null) {
|
||||
plugin.getLogger().warning("ChunkSnapshotManager: World " + parts[0] + " not found. Please report this on our discord (discord.cubi.games)'");
|
||||
continue;
|
||||
}
|
||||
Chunk c = w.getChunkAt(
|
||||
Integer.parseInt(parts[1]),
|
||||
Integer.parseInt(parts[2])
|
||||
);
|
||||
e.setValue(takeSnapshot(c, now));
|
||||
}
|
||||
}
|
||||
if (cfg.debugMode) {
|
||||
plugin.getLogger().info("ChunkSnapshotManager: Refreshed " + chunksRefreshed + " chunks out of " + chunksToRefreshMaximum + " maximum.");
|
||||
}
|
||||
}
|
||||
}.runTaskTimerAsynchronously(plugin, cfg.snapshotRefreshInterval * 2L, cfg.snapshotRefreshInterval * 2L /* This runs 10 times per refreshInterval, spreading out the refreshes */);
|
||||
}
|
||||
|
||||
public void onChunkLoad(Chunk c) {
|
||||
dataMap.put(key(c), takeSnapshot(c, System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
public void onChunkUnload(Chunk c) {
|
||||
dataMap.remove(key(c));
|
||||
}
|
||||
|
||||
// Used by EventListener to update the delta map when a block is placed or broken
|
||||
public void onBlockChange(Location loc, Material m) {
|
||||
if (cfg.debugMode) {
|
||||
Bukkit.getLogger().info("ChunkSnapshotManager: Block change at " + loc + " to " + m);
|
||||
}
|
||||
Data d = dataMap.get(key(loc.getChunk()));
|
||||
if (d != null) {
|
||||
d.delta.put(loc, m);
|
||||
if (cfg.checkTileEntities) {
|
||||
// Check if the block is a tile entity
|
||||
BlockState data = loc.getBlock().getState();
|
||||
loc = loc.clone().add(0.5, 0.5, 0.5);
|
||||
if (data instanceof TileState) {
|
||||
if (cfg.debugMode){
|
||||
Bukkit.getLogger().info("ChunkSnapshotManager: Tile entity at " + loc);
|
||||
}
|
||||
d.tileEntities.add(loc);
|
||||
} else {
|
||||
d.tileEntities.remove(loc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Data takeSnapshot(Chunk c, long now) {
|
||||
World w = c.getWorld();
|
||||
Data data = new Data(c.getChunkSnapshot(), now);
|
||||
int chunkX = c.getX() * 16;
|
||||
int chunkZ = c.getZ() * 16;
|
||||
int minHeight = w.getMinHeight();
|
||||
int maxHeight = w.getMaxHeight();
|
||||
data.maxHeight = maxHeight;
|
||||
data.minHeight = minHeight;
|
||||
if (cfg.checkTileEntities) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
for (int y = minHeight; y < maxHeight; y++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
BlockState bs = data.snapshot.getBlockData(x, y, z).createBlockState();
|
||||
|
||||
if (bs instanceof TileState) {
|
||||
data.tileEntities.add(new Location(w, x+ chunkX +0.5, y+0.5, z + chunkZ+0.5));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private String key(Chunk c) {
|
||||
return c.getWorld().getName() + ":" + c.getX() + ":" + c.getZ();
|
||||
}
|
||||
|
||||
public Material getMaterialAt(Location loc) {
|
||||
Data d = dataMap.get(key(loc.getChunk()));
|
||||
if (d == null) {
|
||||
Chunk c = loc.getChunk();
|
||||
//dataMap.put(key(c), takeSnapshot(c, System.currentTimeMillis())); infinite loop
|
||||
System.err.println("ChunkSnapshotManager: No snapshot for " + c+ " Please report this on our discord (discord.cubi.games)'");
|
||||
return loc.getBlock().getType();
|
||||
}
|
||||
double yLevel = loc.getY();
|
||||
if (yLevel < d.minHeight || yLevel > d.maxHeight) {
|
||||
return null;
|
||||
}
|
||||
Material dm = d.delta.get(loc);
|
||||
if (dm != null) {
|
||||
return dm;
|
||||
}
|
||||
int x = loc.getBlockX() & 0xF;
|
||||
int y = loc.getBlockY();
|
||||
int z = loc.getBlockZ() & 0xF;
|
||||
|
||||
return d.snapshot.getBlockType(x, y, z);
|
||||
}
|
||||
|
||||
//get TileEntity Locations in chunk
|
||||
public Set<Location> getTileEntitiesInChunk(String worldName, int x, int z) {
|
||||
Data d = dataMap.get(worldName + ":" + x + ":" + z);
|
||||
if (d == null) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return d.tileEntities;
|
||||
}
|
||||
|
||||
public int getNumberOfCachedChunks() {
|
||||
return dataMap.size();
|
||||
//created to use in a debug command maybe
|
||||
}
|
||||
|
||||
}
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
package games.cubi.raycastedEntityOcclusion.Snapshot;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
|
||||
public class EntitySnapshotManager {
|
||||
|
||||
public static class EntityData {
|
||||
|
||||
//Entity data for a single entity in a world.
|
||||
|
||||
private volatile Location location;
|
||||
/** Player UUID → can-see flag (true/false). Absence = NOT_SET. */
|
||||
private final Map<UUID, Boolean> visibility = new ConcurrentHashMap<>();
|
||||
|
||||
public EntityData(Location initial) {
|
||||
this.location = initial.clone();
|
||||
}
|
||||
|
||||
/* ---- location ---- */
|
||||
public Location getLocation() { return location.clone(); }
|
||||
public void setLocation(Location loc) { this.location = loc.clone(); }
|
||||
|
||||
/* ---- visibility ---- */
|
||||
public void setVisibleFor(UUID playerId, boolean canSee) {
|
||||
visibility.put(playerId, canSee);
|
||||
}
|
||||
public void clearVisibility(UUID playerId) { visibility.remove(playerId); }
|
||||
|
||||
public Boolean getVisibility(UUID playerId) {
|
||||
return visibility.get(playerId); // may be null
|
||||
}
|
||||
}
|
||||
|
||||
// Cache: world-name → (entity-UUID → data)
|
||||
private final Map<String, Map<UUID, EntityData>> cache = new ConcurrentHashMap<>();
|
||||
|
||||
public void addEntity(Entity entity) {
|
||||
Objects.requireNonNull(entity, "EntitySnapshotManager: Cannot add null entity");
|
||||
cache.computeIfAbsent(entity.getWorld().getName(),
|
||||
w -> new ConcurrentHashMap<>())
|
||||
.putIfAbsent(entity.getUniqueId(),
|
||||
new EntityData(entity.getLocation()));
|
||||
}
|
||||
|
||||
public void removeEntity(Entity entity) {
|
||||
Map<UUID, EntityData> entitiesInWorld = cache.get(entity.getWorld().getName());
|
||||
if (entitiesInWorld != null) {
|
||||
entitiesInWorld.remove(entity.getUniqueId());
|
||||
if (entitiesInWorld.isEmpty()) cache.remove(entity.getWorld().getName());
|
||||
}
|
||||
}
|
||||
|
||||
/** Updates (or inserts) the latest location for the entity. */
|
||||
public void updateLocation(Entity entity) {
|
||||
cache.computeIfAbsent(entity.getWorld().getName(),
|
||||
w -> new ConcurrentHashMap<>())
|
||||
.compute(entity.getUniqueId(), (id, data) -> {
|
||||
if (data == null) return new EntityData(entity.getLocation());
|
||||
data.setLocation(entity.getLocation());
|
||||
return data;
|
||||
});
|
||||
}
|
||||
|
||||
// put anywhere inside EntitySnapshotManager
|
||||
public @Nullable Location getLocation(Entity entity) {
|
||||
Map<UUID, EntityData> entitiesInWorld = cache.get(entity.getWorld().getName());
|
||||
if (entitiesInWorld == null) return null;
|
||||
EntityData data = entitiesInWorld.get(entity.getUniqueId());
|
||||
return (data == null) ? null : data.getLocation();
|
||||
}
|
||||
|
||||
|
||||
/* ---- visibility helpers ---- */
|
||||
public void setVisibility(Entity entity, Player player, boolean canSee) {
|
||||
Map<UUID, EntityData> entitiesInWorld = cache.get(entity.getWorld().getName());
|
||||
if (entitiesInWorld != null) {
|
||||
EntityData d = entitiesInWorld.get(entity.getUniqueId());
|
||||
if (d != null) d.setVisibleFor(player.getUniqueId(), canSee);
|
||||
}
|
||||
}
|
||||
|
||||
public void clearVisibility(Entity entity, Player player) {
|
||||
Map<UUID, EntityData> entitiesInWorld = cache.get(entity.getWorld().getName());
|
||||
if (entitiesInWorld != null) {
|
||||
EntityData d = entitiesInWorld.get(entity.getUniqueId());
|
||||
if (d != null) d.clearVisibility(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Boolean getVisibility(Entity entity, Player player) {
|
||||
Map<UUID, EntityData> entitiesInWorld = cache.get(entity.getWorld().getName());
|
||||
if (entitiesInWorld == null) return null;
|
||||
EntityData d = entitiesInWorld.get(entity.getUniqueId());
|
||||
return (d == null) ? null : d.getVisibility(player.getUniqueId());
|
||||
}
|
||||
|
||||
/* ---- miscellaneous ---- */
|
||||
public Collection<EntityData> getEntitiesInWorld(World world) {
|
||||
Map<UUID, EntityData> entitiesInWorld = cache.get(world.getName());
|
||||
return (entitiesInWorld == null) ? Collections.emptyList() : entitiesInWorld.values();
|
||||
}
|
||||
|
||||
public List<Entity> getBukkitEntitiesNear(Location origin, int radiusX, int radiusY, int radiusZ) {
|
||||
|
||||
World world = origin.getWorld();
|
||||
Map<UUID, EntityData> entitiesInWorld = cache.get(world.getName());
|
||||
if (entitiesInWorld == null || entitiesInWorld.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
double ox = origin.getX(), oy = origin.getY(), oz = origin.getZ();
|
||||
double minX = ox - radiusX, maxX = ox + radiusX;
|
||||
double minY = oy - radiusY, maxY = oy + radiusY;
|
||||
double minZ = oz - radiusZ, maxZ = oz + radiusZ;
|
||||
|
||||
List<Entity> result = new ArrayList<>();
|
||||
for (Map.Entry<UUID, EntityData> entry : entitiesInWorld.entrySet()) {
|
||||
EntityData data = entry.getValue();
|
||||
Location loc = data.getLocation();
|
||||
double x = loc.getX(), y = loc.getY(), z = loc.getZ();
|
||||
|
||||
if (x < minX || x > maxX || y < minY || y > maxY || z < minZ || z > maxZ) {
|
||||
|
||||
Entity live = world.getEntity(entry.getKey());
|
||||
if (live != null) {
|
||||
if (!live.isDead()) {
|
||||
result.add(live);
|
||||
}
|
||||
else removeEntity(live);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return cache.values().stream().mapToInt(Map::size).sum();
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package games.cubi.raycastedEntityOcclusion;
|
||||
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.EventHandler;
|
||||
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
|
||||
public class UpdateChecker {
|
||||
private final RaycastedEntityOcclusion plugin;
|
||||
|
||||
public UpdateChecker(RaycastedEntityOcclusion plugin) {
|
||||
this.plugin = plugin;
|
||||
plugin.getLogger().info("Checking for updates...");
|
||||
checkForUpdates(plugin, Bukkit.getConsoleSender());
|
||||
}
|
||||
|
||||
|
||||
public static CompletableFuture<String> fetchFeaturedVersion(RaycastedEntityOcclusion plugin) {
|
||||
CompletableFuture<String> future = new CompletableFuture<>();
|
||||
|
||||
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
|
||||
|
||||
final String url = "https://api.modrinth.com/v2/project/raycasted-entity-occlusions/version?featured=true";
|
||||
try (final InputStreamReader reader = new InputStreamReader(new URL(url).openConnection().getInputStream())) {
|
||||
final JsonArray array = new JsonArray();
|
||||
array.add(new BufferedReader(reader).readLine());
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
|
||||
sb.append(array.get(i).getAsString());
|
||||
}
|
||||
String apiData = sb.toString();
|
||||
JsonArray jsonArray = JsonParser.parseString(apiData).getAsJsonArray();
|
||||
JsonObject firstObject = jsonArray.get(0).getAsJsonObject();
|
||||
String versionNumber = firstObject.get("version_number").getAsString();
|
||||
|
||||
future.complete(versionNumber);
|
||||
|
||||
} catch (IOException e) {
|
||||
future.completeExceptionally(new IllegalStateException("Unable to fetch latest version", e));
|
||||
}
|
||||
});
|
||||
return future;
|
||||
}
|
||||
|
||||
public static void checkForUpdates(RaycastedEntityOcclusion plugin, CommandSender audience) {
|
||||
//plugin.getLogger().info("Fetching latest version from Modrinth...");
|
||||
fetchFeaturedVersion(plugin).thenAccept(version -> {
|
||||
//plugin.getLogger().info("Latest version fetched: " + version);
|
||||
// This runs synchronously when the version is fetched
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
//plugin.getLogger().info("Checking if current version matches the latest version...");
|
||||
if (plugin.getDescription().getVersion().equals(version)) {
|
||||
audience.sendRichMessage("<green>You are using the latest version of Raycasted Entity Occlusions.");
|
||||
} else {
|
||||
audience.sendRichMessage("<red>You are not using the latest version of Raycasted Entity Occlusions. Please update to <green>v" + version);
|
||||
}
|
||||
});
|
||||
}).exceptionally(ex -> {
|
||||
// Handle error (e.g., log the exception)
|
||||
Bukkit.getScheduler().runTask(plugin, () -> {
|
||||
plugin.getLogger().warning("Failed to fetch version: " + ex.getMessage());
|
||||
});
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
config-version: 1.0 # Do not change this value, it is used internally by the plugin to determine if the config is up to date.
|
||||
|
||||
checks:
|
||||
entities:
|
||||
enabled: true
|
||||
max-occluding-count: 3
|
||||
raycast-radius: 48
|
||||
always-show-radius: 16 # radius to always show entities
|
||||
recheck-interval: 50 # ticks between forced rechecks for visible entities
|
||||
engine-mode: 1 # 1 = straight-line; 2 = predictive and straight-line
|
||||
tile-entities:
|
||||
enabled: true
|
||||
max-occluding-count: 3
|
||||
raycast-radius: 48
|
||||
always-show-radius: 16
|
||||
recheck-interval: 0 # seconds between forced rechecks for visible tile entities. If set to 0, they will never be rechecked.
|
||||
engine-mode: 1 # 1 = straight-line; 2 = predictive and straight-line
|
||||
players:
|
||||
enabled: false
|
||||
only-cull-sneaking: false
|
||||
max-occluding-count: 3
|
||||
raycast-radius: 48
|
||||
always-show-radius: 16
|
||||
recheck-interval: 50 # ticks between forced rechecks for visible players
|
||||
engine-mode: 1 # 1 = straight-line; 2 = predictive and straight-line
|
||||
snapshots:
|
||||
chunk-refresh-interval: 60 # seconds between chunk snapshot refresh, won't change without restart
|
||||
debug:
|
||||
log-level: 1 # Scale from 0-10, where larger numbers mean more verbose logging and 0 disables logging
|
||||
particles: false # enable debug particles
|
||||
@@ -1,18 +0,0 @@
|
||||
snapshot-refresh-interval: 60 # seconds between chunk snapshot refresh, won't change without restart
|
||||
|
||||
engine-mode: 1 # 1 = straight-line; 2 = predictive and straight-line
|
||||
max-occluding-count: 3 # blocks before blocking
|
||||
|
||||
debug-mode: false # enable debug particles and more verbose logging
|
||||
|
||||
always-show-radius: 16 # radius to always show entities
|
||||
raycast-radius: 48 # beyond this, entities auto-hide
|
||||
search-radius: 48 # search radius for entities
|
||||
|
||||
cull-players: false # cull hidden players as well as other entities
|
||||
only-cull-sneaking-players: false # only cull sneaking players (requires cull-players)
|
||||
|
||||
recheck-interval: 50 # ticks between forced rechecks for visible entities
|
||||
|
||||
check-tile-entities: true # check tile entities for occlusion
|
||||
tile-entity-recheck-interval: 0 # seconds between forced rechecks for visible tile entities. If set to 0, they will never be rechecked.
|
||||
@@ -0,0 +1,19 @@
|
||||
snapshot-refresh-interval: 60 # seconds between chunk snapshot refresh, won't change without restart
|
||||
|
||||
engine-mode: 1 # 1 = straight-line; 2 = predictive and straight-line
|
||||
max-occluding-count: 3 # blocks before blocking
|
||||
|
||||
debug-mode: false # enable debug particles and more verbose logging
|
||||
debug-level: 1 # Higher level results in more verbose logs. 0-10
|
||||
|
||||
always-show-radius: 16 # radius to always show entities
|
||||
raycast-radius: 48 # beyond this, entities auto-hide
|
||||
search-radius: 48 # search radius for entities
|
||||
|
||||
cull-players: false # cull hidden players as well as other entities
|
||||
only-cull-sneaking-players: false # only cull sneaking players (requires cull-players)
|
||||
|
||||
recheck-interval: 50 # ticks between forced rechecks for visible entities
|
||||
|
||||
check-tile-entities: true # check tile entities for occlusion
|
||||
tile-entity-recheck-interval: 0 # seconds between forced rechecks for visible tile entities. If set to 0, they will never be rechecked.
|
||||
@@ -1,19 +1,19 @@
|
||||
name: RaycastedEntityOcclusions
|
||||
name: RaycastedAntiESP
|
||||
version: ${version}
|
||||
main: games.cubi.raycastedEntityOcclusion.RaycastedEntityOcclusion
|
||||
main: games.cubi.raycastedAntiESP.RaycastedAntiESP
|
||||
api-version: '1.21'
|
||||
prefix: REO
|
||||
prefix: RaycastedAntiESP
|
||||
authors: [ _Cubicake ]
|
||||
load: STARTUP
|
||||
website: https://cubi.games
|
||||
permissions:
|
||||
raycastedentityocclusions.command:
|
||||
description: Permission to use the RaycastedEntityOcclusions command
|
||||
raycastedantiesp.command:
|
||||
description: Permission to use the /RaycastedAntiESP command
|
||||
default: op
|
||||
raycastedentityocclusions.bypass:
|
||||
description: Permission to bypass all checks
|
||||
raycastedantiesp.bypass:
|
||||
description: Permission to bypass all checks. A restart is needed to apply this permission.
|
||||
default: false
|
||||
raycastedentityocclusions.updatecheck:
|
||||
raycastedantiesp.updatecheck:
|
||||
description: Permission to check for plugin updates
|
||||
default: op
|
||||
softdepend:
|
||||
|
||||
Reference in new issue
Block a user