Compare commits

..
2 Commits
Author SHA1 Message Date
Cubicake e97bad3279 Merge pull request #87 from Cubicake/main
Update velocity branch
2026-08-21 12:33:18 +09:30
Cubicake 49812cc476 VERY early stages of velocity port 2026-07-09 13:26:50 +09:30
44 changed files with 598 additions and 749 deletions

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
plugins {
id("io.papermc.paperweight.userdev") version "2.0.0-beta.21" apply false
id("xyz.jpenilla.run-paper") version "3.0.2" apply false
}
+1 -3
View File
@@ -36,11 +36,9 @@ dependencies {
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testImplementation("it.unimi.dsi:fastutil:8.5.18")
compileOnly("com.google.code.gson:gson:2.11.0")
}
val coreVersion = "0.7.2-SNAPSHOT"
val coreVersion = "0.7.1-SNAPSHOT"
val isRelease = gradle.startParameter.taskNames.any {
it.contains("buildRelease")
@@ -23,10 +23,6 @@ public class RaycastConfig implements Config {
private final short visibleRecheckIntervalTicks;
private final boolean keepClientEntityWhenHidden;
public final int alwaysShowRadiusSquared;
public final int raycastRadiusSquared;
public final int hideOnSpawnDistanceSquared;
public RaycastConfig(boolean enabled, boolean hideSoundsWhenHidden, int maxOccludingCount, int alwaysShowRadius,
int raycastRadius, int hideOnSpawnDistance, int visibleRecheckIntervalTicks) {
this(enabled, hideSoundsWhenHidden, maxOccludingCount, alwaysShowRadius, raycastRadius, hideOnSpawnDistance,
@@ -44,10 +40,6 @@ public class RaycastConfig implements Config {
this.hideOnSpawnDistance = (short) hideOnSpawnDistance;
this.visibleRecheckIntervalTicks = (short) visibleRecheckIntervalTicks;
this.keepClientEntityWhenHidden = keepClientEntityWhenHidden;
alwaysShowRadiusSquared = alwaysShowRadius * alwaysShowRadius;
raycastRadiusSquared = raycastRadius * raycastRadius;
hideOnSpawnDistanceSquared = hideOnSpawnDistance * hideOnSpawnDistance;
}
protected static RaycastConfig load(ConfigurationNode node, String path, boolean hasHideSoundsWhenHidden) {
@@ -8,9 +8,9 @@
package games.cubi.raycastedantiesp.core.engine;
import games.cubi.locatables.api.ImmutableSpatial;
import games.cubi.locatables.api.Locatable;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.AsyncRunner;
import games.cubi.raycastedantiesp.core.config.ConfigManager;
import games.cubi.raycastedantiesp.core.config.DebugConfig;
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
@@ -27,6 +27,7 @@ import games.cubi.raycastedantiesp.core.view.BlockView;
import games.cubi.raycastedantiesp.core.view.EntityView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -103,7 +104,7 @@ public abstract class AsyncEngine implements Engine {
int latestTick = currentTickSupplier.getAsInt();
if (latestTick > startTick) {
// If running behind, don't yield the thread, just run the next tick immediately
Logger.warning("Tick thread completed tick #" + startTick + " after tick #" + latestTick + " had already begun. Starting next tick immediately instead of yielding thread to scheduler. This is probably safe to ignore but may suggest that your server is overloaded.", 5, AsyncEngine.class);
Logger.warning("Tick thread completed tick #" + startTick + " after tick #" + latestTick + " had already begun. Starting next tick immediately instead of yielding thread to scheduler. This is probably safe to ignore but may suggest that your server is overloaded.", 5);
startTick = latestTick;
scheduledNanos = System.nanoTime();
scheduledTick = latestTick;
@@ -171,13 +172,13 @@ public abstract class AsyncEngine implements Engine {
final int currentTick = startTick;
runningTick.set(currentTick);
claimedRunningTick = true;
PlayerData[] allPlayers = PlayerRegistry.get().getPlayerDataArray();
Collection<PlayerData> allPlayers = PlayerRegistry.getInstance().getAllPlayerData();
EntityConfig entityConfig = config.getEntityConfig();
PlayerConfig playerConfig = config.getPlayerConfig();
TileEntityConfig tileEntityConfig = config.getTileEntityConfig();
if (recordTimings) {
timings = new TickTimings(scheduledTick, scheduledNanos, currentTick, startNanos, threads, allPlayers.length);
timings = new TickTimings(scheduledTick, scheduledNanos, currentTick, startNanos, threads, allPlayers.size());
}
/*
Logger.debug("Tick #" + currentTick);
@@ -193,30 +194,24 @@ public abstract class AsyncEngine implements Engine {
// If only one thread is configured, just use the current async thread to avoid the overhead of scheduling tasks and context switching.
if (threads == 1) {
handedOffToSubTick = true;
subTick(allPlayers, entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick, timings, tickTimingStats);
subTick(new ArrayList<>(allPlayers), entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick, timings, tickTimingStats);
return true;
}
List<PlayerData[]> batches = new ArrayList<>(threads);
int playerCount = allPlayers.length;
List<List<PlayerData>> batches = new ArrayList<>(threads);
for (int i = 0; i < threads; i++) {
int batchSize = (playerCount + threads - 1 - i) / threads;
batches.add(new PlayerData[batchSize]);
batches.add(new ArrayList<>());
}
int index = 0;
for (PlayerData playerData : allPlayers) {
int batchIndex = index % threads;
int position = index / threads;
batches.get(batchIndex)[position] = playerData;
index++;
batches.get(index++ % threads).add(playerData);
}
TickTimings tickTimings = timings; // needs to be effectively-final for lambda
int scheduledBatches = 0;
try {
for (PlayerData[] batch : batches) {
for (List<PlayerData> batch : batches) {
asyncRunner.runNow(() -> subTick(batch, entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick, tickTimings, tickTimingStats));
scheduledBatches++;
}
@@ -249,7 +244,7 @@ public abstract class AsyncEngine implements Engine {
* @param timingStats the timing sink selected when this tick started, so config changes during
* worker execution do not split one tick across sinks.
*/
private void subTick(PlayerData[] batch, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig, DebugConfig debugConfig, int currentTick, TickTimings timings, TimingStats timingStats) {
private void subTick(List<PlayerData> batch, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig, DebugConfig debugConfig, int currentTick, TickTimings timings, TimingStats timingStats) {
TickTimingBatch batchTimings = timings == null ? TickTimingBatchNoOp.INSTANCE : new TickTimingBatch();
long batchStartNanos = batchTimings.startBatch();
try {
@@ -334,7 +329,7 @@ public abstract class AsyncEngine implements Engine {
}
}
private void processTickForPlayers(PlayerData[] playerDataList, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig,
private void processTickForPlayers(List<PlayerData> playerDataList, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig,
boolean debugParticles, int currentTick, TickTimingBatch timings) {
for (PlayerData playerData : playerDataList) {
@@ -398,7 +393,7 @@ public abstract class AsyncEngine implements Engine {
}
timings.incrementEntityRaycasts();
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(entityConfig.getMaxOccludingCount(), entityConfig.alwaysShowRadiusSquared, entityConfig.raycastRadiusSquared, debugParticles, entity.getYOffset(), blockView, playerLocation, entity, particleSpawner);
boolean canSee = RaycastUtil.raycast(playerLocation, entity, entityConfig.getMaxOccludingCount(), entityConfig.getAlwaysShowRadius(), entityConfig.getRaycastRadius(), debugParticles, blockView, entity.getYOffset(), 1, particleSpawner);
entityView.setVisibility(entity, canSee, currentTick, worldEpoch);
});
timings.addEntityChecked(checked);
@@ -416,7 +411,7 @@ public abstract class AsyncEngine implements Engine {
return;
}
timings.incrementPlayerRaycasts();
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(playerConfig.getMaxOccludingCount(), playerConfig.alwaysShowRadiusSquared, playerConfig.raycastRadiusSquared, debugParticles, 1.5f, blockView, playerLocation, otherPlayer, particleSpawner);
boolean canSee = RaycastUtil.raycast(playerLocation, otherPlayer, playerConfig.getMaxOccludingCount(), playerConfig.getAlwaysShowRadius(), playerConfig.getRaycastRadius(), debugParticles, blockView, 1.5f, 1, particleSpawner);
playerView.setVisibility(otherPlayer, canSee, currentTick, worldEpoch);
});
timings.addPlayerChecked(checked);
@@ -443,7 +438,7 @@ public abstract class AsyncEngine implements Engine {
return BlockView.VisibilityResolver.HIDE;
}
timings.incrementTileRaycasts();
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(tileEntityConfig.getMaxOccludingCount(), tileEntityConfig.alwaysShowRadiusSquared, tileEntityConfig.raycastRadiusSquared, debugParticles, 0, blockView, playerLocation, tileEntityLocation, particleSpawner);
boolean canSee = RaycastUtil.raycast(playerLocation, tileEntityLocation, tileEntityConfig.getMaxOccludingCount() + 1, tileEntityConfig.getAlwaysShowRadius(), tileEntityConfig.getRaycastRadius(), debugParticles, blockView, 1, particleSpawner);
return canSee ? BlockView.VisibilityResolver.SHOW : BlockView.VisibilityResolver.HIDE;
});
timings.addTileChecked(checked);
@@ -6,7 +6,7 @@
* See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core;
package games.cubi.raycastedantiesp.core.engine;
public interface AsyncRunner {
void runNow(Runnable task);
@@ -28,9 +28,6 @@ import static games.cubi.raycastedantiesp.core.tracked.NettyEntity.NO_VEHICLE;
* Per-player mutable state intended for Netty-side packet tracking and deferred reconciliation.
*/
public class NettyData implements Clearable {
//
public boolean packetsAreWithinBundle = false;
//
private static final int DEFAULT_MAP_SIZE = 16;
//
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -9,16 +9,12 @@
package games.cubi.raycastedantiesp.core.players;
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
import games.cubi.raycastedantiesp.core.utils.VarHandler;
import java.lang.invoke.VarHandle;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
public final class PlayerRegistry {
public class PlayerRegistry {
@FunctionalInterface
public interface SelfEntityCreator {
@@ -29,30 +25,26 @@ public final class PlayerRegistry {
private PlayerRegistry() {}
public static PlayerRegistry get() {
public static PlayerRegistry getInstance() {
return instance;
}
private final ConcurrentHashMap<UUID, PlayerData> playerDataMap = new ConcurrentHashMap<>();
private final Collection<PlayerData> unmodifiablePlayerData = Collections.unmodifiableCollection(playerDataMap.values());
private volatile PlayerData[] playerDataArray = new PlayerData[0]; private static final VarHandle PLAYER_DATA_ARRAY = VarHandler.get(PlayerRegistry.class, "playerDataArray", PlayerData[].class);
/** Forcefully registers a player and returns the new PlayerData, even if they were already registered.**/
public synchronized PlayerData registerAndGetPlayer(UUID playerUUID, int joinTick, int selfEntityID, SelfEntityCreator selfEntityCreator) {
public PlayerData registerAndGetPlayer(UUID playerUUID, int joinTick, int selfEntityID, SelfEntityCreator selfEntityCreator) {
PlayerData newData = new PlayerData(playerUUID, false, joinTick, selfEntityID, selfEntityCreator);
PlayerData old = playerDataMap.put(playerUUID, newData);
if (old != null) old.markDisconnected();
updatePlayerDataArray();
return newData;
}
public synchronized void unregisterPlayer(UUID playerUUID) {
public void unregisterPlayer(UUID playerUUID) {
PlayerData unregisteredPlayer = playerDataMap.remove(playerUUID);
if (unregisteredPlayer == null) {
return;
}
unregisteredPlayer.markDisconnected();
updatePlayerDataArray();
}
public PlayerData getPlayerData(UUID playerUUID) {
@@ -64,34 +56,9 @@ public final class PlayerRegistry {
}
/**
* @return Live, unmodifiable view of all PlayerData instances.
* @return Live, mutable collection of all PlayerData instances.
* **/
public Collection<PlayerData> getAllPlayerData() {
return unmodifiablePlayerData;
}
private void updatePlayerDataArray() {
PLAYER_DATA_ARRAY.setRelease(this, playerDataMap.values().toArray(PlayerData[]::new));
}
/**
* Do not mutate this array, all changes must go through {@link #registerAndGetPlayer(UUID, int, int, SelfEntityCreator)} /
* {@link #unregisterPlayer(UUID)}.
* <p></p>
* Changes to this array will be lost on next player join/leave, and will not apply everywhere.
*/
public PlayerData[] getPlayerDataArray() {
return (PlayerData[]) PLAYER_DATA_ARRAY.getAcquire(this);
}
public void forEachPlayer(Consumer<PlayerData> consumer) {
PlayerData[] data = getPlayerDataArray();
for (PlayerData player : data) {
consumer.accept(player);
}
}
public int getPlayerCount() {
return playerDataMap.size();
return playerDataMap.values();
}
}
@@ -8,118 +8,274 @@
package games.cubi.raycastedantiesp.core.raycast;
import games.cubi.locatables.api.Locatable;
import games.cubi.locatables.api.Spatial;
import games.cubi.locatables.api.BlockSpatial;
import games.cubi.locatables.api.*;
import games.cubi.locatables.implementations.MutableChunkSection;
import games.cubi.locatables.implementations.MutableSpatialImpl;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
import games.cubi.raycastedantiesp.core.view.BlockView;
import java.util.UUID;
public class RaycastUtil {
//True: Has line-of-sight
//This is deliberately a ray-stepping algorithm rather than DDA as it is much faster (2x in benchmarking)
//Missing blocks is acceptable, as it will be assumed the player can see past those corners.
//While this uses objects, JHM and in-game profiling have both shown that all objects used here are consistently scalarised by the JVM.
/**
* Mutable position and chunk-section state is flattened into the advancer so C2 only
* needs to scalarise one state holder while retaining a readable ray-stepping method.
*/
public static boolean raycastUnrolledAccumulated(int maxOccluding, final int alwaysShowRadiusSquared, final int maxRaycastRadiusSquared, boolean debug,
float yOffsetEnd, final BlockView snap, final Locatable start, final Spatial end, ParticleSpawner spawner) {
double startX = start.x();
double startY = start.y();
double startZ = start.z();
double endOffset = end instanceof BlockSpatial ? 0.5 : 0.0;
RayDirection direction = RayDirection.from(end.x() + endOffset, end.y() + endOffset + yOffsetEnd, end.z() + endOffset, startX, startY, startZ);
double lengthSquared = direction.getLengthSquared();
if (lengthSquared <= alwaysShowRadiusSquared) return true;
if (lengthSquared > maxRaycastRadiusSquared) return false;
double total = direction.normaliseAndGetLength(lengthSquared);
float finalDist = (float) (total - 1);
public static boolean raycast(Locatable start, Spatial end, int maxOccluding, int alwaysShowRadius, int maxRaycastRadius, boolean debug, BlockView snap, float stepSize, ParticleSpawner particleSpawner) {
//return raycastCubiNoAllocUnrolledLongBitsAccumulated(maxOccluding, alwaysShowRadius, maxRaycastRadius, debug, 1, snap, start.x(), start.y(), start.z(), end.x(), end.y(), end.z());
final RayAdvancer rayAdvancer = debug ? new DebugRayAdvancer(startX, startY, startZ, direction, snap, start.world(), spawner) : new RayAdvancer(startX, startY, startZ, direction, snap);
int remainingSteps = (int) Math.floor(finalDist);
while (remainingSteps >= 4) {
rayAdvancer.advance();
rayAdvancer.advance();
rayAdvancer.advance();
rayAdvancer.advance();
if (rayAdvancer.occluded > maxOccluding) return false;
remainingSteps -= 4;
}
while (remainingSteps-- > 0) rayAdvancer.advance();
return rayAdvancer.occluded <= maxOccluding;
//return raycastUnrolledAccumulated(maxOccluding, alwaysShowRadius, maxRaycastRadius, debug, 1, snap, start, end);
return raycast(start, end, maxOccluding, alwaysShowRadius, maxRaycastRadius, debug, snap, 0f, stepSize, particleSpawner);
}
private static sealed class RayAdvancer extends RayPosition permits DebugRayAdvancer {
public static boolean raycast(Locatable start, Spatial end, int maxOccluding, int alwaysShowRadius, int maxRaycastRadius, boolean debug, BlockView snap, float yOffsetEnd, float stepSize, ParticleSpawner particleSpawner) {
double endOffset = end instanceof BlockSpatial ? 0.5 : 0.0;
MutableFloatingSpatial clonedEnd = new MutableSpatialImpl(end.x() + endOffset, end.y() + endOffset + yOffsetEnd, end.z() + endOffset);
//Equivalent to end.cloneAndIfBlockThenCentre(); but not used since the JVM was not reliably scalarising that method (probably due to the polymorphic overriding?). This causes 0 object allocations.
float total = (float) (start.distance(clonedEnd) - stepSize); //benchmarking shows that calling distance() is faster than distanceSquared() then checking distanceSquared < stepSize*stepSize every time despite the latter replacing a square root with multiplication
if (total <= alwaysShowRadius) return true;
if (total > maxRaycastRadius) return false;
if (debug && particleSpawner == null) {
Logger.errorAndReturn(new RuntimeException("raycast called with debug enabled but no ParticleSpawner supplied"), 2, RaycastUtil.class);
}
Spatial dir = clonedEnd.subtract(start).normalise().scalarMultiply(stepSize);
MutableFloatingSpatial current = new MutableSpatialImpl(start.x(),start.y(),start.z());
MutableChunkSection currentChunk = new MutableChunkSection().updateFrom(current);
ChunkOcclusionView currentOcclusionView = snap.getChunkOcclusionView(currentChunk);
for (float traveled = 0; traveled < total; traveled += stepSize) {
current.add(dir);
if (!ChunkSectionEquality.equals(currentChunk, current)) {
currentChunk.updateFrom(current);
currentOcclusionView = snap.getChunkOcclusionView(currentChunk);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(current.blockX(), current.blockY(), current.blockZ())) {
maxOccluding--;
if (debug) particleSpawner.spawnParticleAt(start.world(), current, ParticleSpawner.Colour.RED);
if (maxOccluding < 1) return false;
continue;
}
if (debug) particleSpawner.spawnParticleAt(start.world(), current, ParticleSpawner.Colour.GREEN);
}
return true;
}
/*
public static boolean raycastCubiNoAllocUnrolledLongBitsAccumulated(int maxOccluding, final int alwaysShowRadius, final int maxRaycastRadius, boolean debug, final int stepSize, BlockView snap,
final double startX, final double startY, final double startZ, final double endX, final double endY, final double endZ) {
if (maxOccluding <= 0) return false;
double total = Math.sqrt(((endX - startX) * (endX - startX)) + ((endY - startY) * (endY - startY)) + ((endZ - startZ) * (endZ - startZ)));
if (total <= alwaysShowRadius) return true;
if (total > maxRaycastRadius) return false;
double finalDist = total - stepSize;
final double dirX = (endX - startX) / total * stepSize;
final double dirY = (endY - startY) / total * stepSize;
final double dirZ = (endZ - startZ) / total * stepSize;
double currentX = startX;
double currentY = startY;
double currentZ = startZ;
int chunkX = ((int) currentX) >> 4;
int chunkY = ((int) currentY) >> 4;
int chunkZ = ((int) currentZ) >> 4;
ChunkOcclusionView currentOcclusionView = snap.getChunkOcclusionView(chunkX, chunkY, chunkZ);
int occluded = 0;
double traveled = 0;
final double fourSteps = stepSize * 4.0;
while (traveled + fourSteps <= finalDist) {
currentX += dirX;
currentY += dirY;
currentZ += dirZ;
int blockX = (int) Math.floor(currentX);
int blockY = (int) Math.floor(currentY);
int blockZ = (int) Math.floor(currentZ);
if (blockX >> 4 != chunkX || blockY >> 4 != chunkY || blockZ >> 4 != chunkZ) {
chunkX = blockX >> 4;
chunkY = blockY >> 4;
chunkZ = blockZ >> 4;
currentOcclusionView = snap.getChunkOcclusionView(chunkX, chunkY, chunkZ);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) occluded ++;
currentX += dirX;
currentY += dirY;
currentZ += dirZ;
blockX = (int) Math.floor(currentX);
blockY = (int) Math.floor(currentY);
blockZ = (int) Math.floor(currentZ);
if (blockX >> 4 != chunkX || blockY >> 4 != chunkY || blockZ >> 4 != chunkZ) {
chunkX = blockX >> 4;
chunkY = blockY >> 4;
chunkZ = blockZ >> 4;
currentOcclusionView = snap.getChunkOcclusionView(chunkX, chunkY, chunkZ);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) occluded ++;
currentX += dirX;
currentY += dirY;
currentZ += dirZ;
blockX = (int) Math.floor(currentX);
blockY = (int) Math.floor(currentY);
blockZ = (int) Math.floor(currentZ);
if (blockX >> 4 != chunkX || blockY >> 4 != chunkY || blockZ >> 4 != chunkZ) {
chunkX = blockX >> 4;
chunkY = blockY >> 4;
chunkZ = blockZ >> 4;
currentOcclusionView = snap.getChunkOcclusionView(chunkX, chunkY, chunkZ);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) occluded ++;
currentX += dirX;
currentY += dirY;
currentZ += dirZ;
blockX = (int) Math.floor(currentX);
blockY = (int) Math.floor(currentY);
blockZ = (int) Math.floor(currentZ);
if (blockX >> 4 != chunkX || blockY >> 4 != chunkY || blockZ >> 4 != chunkZ) {
chunkX = blockX >> 4;
chunkY = blockY >> 4;
chunkZ = blockZ >> 4;
currentOcclusionView = snap.getChunkOcclusionView(chunkX, chunkY, chunkZ);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) occluded ++;
if (occluded >= maxOccluding) return false;
traveled += fourSteps;
}
for (; traveled < finalDist; traveled += stepSize) {
currentX += dirX;
currentY += dirY;
currentZ += dirZ;
int blockX = (int) Math.floor(currentX);
int blockY = (int) Math.floor(currentY);
int blockZ = (int) Math.floor(currentZ);
if (blockX >> 4 != chunkX || blockY >> 4 != chunkY || blockZ >> 4 != chunkZ) {
chunkX = blockX >> 4;
chunkY = blockY >> 4;
chunkZ = blockZ >> 4;
currentOcclusionView = snap.getChunkOcclusionView(chunkX, chunkY, chunkZ);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) occluded ++;
}
return occluded < maxOccluding;
}*/
/**
* The local spatial and chunk-section objects do not escape this method, so the JVM
* should be able to scalarise them while keeping the ray-stepping code easier to follow.
*/
public static boolean raycastUnrolledAccumulated(int maxOccluding, final int alwaysShowRadius, final int maxRaycastRadius, boolean debug,
final float stepSize, final BlockView snap, final Spatial start, final Spatial end) {
RayPosition current = RayPosition.from(start);
RayDirection direction = RayDirection.from(end, current);
double total = direction.getLengthAndNormalise(stepSize);
if (total <= alwaysShowRadius) return true;
if (total > maxRaycastRadius) return false;
float finalDist = (float) (total - stepSize);
final RayAdvancer rayAdvancer = new RayAdvancer(current, direction, snap);
float traveled = 0;
final float fourSteps = stepSize * 4.0f;
while (traveled + fourSteps <= finalDist) {
rayAdvancer.advance();
rayAdvancer.advance();
rayAdvancer.advance();
rayAdvancer.advance();
if (rayAdvancer.occluded >= maxOccluding) return false;
traveled += fourSteps;
}
for (; traveled < finalDist; traveled += stepSize) {
rayAdvancer.advance();
}
return rayAdvancer.occluded < maxOccluding;
}
private static final class RayAdvancer {
private final RayPosition current;
private final RayDirection direction;
private final RayChunkSection currentChunk;
private final BlockView blockView;
private int chunkX, chunkY, chunkZ;
private ChunkOcclusionView currentOcclusionView;
private int occluded = 0;
private RayAdvancer(double startX, double startY, double startZ, RayDirection direction, BlockView blockView) {
super(startX, startY, startZ);
this.direction = direction;
chunkX = blockX() >> 4;
chunkY = blockY() >> 4;
chunkZ = blockZ() >> 4;
currentOcclusionView = blockView.getChunkOcclusionView(chunkX, chunkY, chunkZ);
private RayAdvancer(RayPosition rayPosition, RayDirection rayDirection, BlockView blockView) {
current = rayPosition;
direction = rayDirection;
currentChunk = new RayChunkSection().updateFrom(current);
currentOcclusionView = blockView.getChunkOcclusionView(currentChunk.chunkX, currentChunk.chunkY, currentChunk.chunkZ);
this.blockView = blockView;
}
private void advance() {
add(direction);
int blockX = blockX();
int blockY = blockY();
int blockZ = blockZ();
if (!isCurrentChunk(blockX, blockY, blockZ)) {
moveToChunk(blockX, blockY, blockZ);
currentOcclusionView = blockView.getChunkOcclusionView(chunkX, chunkY, chunkZ);
current.advance(direction);
int blockX = current.blockX();
int blockY = current.blockY();
int blockZ = current.blockZ();
if (blockX >> 4 != currentChunk.chunkX || blockY >> 4 != currentChunk.chunkY || blockZ >> 4 != currentChunk.chunkZ) {
currentChunk.updateFrom(current);
currentOcclusionView = blockView.getChunkOcclusionView(currentChunk.chunkX, currentChunk.chunkY, currentChunk.chunkZ);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) {
occluded++;
particleRed();
} else particleGreen();
}
private boolean isCurrentChunk(int blockX, int blockY, int blockZ) {
return blockX >> 4 == chunkX && blockY >> 4 == chunkY && blockZ >> 4 == chunkZ;
// ((nextChunkX ^ chunkX) | (nextChunkY ^ chunkY) | (nextChunkZ ^ chunkZ)) != 0 is slower than this
}
private void moveToChunk(int blockX, int blockY, int blockZ) {
chunkX = blockX >> 4;
chunkY = blockY >> 4;
chunkZ = blockZ >> 4;
}
void particleGreen() {}
void particleRed() {}
}
private static final class DebugRayAdvancer extends RayAdvancer {
private final UUID world;
private final ParticleSpawner particleSpawner;
private DebugRayAdvancer(double startX, double startY, double startZ, RayDirection direction, BlockView blockView, UUID world, ParticleSpawner particleSpawner) {
super(startX, startY, startZ, direction, blockView);
this.world = world;
this.particleSpawner = particleSpawner;
}
void particleGreen() {
particleSpawner.spawnParticleAt(world, x, y, z, ParticleSpawner.Colour.GREEN);
}
void particleRed() {
particleSpawner.spawnParticleAt(world, x, y, z, ParticleSpawner.Colour.RED);
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) occluded++;
}
}
private static sealed class RayPosition permits RayAdvancer {
double x, y, z;
private static final class RayPosition {
private double x, y, z;
private void advance(RayDirection direction) {
x += direction.x;
y += direction.y;
z += direction.z;
}
private int blockX() {
return (int) Math.floor(x);
}
private int blockY() {
return (int) Math.floor(y);
}
private int blockZ() {
return (int) Math.floor(z);
}
private int chunkX() {
return blockX() >> 4;
}
private int chunkY() {
return blockY() >> 4;
}
private int chunkZ() {
return blockZ() >> 4;
}
private RayPosition(double x, double y, double z) {
this.x = x;
@@ -127,22 +283,8 @@ public class RaycastUtil {
this.z = z;
}
final void add(RayDirection direction) {
x += direction.x;
y += direction.y;
z += direction.z;
}
final int blockX() {
return (int) Math.floor(x);
}
final int blockY() {
return (int) Math.floor(y);
}
final int blockZ() {
return (int) Math.floor(z);
private static RayPosition from(Spatial spatial) {
return new RayPosition(spatial.x(), spatial.y(), spatial.z());
}
}
@@ -155,21 +297,28 @@ public class RaycastUtil {
this.z = z;
}
private static RayDirection from(double endX, double endY, double endZ, double startX, double startY, double startZ) {
return new RayDirection(endX - startX, endY - startY, endZ - startZ);
private static RayDirection from(Spatial end, RayPosition start) {
return new RayDirection(end.x() - start.x, end.y() - start.y, end.z() - start.z);
}
private double getLengthSquared() {
return x * x + y * y + z * z;
}
private double normaliseAndGetLength(double lengthSquared) {
double len = Math.sqrt(lengthSquared);
double scale = 1 / len;
x *= scale;
y *= scale;
z *= scale;
private double getLengthAndNormalise(float stepSize) {
double len = Math.sqrt(x * x + y * y + z * z);
x = (x / len) * stepSize;
y = (y / len) * stepSize;
z = (z / len) * stepSize;
return len;
}
}
private static final class RayChunkSection {
private int chunkX, chunkY, chunkZ;
private RayChunkSection updateFrom(RayPosition other) {
this.chunkX = other.chunkX();
this.chunkY = other.chunkY();
this.chunkZ = other.chunkZ();
return this;
}
}
}
@@ -15,10 +15,9 @@ import games.cubi.raycastedantiesp.core.utils.VarHandler;
import java.lang.invoke.VarHandle;
/** Tile desired visibility and lifecycle are shared with the engine; client, block, and replay data are packet-thread-only. */
/** Tile visibility and lifecycle are shared with the engine; block and replay data are packet-thread-only. */
public abstract class NettyTileEntity<PacketReplayData extends Clearable> extends InvasivelyLinkedSWMRList<NettyTileEntity<PacketReplayData>> implements TrackedTileEntity<PacketReplayData> {
private volatile boolean visible;
private boolean clientVisible;
private volatile int lastChecked; private static final VarHandle LAST_CHECKED = VarHandler.get(NettyTileEntity.class, "lastChecked", int.class);
private char blockID;
private PacketReplayData extraData;
@@ -33,7 +32,6 @@ public abstract class NettyTileEntity<PacketReplayData extends Clearable> extend
this.blockID = blockID;
this.visible = visible;
this.clientVisible = visible;
LAST_CHECKED.set(this, lastChecked);
}
@@ -42,7 +40,6 @@ public abstract class NettyTileEntity<PacketReplayData extends Clearable> extend
this.y = y;
this.z = z;
this.visible = visible;
this.clientVisible = visible;
this.blockID = blockID;
LAST_CHECKED.set(this, NEVER_CHECKED);
}
@@ -58,17 +55,6 @@ public abstract class NettyTileEntity<PacketReplayData extends Clearable> extend
return this;
}
@Override
public boolean clientVisible() {
return clientVisible;
}
@Override
public TrackedTileEntity<PacketReplayData> setClientVisible(boolean clientVisible) {
this.clientVisible = clientVisible;
return this;
}
@Override
public int lastChecked() {
return (int) LAST_CHECKED.getAcquire(this);
@@ -17,10 +17,6 @@ public interface TrackedTileEntity<T> extends ImmutableBlockSpatial, Clearable {
boolean visible();
TrackedTileEntity<T> setVisible(boolean visible);
/** Packet-thread-only client state. */
boolean clientVisible();
TrackedTileEntity<T> setClientVisible(boolean clientVisible);
int lastChecked();
TrackedTileEntity<T> setLastChecked(int lastChecked);
@@ -168,7 +168,6 @@ public abstract class AbstractBlockView<R extends Clearable, T extends NettyTile
public void recordOutboundTileEntityVisibility(TrackedTileEntity<?> tileEntity, boolean visible) {
if (tileEntity != null) {
tileEntity.setVisible(visible);
tileEntity.setClientVisible(visible);
tileEntity.setLastChecked(TrackedTileEntity.NEVER_CHECKED);
}
}
@@ -192,8 +191,6 @@ public abstract class AbstractBlockView<R extends Clearable, T extends NettyTile
if (!tileEntity.visible()) {
tileEntity.setVisible(true);
tileEntity.setLastChecked(currentTick);
}
if (!tileEntity.clientVisible()) {
visibilityRepairConsumer.accept(tileEntity);
}
});
@@ -55,23 +55,21 @@ public interface BlockView extends Clearable {
TrackedTileEntity<?> getTrackedTileEntity(UUID world, BlockSpatial position);
/** Returns the engine's desired visibility, not the state currently applied to the client. */
boolean isVisible(UUID world, BlockSpatial position, int currentTick);
/**
* Records visibility established by the current outbound packet without queuing another packet. This synchronizes
* both desired and client visibility and resets the check timestamp because the transmitted state supersedes the
* result of any previous visibility check. The tile entity must be the current state returned by this view's
* structural-writer operations.
* Records visibility established by the current outbound packet without queuing another packet. This also resets
* the check timestamp because the transmitted state supersedes the result of any previous visibility check. The
* tile entity must be the current state returned by this view's structural-writer operations.
*/
void recordOutboundTileEntityVisibility(TrackedTileEntity<?> tileEntity, boolean visible);
/**
* Applies a mode change from the structural writer.
*
* Sets every desired state visible when checks are disabled and invokes {@code visibilityRepairConsumer} for each
* tile entity still hidden from the client. The structural writer must send their current state directly rather
* than publishing them to the engine transition queue.
* Invokes {@code visibilityRepairConsumer} for each tile entity made visible when checks are disabled. The
* structural writer must send their current state directly rather than publishing them to the engine transition
* queue.
*/
void applyTileEntityCheckMode(boolean enabled, int currentTick, Consumer<TrackedTileEntity<?>> visibilityRepairConsumer);
@@ -50,9 +50,11 @@ public abstract class PacketEntityViewController<P> {
protected EntityConfig entityConfig = null;
protected PlayerConfig playerConfig = null;
protected double hideOnSpawnEntityDistanceSquared = 0;
protected double hideOnSpawnPlayerDistanceSquared = 0;
protected void handleWorldStatePacket(UUID player, String world, UUID worldUUID, int minWorldHeight, int currentTick) {
PlayerData playerData = PlayerRegistry.get().getPlayerData(player);
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player);
if (playerData == null) {
Logger.error("Received world state packet for unknown player, uuid=" + player, 2, PacketEntityViewController.class);
return;
@@ -89,7 +91,7 @@ public abstract class PacketEntityViewController<P> {
}
protected PlayerData handlePlayPhaseLoginPacket(int entityID, UUID playerUUID, int currentTick) {
return PlayerRegistry.get().registerAndGetPlayer(playerUUID, currentTick, entityID, this::createSelfEntity);
return PlayerRegistry.getInstance().registerAndGetPlayer(playerUUID, currentTick, entityID, this::createSelfEntity);
}
protected abstract NettyEntity<?> createSelfEntity(PlayerData ownData, int entityID, UUID playerUUID);
@@ -101,7 +103,7 @@ public abstract class PacketEntityViewController<P> {
if (player == null) {
return;
}
PlayerRegistry.get().unregisterPlayer(player);
PlayerRegistry.getInstance().unregisterPlayer(player);
}
/**
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
@@ -121,13 +123,11 @@ public abstract class PacketEntityViewController<P> {
NettyEntity<?> entity = Logger.requireNonNull(processEntitySpawn(playerData, packet, world, currentTick), "processEntitySpawn returned null", 3, PacketEntityViewController.class);
RaycastConfig config = (isPlayer) ? playerConfig : entityConfig;
if (config.enabled()) {
if ((!isPlayer && entityConfig.enabled()) || isPlayer && playerConfig.enabled()) {
Locatable ownLocation = playerData.ownLocation();
boolean staleOwnLocation = ownLocation == null || ownLocation.world() == null || !ownLocation.world().equals(world);
double distanceSquared = staleOwnLocation ? Double.POSITIVE_INFINITY : ownLocation.distanceSquared(entity);
if (distanceSquared > config.hideOnSpawnDistanceSquared) {
if (distanceSquared > (isPlayer ? hideOnSpawnPlayerDistanceSquared : hideOnSpawnEntityDistanceSquared)) {
entity.setVisible(false);
entity.setClientVisible(false);
if (isPlayer) {
@@ -294,32 +294,9 @@ class ChunkSectionStoreTest {
assertEquals(1, visibilityRepairs.size());
assertSame(tileEntity, visibilityRepairs.getFirst());
assertTrue(tileEntity.visible());
assertFalse(tileEntity.clientVisible());
assertFalse(view.hasPendingTransitions());
}
@Test
void disablingTileChecksRepairsClientHiddenEngineVisibleTiles() {
TestBlockView view = new TestBlockView(ODD_OCCLUDING, false);
UUID world = UUID.randomUUID();
ImmutableBlockSpatialImpl position = new ImmutableBlockSpatialImpl(1, 64, 2);
ArrayList<TrackedTileEntity<?>> visibilityRepairs = new ArrayList<>();
view.applyTileEntityCheckMode(true, 0, unused -> {});
TestTileEntity tileEntity = view.updateOrInsertTileEntity(world, position, 99, true);
tileEntity.setClientVisible(false);
view.applyTileEntityCheckMode(false, 1, tile -> {
visibilityRepairs.add(tile);
tile.setClientVisible(true);
});
assertEquals(1, visibilityRepairs.size());
assertSame(tileEntity, visibilityRepairs.getFirst());
assertTrue(tileEntity.visible());
assertTrue(tileEntity.clientVisible());
}
@Test
void modeGenerationRejectsInFlightHideAndForcesFirstEnabledCheck() {
TestBlockView view = new TestBlockView(ODD_OCCLUDING, false);
@@ -48,7 +48,7 @@ class PacketEntityViewControllerTest {
@AfterEach
void unregisterPlayers() {
for (UUID player : registeredPlayers) {
PlayerRegistry.get().unregisterPlayer(player);
PlayerRegistry.getInstance().unregisterPlayer(player);
}
registeredPlayers.clear();
}
@@ -59,7 +59,7 @@ class PacketEntityViewControllerTest {
CONTROLLER.replacementPassengerPackets.clear();
UUID playerUUID = UUID.randomUUID();
registeredPlayers.add(playerUUID);
PlayerData playerData = PlayerRegistry.get().registerAndGetPlayer(
PlayerData playerData = PlayerRegistry.getInstance().registerAndGetPlayer(
playerUUID,
0,
1,
Submodule leafpile updated: b2080dd600...dca89261e9.
@@ -47,6 +47,7 @@ public abstract class PacketEventsBlockViewController implements PacketListener
private final IntSupplier currentTickSupplier;
private final PacketEventsCommonViewController common;
private TileEntityConfig tileEntityConfig = null;
private int hideOnSpawnDistanceSquared = 0;
protected PacketEventsBlockViewController(BlockInfoResolver blockInfoResolver, boolean trackAllBlocks, IntSupplier currentTickSupplier) {
this.blockInfoResolver = blockInfoResolver;
@@ -75,9 +76,10 @@ public abstract class PacketEventsBlockViewController implements PacketListener
if (!(ConfigManager.get().getTileEntityConfig() == tileEntityConfig)) {
tileEntityConfig = ConfigManager.get().getTileEntityConfig();
hideOnSpawnDistanceSquared = tileEntityConfig.hideOnSpawnDistance() * tileEntityConfig.hideOnSpawnDistance();
}
PlayerData playerData = PlayerRegistry.get().getPlayerData(viewerUUID);
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(viewerUUID);
if (playerData == null) {
return;
}
@@ -89,16 +91,14 @@ public abstract class PacketEventsBlockViewController implements PacketListener
blockView.applyTileEntityCheckMode(tileChecksEnabled, currentTick,
tileEntity -> sendTileEntityVisibilityRepair(event.getUser(), tileEntity));
handleBlockPackets(event, event.getUser(), playerData, world, tileChecksEnabled);
handleBlockPackets(event, event.getUser(), playerData, world, currentTick, tileChecksEnabled);
// The entity controller is guaranteed to have run first, so it is safe to assume this var is accurate.
if (blockView.hasPendingTransitions() && !playerData.nettyData().packetsAreWithinBundle) {
User viewer = event.getUser();
event.getTasksAfterSend().add(() -> processTileEntityTransitions(viewer, playerData));
if (blockView.hasPendingTransitions()) {
processTileEntityTransitions(event.getUser(), playerData);
}
}
private void handleBlockPackets(PacketSendEvent event, User viewer, PlayerData playerData, UUID world, boolean tileChecksEnabled) {
private void handleBlockPackets(PacketSendEvent event, User viewer, PlayerData playerData, UUID world, int currentTick, boolean tileChecksEnabled) {
if (world == null) {
return;
}
@@ -124,14 +124,9 @@ public abstract class PacketEventsBlockViewController implements PacketListener
return;
}
ensureTileReplayData(tileEntity).setBlockEntityData(packet.getBlockEntityType(), packet.getNBT());
boolean visible = tileEntity.visible();
boolean clientVisible = tileEntity.clientVisible();
if (!visible || !clientVisible) {
if (tileChecksEnabled && !blockView.isVisible(world, position, currentTick)) {
event.setCancelled(true);
if (!visible && clientVisible) {
sendHiddenBlock(viewer, position);
tileEntity.setClientVisible(false);
}
sendHiddenBlock(viewer, position);
}
} else if (event.getPacketType() == PacketType.Play.Server.CHUNK_DATA) {
WrapperPlayServerChunkData packet = new WrapperPlayServerChunkData(event);
@@ -164,13 +159,9 @@ public abstract class PacketEventsBlockViewController implements PacketListener
TrackedTileEntity<?> state = blockView.updateOrInsertTileEntity(world, key, blockID, visibleIfNew);
if (!tileChecksEnabled) {
blockView.recordOutboundTileEntityVisibility(state, true);
} else if (state != null) {
boolean visible = state.visible();
if (!visible) {
change.setBlockId(getHiddenBlockId(key.blockY()));
event.markForReEncode(true);
}
state.setClientVisible(visible);
} else if (state != null && !state.visible()) {
change.setBlockId(getHiddenBlockId(key.blockY()));
event.markForReEncode(true);
}
} else {
blockView.removeTileEntity(world, key);
@@ -225,9 +216,6 @@ public abstract class PacketEventsBlockViewController implements PacketListener
if (state == null || state.blockID() == 0) {
return;
}
if (!transitionMatchesCurrentVisibility(type, state.visible())) {
return;
}
switch (type) {
case HIDE -> {
if (!blockView.isCurrentEnabledTileEntityMode(modeToken)) {
@@ -235,14 +223,13 @@ public abstract class PacketEventsBlockViewController implements PacketListener
state.setLastChecked(TrackedTileEntity.NEVER_CHECKED);
return;
}
if (state.clientVisible()) {
viewer.writePacketSilently(getBlockChangeWith(tileEntity.blockX(), tileEntity.blockY(), tileEntity.blockZ(), getHiddenBlockId(tileEntity.blockY())));
state.setClientVisible(false);
}
viewer.writePacketSilently(getBlockChangeWith(tileEntity.blockX(), tileEntity.blockY(), tileEntity.blockZ(), getHiddenBlockId(tileEntity.blockY())));
}
case SHOW -> {
if (!state.visible()) {
return;
}
sendTileEntity(viewer, state);
state.setClientVisible(true);
}
}
}
@@ -252,7 +239,6 @@ public abstract class PacketEventsBlockViewController implements PacketListener
TrackedTileEntity<PacketEventsTileEntityReplayData> state = (TrackedTileEntity<PacketEventsTileEntityReplayData>) tileEntity;
if (state.blockID() != 0) {
sendTileEntity(viewer, state);
state.setClientVisible(true);
}
}
@@ -277,13 +263,9 @@ public abstract class PacketEventsBlockViewController implements PacketListener
TrackedTileEntity<?> state = playerData.blockView().updateOrInsertTileEntity(world, location, blockID, visibleIfNew);
if (!tileChecksEnabled) {
playerData.blockView().recordOutboundTileEntityVisibility(state, true);
} else if (state != null) {
boolean visible = state.visible();
if (!visible) {
event.setCancelled(true);
sendHiddenBlock(viewer, location);
}
state.setClientVisible(visible);
} else if (state != null && !state.visible()) {
event.setCancelled(true);
sendHiddenBlock(viewer, location);
}
} else {
playerData.blockView().removeTileEntity(world, location);
@@ -304,7 +286,7 @@ public abstract class PacketEventsBlockViewController implements PacketListener
if (playerLocation == null || playerLocation.world() == null || !playerLocation.world().equals(packetWorld)) {
return false;
}
return location.distanceSquared(playerLocation) <= tileEntityConfig.hideOnSpawnDistanceSquared;
return location.distanceSquared(playerLocation) <= hideOnSpawnDistanceSquared;
}
private WrapperPlayServerBlockEntityData buildBlockEntityDataPacket(BlockSpatial location, PacketEventsTileEntityReplayData replayData) {
@@ -315,13 +297,6 @@ public abstract class PacketEventsBlockViewController implements PacketListener
);
}
static boolean transitionMatchesCurrentVisibility(BlockViewTransition.Type type, boolean visible) {
return switch (type) {
case SHOW -> visible;
case HIDE -> !visible;
};
}
@SuppressWarnings("unchecked")
private static TrackedTileEntity<PacketEventsTileEntityReplayData> getTrackedTileEntity(BlockView blockView, UUID world, BlockSpatial position) {
return (TrackedTileEntity<PacketEventsTileEntityReplayData>) blockView.getTrackedTileEntity(world, position);
@@ -90,7 +90,7 @@ public abstract class PacketEventsEntityViewController extends PacketEntityViewC
return;
}
PlayerData playerData = PlayerRegistry.get().getPlayerData(viewerUUID);
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(viewerUUID);
if (event.getPacketType() == PacketType.Play.Server.JOIN_GAME) {
WrapperPlayServerJoinGame packet = new WrapperPlayServerJoinGame(event);
@@ -106,10 +106,12 @@ public abstract class PacketEventsEntityViewController extends PacketEntityViewC
if (ConfigManager.get().getEntityConfig() != entityConfig) {
entityConfig = ConfigManager.get().getEntityConfig();
hideOnSpawnEntityDistanceSquared = entityConfig.hideOnSpawnDistance() * entityConfig.hideOnSpawnDistance();
}
if (ConfigManager.get().getPlayerConfig() != playerConfig) {
playerConfig = ConfigManager.get().getPlayerConfig();
hideOnSpawnPlayerDistanceSquared = playerConfig.hideOnSpawnDistance() * playerConfig.hideOnSpawnDistance();
}
UUID world = COMMON.resolvePacketWorld(playerData, event.getUser());
@@ -117,13 +119,7 @@ public abstract class PacketEventsEntityViewController extends PacketEntityViewC
handleEntityPackets(event, event.getUser(), playerData, world, currentTick);
boolean isInBundle = playerData.nettyData().packetsAreWithinBundle;
if (event.getPacketType() == PacketType.Play.Server.BUNDLE) {
isInBundle = !isInBundle;
playerData.nettyData().packetsAreWithinBundle = isInBundle;
}
if (!isInBundle && (playerData.entityView().hasPendingTransitions() || playerData.playerView().hasPendingTransitions())) {
if (playerData.entityView().hasPendingTransitions() || playerData.playerView().hasPendingTransitions()) {
PlayerData transitionData = playerData;
User viewer = event.getUser();
event.getTasksAfterSend().add(() -> processPendingEntityTransitions(transitionData, viewer));
@@ -105,13 +105,9 @@ abstract class AbstractChunkParser<D> implements ChunkParser {
TrackedTileEntity<?> state = blockView.updateOrInsertTileEntity(world, key, blockID, !mutatePackets);
if (!mutatePackets) {
blockView.recordOutboundTileEntityVisibility(state, true);
} else if (state != null) {
boolean visible = state.visible();
if (!visible) {
section.set(localX, localY, localZ, hiddenBlockID.applyAsInt(blockY));
mutatedBlock = true;
}
state.setClientVisible(visible);
} else if (state != null && !state.visible()) {
section.set(localX, localY, localZ, hiddenBlockID.applyAsInt(blockY));
mutatedBlock = true;
}
}
}
@@ -188,7 +184,7 @@ abstract class AbstractChunkParser<D> implements ChunkParser {
TrackedTileEntity<PacketEventsTileEntityReplayData> state = tracked(blockView, world, key);
if (state != null) {
replayData(state).setBlockEntityData(BlockEntityTypes.getById(clientVersion, tileEntity.getType()), tileEntity.getNBT());
return !state.clientVisible();
return !state.visible();
}
Logger.warning("Managed chunk block entity was missing from tracked state at " + blockX + "," + blockY + "," + blockZ, 3, AbstractChunkParser.class);
return true;
@@ -43,7 +43,7 @@ class PEEntityStateReconciliationTaskTest {
@AfterEach
void unregisterPlayers() {
for (UUID player : registeredPlayers) {
PlayerRegistry.get().unregisterPlayer(player);
PlayerRegistry.getInstance().unregisterPlayer(player);
}
registeredPlayers.clear();
}
@@ -131,7 +131,7 @@ class PEEntityStateReconciliationTaskTest {
private PlayerData playerData() {
UUID playerUUID = UUID.randomUUID();
registeredPlayers.add(playerUUID);
return PlayerRegistry.get().registerAndGetPlayer(
return PlayerRegistry.getInstance().registerAndGetPlayer(
playerUUID,
0,
1,
@@ -13,7 +13,6 @@ import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.tracked.NettyTileEntity;
import games.cubi.raycastedantiesp.core.tracked.TrackedTileEntity;
import games.cubi.raycastedantiesp.core.view.BlockView;
import games.cubi.raycastedantiesp.core.view.BlockViewTransition;
import games.cubi.raycastedantiesp.packetevents.view.PacketEventsBlockView;
import org.junit.jupiter.api.Test;
@@ -56,7 +55,6 @@ class PacketEventsBlockViewControllerTest {
assertSame(original, transitionEntity.get());
assertTrue(((NettyTileEntity<?>) original).isRemoved());
assertTrue(original.clientVisible());
original.setLastChecked(42);
assertTrue(((NettyTileEntity<?>) original).isRemoved());
assertNull(PacketEventsBlockViewController.resolveCurrentTransitionState(transitionEntity.get(), 2, 2));
@@ -79,18 +77,6 @@ class PacketEventsBlockViewControllerTest {
assertSame(transitionEntity.get(), PacketEventsBlockViewController.resolveCurrentTransitionState(transitionEntity.get(), 2, 2));
}
@Test
void staleVisibilityTransitionsAreIgnored() {
assertFalse(PacketEventsBlockViewController.transitionMatchesCurrentVisibility(
BlockViewTransition.Type.SHOW, false));
assertFalse(PacketEventsBlockViewController.transitionMatchesCurrentVisibility(
BlockViewTransition.Type.HIDE, true));
assertTrue(PacketEventsBlockViewController.transitionMatchesCurrentVisibility(
BlockViewTransition.Type.SHOW, true));
assertTrue(PacketEventsBlockViewController.transitionMatchesCurrentVisibility(
BlockViewTransition.Type.HIDE, false));
}
@Test
void showTransitionCannotTargetReplacementAtSameCoordinates() {
UUID world = UUID.randomUUID();
@@ -84,7 +84,6 @@ class ChunkParserTest {
var tracked = view.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1));
assertNotNull(tracked);
assertTrue(tracked.visible());
assertTrue(tracked.clientVisible());
assertNotNull(tracked.extraData());
}
@@ -103,9 +102,7 @@ class ChunkParserTest {
assertNotNull(replacement);
assertEquals(1, section.getBlockId(3, 2, 1));
assertEquals(0, replacement.getTileEntities().length);
var tracked = view.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1));
assertFalse(tracked.visible());
assertFalse(tracked.clientVisible());
assertFalse(view.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1)).visible());
}
@Test
@@ -152,8 +149,6 @@ class ChunkParserTest {
TileEntity tile = new TileEntity((byte) (3 << 4 | 1), (short) 2, 0, null);
Column initialColumn = new Column(0, 0, true, new BaseChunk[]{initial}, new TileEntity[]{tile});
new NonMutatingBlockChunkParser(RESOLVER, ignored -> 1).parse(view, world, initialColumn, 0);
TrackedTileEntity<?> tracked = view.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1));
tracked.setClientVisible(false);
view.applyTileEntityCheckMode(true, 1, unused -> {});
Chunk_v1_18 resend = airSection();
@@ -163,8 +158,7 @@ class ChunkParserTest {
assertNull(replacement);
assertEquals(99, resend.getBlockId(3, 2, 1));
assertTrue(tracked.visible());
assertTrue(tracked.clientVisible());
assertTrue(view.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1)).visible());
}
@Test
@@ -212,7 +206,6 @@ class ChunkParserTest {
assertSame(section, column.getChunks()[0]);
assertSame(tileEntities, column.getTileEntities());
assertTrue(tracked.visible());
assertTrue(tracked.clientVisible());
assertEquals(TrackedTileEntity.NEVER_CHECKED, tracked.lastChecked());
assertEquals(99, section.getBlockId(3, 2, 1));
assertNull(view.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(4, 2, 1)));
@@ -230,9 +223,7 @@ class ChunkParserTest {
nonMutatingView, world, new Column(0, 0, true, new BaseChunk[]{nonMutatingSection}, new TileEntity[]{tile}), 0
);
assertNull(nonMutatingReplacement);
var nonMutatingTracked = nonMutatingView.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1));
assertTrue(nonMutatingTracked.visible());
assertTrue(nonMutatingTracked.clientVisible());
assertTrue(nonMutatingView.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1)).visible());
Chunk_v1_18 mutatingSection = airSection();
mutatingSection.set(3, 2, 1, 99);
@@ -243,9 +234,7 @@ class ChunkParserTest {
);
assertNotNull(mutatingReplacement);
assertEquals(1, mutatingSection.getBlockId(3, 2, 1));
var mutatingTracked = mutatingView.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1));
assertFalse(mutatingTracked.visible());
assertFalse(mutatingTracked.clientVisible());
assertFalse(mutatingView.getTrackedTileEntity(world, new ImmutableBlockSpatialImpl(3, 2, 1)).visible());
}
@Test
+3 -3
View File
@@ -11,8 +11,8 @@ import org.gradle.jvm.toolchain.JavaToolchainService
plugins {
id("java-library")
id("io.papermc.paperweight.userdev")
id("xyz.jpenilla.run-paper")
id("io.papermc.paperweight.userdev") version "2.0.0-beta.21"
id("xyz.jpenilla.run-paper") version "3.0.2"
id("com.gradleup.shadow") version "9.4.0"
}
@@ -64,7 +64,7 @@ val javaToolchainService = project.extensions.getByType(JavaToolchainService::cl
group = "games.cubi.raycastedantiesp.paper"
val platformPaperVersion: String = "0.10.2-SNAPSHOT"
val platformPaperVersion: String = "0.10.1-SNAPSHOT"
val coreVersion = project(":core").version.toString()
val commitShort = providers.exec {
@@ -19,6 +19,7 @@ import games.cubi.raycastedantiesp.core.players.PlayerData;
import games.cubi.raycastedantiesp.paper.utils.PaperListener;
import io.papermc.paper.event.player.PlayerClientLoadedWorldEvent;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -31,7 +32,7 @@ import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.function.IntSupplier;
import static games.cubi.raycastedantiesp.paper.RaycastedAntiESP.checkForUpdates;
import static games.cubi.raycastedantiesp.paper.UpdateChecker.checkForUpdates;
public class EventListener extends PaperListener {
private final RaycastedAntiESP plugin;
@@ -63,7 +64,7 @@ public class EventListener extends PaperListener {
if (player.hasMetadata("NPC")) return;
PlayerData playerData = PlayerRegistry.get().getPlayerData(player.getUniqueId());
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
if (playerData == null) {
Logger.error("Player joined before packet state was registered. Kicking player=" + player.getName() + " uuid=" + player.getUniqueId(), 1, EventListener.class);
player.kick(MiniMessage.miniMessage().deserialize("RaycastedAntiESP failed to initialise your packet state. Please reconnect. Report this issue to the server you are playing on if you are still unable to join."));
@@ -83,7 +84,7 @@ public class EventListener extends PaperListener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent event) {
PlayerData playerData = PlayerRegistry.get().getPlayerData(event.getPlayer().getUniqueId());
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(event.getPlayer().getUniqueId());
if (playerData == null) return;
updateOwnLocation(playerData, event.getPlayer().getEyeLocation());
}
@@ -120,7 +121,7 @@ public class EventListener extends PaperListener {
}
private void updateOwnLocation(Player player, Location location) {
PlayerData playerData = PlayerRegistry.get().getPlayerData(player.getUniqueId());
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
if (playerData == null || location == null) {
return;
}
@@ -34,21 +34,21 @@ public class FancyCompatibility {
@EventHandler(priority = EventPriority.LOWEST)
public void npcLoad(NpcSpawnEvent event) {
int id = event.getNpc().getEntityId();
Logger.debug("NpcSpawnEvent called, adding entity: " + id);
Logger.info("NpcSpawnEvent called, adding entity: " + id, 1);
EntityBypassRegistry.addEntity(id);
}
@EventHandler(priority = EventPriority.LOWEST)
public void npcLoad(NpcCreateEvent event) {
int id = event.getNpc().getEntityId();
Logger.debug("NpcCreateEvent called, adding entity: " + id);
Logger.info("NpcCreateEvent called, adding entity: " + id, 1);
EntityBypassRegistry.addEntity(id);
}
@EventHandler(priority = EventPriority.LOWEST)
public void npcLoad(NpcModifyEvent event) {
int id = event.getNpc().getEntityId();
Logger.debug("NpcModifyEvent called, adding entity: " + id);
Logger.info("NpcModifyEvent called, adding entity: " + id, 1);
EntityBypassRegistry.addEntity(id);
}
}
@@ -71,7 +71,7 @@ public class FancyCompatibility {
private void add(Hologram hologram) {
int id = hologram.getEntityId();
Logger.debug("Hologram event called, adding entity: " + id);
Logger.info("Hologram event called, adding entity: " + id, 1);
EntityBypassRegistry.addEntity(id);
}
}
@@ -9,7 +9,6 @@
package games.cubi.raycastedantiesp.paper;
import games.cubi.raycastedantiesp.core.Core;
import games.cubi.raycastedantiesp.core.UpdateChecker;
import games.cubi.raycastedantiesp.paper.commands.Attribution;
import games.cubi.raycastedantiesp.paper.commands.AttributionBrigadier;
import games.cubi.raycastedantiesp.paper.commands.RaycastedAntiESPCommandBrigadier;
@@ -29,14 +28,12 @@ import games.cubi.raycastedantiesp.paper.bStats.MetricsCollector;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.paper.utils.FoliaTicker;
import games.cubi.raycastedantiesp.paper.utils.PaperScheduler;
import games.cubi.raycastedantiesp.paper.utils.PaperTicker;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
@@ -101,12 +98,10 @@ public final class RaycastedAntiESP extends JavaPlugin implements CommandExecuto
ViewRegistry.initialise(worldEpoch -> new PacketEventsBlockView(blockInfoResolver, trackAllBlocks, worldEpoch), PacketEventsEntityView::createEntityView, PacketEventsEntityView::createPlayerView);
PacketEventsCommonViewController.initialise(new PaperPacketEventsCommonViewController(currentTickSupplier));
packetEventsController = new PaperPacketEventsEntityViewController(currentTickSupplier);
// PaperPacketEventsEntityViewController must be constructed before PaperPacketEventsBlockViewController
// as the entity controller must run before the block controller
new PaperPacketEventsBlockViewController(blockInfoResolver, trackAllBlocks, currentTickSupplier);
engine = new PaperAsyncEngine(this, config, currentTickSupplier);
checkForUpdates(this, Bukkit.getConsoleSender());
UpdateChecker.checkForUpdates(this, Bukkit.getConsoleSender());
EventListener.initialise(this, engine, currentTickSupplier);
this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS.newHandler(event -> {
@@ -146,18 +141,6 @@ public final class RaycastedAntiESP extends JavaPlugin implements CommandExecuto
loggerAdapter.forceFlushToFileNow();
}
public static void checkForUpdates(RaycastedAntiESP plugin, CommandSender audience) {
UpdateChecker.fetchUpdateCheck(new PaperAsyncEngine.PaperAsyncRunner(plugin.getServer().getAsyncScheduler())).thenAccept(report -> {
if (report.results().isEmpty()) {
return;
}
PaperScheduler.runForAudience(plugin, audience, () -> audience.sendRichMessage(UpdateChecker.formatUpdateMessage(report)));
}).exceptionally(ex -> {
Logger.error("An error occurred while checking for plugin updates", ex, 4, UpdateChecker.class);
return null;
});
}
public static ConfigManager getConfigManager() {
return config;
@@ -1,14 +1,27 @@
package games.cubi.raycastedantiesp.core;
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP.
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
* See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.paper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.config.ConfigManager;
import games.cubi.raycastedantiesp.core.config.UpdateConfig;
import games.cubi.raycastedantiesp.core.utils.BuildProperties;
import games.cubi.raycastedantiesp.core.utils.BuildProperties.Version;
import games.cubi.raycastedantiesp.paper.utils.PaperScheduler;
import java.io.BufferedReader;
import java.io.IOException;
@@ -25,9 +38,7 @@ import java.util.concurrent.TimeUnit;
public class UpdateChecker {
private static final String VERSION_API_ENDPOINT = "https://api.modrinth.com/v2/project/bCjNZu0C/version?include_changelog=false";
private static final String PLATFORM_NAME = "Paper";
private static final String MODRINTH_PAGE_URL = "https://modrinth.com/project/bCjNZu0C/";
private static final String MODRINTH_MM_LINK = "<hover:show_text:'" + MODRINTH_PAGE_URL + "'><aqua><u><click:open_url:'" + MODRINTH_PAGE_URL + "'>" + MODRINTH_PAGE_URL + "</click></u></aqua></hover>";
private static final String MODRINTH_PAGE_URL = "https://modrinth.com/project/bCjNZu0C";
enum UpdateChannel {
STABLE("release", "release"),
@@ -71,8 +82,8 @@ public class UpdateChecker {
record ApiVersion(String rawVersion, Version coreVersion, Version platformVersion) {}
public record UpdateCheckReport(List<UpdateCheckResult> results) {
public UpdateCheckReport {
record UpdateCheckReport(List<UpdateCheckResult> results) {
UpdateCheckReport {
results = List.copyOf(results);
}
@@ -103,20 +114,20 @@ public class UpdateChecker {
}
}
private static CompletableFuture<List<VersionEntry>> fetchVersions(AsyncRunner runner) {
private static CompletableFuture<List<VersionEntry>> fetchVersions(RaycastedAntiESP plugin) {
CompletableFuture<List<VersionEntry>> future = new CompletableFuture<>();
runner.runNow(() -> {
Bukkit.getAsyncScheduler().runNow(plugin, ignored -> {
try {
URLConnection connection = new URI(VERSION_API_ENDPOINT).toURL().openConnection();
connection.setConnectTimeout(5_000); //ms
connection.setReadTimeout(5_000); //ms
try (
final InputStreamReader reader = new InputStreamReader(connection.getInputStream());
final BufferedReader bufferedReader = new BufferedReader(reader)
) {
future.complete(parseVersionEntries(bufferedReader));
}
URLConnection connection = new URI(VERSION_API_ENDPOINT).toURL().openConnection();
connection.setConnectTimeout(5_000); //ms
connection.setReadTimeout(5_000); //ms
try (
final InputStreamReader reader = new InputStreamReader(connection.getInputStream());
final BufferedReader bufferedReader = new BufferedReader(reader)
) {
future.complete(parseVersionEntries(bufferedReader));
}
} catch (IOException | URISyntaxException e) {
future.completeExceptionally(new IllegalStateException("Unable to fetch latest version", e));
}
@@ -147,13 +158,13 @@ public class UpdateChecker {
return List.copyOf(versionEntries);
}
public static CompletableFuture<UpdateCheckReport> fetchUpdateCheck(AsyncRunner runner) {
private static CompletableFuture<UpdateCheckReport> fetchUpdateCheck(RaycastedAntiESP plugin) {
UpdateConfig updateConfig = ConfigManager.get().getUpdateConfig();
if (!updateConfig.anyChannelEnabled()) {
return CompletableFuture.completedFuture(new UpdateCheckReport(List.of()));
}
return fetchVersions(runner).thenApply(versionEntries -> checkVersions(
return fetchVersions(plugin).thenApply(versionEntries -> checkVersions(
BuildProperties.CORE.version(),
BuildProperties.PLATFORM.version(),
versionEntries,
@@ -264,14 +275,14 @@ public class UpdateChecker {
static String formatUpdateMessage(UpdateCheckResult result) {
return switch (result.status()) {
case BEHIND -> "<red>You are behind the latest " + result.channel().messageName() + " of RaycastedAntiESP. Please upgrade to <green>v" + result.apiVersion().rawVersion() + "<red> at " + MODRINTH_MM_LINK + "<red>.";
case BEHIND -> "<red>You are behind the latest " + result.channel().messageName() + " of RaycastedAntiESP. Please upgrade to <green>v" + result.apiVersion().rawVersion() + "<red> at " + modrinthLink() + "<red>.";
case UP_TO_DATE -> "<green>You are up to date with the latest " + result.channel().messageName() + " of RaycastedAntiESP.";
case AHEAD, NO_COMPARABLE_VERSION -> "<yellow>You are ahead of the latest " + result.channel().messageName() + " of RaycastedAntiESP.";
case INVALID_CURRENT_VERSION -> "<red>Unable to check for updates to RaycastedAntiESP, invalid current version format.";
};
}
public static String formatUpdateMessage(UpdateCheckReport report) {
static String formatUpdateMessage(UpdateCheckReport report) {
List<String> messages = new ArrayList<>();
for (UpdateCheckResult result : report.results()) {
messages.add(formatUpdateMessage(result));
@@ -279,4 +290,20 @@ public class UpdateChecker {
return String.join("\n", messages);
}
private static String modrinthLink() {
return "<hover:show_text:'" + MODRINTH_PAGE_URL + "'><aqua><u><click:open_url:'" + MODRINTH_PAGE_URL + "'>" + MODRINTH_PAGE_URL + "</click></u></aqua></hover>";
}
public static void checkForUpdates(RaycastedAntiESP plugin, CommandSender audience) {
fetchUpdateCheck(plugin).thenAccept(report -> {
if (report.results().isEmpty()) {
return;
}
PaperScheduler.runForAudience(plugin, audience, () -> audience.sendRichMessage(formatUpdateMessage(report)));
}).exceptionally(ex -> {
Logger.error("An error occurred while checking for plugin updates", ex, 4, UpdateChecker.class);
return null;
});
}
}
@@ -9,6 +9,11 @@
package games.cubi.raycastedantiesp.paper.bStats;
import games.cubi.raycastedantiesp.core.config.ConfigManager;
import games.cubi.raycastedantiesp.core.config.raycast.ChunkSectionConfig;
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
import games.cubi.raycastedantiesp.core.config.raycast.SoundEffectsConfig;
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
import games.cubi.raycastedantiesp.core.players.PlayerData;
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
import games.cubi.raycastedantiesp.paper.RaycastedAntiESP;
@@ -103,12 +108,12 @@ public class MetricsCollector {
}
private String getPlayerCount() {
return bucketPlayerCount(PlayerRegistry.get().getPlayerCount());
return bucketPlayerCount(PlayerRegistry.getInstance().getAllPlayerData().size());
}
private String getMedianEntityCount() {
return bucketMedianEntityCounts(
PlayerRegistry.get().getAllPlayerData(),
PlayerRegistry.getInstance().getAllPlayerData(),
PlayerData::isConnected,
playerData -> playerData.entityView().size()
);
@@ -8,6 +8,8 @@
package games.cubi.raycastedantiesp.paper.commands;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import games.cubi.locatables.api.Locatable;
import games.cubi.locatables.api.MutableFloatingSpatial;
import games.cubi.locatables.api.Spatial;
@@ -20,9 +22,9 @@ import games.cubi.raycastedantiesp.core.players.PlayerData;
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
import games.cubi.raycastedantiesp.core.raycast.RaycastUtil;
import games.cubi.raycastedantiesp.core.view.AbstractBlockView;
import games.cubi.raycastedantiesp.core.view.BlockView;
import games.cubi.raycastedantiesp.core.view.EntityView;
import games.cubi.raycastedantiesp.paper.RaycastedAntiESP;
import games.cubi.raycastedantiesp.paper.UpdateChecker;
import games.cubi.raycastedantiesp.paper.packets.PacketEventsPaperBlockInfoResolver;
import games.cubi.raycastedantiesp.paper.utils.PaperScheduler;
@@ -30,7 +32,6 @@ import io.github.retrooper.packetevents.util.SpigotConversionUtil;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.strokkur.commands.*;
import net.strokkur.commands.arguments.IntArg;
import net.strokkur.commands.arguments.StringArg;
import net.strokkur.commands.arguments.StringArgType;
import net.strokkur.commands.paper.Description;
@@ -43,10 +44,6 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Locale;
import java.util.SplittableRandom;
import java.util.UUID;
// Credit to Strokkur for making StrokkCommands, a non-hideous way to use the power of brigadier.
@@ -114,7 +111,7 @@ public class RaycastedAntiESPCommand {
@Executes("check-for-updates")
void checkForUpdatesCommand(CommandSender sender) {
RaycastedAntiESP.checkForUpdates(RaycastedAntiESP.get(), sender);
UpdateChecker.checkForUpdates(RaycastedAntiESP.get(), sender);
}
@Executes("print-block-ids")
@@ -145,7 +142,7 @@ public class RaycastedAntiESPCommand {
assert Attribution.class == Attribution.class;
assert Attribution.READ_COMMENTS_BEFORE_EDITING_OR_DELETING_CLASS_OR_FACE_LEGAL_ACTION == 0; //Using constant from Attribution class to ensure that it cannot be deleted without the developer noticing that they are obligated to replace it with an equivalent notice.
Player player = (Player) sender;
PlayerData playerData = PlayerRegistry.get().getPlayerData(player.getUniqueId());
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
Entity closestEntity = player.getNearbyEntities(10,10,10).getFirst();
if (closestEntity == null) return;
player.sendRichMessage("Closest entity is "+closestEntity.getName());
@@ -161,158 +158,50 @@ public class RaycastedAntiESPCommand {
sender.sendRichMessage("Drift is X: "+driftX+" Z: "+driftZ);
}
@Subcommand("benchmark")
static class BenchmarkCommand {
private static final int BENCHMARK_CORPUS_SIZE = 8192;
private static final int BENCHMARK_CORPUS_MASK = BENCHMARK_CORPUS_SIZE - 1;
private static final int BENCHMARK_BATCH_SIZE = 2048;
private static final int BENCHMARK_WARMUP_BATCHES = 1250;
private static final int BENCHMARK_MEASUREMENT_BATCHES = 512;
private static final int BENCHMARK_ROUNDS = 5;
private static final int DEFAULT_RAYCAST_DISTANCE = 50;
private static final long BENCHMARK_SEED = 0x6a09e667f3bcc909L;
private static volatile long benchmarkSink;
@Executes("benchmark")
void debugCommand(Player player) throws CommandSyntaxException {
//benchmark raycast speed by generating 1000 locatables normally distributed approx 50 blocks around the player and raycasting to them, then printing the average time taken
@DefaultExecutes
void benchmark(Player player) {
benchmark(player, DEFAULT_RAYCAST_DISTANCE);
Locatable[] locatables = new Locatable[10000];
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
Locatable playerLocatable = playerData.ownLocation();
MutableFloatingSpatial unitDirection = new MutableSpatialImpl(0, 0, 0);
for (int i = 0; i < locatables.length; i++) {
unitDirection.setX(Math.random() - 0.5);
unitDirection.setY(Math.random() - 0.5);
unitDirection.setZ(Math.random() - 0.5);
unitDirection.normalise();
unitDirection.scalarMultiply(50);
locatables[i] = new MutableLocatableImpl(playerLocatable.world(), playerLocatable.x(), playerLocatable.y(), playerLocatable.z()).add(unitDirection);
}
@DefaultExecutes
void benchmark(Player player, @IntArg(min = 1, max = Short.MAX_VALUE - 1) int raycastDistance) {
Locatable[] locatables = new Locatable[BENCHMARK_CORPUS_SIZE];
PlayerData playerData = PlayerRegistry.get().getPlayerData(player.getUniqueId());
Locatable currentPlayerLocation = playerData.ownLocation();
Locatable playerLocatable = new MutableLocatableImpl(currentPlayerLocation.world(), currentPlayerLocation.x(), currentPlayerLocation.y(), currentPlayerLocation.z());
MutableFloatingSpatial unitDirection = new MutableSpatialImpl(0, 0, 0);
SplittableRandom random = new SplittableRandom(BENCHMARK_SEED);
for (int i = 0; i < locatables.length; i++) {
unitDirection.setX(random.nextDouble(-0.5, 0.5));
unitDirection.setY(random.nextDouble(-0.5, 0.5));
unitDirection.setZ(random.nextDouble(-0.5, 0.5));
unitDirection.normalise();
unitDirection.scalarMultiply(raycastDistance);
locatables[i] = new MutableLocatableImpl(playerLocatable.world(), playerLocatable.x(), playerLocatable.y(), playerLocatable.z()).add(unitDirection);
}
BlockView blockView = playerData.blockView();
int maxRaycastRadius = Math.max(100, raycastDistance + 1);
int maxRaycastRadiusSquared = maxRaycastRadius * maxRaycastRadius;
player.sendRichMessage("Running deterministic raycast benchmark at distance " + raycastDistance + "...");
Bukkit.getAsyncScheduler().runNow(RaycastedAntiESP.get(), (ignored) -> {
java.lang.management.ThreadMXBean managementBean = ManagementFactory.getThreadMXBean();
com.sun.management.ThreadMXBean allocationBean = managementBean instanceof com.sun.management.ThreadMXBean bean ? bean : null;
if (allocationBean != null && allocationBean.isThreadAllocatedMemorySupported() && !allocationBean.isThreadAllocatedMemoryEnabled()) {
allocationBean.setThreadAllocatedMemoryEnabled(true);
}
long threadId = Thread.currentThread().threadId();
boolean measureAllocations = allocationBean != null && allocationBean.isThreadAllocatedMemoryEnabled();
long warmupChecksum = 0;
int corpusIndex = 0;
for (int batch = 0; batch < BENCHMARK_WARMUP_BATCHES; batch++) {
warmupChecksum += runRaycastBatch(playerLocatable, locatables, corpusIndex, maxRaycastRadiusSquared, blockView);
corpusIndex = (corpusIndex + BENCHMARK_BATCH_SIZE) & BENCHMARK_CORPUS_MASK;
}
benchmarkSink = warmupChecksum;
double[] nanosecondsPerRay = new double[BENCHMARK_ROUNDS];
double[] bytesPerRay = new double[BENCHMARK_ROUNDS];
long[] checksums = new long[BENCHMARK_ROUNDS];
double[] batchNanosecondsPerRay = new double[BENCHMARK_ROUNDS * BENCHMARK_MEASUREMENT_BATCHES];
int invocationsPerRound = BENCHMARK_BATCH_SIZE * BENCHMARK_MEASUREMENT_BATCHES;
int batchSampleIndex = 0;
for (int round = 0; round < BENCHMARK_ROUNDS; round++) {
long allocatedBefore = measureAllocations ? allocationBean.getThreadAllocatedBytes(threadId) : 0;
long startTime = System.nanoTime();
long checksum = 0;
corpusIndex = 0;
for (int batch = 0; batch < BENCHMARK_MEASUREMENT_BATCHES; batch++) {
long batchStartTime = System.nanoTime();
int batchChecksum = runRaycastBatch(playerLocatable, locatables, corpusIndex, maxRaycastRadiusSquared, blockView);
long batchDuration = System.nanoTime() - batchStartTime;
checksum += batchChecksum;
batchNanosecondsPerRay[batchSampleIndex++] = batchDuration / (double) BENCHMARK_BATCH_SIZE;
corpusIndex = (corpusIndex + BENCHMARK_BATCH_SIZE) & BENCHMARK_CORPUS_MASK;
}
long duration = System.nanoTime() - startTime;
long allocated = measureAllocations ? allocationBean.getThreadAllocatedBytes(threadId) - allocatedBefore : 0;
benchmarkSink = checksum;
nanosecondsPerRay[round] = duration / (double) invocationsPerRound;
bytesPerRay[round] = measureAllocations ? allocated / (double) invocationsPerRound : Double.NaN;
checksums[round] = checksum;
}
double[] sortedTimes = nanosecondsPerRay.clone();
Arrays.sort(sortedTimes);
double medianTime = sortedTimes[sortedTimes.length / 2];
double meanTime = mean(nanosecondsPerRay);
double standardDeviation = standardDeviation(nanosecondsPerRay, meanTime);
double coefficientOfVariation = standardDeviation / meanTime * 100.0;
double[] sortedBatchTimes = batchNanosecondsPerRay.clone();
Arrays.sort(sortedBatchTimes);
double batchP50 = percentile(sortedBatchTimes, 0.50);
double batchP90 = percentile(sortedBatchTimes, 0.90);
double batchP95 = percentile(sortedBatchTimes, 0.95);
double batchP99 = percentile(sortedBatchTimes, 0.99);
double batchMax = sortedBatchTimes[sortedBatchTimes.length - 1];
String benchmarkThread = Thread.currentThread().getName() + " (id " + threadId + ")";
PaperScheduler.runForAudience(RaycastedAntiESP.get(), player, () -> {
player.sendRichMessage("Benchmark thread: " + benchmarkThread);
player.sendRichMessage("Warmup rays: " + (BENCHMARK_BATCH_SIZE * BENCHMARK_WARMUP_BATCHES));
for (int round = 0; round < BENCHMARK_ROUNDS; round++) {
String allocationResult = measureAllocations ? String.format(Locale.ROOT, "%.3f B/ray", bytesPerRay[round]) : "allocation unavailable";
player.sendRichMessage(String.format(Locale.ROOT, "Round %d: %.3f ns/ray, %s, checksum %d", round + 1, nanosecondsPerRay[round], allocationResult, checksums[round]));
}
player.sendRichMessage(String.format(Locale.ROOT, "Rounds: median %.3f, mean %.3f, min %.3f, max %.3f ns/ray", medianTime, meanTime, sortedTimes[0], sortedTimes[sortedTimes.length - 1]));
player.sendRichMessage(String.format(Locale.ROOT, "Round deviation: %.3f ns/ray (CV %.2f%%)", standardDeviation, coefficientOfVariation));
player.sendRichMessage(String.format(Locale.ROOT, "Batches (%d rays, %d samples): p50 %.3f, p90 %.3f, p95 %.3f, p99 %.3f, max %.3f ns/ray",
BENCHMARK_BATCH_SIZE, sortedBatchTimes.length, batchP50, batchP90, batchP95, batchP99, batchMax));
});
});
}
private static double mean(double[] values) {
double total = 0;
for (double value : values) total += value;
return total / values.length;
}
private static double standardDeviation(double[] values, double mean) {
double squaredDifferenceTotal = 0;
for (double value : values) {
double difference = value - mean;
squaredDifferenceTotal += difference * difference;
}
return Math.sqrt(squaredDifferenceTotal / values.length);
}
private static double percentile(double[] sortedValues, double percentile) {
double index = (sortedValues.length - 1) * percentile;
int lowerIndex = (int) index;
int upperIndex = Math.min(lowerIndex + 1, sortedValues.length - 1);
double fraction = index - lowerIndex;
return sortedValues[lowerIndex] + (sortedValues[upperIndex] - sortedValues[lowerIndex]) * fraction;
}
private static int runRaycastBatch(Locatable start, Locatable[] targets, int startIndex, int maxRaycastRadiusSquared, BlockView blockView) {
Bukkit.getAsyncScheduler().runNow(RaycastedAntiESP.get(), (ignored) -> {
int successfulRays = 0;
for (int offset = 0; offset < BENCHMARK_BATCH_SIZE; offset++) {
if (RaycastUtil.raycastUnrolledAccumulated(3, 0, maxRaycastRadiusSquared, false, 0f, blockView, start, targets[startIndex + offset], null)) successfulRays++;
long startTime = System.nanoTime();
for (Locatable locatable : locatables) {
if (RaycastUtil.raycast(playerLocatable, locatable, 3, 0, 100, false, playerData.blockView(), 1, null)) successfulRays++;
}
return successfulRays;
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
double averageTime = duration / (double) locatables.length;
final int successfulRaysFinal = successfulRays;
PaperScheduler.runForAudience(RaycastedAntiESP.get(), player, () -> {
player.sendRichMessage("Average raycast time: " + averageTime + " nanoseconds");
player.sendRichMessage("Total raycast time: " + duration + " nanoseconds");
player.sendRichMessage("Successful rays: " + successfulRaysFinal + "/" + locatables.length);
});
});
}
@Executes("loaded-chunks")
void loadedChunksCommand(Player player) {
PlayerData playerData = PlayerRegistry.get().getPlayerData(player.getUniqueId());
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
AbstractBlockView<?, ?> pbsm = (AbstractBlockView<?, ?>) playerData.blockView();
player.sendMessage(pbsm.loadedChunkCount() +"chunks loaded");
}
@Executes("entity-id")
void getFromEntityID(int entityID, Player player) {
PlayerData playerData = PlayerRegistry.get().getPlayerData(player.getUniqueId());
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
if (playerData == null) {
player.sendRichMessage("<red>No player data is registered for " + describeViewer(player.getUniqueId()) + ".");
return;
@@ -336,7 +225,7 @@ public class RaycastedAntiESPCommand {
void getFromEntityID(int entityID, CommandSender sender) {
sender.sendRichMessage("<white>Searching all connected player views for entity ID " + entityID + ":");
int matches = 0;
for (PlayerData playerData : PlayerRegistry.get().getPlayerDataArray()) {
for (PlayerData playerData : PlayerRegistry.getInstance().getAllPlayerData()) {
if (!playerData.isConnected()) {
continue;
}
@@ -355,7 +244,7 @@ public class RaycastedAntiESPCommand {
}
void getFromUUID(UUID entityUUID, CommandSender sender) {
int matches = 0;
for (PlayerData playerData : PlayerRegistry.get().getPlayerDataArray()) {
for (PlayerData playerData : PlayerRegistry.getInstance().getAllPlayerData()) {
if (!playerData.isConnected()) {
continue;
}
@@ -429,7 +318,7 @@ public class RaycastedAntiESPCommand {
public void helpCommand(@NotNull CommandSender sender) {
sender.sendRichMessage("<white>Test subcommands:");
sender.sendRichMessage("<green>/raycastedantiesp test location-drift <gray>- Tests the drift between Bukkit and PacketEvents entity locations");
sender.sendRichMessage("<green>/raycastedantiesp test benchmark <player> [distance] <gray>- Benchmarks deterministic rays at the requested distance (default 50)");
sender.sendRichMessage("<green>/raycastedantiesp test benchmark <gray>- Benchmarks raycast speed by raycasting to 1000 random locatables around the player and printing the average time taken");
sender.sendRichMessage("<green>/raycastedantiesp test loaded-chunks <gray>- Shows the number of chunks currently loaded in the player's block view");
sender.sendRichMessage("<green>/raycastedantiesp test entity-id <entity ID> [player] <gray>- Finds an entity by ID in one player's views, or in all player views when no player is supplied");
sender.sendRichMessage("<green>/raycastedantiesp test entity-uuid <entity> <gray>- Shows Bukkit data and all tracked view data for a native entity selection or UUID");
@@ -9,7 +9,7 @@
package games.cubi.raycastedantiesp.paper.engine;
import games.cubi.raycastedantiesp.core.config.ConfigManager;
import games.cubi.raycastedantiesp.core.AsyncRunner;
import games.cubi.raycastedantiesp.core.engine.AsyncRunner;
import games.cubi.raycastedantiesp.core.engine.AsyncEngine;
import games.cubi.raycastedantiesp.paper.PaperParticleSpawner;
import games.cubi.raycastedantiesp.paper.RaycastedAntiESP;
@@ -69,8 +69,7 @@ public class PacketEventsPaperBlockInfoResolver implements BlockInfoResolver {
run = false;
continue;
}
Material material = blockData.getMaterial();
if (material == Material.AIR) {
if (blockData.getMaterial() == Material.AIR) {
airs++;
if (airs > 80000) { // There is a sequence of ~40 air blocks around ID 100, and another of several hundred at ~3000. We scan forwards 80k to future-proof any mojank. Since it runs once at startup, perf is irrelevant here
run = false;
@@ -80,12 +79,12 @@ public class PacketEventsPaperBlockInfoResolver implements BlockInfoResolver {
else {
airs = 0;
lastNonAirID = iterator;
if (materialToIDMode) {
Logger.info(blockData.getAsString() + iterator,1);
}
}
boolean occluding = material != Material.BARRIER && material.isOccluding();
if (materialToIDMode && material != Material.AIR) {
Logger.info(blockData.getAsString() + iterator + occluding,1);
}
occlusion.put(iterator, occluding);
occlusion.put(iterator, blockData.getMaterial().isOccluding());
try {
if (blockData.createBlockState() instanceof TileState) {
//Logger.debug("tile at" + iterator + " is tile entity" + material.name());
@@ -12,6 +12,7 @@ import com.destroystokyo.paper.event.server.ServerTickStartEvent;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.Ticker;
import games.cubi.raycastedantiesp.core.engine.AsyncEngine;
import games.cubi.raycastedantiesp.core.engine.AsyncRunner;
import games.cubi.raycastedantiesp.core.utils.VarHandler;
import games.cubi.raycastedantiesp.paper.EventListener;
import games.cubi.raycastedantiesp.paper.RaycastedAntiESP;
@@ -21,6 +22,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import java.lang.invoke.VarHandle;
import java.util.function.IntSupplier;
public class PaperTicker extends PaperListener implements Ticker {
private volatile int currentTick; private static final VarHandle CURRENT_TICK = VarHandler.get(PaperTicker.class, "currentTick", int.class);
@@ -6,7 +6,7 @@
* See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core;
package games.cubi.raycastedantiesp.paper;
import games.cubi.raycastedantiesp.core.utils.BuildProperties.Version;
import org.junit.jupiter.api.Test;
-165
View File
@@ -1,165 +0,0 @@
import java.time.Instant
import org.gradle.jvm.toolchain.JavaToolchainService
plugins {
id("java-library")
id("com.gradleup.shadow") version "9.4.0"
id("xyz.jpenilla.run-paper")
}
repositories {
mavenCentral()
maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/")
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
maven { url = uri("https://repo.codemc.io/repository/maven-snapshots/") }
maven { url = uri("https://eldonexus.de/repository/maven-public/") }
}
dependencies {
compileOnly("org.spigotmc:spigot-api:1.21.2-R0.1-SNAPSHOT")
compileOnly("com.github.retrooper:packetevents-spigot:2.12.0")
compileOnly("org.spongepowered:configurate-core:4.2.0")
compileOnly("org.spongepowered:configurate-yaml:4.2.0")
implementation("org.jetbrains:annotations:24.0.1")
implementation("org.bstats:bstats-bukkit:3.2.1")
implementation(project(":leafpile"))
implementation(project(":locatables"))
implementation(project(":logging"))
implementation(project(":core"))
implementation(project(":packetevents"))
testImplementation(platform("org.junit:junit-bom:5.10.2"))
testImplementation("org.junit.jupiter:junit-jupiter-api")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
configurations.named("testRuntimeClasspath") {
exclude(group = "at.yawk.lz4", module = "lz4-java")
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(21)
}
val javaToolchainService = project.extensions.getByType(JavaToolchainService::class.java)
group = "games.cubi.raycastedantiesp.spigot"
val platformPaperVersion: String = "0.0.1-SNAPSHOT"
val coreVersion = project(":core").version.toString()
val commitShort = providers.exec {
commandLine("git", "rev-parse", "--short=8", "HEAD")
}.standardOutput.asText.map { it.trim() }
val commitFull = providers.exec {
commandLine("git", "rev-parse", "HEAD")
}.standardOutput.asText.map { it.trim() }
val buildTime = providers.provider {
Instant.now().toString().replace(":", "-") // Replace colons to avoid issues in file names on some platforms
}
val isRelease = gradle.startParameter.taskNames.any {
it.contains("buildSpigotRelease")
}
fun getVersionString(): String {
if (isRelease) {
val paperVersion = platformPaperVersion.substringBefore("-") // Remove any suffixes like "-SNAPSHOT"
return "${coreVersion}-Spigot-${paperVersion}-RELEASE"
} else {
return "${coreVersion}-Spigot-${platformPaperVersion}+build-${buildTime.get()}+git-${commitShort.get()}"
}
}
fun getBasicVersionString(): String {
return if (isRelease) {
platformPaperVersion.substringBefore("-") // Remove any suffixes like "-SNAPSHOT"
} else {
platformPaperVersion
}
}
version = getVersionString()
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.
javaLauncher = javaToolchainService.launcherFor {
//languageVersion.set(paperRunJavaVersion.map(JavaLanguageVersion::of))
languageVersion.set(JavaLanguageVersion.of(25))
}
minecraftVersion("26.1.2")
//minecraftVersion("1.21.11")
jvmArgs("-Xms4G", "-Xmx4G", "-Dcom.mojang.eula.agree=true")
}
processResources {
val props = mapOf("version" to version.toString())
inputs.properties(props)
filesMatching("plugin.yml") {
expand(props)
}
val gitProps = mapOf(
"short_git" to commitShort.get(),
"long_git" to commitFull.get(),
"build_time" to buildTime.get(),
"version" to getBasicVersionString()
)
inputs.properties(gitProps)
filesMatching("build-properties/platform.yml") {
expand(gitProps)
}
}
test {
useJUnitPlatform()
}
}
tasks.shadowJar {
dependencies {
include(project(":logging"))
include(project(":locatables"))
include(project(":core"))
include(project(":packetevents"))
include(project(":leafpile"))
include(dependency("org.bstats:bstats-base:3.2.1"))
include(dependency("org.bstats:bstats-bukkit:3.2.1"))
}
relocate(
"ca.spottedleaf",
"games.cubi.libs.raycastedantiesp.spottedleaf"
)
relocate(
"org.bstats",
"games.cubi.libs.raycastedantiesp.bstats"
)
minimize {} // get rid of leafpile bloat
archiveBaseName.set("RaycastedAntiESP")
archiveClassifier.set("")
}
tasks.jar {
archiveBaseName.set("Incorrectly-Compiled-Without-ShadowJar")
}
// This is the task to run to test if changes to the plugin are working
tasks.register("buildSpigotSnapshot") {
group = "raycasted anti-esp" //Not caps sensitive so using spacing and hyphen
description = "Builds a snapshot version of the plugin with git and build-time metadata included in the file name."
dependsOn("shadowJar")
}
tasks.register("buildSpigotRelease") {
group = "raycasted anti-esp"
description = "Builds a release version of the plugin with a clean version number (no git or build-time metadata) included in the file name."
dependsOn("shadowJar")
}
@@ -1,16 +0,0 @@
package games.cubi.raycastedantiesp.spigot;
import org.bukkit.plugin.java.JavaPlugin;
public final class RaycastedAntiESP extends JavaPlugin {
@Override
public void onEnable() {
// Plugin startup logic
}
@Override
public void onDisable() {
// Plugin shutdown logic
}
}
@@ -1,9 +0,0 @@
name: RaycastedAntiESP
prefix: RaycastedAntiESP
version: '$version'
main: games.cubi.raycastedantiesp.spigot.RaycastedAntiESP
api-version: '1.21'
load: STARTUP
authors: [_Cubicake]
+62
View File
@@ -0,0 +1,62 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP.
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
* See README.md for warranty disclaimer and further information.
*/
plugins {
id 'java'
id("xyz.jpenilla.run-velocity") version "3.0.2"
}
group = 'games.cubi'
version = '0.0.1-SNAPSHOT'
repositories {
mavenCentral()
maven {
name = "papermc-repo"
url = "https://repo.papermc.io/repository/maven-public/"
}
}
dependencies {
compileOnly("com.velocitypowered:velocity-api:3.5.0-SNAPSHOT")
annotationProcessor("com.velocitypowered:velocity-api:3.5.0-SNAPSHOT")
}
tasks {
runVelocity {
// Configure the Velocity 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.
velocityVersion("3.5.0-SNAPSHOT")
}
}
def targetJavaVersion = 21
java {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
options.release.set(targetJavaVersion)
}
def templateSource = file('src/main/templates')
def templateDest = layout.buildDirectory.dir('generated/sources/templates')
def generateTemplates = tasks.register('generateTemplates', Copy) { task ->
def props = [
'version': project.version
]
task.inputs.properties props
task.from templateSource
task.into templateDest
task.expand props
}
sourceSets.main.java.srcDir(generateTemplates)
+8
View File
@@ -0,0 +1,8 @@
#
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright © 2026 Cubicake.
# This file is part of RaycastedAntiESP.
# RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
# See README.md for warranty disclaimer and further information.
#
@@ -0,0 +1,9 @@
#
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright © 2026 Cubicake.
# This file is part of RaycastedAntiESP.
# RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
# See README.md for warranty disclaimer and further information.
#
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
+9
View File
@@ -0,0 +1,9 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP.
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
* See README.md for warranty disclaimer and further information.
*/
rootProject.name = 'platform-velocity'
@@ -0,0 +1,32 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP.
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
* See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.velocity;
import com.google.inject.Inject;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.plugin.Plugin;
import org.slf4j.Logger;
@Plugin(
id = "raycastedantiesp",
name = "RaycastedAntiESP",
version = BuildConstants.VERSION,
description = "Packet-based Anti-ESP plugin",
url = "https://cubi.games",
authors = {"_Cubicake"}
)
public class VeloRaycastedAntiESP {
@Inject private Logger logger;
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
}
}
@@ -0,0 +1,15 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP.
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
* See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.velocity;
// The constants are replaced before compilation
public class BuildConstants {
public static final String VERSION = "${version}";
}
+9 -1
View File
@@ -1,3 +1,11 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP.
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
* See README.md for warranty disclaimer and further information.
*/
rootProject.name = 'RaycastedAntiESP'
dependencyResolutionManagement {
versionCatalogs {
@@ -11,6 +19,6 @@ include 'locatables'
include 'logging'
include 'core'
include 'platform-paper'
include 'platform-spigot'
include 'packetevents'
include 'leafpile'
include 'platform-velocity'