Javadoc and Formatting fixes. (#619)

Javadoc and Formatting fixes.

Also, extremely minor code changes which have been tested.
This commit is only part one of two commits that aim to fix problems with formatting in our project. In part two I will modify the Google Java Style Guide (since it closely matches our code style) for our project so there is guidance on how to format and document. 

* Updated PlotSquared URL
* Removed plugin acronyms
* Fixed a typo
* Fixed grammar
* Use modern block id's
* Update YouTube video URL
This commit is contained in:
Matt
2020-10-05 13:41:41 -04:00
committed by GitHub
parent b06d943f7c
commit 96dcb95b7c
393 changed files with 6537 additions and 4700 deletions

View File

@ -79,70 +79,57 @@ public class Fawe {
private static final Logger log = LoggerFactory.getLogger(Fawe.class);
/**
* The FAWE instance;
*/
private static Fawe INSTANCE;
private static Fawe instance;
/**
* TPS timer
* The ticks-per-second timer.
*/
private final FaweTimer timer;
private FaweVersion version;
private VisualQueue visualQueue;
private TextureUtil textures;
// TODO: Ping @MattBDev to reimplement 2020-02-04
// private DefaultTransformParser transformParser;
private QueueHandler queueHandler;
/**
* Get the implementation specific class
*
* @return
* Get the implementation specific class.
*/
@SuppressWarnings("unchecked")
public static <T extends IFawe> T imp() {
return INSTANCE != null ? (T) INSTANCE.IMP : null;
return instance != null ? (T) instance.implementation : null;
}
/**
* Get the implementation independent class
*
* @return
* Get the implementation independent class.
*/
public static Fawe get() {
return INSTANCE;
return instance;
}
/**
* Setup Fawe
*
* @param implementation
* @throws InstanceAlreadyExistsException
* This method is not for public use. If you have to ask what it does then you shouldn't be using it.
*/
public static void set(final IFawe implementation) throws InstanceAlreadyExistsException, IllegalArgumentException {
if (INSTANCE != null) {
throw new InstanceAlreadyExistsException("FAWE has already been initialized with: " + INSTANCE.IMP);
if (instance != null) {
throw new InstanceAlreadyExistsException("FAWE has already been initialized with: " + instance.implementation);
}
if (implementation == null) {
throw new IllegalArgumentException("Implementation may not be null.");
}
INSTANCE = new Fawe(implementation);
instance = new Fawe(implementation);
}
public static void debugPlain(String s) {
if (INSTANCE != null) {
INSTANCE.IMP.debug(s);
if (instance != null) {
instance.implementation.debug(s);
} else {
System.out.println(s);
log.debug(s);
}
}
/**
* Write something to the console
*
* @param s
* Write something to the console.
*/
public static void debug(String s) {
Actor actor = Request.request().getActor();
@ -152,9 +139,9 @@ public class Fawe {
}
debugPlain(s);
}
/**
* Write something to the console
* Write something to the console.
*
* @param c The Component to be printed
*/
@ -168,24 +155,26 @@ public class Fawe {
}
/**
* The platform specific implementation
* The platform specific implementation.
*/
private final IFawe IMP;
private final IFawe implementation;
private Thread thread;
private Fawe(final IFawe implementation) {
INSTANCE = this;
this.IMP = implementation;
instance = this;
this.implementation = implementation;
this.thread = Thread.currentThread();
/*
* Implementation dependent stuff
*/
this.setupConfigs();
TaskManager.IMP = this.IMP.getTaskManager();
TaskManager.IMP = this.implementation.getTaskManager();
TaskManager.IMP.async(() -> {
MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.HISTORY), TimeUnit.DAYS.toMillis(Settings.IMP.HISTORY.DELETE_AFTER_DAYS), false);
MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.CLIPBOARD), TimeUnit.DAYS.toMillis(Settings.IMP.CLIPBOARD.DELETE_AFTER_DAYS), false);
MainUtil.deleteOlder(MainUtil.getFile(this.implementation
.getDirectory(), Settings.IMP.PATHS.HISTORY), TimeUnit.DAYS.toMillis(Settings.IMP.HISTORY.DELETE_AFTER_DAYS), false);
MainUtil.deleteOlder(MainUtil.getFile(this.implementation
.getDirectory(), Settings.IMP.PATHS.CLIPBOARD), TimeUnit.DAYS.toMillis(Settings.IMP.CLIPBOARD.DELETE_AFTER_DAYS), false);
});
/*
@ -197,11 +186,10 @@ public class Fawe {
// Delayed worldedit setup
TaskManager.IMP.later(() -> {
try {
// TODO: Ping @MattBDev to reimplement 2020-02-04
// transformParser = new DefaultTransformParser(getWorldEdit());
visualQueue = new VisualQueue(3);
WEManager.IMP.managers.addAll(Fawe.this.IMP.getMaskManagers());
} catch (Throwable ignored) {}
WEManager.IMP.managers.addAll(Fawe.this.implementation.getMaskManagers());
} catch (Throwable ignored) {
}
}, 0);
TaskManager.IMP.repeat(timer, 1);
@ -214,17 +202,12 @@ public class Fawe {
if (queueHandler == null) {
synchronized (this) {
if (queueHandler == null) {
queueHandler = IMP.getQueueHandler();
queueHandler = implementation.getQueueHandler();
}
}
}
return queueHandler;
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// public DefaultTransformParser getTransformParser() {
// return transformParser;
// }
public TextureUtil getCachedTextureUtil(boolean randomize, int min, int max) {
// TODO NOT IMPLEMENTED - optimize this by caching the default true/0/100 texture util
@ -257,32 +240,27 @@ public class Fawe {
}
/**
* The FaweTimer is a useful class for monitoring TPS
*
* @return FaweTimer
* Gets the TPS monitor.
*/
public FaweTimer getTimer() {
return timer;
}
/**
* The visual queue is used to queue visualizations
*
* @return
* Get the visual queue.
*/
public VisualQueue getVisualQueue() {
return visualQueue;
}
/**
* The FAWE version
* - Unofficial jars may be lacking version information
* The FAWE version.
*
* @apiNote Unofficial jars may be lacking version information
* @return FaweVersion
*/
public
@Nullable
FaweVersion getVersion() {
public FaweVersion getVersion() {
return version;
}
@ -293,8 +271,8 @@ public class Fawe {
public void setupConfigs() {
MainUtil.copyFile(MainUtil.getJarFile(), "lang/strings.json", null);
// Setting up config.yml
File file = new File(this.IMP.getDirectory(), "config.yml");
Settings.IMP.PLATFORM = IMP.getPlatform().replace("\"", "");
File file = new File(this.implementation.getDirectory(), "config.yml");
Settings.IMP.PLATFORM = implementation.getPlatform().replace("\"", "");
try (InputStream stream = getClass().getResourceAsStream(File.separator + "fawe.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(stream))) {
String versionString = br.readLine();
@ -305,14 +283,12 @@ public class Fawe {
Settings.IMP.DATE = new Date(100 + version.year, version.month, version.day).toGMTString();
Settings.IMP.BUILD = "https://ci.athion.net/job/FastAsyncWorldEdit-1.16/" + version.build;
Settings.IMP.COMMIT = "https://github.com/IntellectualSites/FastAsyncWorldEdit/commit/" + Integer.toHexString(version.hash);
} catch (Throwable ignore) {}
} catch (Throwable ignored) {
}
try {
Settings.IMP.reload(file);
} catch (Throwable e) {
debug("====== Failed to load config ======");
debug("Please validate your yaml files:");
e.printStackTrace();
debug("====================================");
log.error("Failed to load config.", e);
}
}
@ -334,22 +310,15 @@ public class Fawe {
if (Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL > 6 || Settings.IMP.HISTORY.COMPRESSION_LEVEL > 6) {
Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL = Math.min(6, Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL);
Settings.IMP.HISTORY.COMPRESSION_LEVEL = Math.min(6, Settings.IMP.HISTORY.COMPRESSION_LEVEL);
debug("====== ZSTD COMPRESSION BINDING NOT FOUND ======");
debug(e.getMessage());
debug("FAWE will work but won't compress data as much");
debug("===============================================");
log.error("ZSTD Compression Binding Not Found.\n"
+ "FAWE will still work but compression won't work as well.\n", e);
}
}
try {
net.jpountz.util.Native.load();
} catch (Throwable e) {
e.printStackTrace();
debug("====== LZ4 COMPRESSION BINDING NOT FOUND ======");
debug(e.getMessage());
debug("FAWE will work but compression will be slower");
debug(" - Try updating your JVM / OS");
debug(" - Report this issue if you cannot resolve it");
debug("===============================================");
log.error("LZ4 Compression Binding Not Found.\n"
+ "FAWE will still work but compression will be slower.\n", e);
}
}
@ -402,22 +371,18 @@ public class Fawe {
}
/**
* Get the main thread
*
* @return
* Get the main thread.
*/
public Thread getMainThread() {
return this.thread;
}
public static boolean isMainThread() {
return INSTANCE == null || INSTANCE.thread == Thread.currentThread();
return instance == null || instance.thread == Thread.currentThread();
}
/**
* Sets the main thread to the current thread
*
* @return
* Sets the main thread to the current thread.
*/
public Thread setMainThread() {
return this.thread = Thread.currentThread();

View File

@ -55,19 +55,20 @@ import javax.annotation.Nullable;
* FaweAPI.[some method]
*/
public class FaweAPI {
/**
* Offers a lot of options for building an EditSession
* Offers a lot of options for building an EditSession.
*
* @param world
* @return A new EditSessionBuilder
* @see EditSessionBuilder
*/
@Deprecated
public static EditSessionBuilder getEditSessionBuilder(World world) {
return new EditSessionBuilder(world);
}
/**
* The TaskManager has some useful methods for doing things asynchronously
* The TaskManager has some useful methods for doing things asynchronously.
*
* @return TaskManager
*/
@ -75,26 +76,15 @@ public class FaweAPI {
return TaskManager.IMP;
}
// /**
// * Add a custom transform for use in
// *
// * @param methods The class with a bunch of transform methods
// * @return true if the transform was registered
// * @see com.sk89q.worldedit.command.TransformCommands
// */
// public static boolean registerTransforms(Object methods) {
// DefaultTransformParser parser = Fawe.get().getTransformParser();
// if (parser != null) parser.register(methods);
// return parser != null;
// }
/**
* You can either use a IQueueExtent or an EditSession to change blocks<br>
* - The IQueueExtent skips a bit of overhead so it's marginally faster<br>
* - The WorldEdit EditSession can do a lot more<br>
* Remember to commit when you're done!<br>
* You can either use a {@code IQueueExtent} or an {@code EditSession} to change blocks.
*
* @param world The name of the world
* <p>
* The {@link IQueueExtent} skips a bit of overhead, so it is marginally faster. {@link
* EditSession} can do a lot more. Remember to commit when you are done!
* </p>
*
* @param world The name of the world
* @param autoQueue If it should start dispatching before you enqueue it.
* @return the queue extent
*/
@ -118,10 +108,10 @@ public class FaweAPI {
}
/**
* Upload the clipboard to the configured web interface
* Upload the clipboard to the configured web interface.
*
* @param clipboard The clipboard (may not be null)
* @param format The format to use (some formats may not be supported)
* @param format The format to use (some formats may not be supported)
* @return The download URL or null
*/
public static URL upload(final Clipboard clipboard, final ClipboardFormat format) {
@ -129,7 +119,7 @@ public class FaweAPI {
}
/**
* Just forwards to ClipboardFormat.SCHEMATIC.load(file)
* Just forwards to ClipboardFormat.SCHEMATIC.load(file).
*
* @param file the file to load
* @return a clipboard containing the schematic
@ -149,7 +139,7 @@ public class FaweAPI {
}
/**
* Check if the server has more than the configured low memory threshold
* Check if the server has more than the configured low memory threshold.
*
* @return True if the server has limited memory
*/
@ -158,28 +148,26 @@ public class FaweAPI {
}
/**
* Get a player's allowed WorldEdit region
*
* @param player
* @return
* Get a player's allowed WorldEdit region.
*/
public static Region[] getRegions(Player player) {
return WEManager.IMP.getMask(player);
}
/**
* Cancel the edit with the following extent<br>
* - The extent must be the one being used by an EditSession, otherwise an error may be thrown <br>
* - Insert an extent into the EditSession using the EditSessionEvent: http://wiki.sk89q.com/wiki/WorldEdit/API/Hooking_EditSession <br>
* Cancel the edit with the following extent.
*
* @param extent
* @param reason
* @see EditSession#getRegionExtent() To get the FaweExtent for an EditSession
* <p>
* The extent must be the one being used by an EditSession, otherwise an error will be thrown.
* Insert an extent into the EditSession using the EditSessionEvent.
* </p>
*
* @see EditSession#getRegionExtent() How to get the FaweExtent for an EditSession
*/
public static void cancelEdit(AbstractDelegateExtent extent, Component reason) {
try {
WEManager.IMP.cancelEdit(extent, new FaweException(reason));
} catch (WorldEditException ignore) {
} catch (WorldEditException ignored) {
}
}
@ -188,10 +176,7 @@ public class FaweAPI {
}
/**
* Get the DiskStorageHistory object representing a File
*
* @param file
* @return
* Get the DiskStorageHistory object representing a File.
*/
public static DiskStorageHistory getChangeSetFromFile(File file) {
if (!file.exists() || file.isDirectory()) {
@ -200,7 +185,7 @@ public class FaweAPI {
if (Settings.IMP.HISTORY.USE_DISK) {
throw new IllegalArgumentException("History on disk not enabled!");
}
if (!file.getName().toLowerCase().endsWith(".bd")) {
if (!file.getName().toLowerCase(Locale.ROOT).endsWith(".bd")) {
throw new IllegalArgumentException("Not a BD file!");
}
String[] path = file.getPath().split(File.separator);
@ -223,16 +208,18 @@ public class FaweAPI {
}
/**
* Used in the RollBack to generate a list of DiskStorageHistory objects<br>
* - Note: An edit outside the radius may be included if it overlaps with an edit inside that depends on it.
* Used in the rollback to generate a list of {@link DiskStorageHistory} objects.
*
* @param origin - The origin location
* @param user - The uuid (may be null)
* @param radius - The radius from the origin of the edit
* @param origin - The origin location
* @param user - The uuid (may be null)
* @param radius - The radius from the origin of the edit
* @param timediff - The max age of the file in milliseconds
* @param shallow - If shallow is true, FAWE will only read the first Settings.IMP.BUFFER_SIZE bytes to obtain history info<br>
* Reading only part of the file will result in unreliable bounds info for large edits
* @param shallow - If shallow is true, FAWE will only read the first {@link
* Settings.HISTORY#BUFFER_SIZE} bytes to obtain history info
* @return a list of DiskStorageHistory Objects
* @apiNote An edit outside the radius may be included if it overlaps with an edit inside
* that depends on it. Reading only part of the file will result in unreliable bounds info
* for large edits.
*/
public static List<DiskStorageHistory> getBDFiles(Location origin, UUID user, int radius, long timediff, boolean shallow) {
Extent extent = origin.getExtent();
@ -312,35 +299,19 @@ public class FaweAPI {
/**
* The DiskStorageHistory class is what FAWE uses to represent the undo on disk.
*
* @param world
* @param uuid
* @param index
* @return
* @see DiskStorageHistory#toEditSession(Player)
*/
public static DiskStorageHistory getChangeSetFromDisk(World world, UUID uuid, int index) {
return new DiskStorageHistory(world, uuid, index);
}
/**
* Compare two versions
* Fix the lighting in a selection. This is a multi-step process as outlined below.
*
* @param version
* @param major
* @param minor
* @param minor2
* @return true if version is >= major, minor, minor2
*/
public static boolean checkVersion(final int[] version, final int major, final int minor, final int minor2) {
return (version[0] > major) || ((version[0] == major) && (version[1] > minor)) || ((version[0] == major) && (version[1] == minor) && (version[2] >= minor2));
}
/**
* Fix the lighting in a selection<br>
* - First removes all lighting, then relights
* - Relights in parallel (if enabled) for best performance<br>
* - Also resends chunks<br>
* <ol>
* <li>Removes all lighting, then relights.</li>
* <li>Relights in parallel (if enabled) for best performance.</li>
* <li>Resends the chunks to the client.</li>
* </ol>
*
* @param world World to relight in
* @param selection Region to relight
@ -395,26 +366,19 @@ public class FaweAPI {
}
/**
* Have a task run when the server is low on memory (configured threshold)
*
* @param run
* Runs a task when the server is low on memory.
*/
public static void addMemoryLimitedTask(Runnable run) {
MemUtil.addMemoryLimitedTask(run);
}
/**
* Have a task run when the server is no longer low on memory (configured threshold)
*
* @param run
* Runs a task when the server is no longer low on memory.
*/
public static void addMemoryPlentifulTask(Runnable run) {
MemUtil.addMemoryPlentifulTask(run);
}
/**
* @return Map of translation ket to value
*/
public static Map<String, String> getTranslations(Locale locale) {
return WorldEdit.getInstance().getTranslationManager().getTranslationMap(locale);
}

View File

@ -312,8 +312,6 @@ public enum FaweCache implements Trimable {
/**
* Convert raw int array to unstretched palette (1.16)
* @param layerOffset
* @param blocks
* @return palette
*/
public Palette toPaletteUnstretched(int layerOffset, int[] blocks) {
@ -518,7 +516,9 @@ public enum FaweCache implements Trimable {
}
list.add(tag);
}
if (clazz == null) clazz = EndTag.class;
if (clazz == null) {
clazz = EndTag.class;
}
return new ListTag(clazz, list);
}
@ -532,7 +532,9 @@ public enum FaweCache implements Trimable {
}
list.add(tag);
}
if (clazz == null) clazz = EndTag.class;
if (clazz == null) {
clazz = EndTag.class;
}
return new ListTag(clazz, list);
}
@ -543,9 +545,9 @@ public enum FaweCache implements Trimable {
int nThreads = Settings.IMP.QUEUE.PARALLEL_THREADS;
ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(nThreads);
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS, queue
, Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
0L, TimeUnit.MILLISECONDS, queue,
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
protected void afterExecute(Runnable r, Throwable t) {
try {
super.afterExecute(r, t);

View File

@ -1,7 +1,11 @@
package com.boydti.fawe;
public class FaweVersion {
public final int year, month, day, hash, build;
public final int year;
public final int month;
public final int day;
public final int hash;
public final int build;
public FaweVersion(int year, int month, int day, int hash, int build) {
this.year = year;

View File

@ -18,8 +18,8 @@ public class CombinedBlocks implements IBlocks {
private final int addMask;
/**
* @param secondary
* @param primary
* TODO Add a constructor here to satisfy checkstyle.
*
* @param addMask - bitMask for force sending sections, else 0 to send the primary ones
*/
public CombinedBlocks(IBlocks secondary, IBlocks primary, int addMask) {
@ -92,11 +92,15 @@ public class CombinedBlocks implements IBlocks {
BlockVector3 pos = entry.getKey();
BlockState block = primary.getBlock(pos.getX(), pos.getY(), pos.getZ());
if (block.getBlockType() == BlockTypes.__RESERVED__) {
if (copy == null) copy = new HashMap<>(tiles);
if (copy == null) {
copy = new HashMap<>(tiles);
}
copy.put(pos, entry.getValue());
}
}
if (copy != null) return copy;
if (copy != null) {
return copy;
}
}
}
return tiles;
@ -116,8 +120,12 @@ public class CombinedBlocks implements IBlocks {
Set<CompoundTag> joined = primary.getEntities();
if (primary != secondary) {
Set<CompoundTag> ents2 = secondary.getEntities();
if (joined.isEmpty()) return ents2;
if (ents2.isEmpty()) return joined;
if (joined.isEmpty()) {
return ents2;
}
if (ents2.isEmpty()) {
return joined;
}
joined = new HashSet<>(joined);
joined.addAll(ents2);
}

View File

@ -15,12 +15,9 @@ import java.util.concurrent.Future;
import java.util.function.Function;
public interface IBatchProcessor {
/**
* Process a chunk that has been set
* @param chunk
* @param get
* @param set
* @return
* Process a chunk that has been set.
*/
IChunkSet processSet(IChunk chunk, IChunkGet get, IChunkSet set);
@ -31,18 +28,13 @@ public interface IBatchProcessor {
}
/**
* Convert this processor into an Extent based processor instead of a queue batch based on
* @param child
* @return
* Convert this processor into an Extent based processor instead of a queue batch based on.
*/
@Nullable
Extent construct(Extent child);
/**
* Utility method to trim a chunk based on min and max Y
* @param set
* @param minY
* @param maxY
* Utility method to trim a chunk based on min and max Y.
* @return false if chunk is empty of blocks
*/
default boolean trimY(IChunkSet set, int minY, int maxY) {
@ -52,7 +44,9 @@ public interface IBatchProcessor {
if (layer == minLayer) {
char[] arr = set.load(layer);
int index = (minY & 15) << 8;
for (int i = 0; i < index; i++) arr[i] = 0;
for (int i = 0; i < index; i++) {
arr[i] = 0;
}
set.setBlocks(layer, arr);
} else {
set.setBlocks(layer, null);
@ -65,7 +59,9 @@ public interface IBatchProcessor {
if (layer == minLayer) {
char[] arr = set.load(layer);
int index = ((maxY + 1) & 15) << 8;
for (int i = index; i < arr.length; i++) arr[i] = 0;
for (int i = index; i < arr.length; i++) {
arr[i] = 0;
}
set.setBlocks(layer, arr);
} else {
set.setBlocks(layer, null);
@ -91,9 +87,8 @@ public interface IBatchProcessor {
}
/**
* Utility method to trim entity and blocks with a provided contains function
* @param set
* @param contains
* Utility method to trim entity and blocks with a provided contains function.
*
* @return false if chunk is empty of NBT
*/
default boolean trimNBT(IChunkSet set, Function<BlockVector3, Boolean> contains) {
@ -110,9 +105,7 @@ public interface IBatchProcessor {
}
/**
* Join two processors and return the result
* @param other
* @return
* Join two processors and return the result.
*/
default IBatchProcessor join(IBatchProcessor other) {
return MultiBatchProcessor.of(this, other);
@ -122,13 +115,11 @@ public interface IBatchProcessor {
return MultiBatchProcessor.of(this, other);
}
default void flush() {}
default void flush() {
}
/**
* Return a new processor after removing all are instances of a specified class
* @param clazz
* @param <T>
* @return
* Return a new processor after removing all are instances of a specified class.
*/
default <T extends IBatchProcessor> IBatchProcessor remove(Class<T> clazz) {
if (clazz.isInstance(this)) {

View File

@ -19,7 +19,7 @@ import java.util.Set;
import java.util.stream.IntStream;
/**
* A shared interface for IGetBlocks and ISetBlocks
* A shared interface for IGetBlocks and ISetBlocks.
*/
public interface IBlocks extends Trimable {

View File

@ -75,16 +75,16 @@ public interface IChunkSet extends IBlocks, OutputExtent {
}
// Default to avoid tricky child classes. We only need it in a few cases anyway.
default void setFastMode(boolean fastMode){}
default void setFastMode(boolean fastMode) {}
default boolean isFastMode() {
return false;
}
// Allow setting for bitmask for flushing lighting. Default to avoid tricky child classes.
default void setBitMask(int bitMask){}
default void setBitMask(int bitMask) {}
default int getBitMask(){
default int getBitMask() {
return -1;
}

View File

@ -49,16 +49,16 @@ public interface IQueueExtent<T extends IChunk> extends Flushable, Trimable, ICh
void init(Extent extent, IChunkCache<IChunkGet> get, IChunkCache<IChunkSet> set);
/**
* Get the cached get object
* - Faster than getting it using NMS and allows for wrapping
* @param x
* @param z
* Get the cached get object. This is faster than getting the object using NMS and allows for
* wrapping.
* @param chunkX
* @param chunkZ
* @return
*/
IChunkGet getCachedGet(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 15) int z);
IChunkGet getCachedGet(@Range(from = 0, to = 15) int chunkX, @Range(from = 0, to = 15) int chunkZ);
/**
* Get the cached chunk set object
* Get the cached chunk set object.
* @param chunkX
* @param chunkZ
* @return
@ -88,19 +88,18 @@ public interface IQueueExtent<T extends IChunk> extends Flushable, Trimable, ICh
boolean isFastMode();
/**
* Create a new root IChunk object<br> - Full chunks will be reused, so a more optimized chunk
* can be returned in that case<br> - Don't wrap the chunk, that should be done in {@link
* #wrap(T)}
* Create a new root IChunk object. Full chunks will be reused, so a more optimized chunk can be
* returned in that case.
*
* @apiNote Don't wrap the chunk, that should be done in {@link IQueueExtent#wrap(IChunk)}
* @param isFull true if a more optimized chunk should be returned
* @return a more optimized chunk object
*/
T create(boolean isFull);
/**
* Wrap the chunk object (i.e., for region restrictions / limits etc.)
* Wrap the chunk object (i.e., for region restrictions / limits etc.).
*
* @param root
* @return wrapped chunk
*/
default T wrap(T root) {
@ -115,15 +114,15 @@ public interface IQueueExtent<T extends IChunk> extends Flushable, Trimable, ICh
}
/**
* Flush all changes to the world - Best to call this async so it doesn't hang the server
* Flush all changes to the world.
* @apiNote Best to call this async, so it doesn't hang the server.
*/
@Override
void flush();
/**
* A filter block is used to iterate over blocks / positions
* - Essentially combines BlockVector3, Extent and BlockState functions in a way that avoids lookups
* @return
* A filter block is used to iterate over blocks / positions. Essentially combines BlockVector3,
* Extent and BlockState functions in a way that avoids lookups.
*/
ChunkFilterBlock initFilterBlock();

View File

@ -1,19 +1,20 @@
package com.boydti.fawe.beta;
/**
* Interface for objects that can be trimmed (memory related)<br> - Trimming will reduce its memory
* footprint
* Interface for objects that can be trimmed (memory related). Trimming will reduce its memory
* footprint.
*/
public interface Trimable {
/**
* Trims the object, reducing its memory footprint
* Trims the object, reducing its memory footprint.
*
* @param aggressive if trimming should be aggressive e.g., Not return early when the first
* @param aggressive if trimming should be aggressive e.g., Not returning early when the first
* element cannot be trimmed
* @return if this object is empty at the end of the trim, and can therefore be deleted
*/
boolean trim(boolean aggressive);
default void recycle() {}
default void recycle() {
}
}

View File

@ -68,19 +68,33 @@ public class BitSetBlocks implements IChunkSet {
return false;
}
@Override public void setBlockLight(int x, int y, int z, int value) {}
@Override
public void setBlockLight(int x, int y, int z, int value) {
}
@Override public void setSkyLight(int x, int y, int z, int value) {}
@Override
public void setSkyLight(int x, int y, int z, int value) {
}
@Override public void setHeightMap(HeightMapType type, int[] heightMap) {}
@Override
public void setHeightMap(HeightMapType type, int[] heightMap) {
}
@Override public void setLightLayer(int layer, char[] toSet) {}
@Override
public void setLightLayer(int layer, char[] toSet) {
}
@Override public void setSkyLightLayer(int layer, char[] toSet) {}
@Override
public void setSkyLightLayer(int layer, char[] toSet) {
}
@Override public void removeSectionLighting(int layer, boolean sky) {}
@Override
public void removeSectionLighting(int layer, boolean sky) {
}
@Override public void setFullBright(int layer) {}
@Override
public void setFullBright(int layer) {
}
@Override
public void setEntity(CompoundTag tag) {
@ -134,11 +148,13 @@ public class BitSetBlocks implements IChunkSet {
return null;
}
@Override public char[][] getLight() {
@Override
public char[][] getLight() {
return new char[0][];
}
@Override public char[][] getSkyLight() {
@Override
public char[][] getSkyLight() {
return new char[0][];
}

View File

@ -139,7 +139,7 @@ public abstract class CharBlocks implements IBlocks {
sections[layer].set(this, layer, index, value);
}
public static abstract class Section {
public abstract static class Section {
public abstract char[] get(CharBlocks blocks, @Range(from = 0, to = 15) int layer);

View File

@ -24,6 +24,7 @@ import java.util.stream.IntStream;
public class CharSetBlocks extends CharBlocks implements IChunkSet {
private static final Pool<CharSetBlocks> POOL = FaweCache.IMP.registerPool(CharSetBlocks.class, CharSetBlocks::new, Settings.IMP.QUEUE.POOL);
public static CharSetBlocks newInstance() {
return POOL.poll();
}
@ -38,7 +39,8 @@ public class CharSetBlocks extends CharBlocks implements IChunkSet {
private boolean fastMode = false;
private int bitMask = -1;
private CharSetBlocks() {}
private CharSetBlocks() {
}
@Override
public void recycle() {
@ -52,7 +54,9 @@ public class CharSetBlocks extends CharBlocks implements IChunkSet {
@Override
public BiomeType getBiomeType(int x, int y, int z) {
if (biomes == null) return null;
if (biomes == null) {
return null;
}
return biomes[(z << 4) | x];
}
@ -213,7 +217,7 @@ public class CharSetBlocks extends CharBlocks implements IChunkSet {
@Override
public boolean setBiome(BlockVector3 position, BiomeType biome) {
return setBiome(position.getX(),position.getY(), position.getZ(), biome);
return setBiome(position.getX(), position.getY(), position.getZ(), biome);
}
@Override

View File

@ -24,7 +24,8 @@ import java.util.UUID;
import java.util.concurrent.Future;
public class FallbackChunkGet implements IChunkGet {
private final int bx, bz;
private final int bx;
private final int bz;
private final Extent extent;
public FallbackChunkGet(Extent extent, int chunkX, int chunkZ) {
@ -32,6 +33,7 @@ public class FallbackChunkGet implements IChunkGet {
this.bx = chunkX << 4;
this.bz = chunkZ << 4;
}
@Override
public BaseBlock getFullBlock(int x, int y, int z) {
return extent.getFullBlock(bx + x, y, bz + z);

View File

@ -20,7 +20,7 @@ public class ChunkCache<T extends Trimable> implements IChunkCache<T> {
}
/**
* Get or create the IGetBlocks
* Get or create the IGetBlocks.
*
* @return cached IGetBlocks
*/

View File

@ -45,7 +45,9 @@ public class AsyncPreloader implements Preloader, Runnable {
@Override
public void update(Player player) {
LocalSession session = WorldEdit.getInstance().getSessionManager().getIfPresent(player);
if (session == null) return;
if (session == null) {
return;
}
World world = player.getWorld();
MutablePair<World, Set<BlockVector2>> existing = cancelAndGet(player);
try {
@ -67,7 +69,8 @@ public class AsyncPreloader implements Preloader, Runnable {
update.notify();
}
}
} catch (IncompleteRegionException ignore){}
} catch (IncompleteRegionException ignored) {
}
}
@Override

View File

@ -28,7 +28,7 @@ import java.util.UUID;
import java.util.concurrent.Future;
/**
* An abstract {@link IChunk} class that implements basic get/set blocks
* An abstract {@link IChunk} class that implements basic get/set blocks.
*/
@SuppressWarnings("rawtypes")
public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
@ -189,7 +189,7 @@ public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
}
@Override
public void setFullBright(ChunkHolder chunk, int layer){
public void setFullBright(ChunkHolder chunk, int layer) {
chunk.chunkSet.setFullBright(layer);
}
@ -317,7 +317,7 @@ public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
}
@Override
public void setFullBright(ChunkHolder chunk, int layer){
public void setFullBright(ChunkHolder chunk, int layer) {
chunk.getOrCreateSet();
chunk.delegate = BOTH;
chunk.setFullBright(layer);
@ -425,7 +425,7 @@ public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
}
@Override
public void setFullBright(ChunkHolder chunk, int layer){
public void setFullBright(ChunkHolder chunk, int layer) {
chunk.chunkSet.setFullBright(layer);
}
@ -603,7 +603,7 @@ public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
}
@Override
public void setFullBright(ChunkHolder chunk, int layer){
public void setFullBright(ChunkHolder chunk, int layer) {
chunk.getOrCreateSet();
chunk.delegate = SET;
chunk.setFullBright(layer);
@ -812,7 +812,7 @@ public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
}
/**
* Get the extent this chunk is in
* Get the extent this chunk is in.
*/
public IQueueExtent<? extends IChunk> getExtent() {
return extent;
@ -911,6 +911,7 @@ public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
public interface IBlockDelegate {
<C extends Future<C>> IChunkGet get(ChunkHolder<C> chunk);
IChunkSet set(ChunkHolder chunk);
boolean setBiome(ChunkHolder chunk, int x, int y, int z, BiomeType biome);

View File

@ -14,12 +14,12 @@ public final class LinkedFilter<T extends Filter, S extends Filter> extends Dele
private final S child;
public LinkedFilter(T parent, S child){
public LinkedFilter(T parent, S child) {
super(parent);
this.child = child;
}
public S getChild(){
public S getChild() {
return this.child;
}

View File

@ -56,7 +56,7 @@ public class MaskFilter<T extends Filter> extends DelegateFilter<T> {
*
* @return number of blocks which passed the Mask test and were applied to
*/
public int getBlocksApplied(){
public int getBlocksApplied() {
return this.changes.get();
}

View File

@ -54,11 +54,6 @@ public abstract class AbstractFilterBlock extends FilterBlock {
return getFullBlock().toBlockState();
}
@Override
public void setBlock(BlockState state) {
setFullBlock(state.toBaseBlock(getBlock().getNbtData()));
}
@Override
public CompoundTag getNbtData() {
return getFullBlock().getNbtData();
@ -79,6 +74,11 @@ public abstract class AbstractFilterBlock extends FilterBlock {
return BlockVector3.at(getX(), getY(), getZ());
}
@Override
public void setBlock(BlockState state) {
setFullBlock(state.toBaseBlock(getBlock().getNbtData()));
}
@Override
public <T extends BlockStateHolder<T>> boolean setBlock(int x, int y, int z, T block)
throws WorldEditException {

View File

@ -16,8 +16,11 @@ public class ArrayFilterBlock extends AbstractExtentFilterBlock {
private final char[] blocks;
private final byte[] heights;
private final int yOffset;
private final int width, length;
private int x, z, index;
private final int width;
private final int length;
private int x;
private int z;
private int index;
public ArrayFilterBlock(Extent extent, char[] blocks, byte[] heights, int width, int length,
int yOffset) {
@ -51,11 +54,6 @@ public class ArrayFilterBlock extends AbstractExtentFilterBlock {
return BlockTypesCache.states[getOrdinal()];
}
@Override
public void setBlock(BlockState state) {
blocks[index] = state.getOrdinalChar();
}
@Override
public BaseBlock getFullBlock() {
return getBlock().toBaseBlock();
@ -90,14 +88,19 @@ public class ArrayFilterBlock extends AbstractExtentFilterBlock {
return z;
}
@Override
public void setBlock(BlockState state) {
blocks[index] = state.getOrdinalChar();
}
@Override
public <T extends BlockStateHolder<T>> boolean setBlock(int x, int y, int z, T block)
throws WorldEditException {
return getExtent().setBlock(x,y, z, block);
return getExtent().setBlock(x, y, z, block);
}
@Override
public boolean setBiome(int x, int y, int z, BiomeType biome) {
return getExtent().setBiome(x,y, z,biome);
return getExtent().setBiome(x, y, z, biome);
}
}

View File

@ -34,10 +34,20 @@ public class CharFilterBlock extends ChunkFilterBlock {
private CharGetBlocks get;
private IChunkSet set;
private char[] getArr;
private @Nullable char[] setArr;
@Nullable
private char[] setArr;
private SetDelegate delegate;
// local
private int layer, index, x, y, z, xx, yy, zz, chunkX, chunkZ;
private int layer;
private int index;
private int x;
private int y;
private int z;
private int xx;
private int yy;
private int zz;
private int chunkX;
private int chunkZ;
public CharFilterBlock(Extent extent) {
super(extent);
@ -107,8 +117,8 @@ public class CharFilterBlock extends ChunkFilterBlock {
}
@Override
public void filter(Filter filter, int yStart, int yEnd) {
for (y = yStart, index = yStart << 8; y <= yEnd; y++) {
public void filter(Filter filter, int startY, int endY) {
for (y = startY, index = startY << 8; y <= endY; y++) {
for (z = 0; z < 16; z++) {
for (x = 0; x < 16; x++, index++) {
filter.applyBlock(this);

View File

@ -23,21 +23,12 @@ public abstract class ChunkFilterBlock extends AbstractExtentFilterBlock {
}
/**
* Initialize with chunk coordinates
* - The layer must also be initialized
* @param chunkX
* @param chunkZ
* @return
* Initialize with chunk coordinates. The layer must also be initialized.
*/
public abstract ChunkFilterBlock initChunk(int chunkX, int chunkZ);
/**
* Initialize a chunk layer
* - The chunk coordinates must also be initialized first
* @param iget
* @param iset
* @param layer
* @return
* Initialize a chunk layer. the Chunk coordinates need to be initialized first.
*/
public abstract ChunkFilterBlock initLayer(IBlocks iget, IChunkSet iset, int layer);
@ -46,55 +37,33 @@ public abstract class ChunkFilterBlock extends AbstractExtentFilterBlock {
/**
* Filter a single block
* @param filter
* @param x
* @param y
* @param z
* Filter a single block.
*/
public abstract void filter(Filter filter, int x, int y, int z);
/**
* Filter a cuboid region
* @param filter
* @param minX
* @param minY
* @param minZ
* @param maxX
* @param maxY
* @param maxZ
* Filter a cuboid region.
*/
public abstract void filter(Filter filter, int minX, int minY, int minZ, int maxX, int maxY,
int maxZ);
/**
* Filter everything in the layer
* @param filter
* Filter everything in the layer.
*/
public abstract void filter(Filter filter);
/**
* Filter everything between y layers
* @param filter
* @param yStart
* @param yEnd
* Filter everything between y layers.
*/
public abstract void filter(Filter filter, int yStart, int yEnd);
public abstract void filter(Filter filter, int startY, int endY);
/**
* Filter with a region
* @param filter
* @param region
* Filter with a region.
*/
public abstract void filter(Filter filter, Region region);
/**
* Filter with a chunk object
* @param chunk
* @param get
* @param set
* @param filter
* @return
* Filter with a chunk object.
*/
public final IChunkSet filter(IChunk chunk, IChunkGet get, IChunkSet set, Filter filter) {
initChunk(chunk.getX(), chunk.getZ());
@ -108,14 +77,7 @@ public abstract class ChunkFilterBlock extends AbstractExtentFilterBlock {
}
/**
* Filter a chunk with a region / filter
* @param chunk
* @param get
* @param set
* @param filter
* @param region
* @param full
* @return
* Filter a chunk with a region / filter.
*/
public final IChunkSet filter(IChunk chunk, IChunkGet get, IChunkSet set, Filter filter, Region region, boolean full) {
if (region != null) {

View File

@ -4,7 +4,9 @@ import com.sk89q.worldedit.world.block.BaseBlock;
public class SingleFilterBlock extends AbstractSingleFilterBlock {
private int x, y, z;
private int x;
private int y;
private int z;
public SingleFilterBlock init(int x, int y, int z, BaseBlock block) {
this.x = x;

View File

@ -28,6 +28,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
@ -281,7 +282,7 @@ public class NMSRelighter implements Relighter {
}
int lightLevel = iChunk.getEmmittedLight(node.getX() & 15, node.getY(), node.getZ() & 15);
BlockState state = this.queue.getBlock(node.getX(), node.getY(), node.getZ());
String id = state.getBlockType().getId().toLowerCase();
String id = state.getBlockType().getId().toLowerCase(Locale.ROOT);
if (lightLevel <= 1) {
continue;
}
@ -319,7 +320,7 @@ public class NMSRelighter implements Relighter {
if (!(checkStairEast(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) {
break east;
}
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
this.computeSpreadBlockLight(x + 1, y, z, currentLight, queue, visited);
break east;
}
@ -370,7 +371,7 @@ public class NMSRelighter implements Relighter {
if (!(checkStairWest(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) {
break west;
}
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
this.computeSpreadBlockLight(x - 1, y, z, currentLight, queue, visited);
break west;
}
@ -421,7 +422,7 @@ public class NMSRelighter implements Relighter {
if (!(checkStairSouth(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) {
break south;
}
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
this.computeSpreadBlockLight(x, y, z + 1, currentLight, queue, visited);
break south;
}
@ -472,7 +473,7 @@ public class NMSRelighter implements Relighter {
if (!(checkStairNorth(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) {
break north;
}
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
this.computeSpreadBlockLight(x, y, z - 1, currentLight, queue, visited);
break north;
}
@ -611,7 +612,7 @@ public class NMSRelighter implements Relighter {
}
private boolean checkStairNorth(BlockState state) {
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
return true;
}
Direction direction = getStairDir(state);
@ -629,7 +630,7 @@ public class NMSRelighter implements Relighter {
}
private boolean checkStairSouth(BlockState state) {
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
return true;
}
Direction direction = getStairDir(state);
@ -647,7 +648,7 @@ public class NMSRelighter implements Relighter {
}
private boolean checkStairEast(BlockState state) {
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
return true;
}
Direction direction = getStairDir(state);
@ -665,7 +666,7 @@ public class NMSRelighter implements Relighter {
}
private boolean checkStairWest(BlockState state) {
if (!state.getBlockType().getId().toLowerCase().contains("stair")) {
if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) {
return true;
}
Direction direction = getStairDir(state);
@ -687,7 +688,7 @@ public class NMSRelighter implements Relighter {
}
private String getStairShape(BlockState state) {
return state.getState(stairShape).toLowerCase();
return state.getState(stairShape).toLowerCase(Locale.ROOT);
}
private boolean isStairOrTrueTop(BlockState state, boolean top) {
@ -784,8 +785,9 @@ public class NMSRelighter implements Relighter {
public void fixBlockLighting() {
synchronized (lightQueue) {
while (!lightLock.compareAndSet(false, true))
while (!lightLock.compareAndSet(false, true)) {
;
}
try {
updateBlockLight(this.lightQueue);
} finally {

View File

@ -3,7 +3,7 @@ package com.boydti.fawe.beta.implementation.lighting;
public interface Relighter {
/**
* Add a chunk to be relit when {@link Relighter#removeLighting} etc are called
* Add a chunk to be relit when {@link Relighter#removeLighting} etc are called.
*
* @param cx chunk x
* @param cz chunk z
@ -14,7 +14,7 @@ public interface Relighter {
boolean addChunk(int cx, int cz, byte[] skipReason, int bitmask);
/**
* Add a block to be relit
* Add a block to be relit.
*
* @param x block x
* @param y block y
@ -23,14 +23,14 @@ public interface Relighter {
void addLightUpdate(int x, int y, int z);
/**
* Safely? Fix block lighting
* Safely? Fix block lighting.
*
* @param sky whether to also relight sky light values
*/
void fixLightingSafe(boolean sky);
/**
* Remove lighting and then relight safely
* Remove lighting and then relight safely.
*
* @param sky whether to also relight sky light values
*/
@ -40,33 +40,33 @@ public interface Relighter {
}
/**
* Clear all chunks and blocks to be relit
* Clear all chunks and blocks to be relit.
*/
void clear();
/**
* Remove all block and sky light values (set to 0 light) in all chunks added to relighter
* Remove all block and sky light values (set to 0 light) in all chunks added to relighter.
*/
void removeLighting();
/**
* Fix block light values in all chunks added to relighter
* Fix block light values in all chunks added to relighter.
*/
void fixBlockLighting();
/**
* Fix sky light values in all chunks added to relighter
* Fix sky light values in all chunks added to relighter.
*/
void fixSkyLighting();
/**
* Are there any block or chunk added to be relit
* Are there any block or chunk added to be relit.
*
* @return is the relight stuff to be relit empty
*/
boolean isEmpty();
public static class SkipReason {
class SkipReason {
public static final byte NONE = 0;
public static final byte AIR = 1;
public static final byte SOLID = 2;

View File

@ -116,8 +116,8 @@ public class ChunkPacket implements Function<byte[], byte[]>, Supplier<byte[]> {
fos.writeVarInt(sectionBytes.length);
fos.write(sectionBytes);
// TODO entities / NBT
// Set<CompoundTag> entities = chunk.getEntities();
// Map<BlockVector3, CompoundTag> tiles = chunk.getTiles();
//Set<CompoundTag> entities = chunk.getEntities();
//Map<BlockVector3, CompoundTag> tiles = chunk.getTiles();
fos.writeVarInt(0); // (Entities / NBT)
return baos.toByteArray();
} catch (Throwable e) {

View File

@ -573,7 +573,9 @@ public class LimitExtent extends AbstractDelegateExtent {
@Deprecated
public <T extends BlockStateHolder<T>> boolean setBlock(BlockVector3 position, T block) throws WorldEditException {
limit.THROW_MAX_CHANGES();
if (block.hasNbtData()) limit.MAX_BLOCKSTATES();
if (block.hasNbtData()) {
limit.MAX_BLOCKSTATES();
}
try {
return super.setBlock(position, block);
} catch (FaweException e) {
@ -587,7 +589,9 @@ public class LimitExtent extends AbstractDelegateExtent {
@Override
public <T extends BlockStateHolder<T>> boolean setBlock(int x, int y, int z, T block) throws WorldEditException {
limit.THROW_MAX_CHANGES();
if (block.hasNbtData()) limit.MAX_BLOCKSTATES();
if (block.hasNbtData()) {
limit.MAX_BLOCKSTATES();
}
try {
return super.setBlock(x, y, z, block);
} catch (FaweException e) {

View File

@ -33,7 +33,7 @@ public class MultiBatchProcessor implements IBatchProcessor {
for (IBatchProcessor processor : processors) {
if (processor instanceof MultiBatchProcessor) {
list.addAll(Arrays.asList(((MultiBatchProcessor) processor).processors));
} else if (!(processor instanceof EmptyBatchProcessor)){
} else if (!(processor instanceof EmptyBatchProcessor)) {
list.add(processor);
}
}
@ -154,7 +154,9 @@ public class MultiBatchProcessor implements IBatchProcessor {
@Override
public void flush() {
for (IBatchProcessor processor : this.processors) processor.flush();
for (IBatchProcessor processor : this.processors) {
processor.flush();
}
}
@Override

View File

@ -44,7 +44,9 @@ public class PersistentChunkSendProcessor extends ChunkSendProcessor {
current.put(pair, (Character) bitMask);
if (previous != null) {
Character lastValue = previous.remove(pair);
if (lastValue != null) bitMask |= lastValue;
if (lastValue != null) {
bitMask |= lastValue;
}
}
}
return new CombinedBlocks(get, set, bitMask);
@ -56,7 +58,9 @@ public class PersistentChunkSendProcessor extends ChunkSendProcessor {
}
public void clear() {
if (queue == null) throw new IllegalStateException("Queue is not provided");
if (queue == null) {
throw new IllegalStateException("Queue is not provided");
}
clear(current);
current.clear();
queue = null;

View File

@ -106,7 +106,8 @@ public class ParallelQueueExtent extends PassthroughExtent implements IQueueWrap
while (true) {
// Get the next chunk posWeakChunk
final int chunkX, chunkZ;
final int chunkX;
final int chunkZ;
synchronized (chunksIter) {
if (!chunksIter.hasNext()) {
break;

View File

@ -21,7 +21,9 @@ public class QueuePool<T> extends ConcurrentLinkedQueue<T> implements Pool<T> {
@Override
public void clear() {
if (!isEmpty()) super.clear();
if (!isEmpty()) {
super.clear();
}
}
}

View File

@ -100,7 +100,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
* Resets the queue.
*/
protected synchronized void reset() {
if (!this.initialized) return;
if (!this.initialized) {
return;
}
if (!this.chunks.isEmpty()) {
for (IChunk chunk : this.chunks.values()) {
chunk.recycle();
@ -175,9 +177,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
if (Fawe.isMainThread()) {
V result = (V)chunk.call();
if (result == null){
if (result == null) {
return (V) (Future) Futures.immediateFuture(null);
}else{
} else {
return result;
}
}
@ -285,7 +287,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
while (!submissions.isEmpty()) {
Future future = submissions.poll();
try {
while (future != null) future = (Future) future.get();
while (future != null) {
future = (Future) future.get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
@ -294,7 +298,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
for (int i = 0; i < overflow; i++) {
Future first = submissions.poll();
try {
while (first != null) first = (Future) first.get();
while (first != null) {
first = (Future) first.get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}

View File

@ -158,13 +158,15 @@ public class AnvilCommands {
name = "deleteallunvisited",
aliases = {"delunvisited" },
desc = "Delete all chunks which haven't been occupied",
descFooter = "occupied for `age-ticks` (20t = 1s) and \n" +
"Have not been accessed since `file-duration` (ms) after creation and\n" +
"Have not been used in the past `chunk-inactivity` (ms)" +
"The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
descFooter = "occupied for `age-ticks` (20t = 1s) and \n"
+ "Have not been accessed since `file-duration` (ms) after creation and\n"
+ "Have not been used in the past `chunk-inactivity` (ms)"
+ "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
)
@CommandPermissions("worldedit.anvil.deleteallunvisited")
public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks, @Arg(desc = "int", def = "60000") int fileDurationMillis) throws WorldEditException {
public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks,
@Arg(desc = "int", def = "60000")
int fileDurationMillis) throws WorldEditException {
// DeleteUninhabitedFilter filter = new DeleteUninhabitedFilter(fileDurationMillis, inhabitedTicks, fileDurationMillis); TODO NOT IMPLEMENTED
// DeleteUninhabitedFilter result = runWithWorld(player, folder, filter, true);
// if (result != null) {
@ -176,14 +178,18 @@ public class AnvilCommands {
name = "deleteallunclaimed",
aliases = {"delallunclaimed" },
desc = "Delete all chunks which haven't been occupied",
descFooter = "Supports: WG, P2, GP:\n" +
"Delete all chunks which aren't claimed AND haven't been occupied for `age-ticks` (20t = 1s) and \n" +
"Have not been accessed since `file-duration` (ms) after creation and\n" +
"Have not been used in the past `chunk-inactivity` (ms)" +
"The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
descFooter = "Supports: WorldGuard, PlotSquared, GriefPrevention:\n"
+ "Delete all chunks which aren't claimed AND haven't been occupied for `age-ticks` (20t = 1s) and \n"
+ "Have not been accessed since `file-duration` (ms) after creation and\n"
+ "Have not been used in the past `chunk-inactivity` (ms)"
+ "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
)
@CommandPermissions("worldedit.anvil.deleteallunclaimed")
public void deleteAllUnclaimed(Player player, int inhabitedTicks, @Arg(desc = "int", def = "60000") int fileDurationMillis, @Switch(name = 'd', desc = "TODO") boolean debug) throws WorldEditException {
public void deleteAllUnclaimed(Player player, int inhabitedTicks,
@Arg(desc = "int", def = "60000")
int fileDurationMillis,
@Switch(name = 'd', desc = "The flag will debug the task")
boolean debug) throws WorldEditException {
// String folder = player.getWorld().getName(); TODO NOT IMPLEMENTED
// DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, fileDurationMillis);
// if (debug) {
@ -198,15 +204,19 @@ public class AnvilCommands {
@Command(
name = "deleteunclaimed",
desc = "Delete all chunks which haven't been occupied",
descFooter = "(Supports: WG, P2, GP):\n" +
"Is not claimed\n" +
"Has not been occupied for `age-ticks` (20t = 1s) and \n" +
"Have not been accessed since `file-duration` (ms) after creation and\n" +
"Have not been used in the past `chunk-inactivity` (ms)" +
"The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
descFooter = "(Supports: WorldGuard, PlotSquared, GriefPrevention):\n"
+ "Is not claimed\n"
+ "Has not been occupied for `age-ticks` (20t = 1s) and \n"
+ "Have not been accessed since `file-duration` (ms) after creation and\n"
+ "Have not been used in the past `chunk-inactivity` (ms)"
+ "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
)
@CommandPermissions("worldedit.anvil.deleteunclaimed")
public void deleteUnclaimed(Player player, EditSession editSession, @Selection Region selection, int inhabitedTicks, @Arg(desc = "int", def = "60000") int fileDurationMillis, @Switch(name = 'd', desc = "TODO") boolean debug) throws WorldEditException {
public void deleteUnclaimed(Player player, EditSession editSession, @Selection Region selection, int inhabitedTicks,
@Arg(desc = "int", def = "60000")
int fileDurationMillis,
@Switch(name = 'd', desc = "The flag will debug the task")
boolean debug) throws WorldEditException {
// DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, fileDurationMillis); TODO NOT IMPLEMENTED
// if (debug) {
// filter.enableDebug();
@ -221,8 +231,8 @@ public class AnvilCommands {
name = "deletealloldregions",
aliases = {"deloldreg" },
desc = "Delete regions which haven't been accessed in a certain amount of time",
descFooter = "You can use seconds (s), minutes (m), hours (h), days (d), weeks (w), years (y)\n" +
"(months are not a unit of time) e.g., 8h5m12s\n"
descFooter = "You can use seconds (s), minutes (m), hours (h), days (d), weeks (w), years (y)\n"
+ "(months are not a unit of time) e.g., 8h5m12s\n"
)
@CommandPermissions("worldedit.anvil.deletealloldregions")
public void deleteAllOldRegions(Player player, String folder, String time) throws WorldEditException {
@ -236,12 +246,13 @@ public class AnvilCommands {
@Command(
name = "trimallplots",
desc = "Trim chunks in a Plot World",
descFooter = "Unclaimed chunks will be deleted\nUnmodified chunks will be deleted\n"
)
@CommandPermissions("worldedit.anvil.trimallplots")
public void trimAllPlots(Player player, @Switch(name = 'v', desc = "Delete unvisited chunks") boolean deleteUnvisited) throws WorldEditException {
public void trimAllPlots(Player player,
@Switch(name = 'v', desc = "Delete unvisited chunks")
boolean deleteUnvisited) throws WorldEditException {
// String folder = player.getWorld().getName(); TODO NOT IMPLEMENTED
// int visitTime = deleteUnvisited ? 1 : -1;
// PlotTrimFilter filter = new PlotTrimFilter(player.getWorld(), 0, visitTime, 600000);
@ -259,7 +270,9 @@ public class AnvilCommands {
desc = "Delete chunks matching a specific biome"
)
@CommandPermissions("worldedit.anvil.trimallair")
public void deleteBiome(Player player, String folder, BiomeType biome, @Switch(name = 'u', desc = "TODO") boolean unsafe) {
public void deleteBiome(Player player, String folder, BiomeType biome,
@Switch(name = 'u', desc = "The flag will run the task unsafe")
boolean unsafe) {
// DeleteBiomeFilterSimple filter = new DeleteBiomeFilterSimple(biome); TODO NOT IMPLEMENTED
// DeleteBiomeFilterSimple result = runWithWorld(player, folder, filter, true, unsafe);
// if (result != null) {
@ -272,7 +285,9 @@ public class AnvilCommands {
desc = "Trim all air in the world"
)
@CommandPermissions("worldedit.anvil.trimallair")
public void trimAllAir(Player player, String folder, @Switch(name = 'u', desc = "TODO") boolean unsafe) throws WorldEditException {
public void trimAllAir(Player player, String folder,
@Switch(name = 'u', desc = "The flag will run the task unsafe")
boolean unsafe) throws WorldEditException {
// TrimAirFilter filter = new TrimAirFilter(); TODO NOT IMPLEMENTED
// TrimAirFilter result = runWithWorld(player, folder, filter, true, unsafe);
// if (result != null) {
@ -282,7 +297,6 @@ public class AnvilCommands {
@Command(
name = "debugfixroads",
desc = "debug - do not use"
)
@CommandPermissions("worldedit.anvil.debugfixroads")
@ -300,7 +314,13 @@ public class AnvilCommands {
desc = "Replace all blocks in the selection with another"
)
@CommandPermissions("worldedit.anvil.replaceall")
public void replaceAllPattern(Player player, String folder, @Arg(name = "from", desc = "String", def = "") String from, Pattern toPattern, @Switch(name = 'd', desc = "TODO") boolean useData, @Switch(name = 'm', desc = "TODO") boolean useMap) throws WorldEditException {
public void replaceAllPattern(Player player, String folder,
@Arg(desc = "String", def = "")
String from, Pattern toPattern,
@Switch(name = 'd', desc = "The flag specifies the data to use")
boolean useData,
@Switch(name = 'm', desc = "The flag specifies the map to use")
boolean useMap) throws WorldEditException {
// MCAFilterCounter filter; TODO NOT IMPLEMENTED
// if (useMap) {
// if (to instanceof RandomPattern) {
@ -329,7 +349,9 @@ public class AnvilCommands {
desc = "Count all blocks in a world"
)
@CommandPermissions("worldedit.anvil.countall")
public void countAll(Player player, EditSession editSession, String folder, String argStr, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException {
public void countAll(Player player, EditSession editSession, String folder, String argStr,
@Switch(name = 'd', desc = "The flag specifies the data to use")
boolean useData) throws WorldEditException {
// Set<BaseBlock> searchBlocks = worldEdit.getBlocks(player, arg, true);
// MCAFilterCounter filter;
// if (useData || arg.contains(":")) { // Optimize for both cases
@ -403,7 +425,9 @@ public class AnvilCommands {
desc = "Count blocks in a selection"
)
@CommandPermissions("worldedit.anvil.count")
public void count(Player player, EditSession editSession, @Selection Region selection, String argStr, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException {
public void count(Player player, EditSession editSession, @Selection Region selection, String argStr,
@Switch(name = 'd', desc = "The flag specifies the data to use")
boolean useData) throws WorldEditException {
// Set<BaseBlock> searchBlocks = worldEdit.getBlocks(player, arg, true); TODO NOT IMPLEMENTED
// MCAFilterCounter filter;
// if (useData || arg.contains(":")) { // Optimize for both cases
@ -425,7 +449,9 @@ public class AnvilCommands {
desc = "Replace all blocks in the selection with another"
)
@CommandPermissions("worldedit.anvil.distr")
public void distr(Player player, EditSession editSession, @Selection Region selection, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException {
public void distr(Player player, EditSession editSession, @Selection Region selection,
@Switch(name = 'd', desc = "The flag specifies the data to use")
boolean useData) throws WorldEditException {
// long total = 0; TODO NOT IMPLEMENTED
// long[] count;
// MCAFilter<long[]> counts;
@ -504,7 +530,11 @@ public class AnvilCommands {
desc = "Replace all blocks in the selection with another"
)
@CommandPermissions("worldedit.anvil.replace")
public void replace(Player player, EditSession editSession, @Selection Region selection, @Arg(name = "from", desc = "String", def = "") String from, String toStr, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException {
public void replace(Player player, EditSession editSession, @Selection Region selection,
@Arg(desc = "String", def = "")
String from, String toStr,
@Switch(name = 'd', desc = "The flag specifies the data to use")
boolean useData) throws WorldEditException {
// final FaweBlockMatcher matchFrom; TODO NOT IMPLEMENTED
// if (from == null) {
// matchFrom = FaweBlockMatcher.NOT_AIR;
@ -526,7 +556,13 @@ public class AnvilCommands {
desc = "Replace all blocks in the selection with a pattern"
)
@CommandPermissions("worldedit.anvil.replace")
public void replacePattern(Player player, EditSession editSession, @Selection Region selection, @Arg(name = "from", desc = "String", def = "") String from, final Pattern toPattern, @Switch(name = 'd', desc = "TODO") boolean useData, @Switch(name = 'm', desc = "TODO") boolean useMap) throws WorldEditException {
public void replacePattern(Player player, EditSession editSession, @Selection Region selection,
@Arg(desc = "String", def = "")
String from, final Pattern toPattern,
@Switch(name = 'd', desc = "The flag specifies the data to use")
boolean useData,
@Switch(name = 'm', desc = "The flag specifies the map to use")
boolean useMap) throws WorldEditException {
// MCAFilterCounter filter; TODO NOT IMPLEMENTED
// if (useMap) {
// if (to instanceof RandomPattern) {
@ -556,7 +592,7 @@ public class AnvilCommands {
desc = "Set all blocks in the selection with a pattern"
)
@CommandPermissions("worldedit.anvil.set")
// Player player, String folder, @Arg(name = "from", desc = "String", def = "") String from, final Pattern toPattern, @Switch(name = 'd', desc = "TODO") boolean useData, @Switch(name = 'm', desc = "TODO") boolean useMap
// Player player, String folder, @Arg(name = "from", desc = "String", def = "") String from, final Pattern toPattern, @Switch(name = 'd', desc = "The flag specifies the data to use") boolean useData, @Switch(name = 'm', desc = "The flag specifies the map to use") boolean useMap
public void set(Player player, EditSession editSession, @Selection Region selection, final Pattern toPattern) throws WorldEditException {
// MCAFilterCounter filter = new SetPatternFilter(to); TODO NOT IMPLEMENTED
// MCAFilterCounter result = runWithSelection(player, editSession, selection, filter);
@ -602,17 +638,18 @@ public class AnvilCommands {
// MCAClipboard clipboard = new MCAClipboard(queue, cuboid, origin);
// FawePlayer fp = FawePlayer.wrap(player);
// fp.setMeta(FawePlayer.METADATA_KEYS.ANVIL_CLIPBOARD, clipboard);
// player.print(TranslatableComponent.of("fawe.worldedit.copy.command.copy" , selection.getArea()));
// player.print(TranslatableComponent.of("fawe.worldedit.copy.command.copy", selection.getArea()));
}
@Command(
name = "paste",
desc = "Paste chunks from your anvil clipboard",
descFooter = "Paste the chunks from your anvil clipboard.\n" +
"The -c flag will align the paste to the chunks."
descFooter = "Paste the chunks from your anvil clipboard."
)
@CommandPermissions("worldedit.anvil.pastechunks")
public void paste(Player player, LocalSession session, EditSession editSession, @Switch(name = 'c', desc = "TODO") boolean alignChunk) throws WorldEditException, IOException {
public void paste(Player player, LocalSession session, EditSession editSession,
@Switch(name = 'c', desc = "Align to chunks")
boolean alignChunk) throws WorldEditException, IOException {
// FawePlayer fp = FawePlayer.wrap(player); TODO NOT IMPLEMENTED
// MCAClipboard clipboard = fp.getMeta(FawePlayer.METADATA_KEYS.ANVIL_CLIPBOARD);
// if (clipboard == null) {
@ -639,6 +676,6 @@ public class AnvilCommands {
// pasteQueue.pasteRegion(copyQueue, copyRegion, offset, iAnvilHistory);
// } catch (IOException e) { throw new RuntimeException(e); }
// });
// player.print(TranslatableComponent.of("fawe.worldedit.paste.command.paste" , player.getPosition().toBlockVector()));
// player.print(TranslatableComponent.of("fawe.worldedit.paste.command.paste", player.getPosition().toBlockVector()));
}
}

View File

@ -245,7 +245,7 @@
// desc = "Set the floor and main block"
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void column(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void column(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// HeightMapMCAGenerator gen = assertSettings(player).getGenerator();
// if (image != null) {
// gen.setColumn(load(image), pattern, !disableWhiteOnly);
@ -264,7 +264,7 @@
// desc = "Set the floor (default: grass)"
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void floorCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void floorCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// floor(player, pattern, image, mask, disableWhiteOnly);
// player.print("Set floor!");
// assertSettings(player).resetComponent();
@ -287,14 +287,14 @@
// desc = "Set the main block (default: stone)"
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void mainCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void mainCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// main(player, pattern, image, maskOpt, disableWhiteOnly);
// player.print("Set main!");
// assertSettings(player).resetComponent();
// component(player);
// }
//
// public void main(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void main(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// HeightMapMCAGenerator gen = assertSettings(player).getGenerator();
// if (image != null) {
// gen.setMain(load(image), pattern, !disableWhiteOnly);
@ -313,7 +313,7 @@
// "e.g., Tallgrass"
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void overlay(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void overlay(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// HeightMapMCAGenerator gen = assertSettings(player).getGenerator();
// if (image != null) {
// gen.setOverlay(load(image), pattern, !disableWhiteOnly);
@ -335,13 +335,13 @@
// " - A good value for radius and iterations would be 1 8."
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void smoothCmd(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void smoothCmd(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// smooth(player, radius, iterations, image, mask, disableWhiteOnly);
// assertSettings(player).resetComponent();
// component(player);
// }
//
// private void smooth(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// private void smooth(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// HeightMapMCAGenerator gen = assertSettings(player).getGenerator();
// if (image != null) {
// gen.smooth(load(image), !disableWhiteOnly, radius, iterations);
@ -355,7 +355,7 @@
// desc = "Create some snow"
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void snow(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void snow(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// HeightMapMCAGenerator gen = assertSettings(player).getGenerator();
// floor(player, BlockTypes.SNOW.getDefaultState().with(PropertyKey.LAYERS, 7), image, mask, disableWhiteOnly);
// main(player, BlockTypes.SNOW_BLOCK, image, mask, disableWhiteOnly);
@ -422,7 +422,7 @@
// Request.request().setExtent(generator);
//
// Set<BlockType> blocks;
// switch (argOpt.toLowerCase()) {
// switch (argOpt.toLowerCase(Locale.ROOT)) {
// case "true":
// case "*": {
// generator.setTextureUtil(Fawe.get().getTextureUtil());
@ -535,7 +535,7 @@
// " - If a mask is used, the biome will be set anywhere the mask applies"
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void biome(Player player, @Arg(desc = "Biome type") BiomeType biome, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){
// public void biome(Player player, @Arg(desc = "Biome type") BiomeType biome, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) {
// HeightMapMCAGenerator gen = assertSettings(player).getGenerator();
// if (image != null) {
// gen.setBiome(load(image), biome, !disableWhiteOnly);
@ -819,7 +819,7 @@
// TextComponent.of("/cfi randomization " + !rand)));
// @NotNull Builder builder = TextComponent.builder(">> Current Settings <<");
// builder.append(newline());
// builder.append(TextComponent.of("Randomization [" + Boolean.toString(rand).toUpperCase() + "]")
// builder.append(TextComponent.of("Randomization [" + Boolean.toString(rand).toUpperCase(Locale.ROOT) + "]")
// .clickEvent(ClickEvent.runCommand(
// "/cfi randomization " + !rand)).hoverEvent(HoverEvent.showText(
// TextComponent.of("/cfi randomization " + !rand))));
@ -871,7 +871,7 @@
// desc = "Select a mask"
// )
// @CommandPermissions("worldedit.anvil.cfi")
// public void mask(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly, InjectedValueAccess context){
// public void mask(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly, InjectedValueAccess context) {
// CFISettings settings = assertSettings(player);
// String[] split = getArguments(context).split(" ");
// int index = 2;
@ -950,7 +950,7 @@
// JsonObject data1 = obj.get("data").getAsJsonObject();
// String link = data1.get("link").getAsString();
// URL url = new URL(link);
// player.print(Caption.of("fawe.web.download.link" , url));
// player.print(Caption.of("fawe.web.download.link", url));
// }
//
// @Command(

View File

@ -20,12 +20,16 @@ public class SuggestInputParseException extends InputParseException {
}
public static SuggestInputParseException of(Throwable other, String prefix, Supplier<List<String>> getSuggestions) {
if (other instanceof InputParseException) return of((InputParseException) other, prefix, getSuggestions);
if (other instanceof InputParseException) {
return of((InputParseException) other, prefix, getSuggestions);
}
return of(new InputParseException(other.getMessage()), prefix, getSuggestions);
}
public static SuggestInputParseException of(InputParseException other, String prefix, Supplier<List<String>> getSuggestions) {
if (other instanceof SuggestInputParseException) return (SuggestInputParseException) other;
if (other instanceof SuggestInputParseException) {
return (SuggestInputParseException) other;
}
return new SuggestInputParseException(other, prefix, getSuggestions);
}
@ -42,7 +46,9 @@ public class SuggestInputParseException extends InputParseException {
Throwable t = e;
while (t.getCause() != null) {
t = t.getCause();
if (t instanceof SuggestInputParseException) return (SuggestInputParseException) t;
if (t instanceof SuggestInputParseException) {
return (SuggestInputParseException) t;
}
}
return null;
}

View File

@ -33,10 +33,7 @@ public class Caption {
}
/**
* Colorize a component with legacy color codes
* @param component
* @param locale
* @return Component
* Colorize a component with legacy color codes.
*/
public static Component color(Component component, Locale locale) {
return color(WorldEditText.format(component, locale));

View File

@ -21,6 +21,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class Config {
@ -32,12 +33,7 @@ public class Config {
}
/**
* Get the value for a node<br>
* Probably throws some error if you try to get a non existent key
*
* @param key
* @param <T>
* @return
* Get the value for a node. Probably throws some error if you try to get a non-existent key.
*/
private <T> T get(String key, Class root) {
String[] split = key.split("\\.");
@ -57,8 +53,7 @@ public class Config {
}
/**
* Set the value of a specific node<br>
* Probably throws some error if you supply non existing keys or invalid values
* Set the value of a specific node. Probably throws some error if you supply non existing keys or invalid values.
*
* @param key config node
* @param value value
@ -103,9 +98,7 @@ public class Config {
}
/**
* Set all values in the file (load first to avoid overwriting)
*
* @param file
* Set all values in the file (load first to avoid overwriting).
*/
public void save(File file) {
Class<? extends Config> root = getClass();
@ -127,7 +120,7 @@ public class Config {
}
/**
* Indicates that a field should be instantiated / created
* Indicates that a field should be instantiated / created.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@ -135,7 +128,7 @@ public class Config {
}
/**
* Indicates that a field cannot be modified
* Indicates that a field cannot be modified.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@ -143,7 +136,7 @@ public class Config {
}
/**
* Creates a comment
* Creates a comment.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@ -152,7 +145,7 @@ public class Config {
}
/**
* The names of any default blocks
* The names of any default blocks.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@ -161,7 +154,7 @@ public class Config {
}
/**
* Any field or class with is not part of the config
* Any field or class with is not part of the config.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
@ -199,10 +192,7 @@ public class Config {
}
/**
* Get the static fields in a section
*
* @param clazz
* @return
* Get the static fields in a section.
*/
private Map<String, Object> getFields(Class clazz) {
HashMap<String, Object> map = new HashMap<>();
@ -317,10 +307,9 @@ public class Config {
}
/**
* Get the field for a specific config node
* Get the field for a specific config node.
*
* @param split the node (split by period)
* @return
*/
private Field getField(String[] split, Class root) {
Object instance = getInstance(split, root);
@ -331,12 +320,12 @@ public class Config {
}
/**
* Get the field for a specific config node and instance<br>
* Note: As expiry can have multiple blocks there will be multiple instances
* Get the field for a specific config node and instance.
*
* @apiNote As expiry can have multiple blocks there will be multiple instances
*
* @param split the node (split by period)
* @param instance the instance
* @return
*/
private Field getField(String[] split, Object instance) {
try {
@ -344,7 +333,7 @@ public class Config {
setAccessible(field);
return field;
} catch (Throwable ignored) {
log.debug("Invalid config field: " + StringMan.join(split, ".") + " for " + toNodeName(instance.getClass().getSimpleName()));
log.debug("Invalid config field: " + StringMan.join(split, ".") + " for " + toNodeName(instance.getClass().getSimpleName()));
return null;
}
}
@ -352,13 +341,13 @@ public class Config {
private Object getInstance(Object instance, Class clazz) throws IllegalAccessException, InstantiationException {
try {
Field instanceField = clazz.getDeclaredField(clazz.getSimpleName());
} catch (Throwable ignore) {
} catch (Throwable ignored) {
}
return clazz.newInstance();
}
/**
* Get the instance for a specific config node
* Get the instance for a specific config node.
*
* @param split the node (split by period)
* @return The instance or null
@ -407,7 +396,7 @@ public class Config {
clazz = found;
split = Arrays.copyOfRange(split, 2, split.length);
continue;
} catch (NoSuchFieldException ignore) {
} catch (NoSuchFieldException ignored) {
}
if (found != null) {
split = Arrays.copyOfRange(split, 1, split.length);
@ -425,31 +414,21 @@ public class Config {
}
/**
* Translate a node to a java field name
*
* @param node
* @return
* Translate a node to a java field name.
*/
private String toFieldName(String node) {
return node.toUpperCase().replaceAll("-", "_");
return node.toUpperCase(Locale.ROOT).replaceAll("-", "_");
}
/**
* Translate a field to a config node
*
* @param field
* @return
* Translate a field to a config node.
*/
private String toNodeName(String field) {
return field.toLowerCase().replace("_", "-");
return field.toLowerCase(Locale.ROOT).replace("_", "-");
}
/**
* Set some field to be accessible
*
* @param field
* @throws NoSuchFieldException
* @throws IllegalAccessException
* Set some field to be accessible.
*/
private void setAccessible(Field field) throws NoSuchFieldException, IllegalAccessException {
field.setAccessible(true);

View File

@ -29,7 +29,7 @@ public class Settings extends Config {
public String COMMIT; // These values are set from FAWE before loading
@Final
public String PLATFORM; // These values are set from FAWE before loading
@Comment({
"Set true to enable WorldEdit restrictions per region (e.g. PlotSquared or WorldGuard).",
"To be allowed to WorldEdit in a region, users need the appropriate",
@ -369,14 +369,14 @@ public class Settings extends Config {
"Might cause client-side FPS lagg in some situations"
})
public boolean KEEP_ENTITIES_IN_BLOCKS = false;
@Comment({
"[SAFE] Experimental freebuild region restrictions",
" - PERM: fawe.freebuild",
" - PERM: fawe.freebuild.<plugin>"
})
public boolean FREEBUILD = false;
@Comment({
"Other experimental features"
})
@ -504,7 +504,9 @@ public class Settings extends Config {
limit = new FaweLimit();
}
ArrayList<String> keys = new ArrayList<>(LIMITS.getSections());
if (keys.remove("default")) keys.add("default");
if (keys.remove("default")) {
keys.add("default");
}
boolean limitFound = false;
for (String key : keys) {
@ -524,13 +526,16 @@ public class Settings extends Config {
limit.SPEED_REDUCTION = Math.min(limit.SPEED_REDUCTION, newLimit.SPEED_REDUCTION);
limit.FAST_PLACEMENT |= newLimit.FAST_PLACEMENT;
limit.CONFIRM_LARGE &= newLimit.CONFIRM_LARGE;
if (limit.STRIP_NBT == null) limit.STRIP_NBT = newLimit.STRIP_NBT.isEmpty() ? Collections.emptySet() : new HashSet<>(newLimit.STRIP_NBT);
else if (limit.STRIP_NBT.isEmpty() || newLimit.STRIP_NBT.isEmpty()) {
if (limit.STRIP_NBT == null) {
limit.STRIP_NBT = newLimit.STRIP_NBT.isEmpty() ? Collections.emptySet() : new HashSet<>(newLimit.STRIP_NBT);
} else if (limit.STRIP_NBT.isEmpty() || newLimit.STRIP_NBT.isEmpty()) {
limit.STRIP_NBT = Collections.emptySet();
} else {
limit.STRIP_NBT = new HashSet<>(limit.STRIP_NBT);
limit.STRIP_NBT.retainAll(newLimit.STRIP_NBT);
if (limit.STRIP_NBT.isEmpty()) limit.STRIP_NBT = Collections.emptySet();
if (limit.STRIP_NBT.isEmpty()) {
limit.STRIP_NBT = Collections.emptySet();
}
}
}
}

View File

@ -3,20 +3,23 @@ package com.boydti.fawe.configuration;
import java.util.Map;
/**
* Represents a source of configurable options and settings
* Represents a source of configurable options and settings.
*/
public interface Configuration extends ConfigurationSection {
/**
* Sets the default value of the given path as provided.
* <p>
* If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.
* <p>
* If value is null, the value will be removed from the default
* Configuration source.
*
* @param path Path of the value to set.
* <p>
* If no source {@link Configuration} was provided as a default collection, then a new {@link
* MemoryConfiguration} will be created to hold the new default value.
* </p>
*
* <p>
* If value is null, the value will be removed from the default Configuration source.
* </p>
*
* @param path Path of the value to set.
* @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null.
*/
@ -25,10 +28,11 @@ public interface Configuration extends ConfigurationSection {
/**
* Sets the default values of the given paths as provided.
*
* <p>
* If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default values.
* If no source {@link Configuration} was provided as a default collection, then a new {@link
* MemoryConfiguration} will be created to hold the new default values.
* </p>
*
* @param defaults A map of Path->Values to add to defaults.
* @throws IllegalArgumentException Thrown if defaults is null.
@ -37,15 +41,17 @@ public interface Configuration extends ConfigurationSection {
/**
* Sets the default values of the given paths as provided.
*
* <p>
* If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.
* If no source {@link Configuration} was provided as a default collection, then a new {@link
* MemoryConfiguration} will be created to hold the new default value.
* </p>
*
* <p>
* This method will not hold a reference to the specified Configuration,
* nor will it automatically update if that Configuration ever changes. If
* you require this, you should set the default source with {@link
* #setDefaults(Configuration)}.
* This method will not hold a reference to the specified Configuration, nor will it
* automatically update if that Configuration ever changes. If you require this, you should set
* the default source with {@link #setDefaults(Configuration)}.
* </p>
*
* @param defaults A configuration holding a list of defaults to copy.
* @throws IllegalArgumentException Thrown if defaults is null or this.
@ -54,9 +60,11 @@ public interface Configuration extends ConfigurationSection {
/**
* Sets the source of all default values for this {@link Configuration}.
*
* <p>
* If a previous source was set, or previous default values were defined,
* then they will not be copied to the new source.
* If a previous source was set, or previous default values were defined, then they will not be
* copied to the new source.
* </p>
*
* @param defaults New source of default values for this configuration.
* @throws IllegalArgumentException Thrown if defaults is null or this.
@ -65,10 +73,12 @@ public interface Configuration extends ConfigurationSection {
/**
* Gets the source {@link Configuration} for this configuration.
*
* <p>
* If no configuration source was set, but default values were added, then
* a {@link MemoryConfiguration} will be returned. If no source was set
* and no defaults were set, then this method will return null.
* If no configuration source was set, but default values were added, then a {@link
* MemoryConfiguration} will be returned. If no source was set and no defaults were set, then
* this method will return null.
* </p>
*
* @return Configuration source for default values, or null if none exist.
*/
@ -76,8 +86,10 @@ public interface Configuration extends ConfigurationSection {
/**
* Gets the {@link ConfigurationOptions} for this {@link Configuration}.
*
* <p>
* All setters through this method are chainable.
* </p>
*
* @return Options for this configuration
*/

View File

@ -5,130 +5,149 @@ import java.util.Map;
import java.util.Set;
/**
* Represents a section of a {@link com.boydti.fawe.configuration.Configuration}
* Represents a section of a {@link Configuration}.
*/
public interface ConfigurationSection {
/**
* Gets a set containing all keys in this section.
* <p>
* If deep is set to true, then this will contain all the keys within any
* child {@link com.boydti.fawe.configuration.ConfigurationSection}s (and their children, etc). These
* will be in a valid path notation for you to use.
* <p>
* If deep is set to false, then this will contain only the keys of any
* direct children, and not their own children.
*
* @param deep Whether or not to get a deep list, as opposed to a shallow
* list.
* <p>
* If deep is set to true, then this will contain all the keys within any child {@link
* ConfigurationSection}s (and their children, etc). These will be in a valid path notation for
* you to use.
* </p>
*
* <p>
* If deep is set to false, then this will contain only the keys of any direct children, and not
* their own children.
* </p>
*
* @param deep Whether or not to get a deep list, as opposed to a shallow list.
* @return Set of keys contained within this ConfigurationSection.
*/
Set<String> getKeys(boolean deep);
/**
* Gets a Map containing all keys and their values for this section.
* <p>
* If deep is set to true, then this will contain all the keys and values
* within any child {@link com.boydti.fawe.configuration.ConfigurationSection}s (and their children,
* etc). These keys will be in a valid path notation for you to use.
* <p>
* If deep is set to false, then this will contain only the keys and
* values of any direct children, and not their own children.
* Gets a Map containing all keys, and their values for this section.
*
* @param deep Whether or not to get a deep list, as opposed to a shallow
* list.
* <p>
* If deep is set to true, then this will contain all the keys and values within any child
* {@link ConfigurationSection}s (and their children, etc). These keys will be in a valid path
* notation for you to use.
* </p>
*
* <p>
* If deep is set to false, then this will contain only the keys and values of any direct
* children, and not their own children.
* </p>
*
* @param deep Whether or not to get a deep list, as opposed to a shallow list.
* @return Map of keys and values of this section.
*/
Map<String, Object> getValues(boolean deep);
/**
* Checks if this {@link com.boydti.fawe.configuration.ConfigurationSection} contains the given path.
* Checks if this {@link ConfigurationSection} contains the given path.
*
* <p>
* If the value for the requested path does not exist but a default value
* has been specified, this will return true.
* If the value for the requested path does not exist, but a default value has been specified,
* this will return true.
* </p>
*
* @param path Path to check for existence.
* @return True if this section contains the requested path, either via
* default or being set.
* @return True if this section contains the requested path, either via default or being set.
* @throws IllegalArgumentException Thrown when path is null.
*/
boolean contains(String path);
/**
* Checks if this {@link com.boydti.fawe.configuration.ConfigurationSection} has a value set for the
* given path.
* Checks if this {@link ConfigurationSection} has a value set for the given path.
*
* <p>
* If the value for the requested path does not exist but a default value
* has been specified, this will still return false.
* If the value for the requested path does not exist, but a default value has been specified,
* this will still return false.
* </p>
*
* @param path Path to check for existence.
* @return True if this section contains the requested path, regardless of
* having a default.
* @return True if this section contains the requested path, regardless of having a default.
* @throws IllegalArgumentException Thrown when path is null.
*/
boolean isSet(String path);
/**
* Gets the path of this {@link com.boydti.fawe.configuration.ConfigurationSection} from its root {@link
* com.boydti.fawe.configuration.Configuration}
* Gets the path of this {@link ConfigurationSection} from its root {@link Configuration}.
*
* <p>
* For any {@link com.boydti.fawe.configuration.Configuration} themselves, this will return an empty
* string.
* For any {@link Configuration} themselves, this will return an empty string.
* </p>
*
* <p>
* If the section is no longer contained within its root for any reason,
* such as being replaced with a different value, this may return null.
* If the section is no longer contained within its root for any reason, such as being replaced
* with a different value, this may return null.
* </p>
*
* <p>
* To retrieve the single name of this section, that is, the final part of
* the path returned by this method, you may use {@link #getName()}.
* To retrieve the single name of this section, that is, the final part of the path returned by
* this method, you may use {@link #getName()}.
*</p>
*
* @return Path of this section relative to its root
*/
String getCurrentPath();
/**
* Gets the name of this individual {@link com.boydti.fawe.configuration.ConfigurationSection}, in the
* path.
* Gets the name of this individual {@link ConfigurationSection}, in the path.
*
* <p>
* This will always be the final part of {@link #getCurrentPath()}, unless
* the section is orphaned.
* This will always be the final part of {@link #getCurrentPath()}, unless the section is
* orphaned.
* </p>
*
* @return Name of this section
*/
String getName();
/**
* Gets the root {@link com.boydti.fawe.configuration.Configuration} that contains this {@link
* com.boydti.fawe.configuration.ConfigurationSection}
* Gets the root {@link Configuration} that contains this {@link ConfigurationSection}.
*
* <p>
* For any {@link com.boydti.fawe.configuration.Configuration} themselves, this will return its own
* object.
* For any {@link Configuration} themselves, this will return its own object.
* </p>
*
* <p>
* If the section is no longer contained within its root for any reason,
* such as being replaced with a different value, this may return null.
* If the section is no longer contained within its root for any reason, such as being replaced
* with a different value, this may return null.
* </p>
*
* @return Root configuration containing this section.
*/
Configuration getRoot();
/**
* Gets the parent {@link com.boydti.fawe.configuration.ConfigurationSection} that directly contains
* this {@link com.boydti.fawe.configuration.ConfigurationSection}.
* Gets the parent {@link ConfigurationSection} that directly contains this {@link
* ConfigurationSection}.
* <p>
* For any {@link com.boydti.fawe.configuration.Configuration} themselves, this will return null.
* For any {@link Configuration} themselves, this will return null.
* </p>
*
* <p>
* If the section is no longer contained within its parent for any reason,
* such as being replaced with a different value, this may return null.
* If the section is no longer contained within its parent for any reason, such as being
* replaced with a different value, this may return null.
* </p>
*
* @return Parent section containing this section.
*/
com.boydti.fawe.configuration.ConfigurationSection getParent();
ConfigurationSection getParent();
/**
* Gets the requested Object by path.
*
* <p>
* If the Object does not exist but a default value has been specified,
* this will return the default value. If the Object does not exist and no
* default value was specified, this will return null.
* If the Object does not exist, but a default value has been specified, this will return the
* default value. If the Object does not exist and no default value was specified, this will
* return null.
* </p>
*
* @param path Path of the Object to get.
* @return Requested Object.
@ -136,69 +155,75 @@ public interface ConfigurationSection {
Object get(String path);
/**
* Gets the requested Object by path, returning a default value if not
* found.
* Gets the requested Object by a path, returning a default value if not found.
*
* <p>
* If the Object does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link com.boydti.fawe.configuration.Configuration}.
* If the Object does not exist then the specified default value will return regardless of if a
* default has been identified in the root {@link Configuration}.
* </p>
*
* @param path Path of the Object to get.
* @param def The default value to return if the path is not found.
* @param def The default value to return if the path is not found.
* @return Requested Object.
*/
Object get(String path, Object def);
/**
* Sets the specified path to the given value.
* <p>
* If value is null, the entry will be removed. Any existing entry will be
* replaced, regardless of what the new value is.
* <p>
* Some implementations may have limitations on what you may store. See
* their individual javadoc for details. No implementations should allow
* you to store {@link com.boydti.fawe.configuration.Configuration}s or {@link com.boydti.fawe.configuration.ConfigurationSection}s,
* please use {@link #createSection(String)} for that.
*
* @param path Path of the object to set.
* <p>
* If value is null, the entry will be removed. Any existing entry will be replaced, regardless
* of what the new value is.
* </p>
*
* <p>
* Some implementations may have limitations on what you may store. See their individual javadoc
* for details. No implementations should allow you to store {@link Configuration}s or {@link
* ConfigurationSection}s, please use {@link #createSection(String)} for that.
* </p>
*
* @param path Path of the object to set.
* @param value New value to set the path to.
*/
void set(String path, Object value);
/**
* Creates an empty {@link com.boydti.fawe.configuration.ConfigurationSection} at the specified path.
* Creates an empty {@link ConfigurationSection} at the specified path.
*
* <p>
* Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link com.boydti.fawe.configuration.ConfigurationSection}, it will
* be orphaned.
* Any value that was previously set at this path will be overwritten. If the previous value was
* itself a {@link ConfigurationSection}, it will be orphaned.
* </p>
*
* @param path Path to create the section at.
* @return Newly created section
*/
com.boydti.fawe.configuration.ConfigurationSection createSection(String path);
ConfigurationSection createSection(String path);
/**
* Creates a {@link com.boydti.fawe.configuration.ConfigurationSection} at the specified path, with
* specified values.
* Creates a {@link ConfigurationSection} at the specified path, with specified values.
*
* <p>
* Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link com.boydti.fawe.configuration.ConfigurationSection}, it will
* be orphaned.
* Any value that was previously set at this path will be overwritten. If the previous value was
* itself a {@link ConfigurationSection}, it will be orphaned.
* </p>
*
* @param path Path to create the section at.
* @param map The values to used.
* @param map The values to used.
* @return Newly created section
*/
com.boydti.fawe.configuration.ConfigurationSection createSection(String path, Map<?, ?> map);
ConfigurationSection createSection(String path, Map<?, ?> map);
// Primitives
/**
* Gets the requested String by path.
* Gets the requested String by a path.
*
* <p>
* If the String does not exist but a default value has been specified,
* this will return the default value. If the String does not exist and no
* default value was specified, this will return null.
* If the String does not exist, but a default value has been specified, this will return the
* default value. If the String does not exist and no default value was specified, this will
* return null.
* </p>
*
* @param path Path of the String to get.
* @return Requested String.
@ -206,12 +231,14 @@ public interface ConfigurationSection {
String getString(String path);
/**
* Gets the requested String by path, returning a default value if not
* Gets the requested String by a path, returning a default value if not
* found.
*
* <p>
* If the String does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link com.boydti.fawe.configuration.Configuration}.
* return regardless of if a default has been identified in the root
* {@link Configuration}.
* </p>
*
* @param path Path of the String to get.
* @param def The default value to return if the path is not found or is
@ -222,11 +249,12 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a String.
*
* <p>
* <p> If the path exists but is not a String, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a String and return appropriately.</p>
* If the path exists but is not a String, this will return false. If the path does not exist,
* this will return false. If the path does not exist, but a default value has been specified,
* this will check if that default value is a String and return appropriately.
* </p>
*
* @param path Path of the String to check.
* @return Whether or not the specified path is a String.
@ -234,11 +262,13 @@ public interface ConfigurationSection {
boolean isString(String path);
/**
* Gets the requested int by path.
* Gets the requested int by a path.
*
* <p>
* <p>If the int does not exist but a default value has been specified, this
* If the int does not exist, but a default value has been specified, this
* will return the default value. If the int does not exist and no default
* value was specified, this will return 0.</p>
* value was specified, this will return 0.
* </p>
*
* @param path Path of the int to get.
* @return Requested int.
@ -246,26 +276,27 @@ public interface ConfigurationSection {
int getInt(String path);
/**
* Gets the requested int by path, returning a default value if not found.
* Gets the requested int by a path, returning a default value if not found.
*
* <p>
* <p>If the int does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link com.boydti.fawe.configuration.Configuration}.</p>
* If the int does not exist then the specified default value will return regardless of if a
* default has been identified in the root {@link Configuration}.
* </p>
*
* @param path Path of the int to get.
* @param def The default value to return if the path is not found or is
* not an int.
* @param def The default value to return if the path is not found or is not an int.
* @return Requested int.
*/
int getInt(String path, int def);
/**
* Checks if the specified path is an int.
*
* <p>
* <p>If the path exists but is not a int, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a int and return appropriately.</p>
* If the path exists but is not an int, this will return false. If the path does not exist,
* this will return false. If the path does not exist, but a default value has been specified,
* this will check if that default value is an int and return appropriately
* </p>
*
* @param path Path of the int to check.
* @return Whether or not the specified path is an int.
@ -273,11 +304,13 @@ public interface ConfigurationSection {
boolean isInt(String path);
/**
* Gets the requested boolean by path.
* Gets the requested boolean by a path.
*
* <p>
* If the boolean does not exist but a default value has been specified,
* this will return the default value. If the boolean does not exist and
* no default value was specified, this will return false.
* If the boolean does not exist, but a default value has been specified, this will return the
* default value. If the boolean does not exist and no default value was specified, this will
* return false.
* </p>
*
* @param path Path of the boolean to get.
* @return Requested boolean.
@ -285,27 +318,27 @@ public interface ConfigurationSection {
boolean getBoolean(String path);
/**
* Gets the requested boolean by path, returning a default value if not
* found.
* Gets the requested boolean by a path, returning a default value if not found.
*
* <p>
* If the boolean does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link com.boydti.fawe.configuration.Configuration}.
* If the boolean does not exist then the specified default value will return regardless of if a
* default has been identified in the root {@link Configuration}.
* </p>
*
* @param path Path of the boolean to get.
* @param def The default value to return if the path is not found or is
* not a boolean.
* @param def The default value to return if the path is not found or is not a boolean.
* @return Requested boolean.
*/
boolean getBoolean(String path, boolean def);
/**
* Checks if the specified path is a boolean.
*
* <p>
* If the path exists but is not a boolean, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a boolean and return appropriately.
* If the path exists but is not a boolean, this will return false. If the path does not exist,
* this will return false. If the path does not exist, but a default value has been specified,
* this will check if that default value is a boolean and return appropriately.
* </p>
*
* @param path Path of the boolean to check.
* @return Whether or not the specified path is a boolean.
@ -313,11 +346,13 @@ public interface ConfigurationSection {
boolean isBoolean(String path);
/**
* Gets the requested double by path.
* Gets the requested double by a path.
*
* <p>
* If the double does not exist but a default value has been specified,
* this will return the default value. If the double does not exist and no
* default value was specified, this will return 0.
* If the double does not exist, but a default value has been specified, this will return the
* default value. If the double does not exist and no default value was specified, this will
* return 0.
* </p>
*
* @param path Path of the double to get.
* @return Requested double.
@ -325,27 +360,27 @@ public interface ConfigurationSection {
double getDouble(String path);
/**
* Gets the requested double by path, returning a default value if not
* found.
* Gets the requested double by a path, returning a default value if not found.
*
* <p>
* If the double does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link com.boydti.fawe.configuration.Configuration}.
* If the double does not exist then the specified default value will return regardless of if a
* default has been identified in the root {@link Configuration}.
* </p>
*
* @param path Path of the double to get.
* @param def The default value to return if the path is not found or is
* not a double.
* @param def The default value to return if the path is not found or is not a double.
* @return Requested double.
*/
double getDouble(String path, double def);
/**
* Checks if the specified path is a double.
*
* <p>
* If the path exists but is not a double, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a double and return appropriately.
* If the path exists but is not a double, this will return false. If the path does not exist,
* this will return false. If the path does not exist, but a default value has been specified,
* this will check if that default value is a double and return appropriately.
* </p>
*
* @param path Path of the double to check.
* @return Whether or not the specified path is a double.
@ -353,11 +388,13 @@ public interface ConfigurationSection {
boolean isDouble(String path);
/**
* Gets the requested long by path.
* Gets the requested long by a path.
*
* <p>
* If the long does not exist but a default value has been specified, this
* will return the default value. If the long does not exist and no
* default value was specified, this will return 0.
* If the long does not exist, but a default value has been specified, this will return the
* default value. If the long does not exist and no default value was specified, this will
* return 0.
* </p>
*
* @param path Path of the long to get.
* @return Requested long.
@ -365,27 +402,27 @@ public interface ConfigurationSection {
long getLong(String path);
/**
* Gets the requested long by path, returning a default value if not
* found.
* Gets the requested long by a path, returning a default value if not found.
*
* <p>
* If the long does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link com.boydti.fawe.configuration.Configuration}.
* If the long does not exist then the specified default value will return regardless of if a
* default has been identified in the root {@link Configuration}.
* </p>
*
* @param path Path of the long to get.
* @param def The default value to return if the path is not found or is
* not a long.
* @param def The default value to return if the path is not found or is not a long.
* @return Requested long.
*/
long getLong(String path, long def);
/**
* Checks if the specified path is a long.
*
* <p>
* If the path exists but is not a long, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a long and return appropriately.
* If the path exists but is not a long, this will return false. If the path does not exist,
* this will return false. If the path does not exist, but a default value has been specified,
* this will check if that default value is a long and return appropriately.
* </p>
*
* @param path Path of the long to check.
* @return Whether or not the specified path is a long.
@ -395,11 +432,13 @@ public interface ConfigurationSection {
// Java
/**
* Gets the requested List by path.
* Gets the requested List by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return null.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return null.
* </p>
*
* @param path Path of the List to get.
* @return Requested List.
@ -407,27 +446,28 @@ public interface ConfigurationSection {
List<?> getList(String path);
/**
* Gets the requested List by path, returning a default value if not
* found.
* Gets the requested List by a path, returning a default value if not found.
*
* <p>
* If the List does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link com.boydti.fawe.configuration.Configuration}.
* If the List does not exist then the specified default value will return regardless of if a
* default has been identified in the root {@link Configuration}.
* </p>
*
* @param path Path of the List to get.
* @param def The default value to return if the path is not found or is
* not a List.
* @param def The default value to return if the path is not found or is not a List.
* @return Requested List.
*/
List<?> getList(String path, List<?> def);
/**
* Checks if the specified path is a List.
*
* <p>
* If the path exists but is not a List, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* path does not exist, this will return false. If the path does not exist, but
* a default value has been specified, this will check if that default
* value is a List and return appropriately.
* </p>
*
* @param path Path of the List to check.
* @return Whether or not the specified path is a List.
@ -436,13 +476,17 @@ public interface ConfigurationSection {
/**
* Gets the requested List of String by path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* If the List does not exist, but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a String if possible,
* but may miss any values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of String.
@ -450,14 +494,18 @@ public interface ConfigurationSection {
List<String> getStringList(String path);
/**
* Gets the requested List of Integer by path.
* Gets the requested List of an Integer by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Integer if possible,
* but may miss any values out if they are not compatible.
* This method will attempt to cast any values into an Integer if possible, but may miss any
* values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Integer.
@ -465,14 +513,18 @@ public interface ConfigurationSection {
List<Integer> getIntegerList(String path);
/**
* Gets the requested List of Boolean by path.
* Gets the requested List of Boolean by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Boolean if possible,
* but may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Boolean if possible, but may miss any
* values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Boolean.
@ -480,14 +532,18 @@ public interface ConfigurationSection {
List<Boolean> getBooleanList(String path);
/**
* Gets the requested List of Double by path.
* Gets the requested List of Double by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Double if possible,
* but may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Double if possible, but may miss any
* values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Double.
@ -495,14 +551,18 @@ public interface ConfigurationSection {
List<Double> getDoubleList(String path);
/**
* Gets the requested List of Float by path.
* Gets the requested List of Float by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Float if possible,
* but may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Float if possible, but may miss any
* values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Float.
@ -510,14 +570,18 @@ public interface ConfigurationSection {
List<Float> getFloatList(String path);
/**
* Gets the requested List of Long by path.
* Gets the requested List of Long by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Long if possible,
* but may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Long if possible, but may miss any
* values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Long.
@ -525,14 +589,18 @@ public interface ConfigurationSection {
List<Long> getLongList(String path);
/**
* Gets the requested List of Byte by path.
* Gets the requested List of Byte by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Byte if possible,
* but may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Byte if possible, but may miss any
* values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Byte.
@ -540,14 +608,18 @@ public interface ConfigurationSection {
List<Byte> getByteList(String path);
/**
* Gets the requested List of Character by path.
* Gets the requested List of Character by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Character if
* possible, but may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Character if possible, but may miss any
* values out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Character.
@ -555,14 +627,18 @@ public interface ConfigurationSection {
List<Character> getCharacterList(String path);
/**
* Gets the requested List of Short by path.
* Gets the requested List of Short by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Short if possible,
* but may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Short if possible, but may miss any values
* out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Short.
@ -570,14 +646,18 @@ public interface ConfigurationSection {
List<Short> getShortList(String path);
/**
* Gets the requested List of Maps by path.
* Gets the requested List of Maps by a path.
*
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* If the List does not exist, but a default value has been specified, this will return the
* default value. If the List does not exist and no default value was specified, this will
* return an empty List.
* </p>
*
* <p>
* This method will attempt to cast any values into a Map if possible, but
* may miss any values out if they are not compatible.
* This method will attempt to cast any values into a Map if possible, but may miss any values
* out if they are not compatible.
* </p>
*
* @param path Path of the List to get.
* @return Requested List of Maps.
@ -586,25 +666,27 @@ public interface ConfigurationSection {
/**
* Gets the requested ConfigurationSection by path.
*
* <p>
* If the ConfigurationSection does not exist but a default value has been
* specified, this will return the default value. If the
* ConfigurationSection does not exist and no default value was specified,
* this will return null.
* If the ConfigurationSection does not exist, but a default value has been specified, this will
* return the default value. If the ConfigurationSection does not exist and no default value was
* specified, this will return null.
* </p>
*
* @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection.
*/
com.boydti.fawe.configuration.ConfigurationSection getConfigurationSection(String path);
ConfigurationSection getConfigurationSection(String path);
/**
* Checks if the specified path is a ConfigurationSection.
* Checks if the specified path is a {@link ConfigurationSection}.
*
* <p>
* If the path exists but is not a ConfigurationSection, this will return
* false. If the path does not exist, this will return false. If the path
* does not exist but a default value has been specified, this will check
* if that default value is a ConfigurationSection and return
* appropriately.
* If the path exists but is not a {@code ConfigurationSection}, this will return false. If the
* path does not exist, this will return false. If the path does not exist, but a default value
* has been specified, this will check if that default value is a ConfigurationSection and
* return appropriately.
* </p>
*
* @param path Path of the ConfigurationSection to check.
* @return Whether or not the specified path is a ConfigurationSection.
@ -612,32 +694,37 @@ public interface ConfigurationSection {
boolean isConfigurationSection(String path);
/**
* Gets the equivalent {@link com.boydti.fawe.configuration.ConfigurationSection} from the default
* {@link com.boydti.fawe.configuration.Configuration} defined in {@link #getRoot()}.
* Gets the equivalent {@link ConfigurationSection} from the default
* {@link Configuration} defined in {@link #getRoot()}.
*
* <p>
* If the root contains no defaults, or the defaults doesn't contain a
* value for this path, or the value at this path is not a {@link
* com.boydti.fawe.configuration.ConfigurationSection} then this will return null.
* ConfigurationSection} then this will return null.
* </p>
*
* @return Equivalent section in root configuration
*/
com.boydti.fawe.configuration.ConfigurationSection getDefaultSection();
ConfigurationSection getDefaultSection();
/**
* Sets the default value in the root at the given path as provided.
* <p>
* If no source {@link com.boydti.fawe.configuration.Configuration} was provided as a default
* collection, then a new {@link com.boydti.fawe.configuration.MemoryConfiguration} will be created to
* hold the new default value.
* <p>
* If value is null, the value will be removed from the default
* Configuration source.
* <p>
* If the value as returned by {@link #getDefaultSection()} is null, then
* this will create a new section at the path, replacing anything that may
* have existed there previously.
*
* @param path Path of the value to set.
* <p>
* If no source {@link Configuration} was provided as a default collection, then a new {@link
* MemoryConfiguration} will be created to hold the new default value.
* </p>
*
* <p>
* If value is null, the value will be removed from the default Configuration source.
* </p>
*
* <p>
* If the value as returned by {@link #getDefaultSection()} is null, then this will create a new
* section at the path, replacing anything that may have existed there previously.
* </p>
*
* @param path Path of the value to set.
* @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null.
*/

View File

@ -295,7 +295,8 @@ public class MemorySection implements com.boydti.fawe.configuration.Configuratio
char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
int i1 = -1;
int i2;
com.boydti.fawe.configuration.ConfigurationSection section = this;
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
String node = path.substring(i2, i1);
@ -377,7 +378,8 @@ public class MemorySection implements com.boydti.fawe.configuration.Configuratio
char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
int i1 = -1;
int i2;
com.boydti.fawe.configuration.ConfigurationSection section = this;
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
String node = path.substring(i2, i1);

View File

@ -1,18 +1,3 @@
/**
* Copyright (c) 2008, http://www.snakeyaml.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml;
import org.yaml.snakeyaml.nodes.Tag;
@ -60,8 +45,7 @@ public final class TypeDescription {
/**
* Set tag to be used to load or dump the type (class).
*
* @param tag
* local or global tag
* @param tag local or global tag
*/
public void setTag(Tag tag) {
this.tag = tag;
@ -72,7 +56,7 @@ public final class TypeDescription {
}
/**
* Get represented type (class)
* Get the represented type (class).
*
* @return type (class) to be described.
*/
@ -81,12 +65,10 @@ public final class TypeDescription {
}
/**
* Specify that the property is a type-safe <code>List</code>.
* Specify that the property is a type-safe {@code List}.
*
* @param property
* name of the JavaBean property
* @param type
* class of List values
* @param property name of the JavaBean property
* @param type class of List values
*/
public void putListPropertyType(String property, Class<? extends Object> type) {
listProperties.put(property, type);
@ -95,8 +77,7 @@ public final class TypeDescription {
/**
* Get class of List values for provided JavaBean property.
*
* @param property
* property name
* @param property property name
* @return class of List values
*/
public Class<? extends Object> getListPropertyType(String property) {
@ -104,14 +85,11 @@ public final class TypeDescription {
}
/**
* Specify that the property is a type-safe <code>Map</code>.
* Specify that the property is a type-safe {@code Map}.
*
* @param property
* property name of this JavaBean
* @param key
* class of keys in Map
* @param value
* class of values in Map
* @param property property name of this JavaBean
* @param key class of keys in Map
* @param value class of values in Map
*/
public void putMapPropertyType(String property, Class<? extends Object> key,
Class<? extends Object> value) {
@ -120,10 +98,9 @@ public final class TypeDescription {
}
/**
* Get keys type info for this JavaBean
* Get keys type info for this JavaBean.
*
* @param property
* property name of this JavaBean
* @param property property name of this JavaBean
* @return class of keys in the Map
*/
public Class<? extends Object> getMapKeyType(String property) {
@ -131,10 +108,9 @@ public final class TypeDescription {
}
/**
* Get values type info for this JavaBean
* Get values type info for this JavaBean.
*
* @param property
* property name of this JavaBean
* @param property property name of this JavaBean
* @return class of values in the Map
*/
public Class<? extends Object> getMapValueType(String property) {

View File

@ -35,10 +35,10 @@ import java.util.regex.Pattern;
*/
public class Yaml {
protected final Resolver resolver;
private String name;
protected BaseConstructor constructor;
protected Representer representer;
protected DumperOptions dumperOptions;
private String name;
/**
* Create Yaml instance. It is safe to create a few instances and use them
@ -212,19 +212,19 @@ public class Yaml {
/**
* <p>
* Serialize a Java object into a YAML string. Override the default root tag
* with <code>rootTag</code>.
* with {@code rootTag}.
* </p>
*
* <p>
* This method is similar to <code>Yaml.dump(data)</code> except that the
* This method is similar to {@code Yaml.dump(data)} except that the
* root tag for the whole document is replaced with the given tag. This has
* two main uses.
* </p>
*
* <p>
* First, if the root tag is replaced with a standard YAML tag, such as
* <code>Tag.MAP</code>, then the object will be dumped as a map. The root
* tag will appear as <code>!!map</code>, or blank (implicit !!map).
* {@code Tag.MAP}, then the object will be dumped as a map. The root
* tag will appear as {@code !!map}, or blank (implicit !!map).
* </p>
*
* <p>
@ -237,11 +237,11 @@ public class Yaml {
* @param data Java object to be serialized to YAML
* @param rootTag the tag for the whole YAML document. The tag should be Tag.MAP
* for a JavaBean to make the tag disappear (to use implicit tag
* !!map). If <code>null</code> is provided then the standard tag
* !!map). If {@code null} is provided then the standard tag
* with the full class name is used.
* @param flowStyle flow style for the whole document. See Chapter 10. Collection
* Styles http://yaml.org/spec/1.1/#id930798. If
* <code>null</code> is provided then the flow style from
* {@code null} is provided then the flow style from
* DumperOptions is used.
* @return YAML String
*/
@ -261,11 +261,11 @@ public class Yaml {
/**
* <p>
* Serialize a Java object into a YAML string. Override the default root tag
* with <code>Tag.MAP</code>.
* with {@code Tag.MAP}.
* </p>
* <p>
* This method is similar to <code>Yaml.dump(data)</code> except that the
* root tag for the whole document is replaced with <code>Tag.MAP</code> tag
* This method is similar to {@code Yaml.dump(data)} except that the
* root tag for the whole document is replaced with {@code Tag.MAP} tag
* (implicit !!map).
* </p>
* <p>
@ -300,18 +300,6 @@ public class Yaml {
return emitter.getEvents();
}
private static class SilentEmitter implements Emitable {
private List<Event> events = new ArrayList<>(100);
public List<Event> getEvents() {
return events;
}
public void emit(Event event) throws IOException {
events.add(event);
}
}
/**
* Parse the only YAML document in a String and produce the corresponding
* Java object. (Because the encoding in known BOM is not respected.)
@ -420,18 +408,6 @@ public class Yaml {
return new YamlIterable(result);
}
private static class YamlIterable implements Iterable<Object> {
private Iterator<Object> iterator;
public YamlIterable(Iterator<Object> iterator) {
this.iterator = iterator;
}
public Iterator<Object> iterator() {
return iterator;
}
}
/**
* Parse all YAML documents in a String and produce corresponding Java
* objects. (Because the encoding in known BOM is not respected.) The
@ -499,26 +475,13 @@ public class Yaml {
return new NodeIterable(result);
}
private static class NodeIterable implements Iterable<Node> {
private Iterator<Node> iterator;
public NodeIterable(Iterator<Node> iterator) {
this.iterator = iterator;
}
public Iterator<Node> iterator() {
return iterator;
}
}
/**
* Add an implicit scalar detector. If an implicit scalar value matches the
* given regexp, the corresponding tag is assigned to the scalar.
*
* @param tag tag to assign to the node
* @param regexp regular expression to match against
* @param first a sequence of possible initial characters or null (which means
* any).
* @param first a sequence of possible initial characters or null (which means any).
*/
public void addImplicitResolver(Tag tag, Pattern regexp, String first) {
resolver.addImplicitResolver(tag, regexp, first);
@ -541,7 +504,7 @@ public class Yaml {
}
/**
* Set a meaningful name to be shown in toString()
* Set a meaningful name to be shown in {@code toString()}.
*
* @param name human readable name
*/
@ -574,6 +537,51 @@ public class Yaml {
return new EventIterable(result);
}
public void setBeanAccess(BeanAccess beanAccess) {
constructor.getPropertyUtils().setBeanAccess(beanAccess);
representer.getPropertyUtils().setBeanAccess(beanAccess);
}
private static class SilentEmitter implements Emitable {
private List<Event> events = new ArrayList<>(100);
public List<Event> getEvents() {
return events;
}
public void emit(Event event) throws IOException {
events.add(event);
}
}
private static class YamlIterable implements Iterable<Object> {
private Iterator<Object> iterator;
public YamlIterable(Iterator<Object> iterator) {
this.iterator = iterator;
}
public Iterator<Object> iterator() {
return iterator;
}
}
private static class NodeIterable implements Iterable<Node> {
private Iterator<Node> iterator;
public NodeIterable(Iterator<Node> iterator) {
this.iterator = iterator;
}
public Iterator<Node> iterator() {
return iterator;
}
}
private static class EventIterable implements Iterable<Event> {
private Iterator<Event> iterator;
@ -586,9 +594,4 @@ public class Yaml {
}
}
public void setBeanAccess(BeanAccess beanAccess) {
constructor.getPropertyUtils().setBeanAccess(beanAccess);
representer.getPropertyUtils().setBeanAccess(beanAccess);
}
}

View File

@ -40,7 +40,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
}
/**
* Gets how much spaces should be used to indent each line.
* Gets how many spaces should be used to indent each line.
*
* <p>
* The minimum value this may be is 2, and the maximum is 9.
@ -53,10 +53,11 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
}
/**
* Sets how much spaces should be used to indent each line.
* Sets how many spaces should be used to indent each line.
*
* <p>
* The minimum value this may be is 2, and the maximum is 9.
*
* </p>
* @param value New indent
* @return This object, for chaining
*/

View File

@ -12,7 +12,7 @@ public class DBHandler {
private final Logger log = LoggerFactory.getLogger(Config.class);
public final static DBHandler IMP = new DBHandler();
public static final DBHandler IMP = new DBHandler();
private Map<World, RollbackDatabase> databases = new ConcurrentHashMap<>(8, 0.9f, 1);

View File

@ -39,21 +39,33 @@ public class RollbackDatabase extends AsyncNotifyQueue {
private final World world;
private Connection connection;
private @Language("sql") String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS `{0}edits` (`player` BLOB(16) NOT NULL,`id` INT NOT NULL, `time` INT NOT NULL,`x1` INT NOT NULL,`x2` INT NOT NULL,`z1` INT NOT NULL,`z2` INT NOT NULL,`y1` INT NOT NULL, `y2` INT NOT NULL, `size` INT NOT NULL, `command` VARCHAR, PRIMARY KEY (player, id))";
private @Language("sql") String UPDATE_TABLE1 = "ALTER TABLE `{0}edits` ADD COLUMN `command` VARCHAR";
private @Language("sql") String UPDATE_TABLE2 = "alter table `{0}edits` add size int default 0 not null";
private @Language("sql") String INSERT_EDIT = "INSERT OR REPLACE INTO `{0}edits` (`player`,`id`,`time`,`x1`,`x2`,`z1`,`z2`,`y1`,`y2`,`command`,`size`) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
private @Language("sql") String PURGE = "DELETE FROM `{0}edits` WHERE `time`<?";
private @Language("sql") String GET_EDITS_USER = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` DESC, `id` DESC";
private @Language("sql") String GET_EDITS_USER_ASC = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` ASC, `id` ASC";
private @Language("sql") String GET_EDITS = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` DESC, `id` DESC";
private @Language("sql") String GET_EDITS_ASC = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` , `id` ";
private @Language("sql") String GET_EDIT_USER = "SELECT * FROM `{0}edits` WHERE `player`=? AND `id`=?";
@Language("SQLite")
private String createTable = "CREATE TABLE IF NOT EXISTS `{0}edits` (`player` BLOB(16) NOT NULL,`id` INT NOT NULL, `time` INT NOT NULL,`x1` INT NOT NULL,`x2` INT NOT NULL,`z1` INT NOT NULL,`z2` INT NOT NULL,`y1` INT NOT NULL, `y2` INT NOT NULL, `size` INT NOT NULL, `command` VARCHAR, PRIMARY KEY (player, id))";
@Language("SQLite")
private String updateTable1 = "ALTER TABLE `{0}edits` ADD COLUMN `command` VARCHAR";
@Language("SQLite")
private String updateTable2 = "alter table `{0}edits` add size int default 0 not null";
@Language("SQLite")
private String insertEdit = "INSERT OR REPLACE INTO `{0}edits` (`player`,`id`,`time`,`x1`,`x2`,`z1`,`z2`,`y1`,`y2`,`command`,`size`) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
@Language("SQLite")
private String purge = "DELETE FROM `{0}edits` WHERE `time`<?";
@Language("SQLite")
private String getEditsUser = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` DESC, `id` DESC";
@Language("SQLite")
private String getEditsUserAsc = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` ASC, `id` ASC";
@Language("SQLite")
private String getEdits = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` DESC, `id` DESC";
@Language("SQLite")
private String getEditsAsc = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` , `id` ";
@Language("SQLite")
private String getEditUser = "SELECT * FROM `{0}edits` WHERE `player`=? AND `id`=?";
private @Language("sql") String DELETE_EDITS_USER = "DELETE FROM `{0}edits` WHERE `player`=? AND `time`>? AND `x2`>=? AND `x1`<=? AND `y2`>=? AND `y1`<=? AND `z2`>=? AND `z1`<=?";
private @Language("sql") String DELETE_EDIT_USER = "DELETE FROM `{0}edits` WHERE `player`=? AND `id`=?";
@Language("SQLite")
private String deleteEditsUser = "DELETE FROM `{0}edits` WHERE `player`=? AND `time`>? AND `x2`>=? AND `x1`<=? AND `y2`>=? AND `y1`<=? AND `z2`>=? AND `z1`<=?";
@Language("SQLite")
private String deleteEditUser = "DELETE FROM `{0}edits` WHERE `player`=? AND `id`=?";
private ConcurrentLinkedQueue<RollbackOptimizedHistory> historyChanges = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<RollbackOptimizedHistory> historyChanges = new ConcurrentLinkedQueue<>();
RollbackDatabase(World world) throws SQLException, ClassNotFoundException {
super((t, e) -> e.printStackTrace());
@ -63,18 +75,18 @@ public class RollbackDatabase extends AsyncNotifyQueue {
connection = openConnection();
// update vars
CREATE_TABLE = CREATE_TABLE.replace("{0}", prefix);
UPDATE_TABLE1 = UPDATE_TABLE1.replace("{0}", prefix);
UPDATE_TABLE2 = UPDATE_TABLE2.replace("{0}", prefix);
INSERT_EDIT = INSERT_EDIT.replace("{0}", prefix);
PURGE = PURGE.replace("{0}", prefix);
GET_EDITS_USER = GET_EDITS_USER.replace("{0}", prefix);
GET_EDITS_USER_ASC = GET_EDITS_USER_ASC.replace("{0}", prefix);
GET_EDITS = GET_EDITS.replace("{0}", prefix);
GET_EDITS_ASC = GET_EDITS_ASC.replace("{0}", prefix);
GET_EDIT_USER = GET_EDIT_USER.replace("{0}", prefix);
DELETE_EDITS_USER = DELETE_EDITS_USER.replace("{0}", prefix);
DELETE_EDIT_USER = DELETE_EDIT_USER.replace("{0}", prefix);
createTable = createTable.replace("{0}", prefix);
updateTable1 = updateTable1.replace("{0}", prefix);
updateTable2 = updateTable2.replace("{0}", prefix);
insertEdit = insertEdit.replace("{0}", prefix);
purge = purge.replace("{0}", prefix);
getEditsUser = getEditsUser.replace("{0}", prefix);
getEditsUserAsc = getEditsUserAsc.replace("{0}", prefix);
getEdits = getEdits.replace("{0}", prefix);
getEditsAsc = getEditsAsc.replace("{0}", prefix);
getEditUser = getEditUser.replace("{0}", prefix);
deleteEditsUser = deleteEditsUser.replace("{0}", prefix);
deleteEditUser = deleteEditUser.replace("{0}", prefix);
try {
init().get();
@ -90,22 +102,24 @@ public class RollbackDatabase extends AsyncNotifyQueue {
public Future<Boolean> init() {
return call(() -> {
try (PreparedStatement stmt = connection.prepareStatement(CREATE_TABLE)) {
try (PreparedStatement stmt = connection.prepareStatement(createTable)) {
stmt.executeUpdate();
}
try (PreparedStatement stmt = connection.prepareStatement(UPDATE_TABLE1)) {
try (PreparedStatement stmt = connection.prepareStatement(updateTable1)) {
stmt.executeUpdate();
} catch (SQLException ignore) {} // Already updated
try (PreparedStatement stmt = connection.prepareStatement(UPDATE_TABLE2)) {
} catch (SQLException ignored) {
} // Already updated
try (PreparedStatement stmt = connection.prepareStatement(updateTable2)) {
stmt.executeUpdate();
} catch (SQLException ignore) {} // Already updated
} catch (SQLException ignored) {
} // Already updated
return true;
});
}
public Future<Integer> delete(UUID uuid, int id) {
return call(() -> {
try (PreparedStatement stmt = connection.prepareStatement(DELETE_EDIT_USER)) {
try (PreparedStatement stmt = connection.prepareStatement(deleteEditUser)) {
stmt.setBytes(1, toBytes(uuid));
stmt.setInt(2, id);
return stmt.executeUpdate();
@ -115,7 +129,7 @@ public class RollbackDatabase extends AsyncNotifyQueue {
public Future<RollbackOptimizedHistory> getEdit(@NotNull UUID uuid, int id) {
return call(() -> {
try (PreparedStatement stmt = connection.prepareStatement(GET_EDIT_USER)) {
try (PreparedStatement stmt = connection.prepareStatement(getEditUser)) {
stmt.setBytes(1, toBytes(uuid));
stmt.setInt(2, id);
ResultSet result = stmt.executeQuery();
@ -155,7 +169,7 @@ public class RollbackDatabase extends AsyncNotifyQueue {
long now = System.currentTimeMillis() / 1000;
final int then = (int) (now - diff);
return call(() -> {
try (PreparedStatement stmt = connection.prepareStatement(PURGE)) {
try (PreparedStatement stmt = connection.prepareStatement(purge)) {
stmt.setInt(1, then);
return stmt.executeUpdate();
}
@ -172,8 +186,8 @@ public class RollbackDatabase extends AsyncNotifyQueue {
Future<Integer> future = call(() -> {
try {
int count = 0;
String stmtStr = ascending ? uuid == null ? GET_EDITS_ASC : GET_EDITS_USER_ASC :
uuid == null ? GET_EDITS : GET_EDITS_USER;
String stmtStr = ascending ? uuid == null ? getEditsAsc : getEditsUserAsc :
uuid == null ? getEdits : getEditsUser;
try (PreparedStatement stmt = connection.prepareStatement(stmtStr)) {
stmt.setInt(1, (int) (minTime / 1000));
stmt.setInt(2, pos1.getBlockX());
@ -197,7 +211,7 @@ public class RollbackDatabase extends AsyncNotifyQueue {
} while (result.next());
}
if (delete && uuid != null) {
try (PreparedStatement stmt = connection.prepareStatement(DELETE_EDITS_USER)) {
try (PreparedStatement stmt = connection.prepareStatement(deleteEditsUser)) {
stmt.setInt(1, (int) (minTime / 1000));
stmt.setInt(2, pos1.getBlockX());
stmt.setInt(3, pos2.getBlockX());
@ -239,7 +253,7 @@ public class RollbackDatabase extends AsyncNotifyQueue {
RollbackOptimizedHistory[] copy = IntStream.range(0, size)
.mapToObj(i -> historyChanges.poll()).toArray(RollbackOptimizedHistory[]::new);
try (PreparedStatement stmt = connection.prepareStatement(INSERT_EDIT)) {
try (PreparedStatement stmt = connection.prepareStatement(insertEdit)) {
// `player`,`id`,`time`,`x1`,`x2`,`z1`,`z2`,`y1`,`y2`,`command`,`size`) VALUES(?,?,?,?,?,?,?,?,?,?,?)"
for (RollbackOptimizedHistory change : copy) {
UUID uuid = change.getUUID();
@ -310,7 +324,7 @@ public class RollbackDatabase extends AsyncNotifyQueue {
}
/**
* Gets the connection with the database
* Gets the connection with the database.
*
* @return Connection with the database, null if none
*/
@ -326,7 +340,7 @@ public class RollbackDatabase extends AsyncNotifyQueue {
}
/**
* Closes the connection with the database
* Closes the connection with the database.
*
* @return true if successful
* @throws SQLException if the connection cannot be closed
@ -346,7 +360,7 @@ public class RollbackDatabase extends AsyncNotifyQueue {
}
/**
* Checks if a connection is open with the database
* Checks if a connection is open with the database.
*
* @return true if the connection is open
*/

View File

@ -37,6 +37,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ -276,7 +277,7 @@ public class MCAChunk implements IChunk {
int ordinal = blocks[i];
int palette = blockToPalette[ordinal];
if (palette == Integer.MAX_VALUE) {
// BlockState state = BlockTypesCache.states[ordinal];
//BlockState state = BlockTypesCache.states[ordinal];
blockToPalette[ordinal] = palette = num_palette;
paletteToBlock[num_palette] = ordinal;
num_palette++;
@ -308,7 +309,7 @@ public class MCAChunk implements IChunk {
String valueStr = value.toString();
if (Character.isUpperCase(valueStr.charAt(0))) {
System.out.println("Invalid uppercase value " + value);
valueStr = valueStr.toLowerCase();
valueStr = valueStr.toLowerCase(Locale.ROOT);
}
out.writeNamedTag(key, valueStr);
}
@ -337,13 +338,13 @@ public class MCAChunk implements IChunk {
}
// out.writeNamedTagName("BlockLight", NBTConstants.TYPE_BYTE_ARRAY);
// out.writeInt(2048);
// out.write(blockLight, layer << 11, 1 << 11);
//
// out.writeNamedTagName("SkyLight", NBTConstants.TYPE_BYTE_ARRAY);
// out.writeInt(2048);
// out.write(skyLight, layer << 11, 1 << 11);
/* out.writeNamedTagName("BlockLight", NBTConstants.TYPE_BYTE_ARRAY);
out.writeInt(2048);
out.write(blockLight, layer << 11, 1 << 11);
out.writeNamedTagName("SkyLight", NBTConstants.TYPE_BYTE_ARRAY);
out.writeInt(2048);
out.write(skyLight, layer << 11, 1 << 11); */
out.writeEndTag();
@ -397,9 +398,13 @@ public class MCAChunk implements IChunk {
@Override
public boolean isEmpty() {
if (deleted) return true;
if (deleted) {
return true;
}
for (boolean hasSection : hasSections) {
if (hasSection) return false;
if (hasSection) {
return false;
}
}
return true;
}
@ -450,15 +455,19 @@ public class MCAChunk implements IChunk {
}
@Override public void removeSectionLighting(int layer, boolean sky) {}
@Override public void removeSectionLighting(int layer, boolean sky) {
}
@Override public void setFullBright(int layer) {}
@Override public void setFullBright(int layer) {
}
@Override
public void setLightLayer(int layer, char[] toSet) {}
public void setLightLayer(int layer, char[] toSet) {
}
@Override
public void setSkyLightLayer(int layer, char[] toSet) {}
public void setSkyLightLayer(int layer, char[] toSet) {
}
@Override
public void setEntity(CompoundTag entityTag) {

View File

@ -66,7 +66,8 @@ public class MCAFile extends ExtentBatchProcessorHolder implements Trimable, ICh
private RandomAccessFile raf;
private boolean deleted;
private int X, Z;
private int X;
private int Z;
private MCAChunk[] chunks;
private boolean[] chunkInitialized;
private Object[] locks;
@ -336,7 +337,7 @@ public class MCAFile extends ExtentBatchProcessorHolder implements Trimable, ICh
if (size != 0) {
try {
onEach.accept(getChunk(x, z));
} catch (Throwable ignore) {
} catch (Throwable ignored) {
}
}
}
@ -462,7 +463,9 @@ public class MCAFile extends ExtentBatchProcessorHolder implements Trimable, ICh
}
public void close() {
if (raf == null) return;
if (raf == null) {
return;
}
synchronized (raf) {
if (raf != null) {
flush(true);

View File

@ -100,7 +100,9 @@ public class StreamDelegate {
default: {
for (; index < keys.length; index++) {
byte[] key = keys[index];
if (key.length < nameLength) continue;
if (key.length < nameLength) {
continue;
}
if (key.length == nameLength) {
break;
} else {

View File

@ -42,7 +42,9 @@ public class DataAnglePattern extends AbstractPattern {
public BaseBlock apply(BlockVector3 position) {
BlockState block = extent.getBlock(position);
int slope = getSlope(block, position, extent);
if (slope == -1) return block.toBaseBlock();
if (slope == -1) {
return block.toBaseBlock();
}
int data = Math.min(slope, 255) >> 4;
return block.withPropertyId(data).toBaseBlock();
}
@ -51,7 +53,9 @@ public class DataAnglePattern extends AbstractPattern {
public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException {
BlockState block = extent.getBlock(getPosition);
int slope = getSlope(block, getPosition, extent);
if (slope == -1) return false;
if (slope == -1) {
return false;
}
int data = Math.min(slope, 255) >> 4;
return extent.setBlock(setPosition, block.withPropertyId(data));
}

View File

@ -136,72 +136,100 @@ public class FaweLimit {
}
public void THROW_MAX_CHANGES() {
if (MAX_CHANGES-- <= 0) throw FaweCache.MAX_CHANGES;
if (MAX_CHANGES-- <= 0) {
throw FaweCache.MAX_CHANGES;
}
}
public void THROW_MAX_FAILS() {
if (MAX_FAILS-- <= 0) throw FaweCache.MAX_CHECKS;
if (MAX_FAILS-- <= 0) {
throw FaweCache.MAX_CHECKS;
}
}
public void THROW_MAX_CHECKS() {
if (MAX_CHECKS-- <= 0) throw FaweCache.MAX_CHECKS;
if (MAX_CHECKS-- <= 0) {
throw FaweCache.MAX_CHECKS;
}
}
public void THROW_MAX_ITERATIONS() {
if (MAX_ITERATIONS-- <= 0) throw FaweCache.MAX_ITERATIONS;
if (MAX_ITERATIONS-- <= 0) {
throw FaweCache.MAX_ITERATIONS;
}
}
public void THROW_MAX_BLOCKSTATES() {
if (MAX_BLOCKSTATES-- <= 0) throw FaweCache.MAX_TILES;
if (MAX_BLOCKSTATES-- <= 0) {
throw FaweCache.MAX_TILES;
}
}
public void THROW_MAX_ENTITIES() {
if (MAX_ENTITIES-- <= 0) throw FaweCache.MAX_ENTITIES;
if (MAX_ENTITIES-- <= 0) {
throw FaweCache.MAX_ENTITIES;
}
}
public void THROW_MAX_CHANGES(int amt) {
if ((MAX_CHANGES -= amt) <= 0) throw FaweCache.MAX_CHANGES;
if ((MAX_CHANGES -= amt) <= 0) {
throw FaweCache.MAX_CHANGES;
}
}
public void THROW_MAX_CHANGES(long amt) {
if ((MAX_CHANGES -= amt) <= 0) throw FaweCache.MAX_CHANGES;
if ((MAX_CHANGES -= amt) <= 0) {
throw FaweCache.MAX_CHANGES;
}
}
public void THROW_MAX_FAILS(int amt) {
if ((MAX_FAILS -= amt) <= 0) throw FaweCache.MAX_CHECKS;
if ((MAX_FAILS -= amt) <= 0) {
throw FaweCache.MAX_CHECKS;
}
}
public void THROW_MAX_CHECKS(int amt) {
if ((MAX_CHECKS -= amt) <= 0) throw FaweCache.MAX_CHECKS;
if ((MAX_CHECKS -= amt) <= 0) {
throw FaweCache.MAX_CHECKS;
}
}
public void THROW_MAX_CHECKS(long amt) {
if ((MAX_CHECKS -= amt) <= 0) throw FaweCache.MAX_CHECKS;
if ((MAX_CHECKS -= amt) <= 0) {
throw FaweCache.MAX_CHECKS;
}
}
public void THROW_MAX_ITERATIONS(int amt) {
if ((MAX_ITERATIONS -= amt) <= 0) throw FaweCache.MAX_ITERATIONS;
if ((MAX_ITERATIONS -= amt) <= 0) {
throw FaweCache.MAX_ITERATIONS;
}
}
public void THROW_MAX_BLOCKSTATES(int amt) {
if ((MAX_BLOCKSTATES -= amt) <= 0) throw FaweCache.MAX_TILES;
if ((MAX_BLOCKSTATES -= amt) <= 0) {
throw FaweCache.MAX_TILES;
}
}
public void THROW_MAX_ENTITIES(int amt) {
if ((MAX_ENTITIES -= amt) <= 0) throw FaweCache.MAX_ENTITIES;
if ((MAX_ENTITIES -= amt) <= 0) {
throw FaweCache.MAX_ENTITIES;
}
}
public boolean isUnlimited() {
return MAX_CHANGES == Integer.MAX_VALUE &&
MAX_FAILS == Integer.MAX_VALUE &&
MAX_CHECKS == Integer.MAX_VALUE &&
MAX_ITERATIONS == Integer.MAX_VALUE &&
MAX_BLOCKSTATES == Integer.MAX_VALUE &&
MAX_ENTITIES == Integer.MAX_VALUE &&
MAX_HISTORY == Integer.MAX_VALUE &&
INVENTORY_MODE == 0 &&
SPEED_REDUCTION == 0 &&
FAST_PLACEMENT &&
(STRIP_NBT == null || STRIP_NBT.isEmpty());
return MAX_CHANGES == Integer.MAX_VALUE
&& MAX_FAILS == Integer.MAX_VALUE
&& MAX_CHECKS == Integer.MAX_VALUE
&& MAX_ITERATIONS == Integer.MAX_VALUE
&& MAX_BLOCKSTATES == Integer.MAX_VALUE
&& MAX_ENTITIES == Integer.MAX_VALUE
&& MAX_HISTORY == Integer.MAX_VALUE
&& INVENTORY_MODE == 0
&& SPEED_REDUCTION == 0
&& FAST_PLACEMENT
&& (STRIP_NBT == null || STRIP_NBT.isEmpty());
}
public void set(FaweLimit limit) {

View File

@ -5,7 +5,7 @@ import com.sk89q.worldedit.regions.CuboidRegion;
@Deprecated
public class RegionWrapper extends CuboidRegion {
private final static RegionWrapper GLOBAL = new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
private static final RegionWrapper GLOBAL = new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
public int minX;
public int maxX;

View File

@ -21,7 +21,6 @@ public class BlendBall implements Brush {
int ty = position.getBlockY();
int tz = position.getBlockZ();
// Map<BlockState, Integer> frequency = Maps.newHashMap();
int[] frequency = new int[BlockTypes.size()];
int maxY = editSession.getMaximumPoint().getBlockY();

View File

@ -64,9 +64,9 @@ public class BlobBrush implements Brush {
}
} else {
AffineTransform transform = new AffineTransform()
.rotateX(ThreadLocalRandom.current().nextInt(360))
.rotateY(ThreadLocalRandom.current().nextInt(360))
.rotateZ(ThreadLocalRandom.current().nextInt(360));
.rotateX(ThreadLocalRandom.current().nextInt(360))
.rotateY(ThreadLocalRandom.current().nextInt(360))
.rotateZ(ThreadLocalRandom.current().nextInt(360));
double manScaleX = 1.25 + seedX * 0.5;
double manScaleY = 1.25 + seedY * 0.5;
@ -93,9 +93,7 @@ public class BlobBrush implements Brush {
double manDist = xScaled + yScaled + zScaled;
double distSqr = x * x * modX + z * z * modZ + y * y * modY;
double distance =
Math.sqrt(distSqr) * sphericity +
MathMan.max(manDist, xScaled * manScaleX, yScaled * manScaleY, zScaled * manScaleZ) * roughness;
double distance = Math.sqrt(distSqr) * sphericity + MathMan.max(manDist, xScaled * manScaleX, yScaled * manScaleY, zScaled * manScaleZ) * roughness;
double noise = this.amplitude * SimplexNoise.noise(seedX + x * distort, seedZ + z * distort, seedZ + z * distort);
if (distance + distance * noise < radius) {

View File

@ -6,6 +6,7 @@ import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.tool.brush.Brush;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
@ -17,7 +18,9 @@ import java.util.List;
public class CatenaryBrush implements Brush, ResettableTool {
private final boolean shell, select, direction;
private final boolean shell;
private final boolean select;
private final boolean direction;
private final double slack;
private BlockVector3 pos1;
@ -34,21 +37,25 @@ public class CatenaryBrush implements Brush, ResettableTool {
@Override
public void build(EditSession editSession, BlockVector3 pos2, final Pattern pattern, double size) throws MaxChangedBlocksException {
boolean visual = editSession.getExtent() instanceof VisualExtent;
Player player = editSession.getPlayer();
if (player == null) {
return; //todo throw error
}
if (pos1 == null || pos2.equals(pos1)) {
if (!visual) {
pos1 = pos2;
editSession.getPlayer().print(Caption.of("fawe.worldedit.brush.brush.line.primary", pos2));
player.print(Caption.of("fawe.worldedit.brush.brush.line.primary", pos2));
}
return;
}
if (this.vertex == null) {
vertex = getVertex(pos1.toVector3(), pos2.toVector3(), slack);
if (this.direction) {
editSession.getPlayer().print(Caption.of("fawe.worldedit.brush.brush.catenary.direction", 2));
player.print(Caption.of("fawe.worldedit.brush.brush.catenary.direction", 2));
return;
}
} else if (this.direction) {
Location loc = editSession.getPlayer().getLocation();
Location loc = player.getLocation();
Vector3 facing = loc.getDirection().normalize();
BlockVector3 midpoint = pos1.add(pos2).divide(2);
BlockVector3 offset = midpoint.subtract(vertex);
@ -62,7 +69,7 @@ public class CatenaryBrush implements Brush, ResettableTool {
e.printStackTrace();
}
if (!visual) {
editSession.getPlayer().print(TranslatableComponent.of("fawe.worldedit.brush.brush.line.secondary"));
player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.line.secondary"));
if (!select) {
pos1 = null;
return;
@ -78,7 +85,9 @@ public class CatenaryBrush implements Brush, ResettableTool {
}
public static BlockVector3 getVertex(Vector3 pos1, Vector3 pos2, double lenPercent) {
if (lenPercent <= 1) return pos1.add(pos2).divide(2).toBlockPoint();
if (lenPercent <= 1) {
return pos1.add(pos2).divide(2).toBlockPoint();
}
double curveLen = pos1.distance(pos2) * lenPercent;
double dy = pos2.getY() - pos1.getY();
double dx = pos2.getX() - pos1.getX();
@ -86,8 +95,10 @@ public class CatenaryBrush implements Brush, ResettableTool {
double dh = Math.sqrt(dx * dx + dz * dz);
double g = Math.sqrt(curveLen * curveLen - dy * dy) / 2;
double a = 0.00001;
for (;g < a * Math.sinh(dh/(2 * a)); a *= 1.00001);
double vertX = (dh-a*Math.log((curveLen + dy)/(curveLen - dy)))/2.0;
for (; g < a * Math.sinh(dh / (2 * a)); a *= 1.00001) {
;
}
double vertX = (dh - a * Math.log((curveLen + dy) / (curveLen - dy))) / 2.0;
double z = (dh / 2) / a;
double oY = (dy - curveLen * (Math.cosh(z) / Math.sinh(z))) / 2;
double vertY = a * 1 + oY;

View File

@ -90,7 +90,7 @@ public class CopyPastaBrush implements Brush, ResettableTool {
ClipboardHolder holder = new ClipboardHolder(newClipboard);
session.setClipboard(holder);
int blocks = builder.size();
player.print(Caption.of("fawe.worldedit.copy.command.copy" , blocks));
player.print(Caption.of("fawe.worldedit.copy.command.copy", blocks));
} else {
AffineTransform transform = null;
if (randomRotate) {
@ -99,7 +99,9 @@ public class CopyPastaBrush implements Brush, ResettableTool {
transform = transform.rotateY(rotate);
}
if (autoRotate) {
if (transform == null) transform = new AffineTransform();
if (transform == null) {
transform = new AffineTransform();
}
Location loc = player.getLocation();
float yaw = loc.getYaw();
float pitch = loc.getPitch();

View File

@ -20,7 +20,10 @@ import java.util.Arrays;
public class ErodeBrush implements Brush {
private static final BlockVector3[] FACES_TO_CHECK = Direction.valuesOf(Direction.Flag.CARDINAL).stream().map(Direction::toBlockVector).toArray(BlockVector3[]::new);
private final int erodeFaces, erodeRecursion, fillFaces, fillRecursion;
private final int erodeFaces;
private final int erodeRecursion;
private final int fillFaces;
private final int fillRecursion;
public ErodeBrush() {
this(2, 1, 5, 1);

View File

@ -30,7 +30,9 @@ public class FallingSphere implements Brush {
int ax = px + x;
int remainingY = remaining - xx;
if (remainingY < 0) continue;
if (remainingY < 0) {
continue;
}
int yRadius = MathMan.usqrt(remainingY);
int startY = Math.max(0, py - yRadius);

View File

@ -99,11 +99,19 @@ public class HeightBrush implements Brush {
for (int z = minZ; z <= maxZ; z++, zIndex += width) {
int zz = bz + z;
int index = zIndex + (bx + minX);
if (index < minIndex) continue;
if (index >= metaHeight.length) break;
if (index < minIndex) {
continue;
}
if (index >= metaHeight.length) {
break;
}
for (int x = minX; x <= maxX; x++, index++) {
if (index < 0) continue;
if (index >= metaHeight.length) break;
if (index < 0) {
continue;
}
if (index >= metaHeight.length) {
break;
}
int xx = bx + x;
int currentBlockHeight = hmmg.getHeight(index);

View File

@ -76,7 +76,6 @@ public class ImageBrush implements Brush {
float yaw = loc.getYaw();
float pitch = loc.getPitch();
AffineTransform transform = new AffineTransform().rotateY((-yaw) % 360).rotateX((pitch - 90) % 360).inverse();
RecursiveVisitor visitor = new RecursiveVisitor(
new ImageBrushMask(solid, center, transform, scale, centerImageX, centerImageZ, width, height, colorFunction, editSession,
session.getTextureUtil()), vector -> true, Integer.MAX_VALUE);

View File

@ -107,7 +107,7 @@ public class InspectBrush extends BrushTool {
player.print(msg);
}
}
player.print(Caption.of("fawe.worldedit.tool.tool.inspect.info.footer" , count));
player.print(Caption.of("fawe.worldedit.tool.tool.inspect.info.footer", count));
} catch (IOException e) {
System.out.println("IOE");
throw new RuntimeException(e);

View File

@ -11,7 +11,9 @@ import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
public class LineBrush implements Brush, ResettableTool {
private final boolean shell, select, flat;
private final boolean shell;
private final boolean select;
private final boolean flat;
private BlockVector3 pos1;
public LineBrush(boolean shell, boolean select, boolean flat) {

View File

@ -33,9 +33,9 @@ public class RockBrush implements Brush {
double distort = this.frequency / size;
double modX = 1d/radius.getX();
double modY = 1d/radius.getY();
double modZ = 1d/radius.getZ();
double modX = 1D / radius.getX();
double modY = 1D / radius.getY();
double modZ = 1D / radius.getZ();
int radiusSqr = (int) (size * size);
int sizeInt = (int) size * 2;

View File

@ -39,10 +39,14 @@ public class SurfaceSpline implements Brush {
boolean vis = editSession.getExtent() instanceof VisualExtent;
if (path.isEmpty() || !pos.equals(path.get(path.size() - 1))) {
int max = editSession.getNearestSurfaceTerrainBlock(pos.getBlockX(), pos.getBlockZ(), pos.getBlockY(), 0, editSession.getMaxY());
if (max == -1) return;
if (max == -1) {
return;
}
path.add(BlockVector3.at(pos.getBlockX(), max, pos.getBlockZ()));
editSession.getPlayer().printInfo(TranslatableComponent.of("fawe.worldedit.brush.spline.primary.2"));
if (!vis) return;
if (!vis) {
return;
}
}
final List<Node> nodes = new ArrayList<>(path.size());
final KochanekBartelsInterpolation interpol = new KochanekBartelsInterpolation();
@ -64,7 +68,9 @@ public class SurfaceSpline implements Brush {
final int tipz = (int) tipv.getZ();
int tipy = MathMan.roundInt(tipv.getY());
tipy = editSession.getNearestSurfaceTerrainBlock(tipx, tipz, tipy, 0, maxY);
if (tipy == -1) continue;
if (tipy == -1) {
continue;
}
if (radius == 0) {
BlockVector3 set = mutable.setComponents(tipx, tipy, tipz);
try {
@ -81,19 +87,25 @@ public class SurfaceSpline implements Brush {
LocalBlockVectorSet newSet = new LocalBlockVectorSet();
final int ceilrad = (int) Math.ceil(radius);
for (BlockVector3 v : vset) {
final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ();
final int tipx = v.getBlockX();
final int tipy = v.getBlockY();
final int tipz = v.getBlockZ();
for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) {
for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) {
if (MathMan.hypot2(loopx - tipx, 0, loopz - tipz) <= radius2) {
int y = editSession.getNearestSurfaceTerrainBlock(loopx, loopz, v.getBlockY(), 0, maxY);
if (y == -1) continue;
if (y == -1) {
continue;
}
newSet.add(loopx, y, loopz);
}
}
}
}
editSession.setBlocks(newSet, pattern);
if (!vis) path.clear();
if (!vis) {
path.clear();
}
}
editSession.getPlayer().printInfo(TranslatableComponent.of("fawe.worldedit.brush.spline.secondary"));
}

View File

@ -4,9 +4,11 @@ public class ArrayHeightMap extends ScalableHeightMap {
// The heights
private final byte[][] height;
// The height map width/length
private final int width, length;
private final int width;
private final int length;
// The size to width/length ratio
private double rx, rz;
private double rx;
private double rz;
public ArrayHeightMap(byte[][] height) {
setSize(5);

View File

@ -13,7 +13,7 @@ import com.sk89q.worldedit.util.Location;
import java.util.concurrent.ThreadLocalRandom;
public interface HeightMap {
double getHeight(int x, int z);
void setSize(int size);
@ -89,7 +89,9 @@ public interface HeightMap {
height = tmpY = session.getNearestSurfaceLayer(xx, zz, tmpY, 0, maxY);
} else {
height = tmpY = session.getNearestSurfaceTerrainBlock(xx, zz, tmpY, 0, maxY);
if (height == -1) continue;
if (height == -1) {
continue;
}
}
oldData[index] = height;
if (height == 0) {
@ -131,7 +133,9 @@ public interface HeightMap {
height = session.getNearestSurfaceLayer(xx, zz, height, 0, maxY);
} else {
height = session.getNearestSurfaceTerrainBlock(xx, zz, height, 0, maxY);
if (height == -1) continue;
if (height == -1) {
continue;
}
}
oldData[index] = height;
if (height == 0) {

View File

@ -15,6 +15,7 @@ import com.sk89q.worldedit.function.pattern.Pattern;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public abstract class Scroll implements ScrollTool {
private BrushTool tool;
@ -32,7 +33,7 @@ public abstract class Scroll implements ScrollTool {
public static Scroll fromArguments(BrushTool tool, Player player, LocalSession session, String actionArgs, boolean message) {
String[] split = actionArgs.split(" ");
Action mode = Action.valueOf(split[0].toUpperCase());
Action mode = Action.valueOf(split[0].toUpperCase(Locale.ROOT));
List<String> args = Arrays.asList(Arrays.copyOfRange(split, 1, split.length));
return fromArguments(tool, player, session, mode, args, message);
}
@ -47,7 +48,9 @@ public abstract class Scroll implements ScrollTool {
return null;
case CLIPBOARD:
if (arguments.size() != 2) {
if (message) player.print(Caption.of("fawe.error.command.syntax" , "clipboard [file]"));
if (message) {
player.print(Caption.of("fawe.error.command.syntax", "clipboard [file]"));
}
return null;
}
String filename = arguments.get(1);
@ -62,7 +65,9 @@ public abstract class Scroll implements ScrollTool {
}
case MASK:
if (arguments.size() < 2) {
if (message) player.print(Caption.of("fawe.error.command.syntax" , "mask [mask 1] [mask 2] [mask 3]..."));
if (message) {
player.print(Caption.of("fawe.error.command.syntax", "mask [mask 1] [mask 2] [mask 3]..."));
}
return null;
}
Mask[] masks = new Mask[arguments.size() - 1];
@ -73,7 +78,9 @@ public abstract class Scroll implements ScrollTool {
return (new ScrollMask(tool, masks));
case PATTERN:
if (arguments.size() < 2) {
if (message) player.print(Caption.of("fawe.error.command.syntax" , "pattern [pattern 1] [pattern 2] [pattern 3]..."));
if (message) {
player.print(Caption.of("fawe.error.command.syntax", "pattern [pattern 1] [pattern 2] [pattern 3]..."));
}
return null;
}
Pattern[] patterns = new Pattern[arguments.size() - 1];

View File

@ -33,34 +33,44 @@ public class ClipboardSpline extends Spline {
private LocalBlockVectorSet buffer;
/**
* Constructor without position-correction. Use this constructor for an interpolation implementation which does not need position-correction.
* <p>
* Be advised that currently subsequent changes to the interpolation parameters may not be supported.
* @param editSession The EditSession which will be used when pasting the clipboard content
* Constructor without position-correction. Use this constructor for an interpolation
* implementation which does not need position-correction.
*
* @param editSession The EditSession which will be used when pasting the clipboard content
* @param clipboardHolder The clipboard that will be pasted along the spline
* @param interpolation An implementation of the interpolation algorithm used to calculate the curve
* @param interpolation An implementation of the interpolation algorithm used to calculate
* the curve
* @apiNote Be advised that currently subsequent changes to the interpolation parameters may
* not be supported.
*/
public ClipboardSpline(EditSession editSession, ClipboardHolder clipboardHolder, Interpolation interpolation) {
this(editSession, clipboardHolder, interpolation, new AffineTransform(), -1);
}
/**
* Constructor with position-correction. Use this constructor for an interpolation implementation that needs position-correction.
* Constructor with position-correction. Use this constructor for an interpolation
* implementation that needs position-correction.
*
* <p>
* Some interpolation implementations calculate the position on the curve (used by {@link #pastePosition(double)})
* based on an equidistant distribution of the nodes on the curve. For example: on a spline with 5 nodes position 0.0 would refer
* to the first node, 0.25 to the second, 0.5 to the third, ... .<br>
* By providing this method with the amount of nodes used by the interpolation implementation the distribution of the
* nodes is converted to a proportional distribution based on the length between two adjacent nodes calculated by {@link Interpolation#arcLength(double, double)}.<br>
* This means that the distance between two positions used to paste the clipboard (e.g., 0.75 - 0.5 = 0.25) on the curve
* will always amount to that part of the length (e.g., 40 units) of the curve. In this example it would amount to
* 0.25 × 40 = 10 units of curve length between these two positions.
* <p>
* Be advised that currently subsequent changes to the interpolation parameters may not be supported.
* @param editSession The EditSession which will be used when pasting the clipboard content
* Some interpolation implementations calculate the position on the curve (used by {@link
* #pastePosition(double)}) based on an equidistant distribution of the nodes on the curve. For
* example: on a spline with 5 nodes position 0.0 would refer to the first node, 0.25 to the
* second, 0.5 to the third, ... .<br> By providing this method with the amount of nodes used by
* the interpolation implementation the distribution of the nodes is converted to a proportional
* distribution based on the length between two adjacent nodes calculated by {@link
* Interpolation#arcLength(double, double)}.<br> This means that the distance between two
* positions used to paste the clipboard (e.g., 0.75 - 0.5 = 0.25) on the curve will always
* amount to that part of the length (e.g., 40 units) of the curve. In this example it would
* amount to 0.25 × 40 = 10 units of curve length between these two positions.
* </p>
*
* @param editSession The EditSession which will be used when pasting the clipboard content
* @param clipboardHolder The clipboard that will be pasted along the spline
* @param interpolation An implementation of the interpolation algorithm used to calculate the curve
* @param nodeCount The number of nodes provided to the interpolation object
* @param interpolation An implementation of the interpolation algorithm used to calculate
* the curve
* @param nodeCount The number of nodes provided to the interpolation object
* @apiNote Be advised that currently subsequent changes to the interpolation parameters may
* not be supported.
*/
public ClipboardSpline(EditSession editSession, ClipboardHolder clipboardHolder, Interpolation interpolation, Transform transform, int nodeCount) {
super(editSession, interpolation, nodeCount);
@ -72,7 +82,7 @@ public class ClipboardSpline extends Spline {
Region region = clipboard.getRegion();
BlockVector3 origin = clipboard.getOrigin();
// center = region.getCenter().setY(origin.getY() - 1);
// center = region.getCenter().setY(origin.getY() - 1);
center = region.getCenter().withY(origin.getY() - 1).toBlockPoint();
this.centerOffset = center.subtract(center.round());
this.center = center.subtract(centerOffset);

View File

@ -2,7 +2,6 @@ package com.boydti.fawe.object.brush.sweep;
import com.boydti.fawe.object.brush.ResettableTool;
import com.boydti.fawe.object.brush.visualization.VisualExtent;
import com.boydti.fawe.util.MathMan;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.EmptyClipboardException;
import com.sk89q.worldedit.LocalSession;
@ -12,15 +11,12 @@ import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.MutableVector3;
import com.sk89q.worldedit.math.Vector2;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.math.interpolation.Interpolation;
import com.sk89q.worldedit.math.interpolation.KochanekBartelsInterpolation;
import com.sk89q.worldedit.math.interpolation.Node;
import com.sk89q.worldedit.math.interpolation.ReparametrisingInterpolation;
import com.sk89q.worldedit.math.transform.AffineTransform;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
@ -91,7 +87,7 @@ public class SweepBrush implements Brush, ResettableTool {
ClipboardSpline spline = new ClipboardSpline(editSession, holder, interpol, transform, nodes.size());
if (dimensions.getBlockX() > dimensions.getBlockZ()) {
if (dimensions.getBlockX() > dimensions.getBlockZ()) {
spline.setDirection(Vector2.at(0, 1));
}

View File

@ -45,7 +45,7 @@ public final class CFIDrawer {
int start = i * size;
int end = Math.min(heights.length, start + size);
pool.submit((Runnable) () -> {
for (int index = start; index < end; index ++) {
for (int index = start; index < end; index++) {
int height = (heights[index] & 0xFF);
char ordinal;
if ((ordinal = overlay[index]) == 0) {
@ -105,11 +105,11 @@ public final class CFIDrawer {
int c0 = tu.getBiome(biomes[index] & 0xFF).grassCombined;
int c2 = getBiome(biomes, index + 1 + width, index);
int c1 = getBiome(biomes, index - 1 - width, index);
// int c3 = getBiome(biomes, index + width, index);
// int c4 = getBiome(biomes, index - width, index);
int r = ((c0 >> 16) & 0xFF) + ((c1 >> 16) & 0xFF) + ((c2 >> 16) & 0xFF);// + ((c3 >> 16) & 0xFF) + ((c4 >> 16) & 0xFF);
int g = ((c0 >> 8) & 0xFF) + ((c1 >> 8) & 0xFF) + ((c2 >> 8) & 0xFF);// + ((c3 >> 8) & 0xFF) + ((c4 >> 8) & 0xFF);
int b = ((c0) & 0xFF) + ((c1) & 0xFF) + ((c2) & 0xFF);// + ((c3) & 0xFF) + ((c4) & 0xFF);
// int c3 = getBiome(biomes, index + width, index);
// int c4 = getBiome(biomes, index - width, index);
int r = ((c0 >> 16) & 0xFF) + ((c1 >> 16) & 0xFF) + ((c2 >> 16) & 0xFF); // + ((c3 >> 16) & 0xFF) + ((c4 >> 16) & 0xFF);
int g = ((c0 >> 8) & 0xFF) + ((c1 >> 8) & 0xFF) + ((c2 >> 8) & 0xFF); // + ((c3 >> 8) & 0xFF) + ((c4 >> 8) & 0xFF);
int b = ((c0) & 0xFF) + ((c1) & 0xFF) + ((c2) & 0xFF); // + ((c3) & 0xFF) + ((c4) & 0xFF);
r = r * 85 >> 8;
g = g * 85 >> 8;
b = b * 85 >> 8;
@ -117,7 +117,9 @@ public final class CFIDrawer {
}
private final int getBiome(byte[] biomes, int newIndex, int index) {
if (newIndex < 0 || newIndex >= biomes.length) newIndex = index;
if (newIndex < 0 || newIndex >= biomes.length) {
newIndex = index;
}
int biome = biomes[newIndex] & 0xFF;
return tu.getBiome(biome).grassCombined;
}
@ -125,16 +127,18 @@ public final class CFIDrawer {
private int getSlope(byte[] heights, int width, int index, int height) {
return (
+ getHeight(heights, index + 1, height)
// + getHeight(heights, index + width, height)
+ getHeight(heights, index + width + 1, height)
- getHeight(heights, index - 1, height)
// - getHeight(heights, index - width, height)
- getHeight(heights, index - width - 1, height)
);
// + getHeight(heights, index + width, height)
+ getHeight(heights, index + width + 1, height)
- getHeight(heights, index - 1, height)
// - getHeight(heights, index - width, height)
- getHeight(heights, index - width - 1, height)
);
}
private int getHeight(byte[] heights, int index, int height) {
if (index < 0 || index >= heights.length) return height;
if (index < 0 || index >= heights.length) {
return height;
}
return heights[index] & 0xFF;
}
}

View File

@ -799,7 +799,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr
try {
blocks.set(x, y, z, combined);
return true;
} catch (IndexOutOfBoundsException ignore) {
} catch (IndexOutOfBoundsException ignored) {
return false;
}
}

View File

@ -20,7 +20,8 @@ public abstract class MCAWriter implements Extent {
private final int length;
private final int width;
private final int area;
private int OX, OZ;
private int OX;
private int OZ;
public MCAWriter(int width, int length, File regionFolder) {
@ -91,7 +92,7 @@ public abstract class MCAWriter implements Extent {
final ForkJoinPool pool = new ForkJoinPool();
int tcx = (width - 1) >> 4;
int tcz = (length - 1) >> 4;
try (CleanableThreadLocal<MCAChunk> chunkStore = createCache()){
try (CleanableThreadLocal<MCAChunk> chunkStore = createCache()) {
final ThreadLocal<byte[]> byteStore1 = ThreadLocal.withInitial(() -> new byte[500000]);
final ThreadLocal<byte[]> byteStore2 = ThreadLocal.withInitial(() -> new byte[500000]);
final ThreadLocal<Deflater> deflateStore = ThreadLocal

View File

@ -22,7 +22,7 @@ public interface StreamChange {
default void flushChanges(File file) throws IOException {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
try (LZ4BlockOutputStream compressed = new LZ4BlockOutputStream(out)) {
// compressed.setLevel(Deflater.BEST_SPEED);
// compressed.setLevel(Deflater.BEST_SPEED);
try (FaweOutputStream fos = new FaweOutputStream(compressed)) {
flushChanges(fos);
}

View File

@ -278,6 +278,10 @@ public abstract class AbstractChangeSet implements ChangeSet, IBatchProcessor {
}
}
public boolean isEmpty() {
return waitingCombined.get() == 0 && waitingAsync.get() == 0 && size() == 0;
}
public void add(BlockVector3 loc, BaseBlock from, BaseBlock to) {
int x = loc.getBlockX();
int y = loc.getBlockY();
@ -308,10 +312,6 @@ public abstract class AbstractChangeSet implements ChangeSet, IBatchProcessor {
}
}
public boolean isEmpty() {
return waitingCombined.get() == 0 && waitingAsync.get() == 0 && size() == 0;
}
public void add(int x, int y, int z, int combinedFrom, BaseBlock to) {
try {
if (to.hasNbtData()) {

View File

@ -29,21 +29,6 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet {
this.waitingAsync = parent.waitingAsync;
}
@Override
public void closeAsync() {
parent.closeAsync();
}
@Override
public void flush() {
parent.flush();
}
@Override
public void close() throws IOException {
parent.close();
}
public final AbstractChangeSet getParent() {
return parent;
}
@ -54,28 +39,13 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet {
}
@Override
public void add(int x, int y, int z, int combinedFrom, int combinedTo) {
parent.add(x, y, z, combinedFrom, combinedTo);
public void closeAsync() {
parent.closeAsync();
}
@Override
public Iterator<Change> backwardIterator() {
return parent.backwardIterator();
}
@Override
public Iterator<Change> forwardIterator() {
return parent.forwardIterator();
}
@Override
public int size() {
return parent.size();
}
@Override
public void addBiomeChange(int x, int z, BiomeType from, BiomeType to) {
parent.addBiomeChange(x, z, from, to);
public void flush() {
parent.flush();
}
@Override
@ -98,6 +68,11 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet {
parent.addEntityCreate(tag);
}
@Override
public void addBiomeChange(int x, int z, BiomeType from, BiomeType to) {
parent.addBiomeChange(x, z, from, to);
}
@Override
public Iterator<Change> getIterator(BlockBag blockBag, int mode, boolean redo) {
return parent.getIterator(blockBag, mode, redo);
@ -108,16 +83,6 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet {
return parent.getIterator(redo);
}
@Override
public void delete() {
parent.delete();
}
@Override
public ChangeSetSummary summarize(Region region, boolean shallow) {
return parent.summarize(region, shallow);
}
@Override
public EditSession toEditSession(Player player) {
return parent.toEditSession(player);
@ -128,6 +93,11 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet {
return parent.toEditSession(player, regions);
}
@Override
public void add(int x, int y, int z, int combinedFrom, int combinedTo) {
parent.add(x, y, z, combinedFrom, combinedTo);
}
@Override
public void add(EntityCreate change) {
parent.add(change);
@ -159,13 +129,28 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet {
}
@Override
public boolean isEmpty() {
return parent.isEmpty();
public void add(int x, int y, int z, int combinedFrom, BaseBlock to) {
parent.add(x, y, z, combinedFrom, to);
}
@Override
public void add(int x, int y, int z, int combinedFrom, BaseBlock to) {
parent.add(x, y, z, combinedFrom, to);
public Iterator<Change> backwardIterator() {
return parent.backwardIterator();
}
@Override
public Iterator<Change> forwardIterator() {
return parent.forwardIterator();
}
@Override
public void close() throws IOException {
parent.close();
}
@Override
public boolean isEmpty() {
return parent.isEmpty();
}
@Override
@ -187,4 +172,19 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet {
public void setRecordChanges(boolean recordChanges) {
parent.setRecordChanges(recordChanges);
}
@Override
public int size() {
return parent.size();
}
@Override
public void delete() {
parent.delete();
}
@Override
public ChangeSetSummary summarize(Region region, boolean shallow) {
return parent.summarize(region, shallow);
}
}

View File

@ -33,9 +33,8 @@ public class BlockBagChangeSet extends AbstractDelegateChangeSet {
*
* @return a block bag, which may be null if none is used
*/
public
@Nullable
BlockBag getBlockBag() {
public BlockBag getBlockBag() {
return blockBag;
}

View File

@ -25,16 +25,22 @@ public class CFIChangeSet extends AbstractChangeSet {
int max = MainUtil.getMaxFileId(folder);
this.file = new File(folder, max + ".cfi");
File parent = this.file.getParentFile();
if (!parent.exists()) this.file.getParentFile().mkdirs();
if (!this.file.exists()) this.file.createNewFile();
if (!parent.exists()) {
this.file.getParentFile().mkdirs();
}
if (!this.file.exists()) {
this.file.createNewFile();
}
hmmg.flushChanges(file);
}
@Override
public void close() {}
public void close() {
}
@Override
public void closeAsync() {}
public void closeAsync() {
}
@Override
public void add(int x, int y, int z, int combinedFrom, int combinedTo) {

View File

@ -65,13 +65,13 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
super(world);
init(uuid, world.getName());
}
private void init(UUID uuid, String worldName) {
File folder = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + worldName + File.separator + uuid);
int max = MainUtil.getMaxFileId(folder);
init(uuid, max);
}
public DiskStorageHistory(World world, UUID uuid, int index) {
super(world);
init(uuid, index);
@ -83,7 +83,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
this.index = i;
initFiles(folder);
}
private void initFiles(File folder) {
nbtfFile = new File(folder, index + ".nbtf");
nbttFile = new File(folder, index + ".nbtt");
@ -174,12 +174,24 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
super.flush();
synchronized (this) {
try {
if (osBD != null) osBD.flush();
if (osBIO != null) osBIO.flush();
if (osNBTF != null) osNBTF.flush();
if (osNBTT != null) osNBTT.flush();
if (osENTCF != null) osENTCF.flush();
if (osENTCT != null) osENTCT.flush();
if (osBD != null) {
osBD.flush();
}
if (osBIO != null) {
osBIO.flush();
}
if (osNBTF != null) {
osNBTF.flush();
}
if (osNBTT != null) {
osNBTT.flush();
}
if (osENTCF != null) {
osENTCF.flush();
}
if (osENTCT != null) {
osENTCT.flush();
}
} catch (Exception e) {
e.printStackTrace();
}

View File

@ -40,7 +40,7 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet {
public FaweStreamChangeSet(World world) {
this(world, Settings.IMP.HISTORY.COMPRESSION_LEVEL, Settings.IMP.HISTORY.STORE_REDO, Settings.IMP.HISTORY.SMALL_EDITS);
}
public FaweStreamChangeSet(World world, int compression, boolean storeRedo, boolean smallLoc) {
super(world);
this.compression = compression;
@ -129,7 +129,9 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet {
}
if (mode == 1 || mode == 4) { // small
posDel = new FaweStreamPositionDelegate() {
int lx, ly, lz;
int lx;
int ly;
int lz;
@Override
public void write(OutputStream out, int x, int y, int z) throws IOException {
@ -169,7 +171,9 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet {
} else {
posDel = new FaweStreamPositionDelegate() {
final byte[] buffer = new byte[5];
int lx, ly, lz;
int lx;
int ly;
int lz;
@Override
public void write(OutputStream stream, int x, int y, int z) throws IOException {
@ -696,7 +700,7 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet {
public Change next() {
try {
return current.next();
} catch (Throwable ignore) {
} catch (Throwable ignored) {
if (i >= iterators.length - 1) {
throw new NoSuchElementException("End of iterator");
}

View File

@ -53,12 +53,24 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
super.flush();
synchronized (this) {
try {
if (idsStream != null) idsStreamZip.flush();
if (biomeStream != null) biomeStreamZip.flush();
if (entCStream != null) entCStreamZip.flush();
if (entRStream != null) entRStreamZip.flush();
if (tileCStream != null) tileCStreamZip.flush();
if (tileRStream != null) tileRStreamZip.flush();
if (idsStream != null) {
idsStreamZip.flush();
}
if (biomeStream != null) {
biomeStreamZip.flush();
}
if (entCStream != null) {
entCStreamZip.flush();
}
if (entRStream != null) {
entRStreamZip.flush();
}
if (tileCStream != null) {
tileCStreamZip.flush();
}
if (tileRStream != null) {
tileRStreamZip.flush();
}
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -39,7 +39,7 @@ public class CPUOptimizedClipboard extends LinearClipboard {
nbtMapLoc = new HashMap<>();
nbtMapIndex = new HashMap<>();
}
@Override
public boolean hasBiomes() {
return biomes != null;
@ -66,7 +66,9 @@ public class CPUOptimizedClipboard extends LinearClipboard {
@Override
public void streamBiomes(IntValueReader task) {
if (!hasBiomes()) return;
if (!hasBiomes()) {
return;
}
int index = 0;
try {
for (int z = 0; z < getLength(); z++) {

View File

@ -57,7 +57,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
private static int HEADER_SIZE = 14;
private static final int MAX_SIZE = Short.MAX_VALUE - Short.MIN_VALUE;
private final HashMap<IntTriple, CompoundTag> nbtMap;
private final File file;
@ -114,7 +114,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
throw new RuntimeException(e);
}
}
@Override
public URI getURI() {
return file.toURI();
@ -207,7 +207,9 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
@Override
public void streamBiomes(IntValueReader task) {
if (!hasBiomes()) return;
if (!hasBiomes()) {
return;
}
int index = 0;
int mbbIndex = HEADER_SIZE + (getVolume() << 1);
try {
@ -266,7 +268,9 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
}
private void closeDirectBuffer(ByteBuffer cb) {
if (cb == null || !cb.isDirect()) return;
if (cb == null || !cb.isDirect()) {
return;
}
// we could use this type cast and call functions without reflection code,
// but static import from sun.* package is risky for non-SUN virtual machine.
//try { ((sun.nio.ch.DirectBuffer)cb).cleaner().clean(); } catch (Exception ex) { }
@ -373,7 +377,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
int diskIndex = HEADER_SIZE + (index << 1);
char ordinal = byteBuffer.getChar(diskIndex);
return BlockState.getFromOrdinal(ordinal);
} catch (IndexOutOfBoundsException ignore) {
} catch (IndexOutOfBoundsException ignored) {
} catch (Exception e) {
e.printStackTrace();
}
@ -448,7 +452,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
public List<? extends Entity> getEntities() {
return new ArrayList<>(entities);
}
@Override
public List<? extends Entity> getEntities(Region region) {
return new ArrayList<>(entities.stream().filter(e -> region.contains(e.getLocation().toBlockPoint())).collect(Collectors.toList()));

View File

@ -91,7 +91,9 @@ public class MemoryOptimizedClipboard extends LinearClipboard {
@Override
public void streamBiomes(IntValueReader task) {
if (!hasBiomes()) return;
if (!hasBiomes()) {
return;
}
try {
int index = 0;
for (int z = 0; z < getLength(); z++) {
@ -308,7 +310,7 @@ public class MemoryOptimizedClipboard extends LinearClipboard {
public List<? extends Entity> getEntities(Region region) {
return new ArrayList<>(entities.stream().filter(e -> region.contains(e.getLocation().toBlockPoint())).collect(Collectors.toList()));
}
@Override
public void removeEntity(Entity entity) {
if (entity instanceof ClipboardEntity) {

View File

@ -28,7 +28,9 @@ public class MultiClipboardHolder extends URIClipboardHolder {
public MultiClipboardHolder(URI uri, URIClipboardHolder... addHolders) {
this(uri);
for (URIClipboardHolder h : addHolders) add(h);
for (URIClipboardHolder h : addHolders) {
add(h);
}
}
public MultiClipboardHolder(Clipboard clipboard) {
@ -44,7 +46,9 @@ public class MultiClipboardHolder extends URIClipboardHolder {
public void remove(URI uri) {
cached = null;
if (getUri().equals(uri)) {
for (ClipboardHolder holder : holders) holder.close();
for (ClipboardHolder holder : holders) {
holder.close();
}
holders.clear();
return;
}
@ -66,7 +70,9 @@ public class MultiClipboardHolder extends URIClipboardHolder {
if (holder instanceof URIClipboardHolder) {
URIClipboardHolder uriHolder = (URIClipboardHolder) holder;
URI uri = uriHolder.getURI(clipboard);
if (uri != null) return uri;
if (uri != null) {
return uri;
}
}
}
return null;
@ -79,7 +85,9 @@ public class MultiClipboardHolder extends URIClipboardHolder {
@Override
public boolean contains(Clipboard clipboard) {
for (ClipboardHolder holder : holders) {
if (holder.contains(clipboard)) return true;
if (holder.contains(clipboard)) {
return true;
}
}
return false;
}
@ -128,7 +136,9 @@ public class MultiClipboardHolder extends URIClipboardHolder {
return true;
}
for (URIClipboardHolder uch : holders) {
if (uch.contains(uri)) return true;
if (uch.contains(uri)) {
return true;
}
}
return false;
}
@ -154,7 +164,9 @@ public class MultiClipboardHolder extends URIClipboardHolder {
for (ClipboardHolder holder : getHolders()) {
if (holder instanceof URIClipboardHolder) {
URI uri = ((URIClipboardHolder) holder).getUri();
if (!uri.toString().isEmpty()) set.add(uri);
if (!uri.toString().isEmpty()) {
set.add(uri);
}
}
}
return set;

View File

@ -24,8 +24,9 @@ public class URIClipboardHolder extends ClipboardHolder {
}
/**
* Get the original clipboard source, typically a file or uri.
* @deprecated If a holder has multiple sources, this will return an empty URI
* @return The original source of this clipboard (usually a file or url)
* @return the source of the clipboard
*/
@Deprecated
public URI getUri() {

View File

@ -61,7 +61,9 @@ public class WorldCopyClipboard extends ReadOnlyClipboard {
@Override
public List<? extends Entity> getEntities() {
if (!hasEntities) return new ArrayList<>();
if (!hasEntities) {
return new ArrayList<>();
}
return getExtent().getEntities(getRegion());
}

View File

@ -33,13 +33,15 @@ public final class BitArray {
}
public final void set(int index, int value) {
if (longLen == 0) return;
if (longLen == 0) {
return;
}
int bitIndexStart = index * bitsPerEntry;
int longIndexStart = bitIndexStart >> 6;
int localBitIndexStart = bitIndexStart & 63;
this.data[longIndexStart] = this.data[longIndexStart] & ~(mask << localBitIndexStart) | (long) value << localBitIndexStart;
if(localBitIndexStart > maxSeqLocIndex) {
if (localBitIndexStart > maxSeqLocIndex) {
int longIndexEnd = longIndexStart + 1;
int localShiftStart = 64 - localBitIndexStart;
int localShiftEnd = bitsPerEntry - localShiftStart;
@ -48,14 +50,16 @@ public final class BitArray {
}
public final int get(int index) {
if (longLen == 0) return 0;
if (longLen == 0) {
return 0;
}
int bitIndexStart = index * bitsPerEntry;
int longIndexStart = bitIndexStart >> 6;
int localBitIndexStart = bitIndexStart & 63;
if(localBitIndexStart <= maxSeqLocIndex) {
return (int)(this.data[longIndexStart] >>> localBitIndexStart & mask);
if (localBitIndexStart <= maxSeqLocIndex) {
return (int) (this.data[longIndexStart] >>> localBitIndexStart & mask);
} else {
int localShift = 64 - localBitIndexStart;
return (int) ((this.data[longIndexStart] >>> localBitIndexStart | this.data[longIndexStart + 1] << localShift) & mask);
@ -65,7 +69,7 @@ public final class BitArray {
public int getLength() {
return longLen;
}
public final void fromRaw(int[] arr) {
final long[] data = this.data;
final int bitsPerEntry = this.bitsPerEntry;

View File

@ -40,7 +40,9 @@ public final class BitArrayUnstretched {
}
public final void set(int index, int value) {
if (longLen == 0) return;
if (longLen == 0) {
return;
}
int bitIndexStart = index * bitsPerEntry + MathMan.floorZero((double) index / longLen) * emptyBitCount;
int longIndexStart = bitIndexStart >> 6;
int localBitIndexStart = bitIndexStart & 63;
@ -48,19 +50,21 @@ public final class BitArrayUnstretched {
}
public final int get(int index) {
if (longLen == 0) return 0;
if (longLen == 0) {
return 0;
}
int bitIndexStart = index * bitsPerEntry + MathMan.floorZero((double) index / longLen) * emptyBitCount;
int longIndexStart = bitIndexStart >> 6;
int localBitIndexStart = bitIndexStart & 63;
return (int)(this.data[longIndexStart] >>> localBitIndexStart & mask);
return (int) (this.data[longIndexStart] >>> localBitIndexStart & mask);
}
public int getLength() {
return longLen;
}
public final void fromRaw(int[] arr) {
final long[] data = this.data;
final int bitsPerEntry = this.bitsPerEntry;

View File

@ -17,10 +17,12 @@ import java.util.Objects;
import java.util.Set;
/**
* The BlockVectorSet is a Memory optimized Set for storing BlockVectors
* - Internally it uses a map of Index->LocalBlockVectorSet
* - All BlockVectors must be a valid world coordinate: y=[0,255],x=[-30000000,30000000],z=[-30000000,30000000]
* - This will use ~8 bytes for every 64 BlockVectors (about 800x less than a HashSet)
* The BlockVectorSet is a memory optimized Set for storing {@link BlockVector3}'s.
*
* <p>
* It uses about 8 bytes of memory for every 64 {@code BlockVector3}s (about 800 times less than a
* {@code HashSet}.
* </p>
*/
public class BlockVectorSet extends AbstractCollection<BlockVector3> implements Set<BlockVector3> {
private Int2ObjectMap<LocalBlockVectorSet> localSets = new Int2ObjectOpenHashMap<>();
@ -92,7 +94,7 @@ public class BlockVectorSet extends AbstractCollection<BlockVector3> implements
return new Iterator<BlockVector3>() {
Int2ObjectMap.Entry<LocalBlockVectorSet> entry = entries.next();
Iterator<BlockVector3> entryIter = entry.getValue().iterator();
MutableBlockVector3 mutable = new MutableBlockVector3();
final MutableBlockVector3 mutable = new MutableBlockVector3();
@Override
public void remove() {
@ -185,7 +187,7 @@ public class BlockVectorSet extends AbstractCollection<BlockVector3> implements
public boolean retainAll(@NotNull Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator it = iterator();
Iterator<BlockVector3> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();

View File

@ -118,7 +118,7 @@ public class CleanableThreadLocal<T> extends ThreadLocal<T> implements Closeable
if (methodRemove != null) {
try {
methodRemove.invoke(tlm, instance);
} catch (Throwable ignore) {
} catch (Throwable ignored) {
}
}
} catch (NoSuchMethodException e) {
@ -158,7 +158,7 @@ public class CleanableThreadLocal<T> extends ThreadLocal<T> implements Closeable
clean(threadLocal);
}
}
} catch(Exception e) {
} catch (Exception e) {
// We will tolerate an exception here and just log it
throw new IllegalStateException(e);
}

View File

@ -139,8 +139,11 @@ public final class DifferentialArray<T> implements DifferentialCollection<T> {
}
}
if (caught != null) {
if (caught instanceof RuntimeException) throw (RuntimeException) caught;
else throw new RuntimeException(caught);
if (caught instanceof RuntimeException) {
throw (RuntimeException) caught;
} else {
throw new RuntimeException(caught);
}
}
}
@ -277,7 +280,7 @@ public final class DifferentialArray<T> implements DifferentialCollection<T> {
changed = true;
try {
changesBytes[index] += (dataBytes[index] - value);
} catch (NullPointerException ignore) {
} catch (NullPointerException ignored) {
changes = (T) (changesBytes = new byte[dataBytes.length]);
changesBytes[index] += (dataBytes[index] - value);
}
@ -288,7 +291,7 @@ public final class DifferentialArray<T> implements DifferentialCollection<T> {
changed = true;
try {
changesInts[index] += dataInts[index] - value;
} catch (NullPointerException ignore) {
} catch (NullPointerException ignored) {
changes = (T) (changesInts = new int[dataInts.length]);
changesInts[index] += dataInts[index] - value;
}
@ -299,7 +302,7 @@ public final class DifferentialArray<T> implements DifferentialCollection<T> {
changed = true;
try {
changesChars[index] += dataChars[index] - value;
} catch (NullPointerException ignore) {
} catch (NullPointerException ignored) {
changes = (T) (changesChars = new char[dataChars.length]);
changesChars[index] += dataChars[index] - value;
}

View File

@ -12,8 +12,10 @@ import java.lang.reflect.Array;
*/
public final class DifferentialBlockBuffer implements DifferentialCollection<char[][][][][]> {
private final int width, length;
private final int t1, t2;
private final int width;
private final int length;
private final int t1;
private final int t2;
private char[][][][][] data;
private char[][][][][] changes;
@ -63,7 +65,9 @@ public final class DifferentialBlockBuffer implements DifferentialCollection<cha
@Override
public void undoChanges(FaweInputStream in) throws IOException {
if (changes != null && changes.length != 0) throw new IllegalStateException("There are uncommitted changes, please flush first");
if (changes != null && changes.length != 0) {
throw new IllegalStateException("There are uncommitted changes, please flush first");
}
boolean modified = in.readBoolean();
if (modified) {
int len = in.readVarInt();
@ -118,7 +122,9 @@ public final class DifferentialBlockBuffer implements DifferentialCollection<cha
}
public void set(int x, int y, int z, char combined) {
if (combined == 0) combined = 1;
if (combined == 0) {
combined = 1;
}
int localX = x & 15;
int localZ = z & 15;
int chunkX = x >> 4;
@ -154,7 +160,9 @@ public final class DifferentialBlockBuffer implements DifferentialCollection<cha
}
} else {
if (changes == null || changes.length == 0) changes = new char[t1][][][][];
if (changes == null || changes.length == 0) {
changes = new char[t1][][][][];
}
appendChange(changes, chunkX, chunkZ, localX, localZ, y, (char) (zMap[localX] - combined));
}
@ -166,25 +174,33 @@ public final class DifferentialBlockBuffer implements DifferentialCollection<cha
if (arr == null) {
src[chunkZ] = new char[0][][][];
return;
} else if (arr.length == 0) return;
} else if (arr.length == 0) {
return;
}
char[][][] arr2 = arr[chunkX];
if (arr2 == null) {
arr[chunkX] = new char[0][][];
return;
} else if (arr2.length == 0) return;
} else if (arr2.length == 0) {
return;
}
char[][] yMap = arr2[y];
if (yMap == null) {
arr2[y] = new char[0][];
return;
} else if (yMap.length == 0) return;
} else if (yMap.length == 0) {
return;
}
char[] zMap = yMap[localZ];
if (zMap == null) {
yMap[localZ] = new char[0];
return;
} else if (zMap.length == 0) return;
} else if (zMap.length == 0) {
return;
}
int current = zMap[localX];
zMap[localX] = combined;

View File

@ -12,8 +12,10 @@ import java.lang.reflect.Array;
*/
public final class DifferentialCharBlockBuffer implements DifferentialCollection<char[][][][][]> {
private final int width, length;
private final int t1, t2;
private final int width;
private final int length;
private final int t1;
private final int t2;
private char[][][][][] data;
private char[][][][][] changes;
@ -63,7 +65,9 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection
@Override
public void undoChanges(FaweInputStream in) throws IOException {
if (changes != null && changes.length != 0) throw new IllegalStateException("There are uncommitted changes, please flush first");
if (changes != null && changes.length != 0) {
throw new IllegalStateException("There are uncommitted changes, please flush first");
}
boolean modified = in.readBoolean();
if (modified) {
int len = in.readVarInt();
@ -118,7 +122,9 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection
}
public void set(int x, int y, int z, char combined) {
if (combined == 0) combined = 1;
if (combined == 0) {
combined = 1;
}
int localX = x & 15;
int localZ = z & 15;
int chunkX = x >> 4;
@ -154,7 +160,9 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection
}
} else {
if (changes == null || changes.length == 0) changes = new char[t1][][][][];
if (changes == null || changes.length == 0) {
changes = new char[t1][][][][];
}
appendChange(changes, chunkX, chunkZ, localX, localZ, y, (char) (zMap[localX] - combined));
}
@ -166,25 +174,33 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection
if (arr == null) {
src[chunkZ] = new char[0][][][];
return;
} else if (arr.length == 0) return;
} else if (arr.length == 0) {
return;
}
char[][][] arr2 = arr[chunkX];
if (arr2 == null) {
arr[chunkX] = new char[0][][];
return;
} else if (arr2.length == 0) return;
} else if (arr2.length == 0) {
return;
}
char[][] yMap = arr2[y];
if (yMap == null) {
arr2[y] = new char[0][];
return;
} else if (yMap.length == 0) return;
} else if (yMap.length == 0) {
return;
}
char[] zMap = yMap[localZ];
if (zMap == null) {
yMap[localZ] = new char[0];
return;
} else if (zMap.length == 0) return;
} else if (zMap.length == 0) {
return;
}
char current = zMap[localX];
zMap[localX] = combined;
@ -210,4 +226,4 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection
}
zMap[localX] = combined;
}
}
}

View File

@ -24,22 +24,23 @@ public final class FastBitSet {
return (bits[i >> 6] & (1L << (i & 0x3F))) != 0;
}
public static final void set(long[] bits, final int i) {
public static void set(long[] bits, final int i) {
bits[i >> 6] |= (1L << (i & 0x3F));
}
public static final void clear(long[] bits, final int i) {
public static void clear(long[] bits, final int i) {
bits[i >> 6] &= ~(1L << (i & 0x3F));
}
public static final void set(long[] bits, final int i, final boolean v) {
if (v)
public static void set(long[] bits, final int i, final boolean v) {
if (v) {
set(bits, i);
else
} else {
clear(bits, i);
}
}
public static final void setRange(long[] bits, final int b, final int e) {
public static void setRange(long[] bits, final int b, final int e) {
final int bt = b >> 6;
final int et = e >> 6;
if (bt != et) {
@ -51,7 +52,7 @@ public final class FastBitSet {
}
}
public static final void clearRange(long[] bits, final int b, final int e) {
public static void clearRange(long[] bits, final int b, final int e) {
final int bt = b >> 6;
final int et = e >> 6;
if (bt != et) {
@ -63,53 +64,70 @@ public final class FastBitSet {
}
}
public static final void setAll(long[] bits) {
public static void setAll(long[] bits) {
Arrays.fill(bits, -1L);
}
public static final void clearAll(long[] bits) {
public static void clearAll(long[] bits) {
Arrays.fill(bits, 0L);
}
public static final void invertAll(long[] bits) {
for (int i = 0; i < bits.length; ++i)
public static void invertAll(long[] bits) {
for (int i = 0; i < bits.length; ++i) {
bits[i] = ~bits[i];
}
}
public static final void and(long[] bits, final long[] other) {
public static void and(long[] bits, final long[] other) {
final int end = Math.min(other.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] &= other[i];
}
}
public static final void or(long[] bits, final long[] other) {
public static void or(long[] bits, final long[] other) {
final int end = Math.min(other.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] |= other[i];
}
}
public static final void nand(long[] bits, final long[] other) {
public static void nand(long[] bits, final long[] other) {
final int end = Math.min(other.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] = ~(bits[i] & other[i]);
}
}
public static final void nor(long[] bits, final long[] other) {
public static void nor(long[] bits, final long[] other) {
final int end = Math.min(other.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] = ~(bits[i] | other[i]);
}
}
public static final void xor(long[] bits, final long[] other) {
public static void xor(long[] bits, final long[] other) {
final int end = Math.min(other.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] ^= other[i];
}
}
public static final long memoryUsage(long[] bits) {
public static long memoryUsage(long[] bits) {
return 8L * bits.length;
}
private static void fill(final long[] a, final int b, final int e, final long l) {
for (int i = b; i < e; ++i) {
a[i] = l;
}
}
public static long calculateMemoryUsage(int entries) {
final int numLongs = (entries + 64) >> 6;
return 8L * numLongs;
}
public final boolean get(final int i) {
return (bits[i >> 6] & (1L << (i & 0x3F))) != 0;
}
@ -123,10 +141,11 @@ public final class FastBitSet {
}
public final void set(final int i, final boolean v) {
if (v)
if (v) {
set(i);
else
} else {
clear(i);
}
}
public final void setRange(final int b, final int e) {
@ -162,45 +181,54 @@ public final class FastBitSet {
}
public final void invertAll() {
for (int i = 0; i < bits.length; ++i)
for (int i = 0; i < bits.length; ++i) {
bits[i] = ~bits[i];
}
}
public final void and(final FastBitSet other) {
final int end = Math.min(other.bits.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] &= other.bits[i];
}
}
public final void or(final FastBitSet other) {
final int end = Math.min(other.bits.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] |= other.bits[i];
}
}
public final void nand(final FastBitSet other) {
final int end = Math.min(other.bits.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] = ~(bits[i] & other.bits[i]);
}
}
public final void nor(final FastBitSet other) {
final int end = Math.min(other.bits.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] = ~(bits[i] | other.bits[i]);
}
}
public final void xor(final FastBitSet other) {
final int end = Math.min(other.bits.length, bits.length);
for (int i = 0; i < end; ++i)
for (int i = 0; i < end; ++i) {
bits[i] ^= other.bits[i];
}
}
public final int cardinality() {
if (size == 0) return 0;
if (size == 0) {
return 0;
}
int count = 0;
for (int i = 0; i < bits.length - 1; ++i)
for (int i = 0; i < bits.length - 1; ++i) {
count += Long.bitCount(bits[i]);
}
return count + Long.bitCount(bits[bits.length - 1] & ~(-1L << (size & 0x3F)));
}
@ -212,16 +240,6 @@ public final class FastBitSet {
return 8L * bits.length;
}
private static void fill(final long[] a, final int b, final int e, final long l) {
for (int i = b; i < e; ++i)
a[i] = l;
}
public static long calculateMemoryUsage(int entries) {
final int numLongs = (entries + 64) >> 6;
return 8L * numLongs;
}
public IntIterator iterator() {
return new IntIterator();
}
@ -240,8 +258,8 @@ public final class FastBitSet {
index++;
}
final long lowBit = Long.lowestOneBit(bitBuffer);
final int bitIndex = Long.bitCount(lowBit-1);
value = ((index-1)<<6)+bitIndex;
final int bitIndex = Long.bitCount(lowBit - 1);
value = ((index - 1) << 6) + bitIndex;
bitBuffer = bitBuffer ^ lowBit;
return true;
}
@ -250,4 +268,4 @@ public final class FastBitSet {
return value;
}
}
}
}

View File

@ -16,15 +16,15 @@ public class FastRandomCollection<T> extends RandomCollection<T> {
}
/**
* Create a new FastRandomCollection if the given values and weights match the criteria.
* The criteria may change at any point, so this method isn't guaranteed to return a
* non-empty Optional in any case.
* Create a new FastRandomCollection if the given values and weights match the criteria. The
* criteria may change at any point, so this method isn't guaranteed to return a non-empty
* {@code Optional} in any case.
*
* @param weights the weight of the values.
* @param random the random generator to use for this collection.
* @param <T> the value type.
* @return an {@link Optional} containing the new collection if it could
* be created, {@link Optional#empty()} otherwise.
* @return an {@link Optional} containing the new collection if it could be created, {@link
* Optional#empty()} otherwise.
* @see RandomCollection for API usage.
*/
public static <T> Optional<RandomCollection<T>> create(Map<T, Double> weights, SimpleRandom random) {

View File

@ -71,21 +71,27 @@ public interface IAdaptedMap<K, V, K2, V2> extends Map<K, V> {
@NotNull
@Override
default Set<K> keySet() {
if (isEmpty()) return Collections.emptySet();
if (isEmpty()) {
return Collections.emptySet();
}
return new AdaptedSetCollection<>(getParent().keySet(), this::adaptKey2);
}
@NotNull
@Override
default Collection<V> values() {
if (isEmpty()) return Collections.emptySet();
if (isEmpty()) {
return Collections.emptySet();
}
return new AdaptedSetCollection<>(getParent().values(), this::adaptValue2);
}
@NotNull
@Override
default Set<Entry<K, V>> entrySet() {
if (isEmpty()) return Collections.emptySet();
if (isEmpty()) {
return Collections.emptySet();
}
return new AdaptedSetCollection<>(getParent().entrySet(), new Function<Entry<K2, V2>, Entry<K, V>>() {
private MutablePair<K, V> entry = new MutablePair<>();
@Override

View File

@ -51,7 +51,9 @@ public class LocalBlockVector2DSet implements Set<BlockVector2> {
public boolean containsRadius(int x, int y, int radius) {
int size = size();
if (size == 0) return false;
if (size == 0) {
return false;
}
if (radius <= 0 || size == 1) {
return contains(x, y);
}

View File

@ -15,7 +15,8 @@ import java.util.Set;
* - This will use 8 bytes for every 64 BlockVectors (about 800x less than a HashSet)
*/
public class LocalBlockVectorSet implements Set<BlockVector3> {
private int offsetX, offsetZ;
private int offsetX;
private int offsetZ;
private final SparseBitSet set;
public LocalBlockVectorSet() {

View File

@ -61,7 +61,9 @@ public class LongHashSet {
public void add(long key) {
int mainIdx = (int) (key & 255);
long outer[][] = this.values[mainIdx];
if (outer == null) this.values[mainIdx] = outer = new long[256][];
if (outer == null) {
this.values[mainIdx] = outer = new long[256][];
}
int outerIdx = (int) ((key >> 32) & 255);
long inner[] = outer[outerIdx];
@ -88,23 +90,33 @@ public class LongHashSet {
public boolean containsKey(long key) {
long[][] outer = this.values[(int) (key & 255)];
if (outer == null) return false;
if (outer == null) {
return false;
}
long[] inner = outer[(int) ((key >> 32) & 255)];
if (inner == null) return false;
if (inner == null) {
return false;
}
for (long entry : inner) {
if (entry == key) return true;
if (entry == key) {
return true;
}
}
return false;
}
public void remove(long key) {
long[][] outer = this.values[(int) (key & 255)];
if (outer == null) return;
if (outer == null) {
return;
}
long[] inner = outer[(int) ((key >> 32) & 255)];
if (inner == null) return;
if (inner == null) {
return;
}
int max = inner.length - 1;
for (int i = 0; i <= max; i++) {
@ -122,11 +134,15 @@ public class LongHashSet {
public long popFirst() {
for (long[][] outer: this.values) {
if (outer == null) continue;
if (outer == null) {
continue;
}
for (int i = 0; i < outer.length; i++) {
long[] inner = outer[i];
if (inner == null || inner.length == 0) continue;
if (inner == null || inner.length == 0) {
continue;
}
this.count--;
long ret = inner[inner.length - 1];
@ -142,11 +158,15 @@ public class LongHashSet {
int index = 0;
long[] ret = new long[this.count];
for (long[][] outer : this.values) {
if (outer == null) continue;
if (outer == null) {
continue;
}
for (int oIdx = outer.length - 1; oIdx >= 0; oIdx--) {
long[] inner = outer[oIdx];
if (inner == null) continue;
if (inner == null) {
continue;
}
for (long entry: inner) {
ret[index++] = entry;
@ -162,10 +182,14 @@ public class LongHashSet {
int index = 0;
long[] ret = new long[this.count];
for (long[][] outer : this.values) {
if (outer == null) continue;
if (outer == null) {
continue;
}
for (long[] inner : outer) {
if (inner == null) continue;
if (inner == null) {
continue;
}
for (long entry : inner) {
ret[index++] = entry;

Some files were not shown because too many files have changed in this diff Show More