Initial commit

This commit is contained in:
2022-09-17 10:49:36 +02:00
parent 1e8420a83e
commit 59a6e1c423
368 changed files with 26176 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
package eu.mhsl.minenet.minigames.util;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.instance.batch.AbsoluteBlockBatch;
import net.minestom.server.instance.batch.ChunkBatch;
import net.minestom.server.utils.chunk.ChunkUtils;
import java.lang.reflect.Field;
public class BatchUtil {
public static long[] getAffectedChunks(AbsoluteBlockBatch batch) {
try {
Field field = batch.getClass().getDeclaredField("chunkBatchesMap");
field.setAccessible(true);
@SuppressWarnings("unchecked")
Long2ObjectMap<ChunkBatch> chunkBatchesMap = (Long2ObjectMap<ChunkBatch>) field.get(batch);
return chunkBatchesMap.keySet().toLongArray();
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void loadAndApplyBatch(AbsoluteBlockBatch batch, InstanceContainer instance, Runnable onFinish) {
batch.awaitReady();
long[] affectedChunks = BatchUtil.getAffectedChunks(batch);
ChunkUtils.optionalLoadAll(instance, affectedChunks, null).thenRun(() -> batch.apply(instance, onFinish));
}
}

View File

@@ -0,0 +1,15 @@
package eu.mhsl.minenet.minigames.util;
import net.kyori.adventure.text.format.NamedTextColor;
public class ColorUtil {
public static NamedTextColor scoreColor(int score) {
switch (score) {
case 1: return NamedTextColor.GOLD;
case 2: return NamedTextColor.GREEN;
case 3: return NamedTextColor.DARK_GREEN;
}
return NamedTextColor.GRAY;
}
}

View File

@@ -0,0 +1,17 @@
package eu.mhsl.minenet.minigames.util;
import net.minestom.server.event.trait.CancellableEvent;
public class CommonEventHandles {
/**
* Cancels the given Event
* @param event
*/
public static void cancel(CancellableEvent event) {
event.setCancelled(true);
}
public static void cancel(CancellableEvent event, boolean condition) {
event.setCancelled(condition);
}
}

View File

@@ -0,0 +1,27 @@
package eu.mhsl.minenet.minigames.util;
import eu.mhsl.minenet.minigames.world.generator.BlockPallet;
import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.block.Block;
public class Intersect {
public static boolean withPressurePlate(Instance instance, BlockPallet target, Pos playerPosition) {
Pos[] corners = {
playerPosition.add(0.3-Position.PIXEL, 0, 0.3-Position.PIXEL),
playerPosition.add(0.3-Position.PIXEL, 0, -0.3+Position.PIXEL),
playerPosition.add(-0.3+Position.PIXEL, 0, 0.3-Position.PIXEL),
playerPosition.add(-0.3+Position.PIXEL, 0, -0.3+Position.PIXEL)
};
for(Pos coroner : corners) {
Block pressed = instance.getBlock(coroner);
if(target.contains(pressed) && playerPosition.y() < playerPosition.blockY() + Position.PIXEL)
return true;
}
return false;
}
}

View File

@@ -0,0 +1,26 @@
package eu.mhsl.minenet.minigames.util;
import net.minestom.server.MinecraftServer;
import net.minestom.server.event.server.ServerTickMonitorEvent;
import net.minestom.server.monitoring.TickMonitor;
import java.util.concurrent.atomic.AtomicReference;
public class Monitoring {
private static final Runtime runtime = Runtime.getRuntime();
private static final AtomicReference<TickMonitor> lastTick = new AtomicReference<>();
static {
MinecraftServer.getGlobalEventHandler().addListener(ServerTickMonitorEvent .class, event -> lastTick.set(event.getTickMonitor()));
}
public static long getRamUsage() {
return (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
}
public static TickMonitor getTickMonitor() {
return lastTick.get() != null ? lastTick.get() : new TickMonitor(0, 0);
}
}

View File

@@ -0,0 +1,27 @@
package eu.mhsl.minenet.minigames.util;
import eu.mhsl.minenet.minigames.instance.Spawnable;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.Player;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.timer.TaskSchedule;
import java.util.Set;
public class MoveInstance {
public static void move(Set<Player> playerList, Spawnable destination) {
playerList.forEach(player -> move(player, destination));
}
public static void move(Entity p, Spawnable destination) {
p.setInstance((Instance) destination, destination.getSpawn());
}
public static void forceCloseInstance(InstanceContainer instance) {
instance.scheduler().scheduleTask(() -> {
instance.getPlayers().forEach(player -> player.kick("you exceeded the switch timeout while an instance got closed"));
MinecraftServer.getInstanceManager().unregisterInstance(instance);
}, TaskSchedule.seconds(10), TaskSchedule.stop());
}
}

View File

@@ -0,0 +1,5 @@
package eu.mhsl.minenet.minigames.util;
public class Position {
public static final double PIXEL = 0.0625;
}

View File

@@ -0,0 +1,11 @@
package eu.mhsl.minenet.minigames.util;
public class RangeMap {
public static double map(double oldValue, double oldMin, double oldMax, double newMin, double newMax) {
double out = (((oldValue - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin;
if(out > newMax) out = newMax;
if(out < newMin) out = newMin;
return out;
}
}

View File

@@ -0,0 +1,61 @@
package eu.mhsl.minenet.minigames.util;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
/**
* Class from the Minestom Arena example
*/
public final class ResourceUtils {
public static void extractResource(String source) throws URISyntaxException, IOException {
final URI uri = Objects.requireNonNull(ResourceUtils.class.getResource("/" + source)).toURI();
FileSystem fileSystem = null;
// Only create a new filesystem if it's a jar file
// (People can run this from their IDE too)
if (uri.toString().startsWith("jar:"))
fileSystem = FileSystems.newFileSystem(uri, Map.of("create", "true"));
try {
final Path jarPath = Paths.get(uri);
final Path target = Path.of("resources/" + source);
if (Files.exists(target)) {
try (Stream<Path> pathStream = Files.walk(target)) {
pathStream.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
Files.walkFileTree(jarPath, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
Path currentTarget = target.resolve(jarPath.relativize(dir).toString());
Files.createDirectories(currentTarget);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
final Path to = target.resolve(jarPath.relativize(file).toString());
Files.copy(file, to, StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
});
} finally {
if (fileSystem != null)
fileSystem.close();
}
}
}

View File

@@ -0,0 +1,5 @@
package eu.mhsl.minenet.minigames.util;
public abstract class Static {
public abstract void load(); //TODO REMOVE
}

View File

@@ -0,0 +1,134 @@
package eu.mhsl.minenet.minigames.util;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextUtil {
public static Component autoWrap(String input, NamedTextColor color) {
System.out.println(wrap(input, 30, "\n", true, "-", " ")); //TODO not working
return Component.text(wrap(input, 30, "\n", true, "-", " "), color);
}
public static Component autoWrap(String input) {
return autoWrap(input, NamedTextColor.WHITE);
}
/**
* Wraps a source String into a series of lines having a maximum specified length. The source is
* wrapped at: spaces, horizontal tabs, system newLine characters, or a specified newLine character
* sequence. Existing newLine character sequences in the source string, whether they be the system
* newLine or the specified newLine, are honored. Existing whitespace (spaces and horizontal tabs)
* is preserved.
* <p>
* When <tt>wrapLongWords</tt> is true, words having a length greater than the specified
* <tt>lineLength</tt> will be broken, the specified <tt>longWordBreak</tt> terminator appended,
* and a new line initiated with the text of the specified <tt>longWordLinePrefix</tt> string. The
* position of the break will be unceremoniously chosen such that <tt>ineLength</tt> is honored.
* One use of <tt>longWordLinePrefix</tt> is to effect "hanging indents" by specifying a series of
* spaces for this parameter. This parameter can contain the lineFeed character(s). Although
* <tt>longWordLinePrefix</tt> can contain the horizontal tab character, the results are not
* guaranteed because no attempt is made to determine the quantity of character positions occupied by a
* horizontal tab.</p>
* <p>
* Example usage:
* <pre>
* wrap( " A very long word is Abracadabra in my book", 11, "\n", true, "-", " ");</pre>
* returns (note the effect of the single-character lineFeed):
* <pre>
* A very
* long word
* is Abraca-
* dabra in
* my book</pre>
* Whereas, the following:
* <pre>
* wrap( " A very long word is Abracadabra in my book", 11, null, true, null, " ");</pre>
* returns (due to the 2-character system linefeed):
* <pre>
* A very
* long
* word is A
* bracada
* bra in
* my book</pre></p>
*
* @param src the String to be word wrapped, may be null
* @param lineLength the maximum line length, including the length of <tt>newLineStr</tt> and, when
* applicable, <tt>longWordLinePrefix</tt>. If the value is insufficient to accommodate
* these two parameters + 1 character, it will be increased accordingly.
* @param newLineStr the string to insert for a new line, or <code>null</code> to use the value
* reported as the system line separator by the JVM
* @param wrapLongWords when <tt>false</tt>, words longer than <tt>wrapLength</t> will not be broken
* @param longWordBreak string with which to precede <tt>newLineStr</tt> on each line of a broken word,
* excepting the last line, or <tt>null</tt> if this feature is not to be used
* @param longWordLinePrefix string with which to prefix each line of a broken word, subsequent
* to the first line, or <tt>null</tt> if no prefix is to be used
* @return a line with newlines inserted, or <code>null</code> if <tt>src</tt> is null
*/
private static String wrap(String src, int lineLength, String newLineStr, boolean wrapLongWords, String longWordBreak, String longWordLinePrefix) {
// Trivial case
if ( src == null ) return null;
if ( newLineStr == null )
newLineStr = System.getProperty( "line.separator" );
if ( longWordBreak == null )
longWordBreak = "";
if ( longWordLinePrefix == null )
longWordLinePrefix = "";
// Adjust maximum line length to accommodate the newLine string
lineLength -= newLineStr.length();
if ( lineLength < 1 )
lineLength = 1;
// Guard for long word break or prefix that would create an infinite loop
if ( wrapLongWords && lineLength - longWordBreak.length() - longWordLinePrefix.length() < 1 )
lineLength += longWordBreak.length() + longWordLinePrefix.length();
int
remaining = lineLength,
breakLength = longWordBreak.length();
Matcher m = Pattern.compile( ".+?[ \\t]|.+?mis" + newLineStr + "singValue|.+?$" ).matcher( src );
StringBuilder cache = new StringBuilder();
while ( m.find() ) {
String word = m.group();
// Breakup long word
while ( wrapLongWords && word.length() > lineLength ) {
cache
.append(word, 0, remaining - breakLength)
.append( longWordBreak )
.append( newLineStr );
word = longWordLinePrefix + word.substring( remaining - breakLength );
remaining = lineLength;
} // if
// Linefeed if word exceeds remaining space
if ( word.length() > remaining ) {
cache
.append( newLineStr )
.append( word );
remaining = lineLength;
} // if
// Word fits in remaining space
else
cache.append( word );
remaining -= word.length();
} // while
return cache.toString();
} // wrap()
}

View File

@@ -0,0 +1,18 @@
package eu.mhsl.minenet.minigames.util;
import java.util.UUID;
public class UuidUtil {
public static UUID unTrimm(String trimmedUuid) {
StringBuilder builder = new StringBuilder(trimmedUuid.trim());
try {
builder.insert(20, "-");
builder.insert(16, "-");
builder.insert(12, "-");
builder.insert(8, "-");
} catch (StringIndexOutOfBoundsException e) {
throw new IllegalArgumentException();
}
return UUID.fromString(builder.toString());
}
}