refactor: Deprecate IMP initializors in favor of builders

This commit is contained in:
NotMyFault 2021-12-22 20:58:23 +01:00
parent 34f971c729
commit 7da921e075
No known key found for this signature in database
GPG Key ID: 158F5701A6AAD00C
129 changed files with 750 additions and 677 deletions

View File

@ -510,10 +510,10 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
chunkPacket.setNativePacket(nmsPacket); chunkPacket.setNativePacket(nmsPacket);
} }
try { try {
FaweCache.IMP.CHUNK_FLAG.get().set(true); FaweCache.INSTANCE.CHUNK_FLAG.get().set(true);
entityPlayer.connection.send(nmsPacket); entityPlayer.connection.send(nmsPacket);
} finally { } finally {
FaweCache.IMP.CHUNK_FLAG.get().set(false); FaweCache.INSTANCE.CHUNK_FLAG.get().set(false);
} }
} }
}); });

View File

@ -250,7 +250,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
} }
} }
}; };
TaskManager.IMP.async(() -> TaskManager.IMP.sync(runnableVal)); TaskManager.taskManager().async(() -> TaskManager.taskManager().sync(runnableVal));
} }
@Override @Override
@ -269,7 +269,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
if (Fawe.isMainThread()) { if (Fawe.isMainThread()) {
runnableVal.run(); runnableVal.run();
} else { } else {
TaskManager.IMP.sync(runnableVal); TaskManager.taskManager().sync(runnableVal);
} }
cachedChanges.clear(); cachedChanges.clear();
cachedChunksToSend.clear(); cachedChunksToSend.clear();

View File

@ -418,7 +418,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
try { try {
ServerLevel nmsWorld = serverLevel; ServerLevel nmsWorld = serverLevel;
LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ); LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ);
boolean fastmode = set.isFastMode() && Settings.IMP.QUEUE.NO_TICK_FASTMODE; boolean fastmode = set.isFastMode() && Settings.settings().QUEUE.NO_TICK_FASTMODE;
// Remove existing tiles. Create a copy so that we can remove blocks // Remove existing tiles. Create a copy so that we can remove blocks
Map<BlockPos, BlockEntity> chunkTiles = new HashMap<>(nmsChunk.getBlockEntities()); Map<BlockPos, BlockEntity> chunkTiles = new HashMap<>(nmsChunk.getBlockEntities());
@ -726,7 +726,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
nmsChunk.mustNotSave = false; nmsChunk.mustNotSave = false;
nmsChunk.markUnsaved(); nmsChunk.markUnsaved();
// send to player // send to player
if (Settings.IMP.LIGHTING.MODE == 0 || !Settings.IMP.LIGHTING.DELAY_PACKET_SENDING) { if (Settings.settings().LIGHTING.MODE == 0 || !Settings.settings().LIGHTING.DELAY_PACKET_SENDING) {
this.send(finalMask, finalLightUpdate); this.send(finalMask, finalLightUpdate);
} }
if (finalizer != null) { if (finalizer != null) {
@ -735,7 +735,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
}; };
} }
if (syncTasks != null) { if (syncTasks != null) {
QueueHandler queueHandler = Fawe.get().getQueueHandler(); QueueHandler queueHandler = Fawe.instance().getQueueHandler();
Runnable[] finalSyncTasks = syncTasks; Runnable[] finalSyncTasks = syncTasks;
// Chain the sync tasks and the callback // Chain the sync tasks and the callback
@ -851,7 +851,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) 1);
} }
if (data == null || data == FaweCache.IMP.EMPTY_CHAR_4096) { if (data == null || data == FaweCache.INSTANCE.EMPTY_CHAR_4096) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) 1);
} }
@ -884,7 +884,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
return data; return data;
} }
char[] paletteToOrdinal = FaweCache.IMP.PALETTE_TO_BLOCK_CHAR.get(); char[] paletteToOrdinal = FaweCache.INSTANCE.PALETTE_TO_BLOCK_CHAR.get();
try { try {
if (num_palette != 1) { if (num_palette != 1) {
for (int i = 0; i < num_palette; i++) { for (int i = 0; i < num_palette; i++) {

View File

@ -215,7 +215,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
e.printStackTrace(); e.printStackTrace();
} }
} }
return TaskManager.IMP.sync(() -> serverLevel.getChunk(chunkX, chunkZ)); return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ));
} }
public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) { public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) {
@ -247,7 +247,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return; return;
} }
LevelChunk levelChunk = optional.get(); LevelChunk levelChunk = optional.get();
TaskManager.IMP.task(() -> { TaskManager.taskManager().task(() -> {
ClientboundLevelChunkPacket chunkPacket = new ClientboundLevelChunkPacket(levelChunk); ClientboundLevelChunkPacket chunkPacket = new ClientboundLevelChunkPacket(levelChunk);
nearbyPlayers(nmsWorld, coordIntPair).forEach(p -> p.connection.send(chunkPacket)); nearbyPlayers(nmsWorld, coordIntPair).forEach(p -> p.connection.send(chunkPacket));
if (lighting) { if (lighting) {
@ -283,10 +283,10 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
if (set == null) { if (set == null) {
return newChunkSection(layer); return newChunkSection(layer);
} }
final int[] blockToPalette = FaweCache.IMP.BLOCK_TO_PALETTE.get(); final int[] blockToPalette = FaweCache.INSTANCE.BLOCK_TO_PALETTE.get();
final int[] paletteToBlock = FaweCache.IMP.PALETTE_TO_BLOCK.get(); final int[] paletteToBlock = FaweCache.INSTANCE.PALETTE_TO_BLOCK.get();
final long[] blockStates = FaweCache.IMP.BLOCK_STATES.get(); final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get();
final int[] blocksCopy = FaweCache.IMP.SECTION_BLOCKS.get(); final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get();
try { try {
int[] num_palette_buffer = new int[1]; int[] num_palette_buffer = new int[1];
Map<BlockVector3, Integer> ticking_blocks = new HashMap<>(); Map<BlockVector3, Integer> ticking_blocks = new HashMap<>();
@ -303,7 +303,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
int num_palette = num_palette_buffer[0]; int num_palette = num_palette_buffer[0];
// BlockStates // BlockStates
int bitsPerEntry = MathMan.log2nlz(num_palette - 1); int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
if (Settings.IMP.PROTOCOL_SUPPORT_FIX || num_palette != 1) { if (Settings.settings().PROTOCOL_SUPPORT_FIX || num_palette != 1) {
bitsPerEntry = Math.max(bitsPerEntry, 4); // Protocol support breaks <4 bits per entry bitsPerEntry = Math.max(bitsPerEntry, 4); // Protocol support breaks <4 bits per entry
} else { } else {
bitsPerEntry = Math.max(bitsPerEntry, 1); // For some reason minecraft needs 4096 bits to store 0 entries bitsPerEntry = Math.max(bitsPerEntry, 1); // For some reason minecraft needs 4096 bits to store 0 entries

View File

@ -129,7 +129,7 @@ public class PaperweightStarlightRelighter implements Relighter {
while (iterator.hasNext()) { while (iterator.hasNext()) {
coords.add(new ChunkPos(iterator.nextLong())); coords.add(new ChunkPos(iterator.nextLong()));
} }
TaskManager.IMP.task(() -> { TaskManager.taskManager().task(() -> {
// trigger chunk load and apply ticket on main thread // trigger chunk load and apply ticket on main thread
List<CompletableFuture<?>> futures = new ArrayList<>(); List<CompletableFuture<?>> futures = new ArrayList<>();
for (ChunkPos pos : coords) { for (ChunkPos pos : coords) {
@ -153,9 +153,9 @@ public class PaperweightStarlightRelighter implements Relighter {
LOGGER.warn("Processed {} chunks instead of {}", i, coords.size()); LOGGER.warn("Processed {} chunks instead of {}", i, coords.size());
} }
// post process chunks on main thread // post process chunks on main thread
TaskManager.IMP.task(() -> postProcessChunks(coords)); TaskManager.taskManager().task(() -> postProcessChunks(coords));
// call callback on our own threads // call callback on our own threads
TaskManager.IMP.async(andThen); TaskManager.taskManager().async(andThen);
} }
) )
); );
@ -184,7 +184,7 @@ public class PaperweightStarlightRelighter implements Relighter {
* Also, if chunk packets are sent delayed, we need to do that here * Also, if chunk packets are sent delayed, we need to do that here
*/ */
private void postProcessChunks(Set<ChunkPos> coords) { private void postProcessChunks(Set<ChunkPos> coords) {
boolean delay = Settings.IMP.LIGHTING.DELAY_PACKET_SENDING; boolean delay = Settings.settings().LIGHTING.DELAY_PACKET_SENDING;
for (ChunkPos pos : coords) { for (ChunkPos pos : coords) {
int x = pos.x; int x = pos.x;
int z = pos.z; int z = pos.z;

View File

@ -232,7 +232,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
PrimaryLevelData newWorldData = new PrimaryLevelData(newWorldSettings, newOpts, Lifecycle.stable()); PrimaryLevelData newWorldData = new PrimaryLevelData(newWorldSettings, newOpts, Lifecycle.stable());
//init world //init world
freshWorld = Fawe.get().getQueueHandler().sync((Supplier<ServerLevel>) () -> new ServerLevel( freshWorld = Fawe.instance().getQueueHandler().sync((Supplier<ServerLevel>) () -> new ServerLevel(
server, server,
server.executor, server.executor,
session, session,
@ -336,7 +336,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
//shutdown chunk provider //shutdown chunk provider
try { try {
Fawe.get().getQueueHandler().sync(() -> { Fawe.instance().getQueueHandler().sync(() -> {
try { try {
freshChunkProvider.close(false); freshChunkProvider.close(false);
} catch (IOException e) { } catch (IOException e) {
@ -348,7 +348,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
//remove world from server //remove world from server
try { try {
Fawe.get().getQueueHandler().sync(this::removeWorldFromWorldsMap); Fawe.instance().getQueueHandler().sync(this::removeWorldFromWorldsMap);
} catch (Exception ignored) { } catch (Exception ignored) {
} }
@ -388,7 +388,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
@Override @Override
protected void populate(LevelChunk levelChunk, Random random, BlockPopulator blockPopulator) { protected void populate(LevelChunk levelChunk, Random random, BlockPopulator blockPopulator) {
// BlockPopulator#populate has to be called synchronously for TileEntity access // BlockPopulator#populate has to be called synchronously for TileEntity access
TaskManager.IMP.task(() -> blockPopulator.populate(freshWorld.getWorld(), random, levelChunk.getBukkitChunk())); TaskManager.taskManager().task(() -> blockPopulator.populate(freshWorld.getWorld(), random, levelChunk.getBukkitChunk()));
} }
@Override @Override
@ -403,7 +403,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
//util //util
private void removeWorldFromWorldsMap() { private void removeWorldFromWorldsMap() {
Fawe.get().getQueueHandler().sync(() -> { Fawe.instance().getQueueHandler().sync(() -> {
try { try {
Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer()); Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer());
map.remove("worldeditregentempworld"); map.remove("worldeditregentempworld");

View File

@ -504,10 +504,10 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
chunkPacket.setNativePacket(nmsPacket); chunkPacket.setNativePacket(nmsPacket);
} }
try { try {
FaweCache.IMP.CHUNK_FLAG.get().set(true); FaweCache.INSTANCE.CHUNK_FLAG.get().set(true);
entityPlayer.connection.send(nmsPacket); entityPlayer.connection.send(nmsPacket);
} finally { } finally {
FaweCache.IMP.CHUNK_FLAG.get().set(false); FaweCache.INSTANCE.CHUNK_FLAG.get().set(false);
} }
} }
}); });

View File

@ -250,7 +250,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
} }
} }
}; };
TaskManager.IMP.async(() -> TaskManager.IMP.sync(runnableVal)); TaskManager.taskManager().async(() -> TaskManager.taskManager().sync(runnableVal));
} }
@Override @Override
@ -269,7 +269,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
if (Fawe.isMainThread()) { if (Fawe.isMainThread()) {
runnableVal.run(); runnableVal.run();
} else { } else {
TaskManager.IMP.sync(runnableVal); TaskManager.taskManager().sync(runnableVal);
} }
cachedChanges.clear(); cachedChanges.clear();
cachedChunksToSend.clear(); cachedChunksToSend.clear();

View File

@ -401,7 +401,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
try { try {
ServerLevel nmsWorld = serverLevel; ServerLevel nmsWorld = serverLevel;
LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ); LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ);
boolean fastmode = set.isFastMode() && Settings.IMP.QUEUE.NO_TICK_FASTMODE; boolean fastmode = set.isFastMode() && Settings.settings().QUEUE.NO_TICK_FASTMODE;
// Remove existing tiles. Create a copy so that we can remove blocks // Remove existing tiles. Create a copy so that we can remove blocks
Map<BlockPos, BlockEntity> chunkTiles = new HashMap<>(nmsChunk.getBlockEntities()); Map<BlockPos, BlockEntity> chunkTiles = new HashMap<>(nmsChunk.getBlockEntities());
@ -755,7 +755,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
nmsChunk.mustNotSave = false; nmsChunk.mustNotSave = false;
nmsChunk.setUnsaved(true); nmsChunk.setUnsaved(true);
// send to player // send to player
if (Settings.IMP.LIGHTING.MODE == 0 || !Settings.IMP.LIGHTING.DELAY_PACKET_SENDING) { if (Settings.settings().LIGHTING.MODE == 0 || !Settings.settings().LIGHTING.DELAY_PACKET_SENDING) {
this.send(finalMask, finalLightUpdate); this.send(finalMask, finalLightUpdate);
} }
if (finalizer != null) { if (finalizer != null) {
@ -764,7 +764,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
}; };
} }
if (syncTasks != null) { if (syncTasks != null) {
QueueHandler queueHandler = Fawe.get().getQueueHandler(); QueueHandler queueHandler = Fawe.instance().getQueueHandler();
Runnable[] finalSyncTasks = syncTasks; Runnable[] finalSyncTasks = syncTasks;
// Chain the sync tasks and the callback // Chain the sync tasks and the callback
@ -881,7 +881,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) 1);
} }
if (data == null || data == FaweCache.IMP.EMPTY_CHAR_4096) { if (data == null || data == FaweCache.INSTANCE.EMPTY_CHAR_4096) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) 1);
} }
@ -921,7 +921,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
return data; return data;
} }
char[] paletteToOrdinal = FaweCache.IMP.PALETTE_TO_BLOCK_CHAR.get(); char[] paletteToOrdinal = FaweCache.INSTANCE.PALETTE_TO_BLOCK_CHAR.get();
try { try {
if (num_palette != 1) { if (num_palette != 1) {
for (int i = 0; i < num_palette; i++) { for (int i = 0; i < num_palette; i++) {

View File

@ -236,7 +236,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
e.printStackTrace(); e.printStackTrace();
} }
} }
return TaskManager.IMP.sync(() -> serverLevel.getChunk(chunkX, chunkZ)); return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ));
} }
public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) { public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) {
@ -268,7 +268,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return; return;
} }
LevelChunk levelChunk = optional.get(); LevelChunk levelChunk = optional.get();
TaskManager.IMP.task(() -> { TaskManager.taskManager().task(() -> {
ClientboundLevelChunkWithLightPacket packet = ClientboundLevelChunkWithLightPacket packet =
new ClientboundLevelChunkWithLightPacket(levelChunk, nmsWorld.getChunkSource().getLightEngine(), null, null new ClientboundLevelChunkWithLightPacket(levelChunk, nmsWorld.getChunkSource().getLightEngine(), null, null
, true, false); // last false is to not bother with x-ray , true, false); // last false is to not bother with x-ray
@ -299,10 +299,10 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
if (set == null) { if (set == null) {
return newChunkSection(layer, biomeRegistry, biomes); return newChunkSection(layer, biomeRegistry, biomes);
} }
final int[] blockToPalette = FaweCache.IMP.BLOCK_TO_PALETTE.get(); final int[] blockToPalette = FaweCache.INSTANCE.BLOCK_TO_PALETTE.get();
final int[] paletteToBlock = FaweCache.IMP.PALETTE_TO_BLOCK.get(); final int[] paletteToBlock = FaweCache.INSTANCE.PALETTE_TO_BLOCK.get();
final long[] blockStates = FaweCache.IMP.BLOCK_STATES.get(); final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get();
final int[] blocksCopy = FaweCache.IMP.SECTION_BLOCKS.get(); final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get();
try { try {
int[] num_palette_buffer = new int[1]; int[] num_palette_buffer = new int[1];
Map<BlockVector3, Integer> ticking_blocks = new HashMap<>(); Map<BlockVector3, Integer> ticking_blocks = new HashMap<>();

View File

@ -130,7 +130,7 @@ public class PaperweightStarlightRelighter implements Relighter {
while (iterator.hasNext()) { while (iterator.hasNext()) {
coords.add(new ChunkPos(iterator.nextLong())); coords.add(new ChunkPos(iterator.nextLong()));
} }
TaskManager.IMP.task(() -> { TaskManager.taskManager().task(() -> {
// trigger chunk load and apply ticket on main thread // trigger chunk load and apply ticket on main thread
List<CompletableFuture<?>> futures = new ArrayList<>(); List<CompletableFuture<?>> futures = new ArrayList<>();
for (ChunkPos pos : coords) { for (ChunkPos pos : coords) {
@ -154,9 +154,9 @@ public class PaperweightStarlightRelighter implements Relighter {
LOGGER.warn("Processed {} chunks instead of {}", i, coords.size()); LOGGER.warn("Processed {} chunks instead of {}", i, coords.size());
} }
// post process chunks on main thread // post process chunks on main thread
TaskManager.IMP.task(() -> postProcessChunks(coords)); TaskManager.taskManager().task(() -> postProcessChunks(coords));
// call callback on our own threads // call callback on our own threads
TaskManager.IMP.async(andThen); TaskManager.taskManager().async(andThen);
} }
) )
); );
@ -185,7 +185,7 @@ public class PaperweightStarlightRelighter implements Relighter {
* Also, if chunk packets are sent delayed, we need to do that here * Also, if chunk packets are sent delayed, we need to do that here
*/ */
private void postProcessChunks(Set<ChunkPos> coords) { private void postProcessChunks(Set<ChunkPos> coords) {
boolean delay = Settings.IMP.LIGHTING.DELAY_PACKET_SENDING; boolean delay = Settings.settings().LIGHTING.DELAY_PACKET_SENDING;
for (ChunkPos pos : coords) { for (ChunkPos pos : coords) {
int x = pos.x; int x = pos.x;
int z = pos.z; int z = pos.z;

View File

@ -238,7 +238,7 @@
// PrimaryLevelData newWorldData = new PrimaryLevelData(newWorldSettings, newOpts, Lifecycle.stable()); // PrimaryLevelData newWorldData = new PrimaryLevelData(newWorldSettings, newOpts, Lifecycle.stable());
// //
// //init world // //init world
// freshWorld = Fawe.get().getQueueHandler().sync((Supplier<ServerLevel>) () -> new ServerLevel( // freshWorld = Fawe.instance().getQueueHandler().sync((Supplier<ServerLevel>) () -> new ServerLevel(
// server, // server,
// server.executor, // server.executor,
// session, // session,
@ -345,7 +345,7 @@
// //
// //shutdown chunk provider // //shutdown chunk provider
// try { // try {
// Fawe.get().getQueueHandler().sync(() -> { // Fawe.instance().getQueueHandler().sync(() -> {
// try { // try {
// freshChunkProvider.close(false); // freshChunkProvider.close(false);
// } catch (IOException e) { // } catch (IOException e) {
@ -357,7 +357,7 @@
// //
// //remove world from server // //remove world from server
// try { // try {
// Fawe.get().getQueueHandler().sync(this::removeWorldFromWorldsMap); // Fawe.instance().getQueueHandler().sync(this::removeWorldFromWorldsMap);
// } catch (Exception ignored) { // } catch (Exception ignored) {
// } // }
// //
@ -397,7 +397,7 @@
// @Override // @Override
// protected void populate(LevelChunk levelChunk, Random random, BlockPopulator blockPopulator) { // protected void populate(LevelChunk levelChunk, Random random, BlockPopulator blockPopulator) {
// // BlockPopulator#populate has to be called synchronously for TileEntity access // // BlockPopulator#populate has to be called synchronously for TileEntity access
// TaskManager.IMP.task(() -> blockPopulator.populate(freshWorld.getWorld(), random, levelChunk.getBukkitChunk())); // TaskManager.taskManager().task(() -> blockPopulator.populate(freshWorld.getWorld(), random, levelChunk.getBukkitChunk()));
// } // }
// //
// @Override // @Override
@ -412,7 +412,7 @@
// //
// //util // //util
// private void removeWorldFromWorldsMap() { // private void removeWorldFromWorldsMap() {
// Fawe.get().getQueueHandler().sync(() -> { // Fawe.instance().getQueueHandler().sync(() -> {
// try { // try {
// Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer()); // Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer());
// map.remove("worldeditregentempworld"); // map.remove("worldeditregentempworld");

View File

@ -68,7 +68,7 @@ public class FaweBukkit implements IFawe, Listener {
public FaweBukkit(Plugin plugin) { public FaweBukkit(Plugin plugin) {
this.plugin = plugin; this.plugin = plugin;
try { try {
Settings.IMP.TICK_LIMITER.ENABLED = !Bukkit.hasWhitelist(); Settings.settings().TICK_LIMITER.ENABLED = !Bukkit.hasWhitelist();
Fawe.set(this); Fawe.set(this);
Fawe.setupInjector(); Fawe.setupInjector();
try { try {
@ -76,7 +76,7 @@ public class FaweBukkit implements IFawe, Listener {
} catch (Throwable e) { } catch (Throwable e) {
LOGGER.error("Brush Listener Failed", e); LOGGER.error("Brush Listener Failed", e);
} }
if (PaperLib.isPaper() && Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING > 1) { if (PaperLib.isPaper() && Settings.settings().EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING > 1) {
new RenderListener(plugin); new RenderListener(plugin);
} }
} catch (final Throwable e) { } catch (final Throwable e) {
@ -89,12 +89,12 @@ public class FaweBukkit implements IFawe, Listener {
platformAdapter = new NMSAdapter(); platformAdapter = new NMSAdapter();
//PlotSquared support is limited to Spigot/Paper as of 02/20/2020 //PlotSquared support is limited to Spigot/Paper as of 02/20/2020
TaskManager.IMP.later(this::setupPlotSquared, 0); TaskManager.taskManager().later(this::setupPlotSquared, 0);
// Registered delayed Event Listeners // Registered delayed Event Listeners
TaskManager.IMP.task(() -> { TaskManager.taskManager().task(() -> {
// Fix for ProtocolSupport // Fix for ProtocolSupport
Settings.IMP.PROTOCOL_SUPPORT_FIX = Settings.settings().PROTOCOL_SUPPORT_FIX =
Bukkit.getPluginManager().isPluginEnabled("ProtocolSupport"); Bukkit.getPluginManager().isPluginEnabled("ProtocolSupport");
// This class // This class
@ -141,7 +141,7 @@ public class FaweBukkit implements IFawe, Listener {
try { try {
this.itemUtil = tmp = new ItemUtil(); this.itemUtil = tmp = new ItemUtil();
} catch (Throwable e) { } catch (Throwable e) {
Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES = false; Settings.settings().EXPERIMENTAL.PERSISTENT_BRUSHES = false;
LOGGER.error("Persistent Brushes Failed", e); LOGGER.error("Persistent Brushes Failed", e);
} }
} }
@ -311,7 +311,7 @@ public class FaweBukkit implements IFawe, Listener {
return; return;
} }
if (PlotSquared.get().getVersion().version[0] == 6) { if (PlotSquared.get().getVersion().version[0] == 6) {
WEManager.IMP.addManager(new com.fastasyncworldedit.bukkit.regions.plotsquared.PlotSquaredFeature()); WEManager.weManager().addManager(new com.fastasyncworldedit.bukkit.regions.plotsquared.PlotSquaredFeature());
LOGGER.info("Plugin 'PlotSquared' v6 found. Using it now."); LOGGER.info("Plugin 'PlotSquared' v6 found. Using it now.");
} else { } else {
LOGGER.error("Incompatible version of PlotSquared found. Please use PlotSquared v6."); LOGGER.error("Incompatible version of PlotSquared found. Please use PlotSquared v6.");

View File

@ -389,7 +389,7 @@ public interface IBukkitAdapter {
* @return list of {@link org.bukkit.entity.Entity} * @return list of {@link org.bukkit.entity.Entity}
*/ */
default List<org.bukkit.entity.Entity> getEntities(org.bukkit.World world) { default List<org.bukkit.entity.Entity> getEntities(org.bukkit.World world) {
return TaskManager.IMP.sync(world::getEntities); return TaskManager.taskManager().sync(world::getEntities);
} }
} }

View File

@ -44,7 +44,7 @@ public class NMSAdapter implements FAWEPlatformAdapterImpl {
} }
char lastOrdinal = 0; char lastOrdinal = 0;
boolean lastticking = false; boolean lastticking = false;
boolean tick_placed = Settings.IMP.EXPERIMENTAL.ALLOW_TICK_PLACED; boolean tick_placed = Settings.settings().EXPERIMENTAL.ALLOW_TICK_PLACED;
for (int i = 0; i < 4096; i++) { for (int i = 0; i < 4096; i++) {
char ordinal = set[i]; char ordinal = set[i];
switch (ordinal) { switch (ordinal) {
@ -121,8 +121,8 @@ public class NMSAdapter implements FAWEPlatformAdapterImpl {
} }
char lastOrdinal = 0; char lastOrdinal = 0;
boolean lastticking = false; boolean lastticking = false;
boolean tick_placed = Settings.IMP.EXPERIMENTAL.ALLOW_TICK_PLACED; boolean tick_placed = Settings.settings().EXPERIMENTAL.ALLOW_TICK_PLACED;
boolean tick_existing = Settings.IMP.EXPERIMENTAL.ALLOW_TICK_EXISTING; boolean tick_existing = Settings.settings().EXPERIMENTAL.ALLOW_TICK_EXISTING;
for (int i = 0; i < 4096; i++) { for (int i = 0; i < 4096; i++) {
char ordinal = set[i]; char ordinal = set[i];
switch (ordinal) { switch (ordinal) {

View File

@ -18,7 +18,7 @@ public class NMSRelighterFactory implements RelighterFactory {
Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) { Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) {
return new NMSRelighter( return new NMSRelighter(
queue, queue,
relightMode != null ? relightMode : RelightMode.valueOf(Settings.IMP.LIGHTING.MODE) relightMode != null ? relightMode : RelightMode.valueOf(Settings.settings().LIGHTING.MODE)
); );
} }

View File

@ -151,7 +151,7 @@ public abstract class Regenerator<IChunkAccess, ProtoChunk extends IChunkAccess,
private boolean generate() throws Exception { private boolean generate() throws Exception {
if (generateConcurrent) { if (generateConcurrent) {
//Using concurrent chunk generation //Using concurrent chunk generation
executor = Executors.newFixedThreadPool(Settings.IMP.QUEUE.PARALLEL_THREADS); executor = Executors.newFixedThreadPool(Settings.settings().QUEUE.PARALLEL_THREADS);
} // else using sequential chunk generation, concurrent not supported } // else using sequential chunk generation, concurrent not supported
//TODO: can we get that required radius down without affecting chunk generation (e.g. strucures, features, ...)? //TODO: can we get that required radius down without affecting chunk generation (e.g. strucures, features, ...)?

View File

@ -50,15 +50,15 @@ public abstract class ChunkListener implements Listener {
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
protected int rateLimit = 0; protected int rateLimit = 0;
protected Location lastCancelPos; protected Location lastCancelPos;
private final int[] badLimit = new int[]{Settings.IMP.TICK_LIMITER.PHYSICS_MS, private final int[] badLimit = new int[]{Settings.settings().TICK_LIMITER.PHYSICS_MS,
Settings.IMP.TICK_LIMITER.FALLING, Settings.IMP.TICK_LIMITER.ITEMS}; Settings.settings().TICK_LIMITER.FALLING, Settings.settings().TICK_LIMITER.ITEMS};
public ChunkListener() { public ChunkListener() {
if (Settings.IMP.TICK_LIMITER.ENABLED) { if (Settings.settings().TICK_LIMITER.ENABLED) {
PluginManager plm = Bukkit.getPluginManager(); PluginManager plm = Bukkit.getPluginManager();
Plugin plugin = Fawe.<FaweBukkit>imp().getPlugin(); Plugin plugin = Fawe.<FaweBukkit>platform().getPlugin();
plm.registerEvents(this, plugin); plm.registerEvents(this, plugin);
TaskManager.IMP.repeat(() -> { TaskManager.taskManager().repeat(() -> {
Location tmpLoc = lastCancelPos; Location tmpLoc = lastCancelPos;
if (tmpLoc != null) { if (tmpLoc != null) {
LOGGER.info("[FAWE Tick Limiter] Detected and cancelled physics lag source at {}", tmpLoc); LOGGER.info("[FAWE Tick Limiter] Detected and cancelled physics lag source at {}", tmpLoc);
@ -80,7 +80,7 @@ public abstract class ChunkListener implements Listener {
counter.put(key, badLimit); counter.put(key, badLimit);
} }
badChunks.clear(); badChunks.clear();
}, Settings.IMP.TICK_LIMITER.INTERVAL); }, Settings.settings().TICK_LIMITER.INTERVAL);
} }
} }
@ -241,13 +241,13 @@ public abstract class ChunkListener implements Listener {
if ((++physSkip & 1023) != 0) { if ((++physSkip & 1023) != 0) {
return; return;
} }
FaweTimer timer = Fawe.get().getTimer(); FaweTimer timer = Fawe.instance().getTimer();
if (timer.getTick() != physTick) { if (timer.getTick() != physTick) {
physTick = timer.getTick(); physTick = timer.getTick();
physStart = System.currentTimeMillis(); physStart = System.currentTimeMillis();
return; return;
} else if (System.currentTimeMillis() - physStart } else if (System.currentTimeMillis() - physStart
< Settings.IMP.TICK_LIMITER.PHYSICS_MS) { < Settings.settings().TICK_LIMITER.PHYSICS_MS) {
return; return;
} }
} }
@ -324,15 +324,15 @@ public abstract class ChunkListener implements Listener {
int cx = x >> 4; int cx = x >> 4;
int cz = z >> 4; int cz = z >> 4;
int[] count = getCount(cx, cz); int[] count = getCount(cx, cz);
if (count[1] >= Settings.IMP.TICK_LIMITER.FALLING) { if (count[1] >= Settings.settings().TICK_LIMITER.FALLING) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (event.getEntityType() == EntityType.FALLING_BLOCK) { if (event.getEntityType() == EntityType.FALLING_BLOCK) {
if (++count[1] >= Settings.IMP.TICK_LIMITER.FALLING) { if (++count[1] >= Settings.settings().TICK_LIMITER.FALLING) {
// Only cancel falling blocks when it's lagging // Only cancel falling blocks when it's lagging
if (Fawe.get().getTimer().getTPS() < 18) { if (Fawe.instance().getTimer().getTPS() < 18) {
cancelNearby(cx, cz); cancelNearby(cx, cz);
if (rateLimit <= 0) { if (rateLimit <= 0) {
rateLimit = 20; rateLimit = 20;
@ -351,7 +351,7 @@ public abstract class ChunkListener implements Listener {
*/ */
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) { public void onChunkLoad(ChunkLoadEvent event) {
if (!Settings.IMP.TICK_LIMITER.FIREWORKS_LOAD_CHUNKS) { if (!Settings.settings().TICK_LIMITER.FIREWORKS_LOAD_CHUNKS) {
Chunk chunk = event.getChunk(); Chunk chunk = event.getChunk();
Entity[] entities = chunk.getEntities(); Entity[] entities = chunk.getEntities();
World world = chunk.getWorld(); World world = chunk.getWorld();
@ -398,11 +398,11 @@ public abstract class ChunkListener implements Listener {
int cx = loc.getBlockX() >> 4; int cx = loc.getBlockX() >> 4;
int cz = loc.getBlockZ() >> 4; int cz = loc.getBlockZ() >> 4;
int[] count = getCount(cx, cz); int[] count = getCount(cx, cz);
if (count[2] >= Settings.IMP.TICK_LIMITER.ITEMS) { if (count[2] >= Settings.settings().TICK_LIMITER.ITEMS) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (++count[2] >= Settings.IMP.TICK_LIMITER.ITEMS) { if (++count[2] >= Settings.settings().TICK_LIMITER.ITEMS) {
cleanup(loc.getChunk()); cleanup(loc.getChunk());
cancelNearby(cx, cz); cancelNearby(cx, cz);
if (rateLimit <= 0) { if (rateLimit <= 0) {

View File

@ -37,13 +37,13 @@ public class ChunkListener9 extends ChunkListener {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (System.currentTimeMillis() - physStart > Settings.IMP.TICK_LIMITER.PHYSICS_MS) { if (System.currentTimeMillis() - physStart > Settings.settings().TICK_LIMITER.PHYSICS_MS) {
physCancelPair = pair; physCancelPair = pair;
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
FaweTimer timer = Fawe.get().getTimer(); FaweTimer timer = Fawe.instance().getTimer();
if (timer.getTick() != physTick) { if (timer.getTick() != physTick) {
physTick = timer.getTick(); physTick = timer.getTick();
physStart = System.currentTimeMillis(); physStart = System.currentTimeMillis();
@ -52,7 +52,7 @@ public class ChunkListener9 extends ChunkListener {
return; return;
} }
if ((++physSkip & 1023) == 0) { if ((++physSkip & 1023) == 0) {
if (System.currentTimeMillis() - physStart > Settings.IMP.TICK_LIMITER.PHYSICS_MS) { if (System.currentTimeMillis() - physStart > Settings.settings().TICK_LIMITER.PHYSICS_MS) {
Block block = event.getBlock(); Block block = event.getBlock();
int cx = block.getX() >> 4; int cx = block.getX() >> 4;
int cz = block.getZ() >> 4; int cz = block.getZ() >> 4;

View File

@ -28,7 +28,7 @@ public class RenderListener implements Listener {
public RenderListener(Plugin plugin) { public RenderListener(Plugin plugin) {
Bukkit.getPluginManager().registerEvents(this, plugin); Bukkit.getPluginManager().registerEvents(this, plugin);
TaskManager.IMP.repeat(new Runnable() { TaskManager.taskManager().repeat(new Runnable() {
private long last = 0; private long last = 0;
@Override @Override
@ -38,7 +38,7 @@ public class RenderListener implements Listener {
} }
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
int tps32 = (int) (Math.round(Fawe.get().getTimer().getTPS()) * 32); int tps32 = (int) (Math.round(Fawe.instance().getTimer().getTPS()) * 32);
long diff = now - last; long diff = now - last;
last = now; last = now;
if (diff > 75) { if (diff > 75) {
@ -56,7 +56,7 @@ public class RenderListener implements Listener {
if (entrySet == null || !entrySet.hasNext()) { if (entrySet == null || !entrySet.hasNext()) {
entrySet = views.entrySet().iterator(); entrySet = views.entrySet().iterator();
} }
int nowTick = (int) (Fawe.get().getTimer().getTick()); int nowTick = (int) (Fawe.instance().getTimer().getTick());
while (entrySet.hasNext()) { while (entrySet.hasNext()) {
Map.Entry<UUID, int[]> entry = entrySet.next(); Map.Entry<UUID, int[]> entry = entrySet.next();
Player player = Bukkit.getPlayer(entry.getKey()); Player player = Bukkit.getPlayer(entry.getKey());
@ -81,17 +81,17 @@ public class RenderListener implements Listener {
private void setViewDistance(Player player, int value) { private void setViewDistance(Player player, int value) {
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
if (value == Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING) { if (value == Settings.settings().EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING) {
views.remove(uuid); views.remove(uuid);
} else { } else {
int[] val = views.get(uuid); int[] val = views.get(uuid);
if (val == null) { if (val == null) {
val = new int[]{value, (int) Fawe.get().getTimer().getTick()}; val = new int[]{value, (int) Fawe.instance().getTimer().getTick()};
UUID uid = player.getUniqueId(); UUID uid = player.getUniqueId();
views.put(uid, val); views.put(uid, val);
} else { } else {
if (value <= val[0]) { if (value <= val[0]) {
val[1] = (int) Fawe.get().getTimer().getTick(); val[1] = (int) Fawe.instance().getTimer().getTick();
} }
if (val[0] == value) { if (val[0] == value) {
return; return;
@ -105,7 +105,7 @@ public class RenderListener implements Listener {
private int getViewDistance(Player player) { private int getViewDistance(Player player) {
int[] value = views.get(player.getUniqueId()); int[] value = views.get(player.getUniqueId());
return value == null ? Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING : value[0]; return value == null ? Settings.settings().EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING : value[0];
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)

View File

@ -33,7 +33,7 @@ public class ResidenceFeature extends BukkitMaskManager implements Listener {
return residence != null && return residence != null &&
(residence.getOwner().equals(player.getName()) || (residence.getOwner().equals(player.getName()) ||
residence.getOwner().equals(player.getUniqueId().toString()) || residence.getOwner().equals(player.getUniqueId().toString()) ||
type == MaskType.MEMBER && TaskManager.IMP.sync(() -> residence type == MaskType.MEMBER && TaskManager.taskManager().sync(() -> residence
.getPermissions() .getPermissions()
.playerHas(player, "build", false))); .playerHas(player, "build", false)));
} }

View File

@ -53,7 +53,7 @@ public class FaweDelegateRegionManager {
int maxY, int maxY,
Runnable whenDone Runnable whenDone
) { ) {
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
synchronized (FaweDelegateRegionManager.class) { synchronized (FaweDelegateRegionManager.class) {
World world = BukkitAdapter.adapt(getWorld(area.getWorldName())); World world = BukkitAdapter.adapt(getWorld(area.getWorldName()));
EditSession session = WorldEdit.getInstance().newEditSessionBuilder().world(world).checkMemory(false). EditSession session = WorldEdit.getInstance().newEditSessionBuilder().world(world).checkMemory(false).
@ -67,14 +67,14 @@ public class FaweDelegateRegionManager {
session.flushQueue(); session.flushQueue();
for (CuboidRegion region : regions) { for (CuboidRegion region : regions) {
FaweAPI.fixLighting(world, region, null, FaweAPI.fixLighting(world, region, null,
RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.IMP.LIGHTING.MODE) RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.settings().LIGHTING.MODE)
); );
} }
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (whenDone != null) { if (whenDone != null) {
TaskManager.IMP.task(whenDone); TaskManager.taskManager().task(whenDone);
} }
} }
} }
@ -92,7 +92,7 @@ public class FaweDelegateRegionManager {
@Nullable Runnable whenDone, @Nullable Runnable whenDone,
@Nonnull PlotManager manager @Nonnull PlotManager manager
) { ) {
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
synchronized (FaweDelegateRegionManager.class) { synchronized (FaweDelegateRegionManager.class) {
final HybridPlotWorld hybridPlotWorld = ((HybridPlotManager) manager).getHybridPlotWorld(); final HybridPlotWorld hybridPlotWorld = ((HybridPlotManager) manager).getHybridPlotWorld();
World world = BukkitAdapter.adapt(getWorld(hybridPlotWorld.getWorldName())); World world = BukkitAdapter.adapt(getWorld(hybridPlotWorld.getWorldName()));
@ -176,10 +176,10 @@ public class FaweDelegateRegionManager {
world, world,
new CuboidRegion(plot.getBottomAbs().getBlockVector3(), plot.getTopAbs().getBlockVector3()), new CuboidRegion(plot.getBottomAbs().getBlockVector3(), plot.getTopAbs().getBlockVector3()),
null, null,
RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.IMP.LIGHTING.MODE) RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.settings().LIGHTING.MODE)
); );
if (whenDone != null) { if (whenDone != null) {
TaskManager.IMP.task(whenDone); TaskManager.taskManager().task(whenDone);
} }
} }
}); });
@ -192,7 +192,7 @@ public class FaweDelegateRegionManager {
Location swapPos, Location swapPos,
final Runnable whenDone final Runnable whenDone
) { ) {
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
synchronized (FaweDelegateRegionManager.class) { synchronized (FaweDelegateRegionManager.class) {
//todo because of the following code this should proably be in the Bukkit module //todo because of the following code this should proably be in the Bukkit module
World pos1World = BukkitAdapter.adapt(getWorld(pos1.getWorldName())); World pos1World = BukkitAdapter.adapt(getWorld(pos1.getWorldName()));
@ -231,7 +231,7 @@ public class FaweDelegateRegionManager {
e.printStackTrace(); e.printStackTrace();
} }
FaweAPI.fixLighting(pos1World, new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()), null, FaweAPI.fixLighting(pos1World, new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()), null,
RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.IMP.LIGHTING.MODE) RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.settings().LIGHTING.MODE)
); );
FaweAPI.fixLighting(pos1World, new CuboidRegion( FaweAPI.fixLighting(pos1World, new CuboidRegion(
swapPos.getBlockVector3(), swapPos.getBlockVector3(),
@ -241,10 +241,10 @@ public class FaweDelegateRegionManager {
swapPos.getZ() + pos2.getZ() - pos1.getZ() swapPos.getZ() + pos2.getZ() - pos1.getZ()
) )
), null, ), null,
RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.IMP.LIGHTING.MODE) RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.settings().LIGHTING.MODE)
); );
if (whenDone != null) { if (whenDone != null) {
TaskManager.IMP.task(whenDone); TaskManager.taskManager().task(whenDone);
} }
} }
}); });
@ -253,7 +253,7 @@ public class FaweDelegateRegionManager {
public void setBiome(CuboidRegion region, int extendBiome, BiomeType biome, String world, Runnable whenDone) { public void setBiome(CuboidRegion region, int extendBiome, BiomeType biome, String world, Runnable whenDone) {
region.expand(BlockVector3.at(extendBiome, 0, extendBiome)); region.expand(BlockVector3.at(extendBiome, 0, extendBiome));
region.expand(BlockVector3.at(-extendBiome, 0, -extendBiome)); region.expand(BlockVector3.at(-extendBiome, 0, -extendBiome));
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
synchronized (FaweDelegateRegionManager.class) { synchronized (FaweDelegateRegionManager.class) {
EditSession editSession = WorldEdit EditSession editSession = WorldEdit
.getInstance() .getInstance()
@ -273,7 +273,7 @@ public class FaweDelegateRegionManager {
e.printStackTrace(); e.printStackTrace();
} }
if (whenDone != null) { if (whenDone != null) {
TaskManager.IMP.task(whenDone); TaskManager.taskManager().task(whenDone);
} }
} }
}); });
@ -285,7 +285,7 @@ public class FaweDelegateRegionManager {
final @NonNull Location pos3, final @NonNull Location pos3,
final @NonNull Runnable whenDone final @NonNull Runnable whenDone
) { ) {
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
synchronized (FaweDelegateRegionManager.class) { synchronized (FaweDelegateRegionManager.class) {
World pos1World = BukkitAdapter.adapt(getWorld(pos1.getWorldName())); World pos1World = BukkitAdapter.adapt(getWorld(pos1.getWorldName()));
World pos3World = BukkitAdapter.adapt(getWorld(pos3.getWorldName())); World pos3World = BukkitAdapter.adapt(getWorld(pos3.getWorldName()));
@ -319,21 +319,21 @@ public class FaweDelegateRegionManager {
pos3.getBlockVector3(), pos3.getBlockVector3(),
pos3.getBlockVector3().add(pos2.getBlockVector3().subtract(pos1.getBlockVector3())) pos3.getBlockVector3().add(pos2.getBlockVector3().subtract(pos1.getBlockVector3()))
), ),
null, RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.IMP.LIGHTING.MODE) null, RelightMode.valueOf(com.fastasyncworldedit.core.configuration.Settings.settings().LIGHTING.MODE)
); );
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (whenDone != null) { if (whenDone != null) {
TaskManager.IMP.task(whenDone); TaskManager.taskManager().task(whenDone);
} }
}); });
return true; return true;
} }
public boolean regenerateRegion(final Location pos1, final Location pos2, boolean ignore, final Runnable whenDone) { public boolean regenerateRegion(final Location pos1, final Location pos2, boolean ignore, final Runnable whenDone) {
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
synchronized (FaweDelegateRegionManager.class) { synchronized (FaweDelegateRegionManager.class) {
World pos1World = BukkitAdapter.adapt(getWorld(pos1.getWorldName())); World pos1World = BukkitAdapter.adapt(getWorld(pos1.getWorldName()));
try (EditSession editSession = WorldEdit.getInstance().newEditSessionBuilder().world(pos1World) try (EditSession editSession = WorldEdit.getInstance().newEditSessionBuilder().world(pos1World)
@ -350,7 +350,7 @@ public class FaweDelegateRegionManager {
editSession.flushQueue(); editSession.flushQueue();
} }
if (whenDone != null) { if (whenDone != null) {
TaskManager.IMP.task(whenDone); TaskManager.taskManager().task(whenDone);
} }
} }
}); });

View File

@ -132,7 +132,7 @@ public class FaweDelegateSchematicHandler {
} }
}; };
if (Fawe.isMainThread()) { if (Fawe.isMainThread()) {
com.fastasyncworldedit.core.util.TaskManager.IMP.async(r); com.fastasyncworldedit.core.util.TaskManager.taskManager().async(r);
} else { } else {
r.run(); r.run();
} }
@ -186,7 +186,7 @@ public class FaweDelegateSchematicHandler {
} }
return; return;
} }
final CompoundTag weTag = (CompoundTag) FaweCache.IMP.asTag(tag); final CompoundTag weTag = (CompoundTag) FaweCache.INSTANCE.asTag(tag);
SchematicHandler.upload(uuid, file, "schem", new RunnableVal<>() { SchematicHandler.upload(uuid, file, "schem", new RunnableVal<>() {
@Override @Override
public void run(OutputStream output) { public void run(OutputStream output) {

View File

@ -35,8 +35,8 @@ public class FaweQueueCoordinator extends QueueCoordinator {
public FaweQueueCoordinator(World world) { public FaweQueueCoordinator(World world) {
super(world); super(world);
this.world = world; this.world = world;
instance = Fawe.get().getQueueHandler().getQueue(world); instance = Fawe.instance().getQueueHandler().getQueue(world);
Fawe.get().getQueueHandler().unCache(); Fawe.instance().getQueueHandler().unCache();
} }
@Override @Override
@ -194,7 +194,7 @@ public class FaweQueueCoordinator extends QueueCoordinator {
@Override @Override
public boolean setTile(int x, int y, int z, CompoundTag tag) { public boolean setTile(int x, int y, int z, CompoundTag tag) {
instance.setTile(x, y, z, (com.sk89q.jnbt.CompoundTag) FaweCache.IMP.asTag(tag)); instance.setTile(x, y, z, (com.sk89q.jnbt.CompoundTag) FaweCache.INSTANCE.asTag(tag));
return true; return true;
} }

View File

@ -37,7 +37,7 @@ public class FaweTrim extends SubCommand {
return false; return false;
} }
ran = true; ran = true;
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
try { try {
// TODO NOT IMPLEMENTED // TODO NOT IMPLEMENTED
//PlotTrim trim = new PlotTrim(plotPlayer, plotPlayer.getPlotAreaAbs(), strings[0], Boolean.parseBoolean(strings[1])); //PlotTrim trim = new PlotTrim(plotPlayer, plotPlayer.getPlotAreaAbs(), strings[0], Boolean.parseBoolean(strings[1]));

View File

@ -89,7 +89,7 @@ public class PlotSetBiome extends Command {
return; return;
} }
plot.addRunning(); plot.addRunning();
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
EditSession session = EditSession session =
WorldEdit WorldEdit
.getInstance() .getInstance()

View File

@ -46,9 +46,9 @@ public class ReplaceAll extends Command {
plot.addRunning(); plot.addRunning();
FawePlayer<Object> fp = FawePlayer.wrap(player.getName()); FawePlayer<Object> fp = FawePlayer.wrap(player.getName());
Captions.TASK_START.send(player); Captions.TASK_START.send(player);
TaskManager.IMP.async(() -> fp.runAction(() -> { TaskManager.taskManager().async(() -> fp.runAction(() -> {
String worldName = plot.getWorldName(); String worldName = plot.getWorldName();
TaskManager.IMP.sync(new RunnableVal<Object>() { TaskManager.taskManager().sync(new RunnableVal<Object>() {
@Override @Override
public void run(Object value) { public void run(Object value) {
SetupUtils.manager.unload(worldName, true); SetupUtils.manager.unload(worldName, true);
@ -58,7 +58,7 @@ public class ReplaceAll extends Command {
String cmd = "/replaceallpattern " + worldName + " " + StringMan.join(args, " "); String cmd = "/replaceallpattern " + worldName + " " + StringMan.join(args, " ");
CommandEvent event = new CommandEvent(actor, cmd); CommandEvent event = new CommandEvent(actor, cmd);
PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event); PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event);
TaskManager.IMP.sync(new RunnableVal<Object>() { TaskManager.taskManager().sync(new RunnableVal<Object>() {
@Override @Override
public void run(Object value) { public void run(Object value) {
plot.teleportPlayer(player); plot.teleportPlayer(player);

View File

@ -34,7 +34,7 @@ public class BukkitItemStack extends BaseItemStack {
@Nullable @Nullable
@Override @Override
public Object getNativeItem() { public Object getNativeItem() {
ItemUtil util = Fawe.<FaweBukkit>imp().getItemUtil(); ItemUtil util = Fawe.<FaweBukkit>platform().getItemUtil();
if (util != null && nativeItem == null) { if (util != null && nativeItem == null) {
return nativeItem = util.getNMSItem(stack); return nativeItem = util.getNMSItem(stack);
} }
@ -58,7 +58,7 @@ public class BukkitItemStack extends BaseItemStack {
public CompoundTag getNbtData() { public CompoundTag getNbtData() {
if (!loadedNBT) { if (!loadedNBT) {
loadedNBT = true; loadedNBT = true;
ItemUtil util = Fawe.<FaweBukkit>imp().getItemUtil(); ItemUtil util = Fawe.<FaweBukkit>platform().getItemUtil();
if (util != null) { if (util != null) {
super.setNbtData(util.getNBT(stack)); super.setNbtData(util.getNBT(stack));
} }
@ -68,7 +68,7 @@ public class BukkitItemStack extends BaseItemStack {
@Override @Override
public void setNbtData(@Nullable CompoundTag nbtData) { public void setNbtData(@Nullable CompoundTag nbtData) {
ItemUtil util = Fawe.<FaweBukkit>imp().getItemUtil(); ItemUtil util = Fawe.<FaweBukkit>platform().getItemUtil();
if (util != null) { if (util != null) {
stack = util.setNBT(stack, nbtData); stack = util.setNBT(stack, nbtData);
nativeItem = null; nativeItem = null;

View File

@ -107,7 +107,7 @@ public class BukkitPlayer extends AbstractPlayerActor {
this.player = player; this.player = player;
//FAWE start //FAWE start
this.permAttachment = plugin.getPermissionAttachmentManager().getOrAddAttachment(player); this.permAttachment = plugin.getPermissionAttachmentManager().getOrAddAttachment(player);
if (player != null && Settings.IMP.CLIPBOARD.USE_DISK) { if (player != null && Settings.settings().CLIPBOARD.USE_DISK) {
BukkitPlayer cached = WorldEditPlugin.getInstance().getCachedPlayer(player); BukkitPlayer cached = WorldEditPlugin.getInstance().getCachedPlayer(player);
if (cached == null) { if (cached == null) {
loadClipboardFromDisk(); loadClipboardFromDisk();
@ -169,7 +169,7 @@ public class BukkitPlayer extends AbstractPlayerActor {
player.getInventory().setItemInMainHand(newItem); player.getInventory().setItemInMainHand(newItem);
HashMap<Integer, ItemStack> overflow = inv.addItem(item); HashMap<Integer, ItemStack> overflow = inv.addItem(item);
if (!overflow.isEmpty()) { if (!overflow.isEmpty()) {
TaskManager.IMP.sync(new RunnableVal<>() { TaskManager.taskManager().sync(new RunnableVal<>() {
@Override @Override
public void run(Object value) { public void run(Object value) {
for (Map.Entry<Integer, ItemStack> entry : overflow.entrySet()) { for (Map.Entry<Integer, ItemStack> entry : overflow.entrySet()) {
@ -243,7 +243,7 @@ public class BukkitPlayer extends AbstractPlayerActor {
} }
org.bukkit.World finalWorld = world; org.bukkit.World finalWorld = world;
//FAWE end //FAWE end
return TaskManager.IMP.sync(() -> player.teleport(new Location( return TaskManager.taskManager().sync(() -> player.teleport(new Location(
finalWorld, finalWorld,
pos.getX(), pos.getX(),
pos.getY(), pos.getY(),

View File

@ -317,7 +317,7 @@ public class BukkitWorld extends AbstractWorld {
@Override @Override
public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 pt) { public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 pt) {
//FAWE start - allow tree commands to be undone and obey region restrictions //FAWE start - allow tree commands to be undone and obey region restrictions
return TaskManager.IMP.sync(() -> WorldEditPlugin.getInstance().getBukkitImplAdapter().generateTree(type, editSession, pt, return TaskManager.taskManager().sync(() -> WorldEditPlugin.getInstance().getBukkitImplAdapter().generateTree(type, editSession, pt,
getWorld() getWorld()
)); ));
//FAWE end //FAWE end

View File

@ -380,7 +380,7 @@ public class WorldEditPlugin extends JavaPlugin {
*/ */
@Override @Override
public void onDisable() { public void onDisable() {
Fawe.get().onDisable(); Fawe.instance().onDisable();
WorldEdit worldEdit = WorldEdit.getInstance(); WorldEdit worldEdit = WorldEdit.getInstance();
worldEdit.getSessionManager().unload(); worldEdit.getSessionManager().unload();
if (platform != null) { if (platform != null) {

View File

@ -314,7 +314,7 @@ public interface BukkitImplAdapter<T> extends IBukkitAdapter {
@Nullable @Nullable
default World createWorld(WorldCreator creator) { default World createWorld(WorldCreator creator) {
return ((FaweBukkit) Fawe.imp()).createWorldUnloaded(creator::createWorld); return ((FaweBukkit) Fawe.platform()).createWorldUnloaded(creator::createWorld);
} }
/** /**

View File

@ -101,17 +101,17 @@ public class Fawe {
this.setupConfigs(); this.setupConfigs();
TaskManager.IMP = this.implementation.getTaskManager(); TaskManager.IMP = this.implementation.getTaskManager();
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
MainUtil.deleteOlder( MainUtil.deleteOlder(
MainUtil.getFile(this.implementation MainUtil.getFile(this.implementation
.getDirectory(), Settings.IMP.PATHS.HISTORY), .getDirectory(), Settings.settings().PATHS.HISTORY),
TimeUnit.DAYS.toMillis(Settings.IMP.HISTORY.DELETE_AFTER_DAYS), TimeUnit.DAYS.toMillis(Settings.settings().HISTORY.DELETE_AFTER_DAYS),
false false
); );
MainUtil.deleteOlder( MainUtil.deleteOlder(
MainUtil.getFile(this.implementation MainUtil.getFile(this.implementation
.getDirectory(), Settings.IMP.PATHS.CLIPBOARD), .getDirectory(), Settings.settings().PATHS.CLIPBOARD),
TimeUnit.DAYS.toMillis(Settings.IMP.CLIPBOARD.DELETE_AFTER_DAYS), TimeUnit.DAYS.toMillis(Settings.settings().CLIPBOARD.DELETE_AFTER_DAYS),
false false
); );
}); });
@ -123,28 +123,49 @@ public class Fawe {
this.timer = new FaweTimer(); this.timer = new FaweTimer();
// Delayed worldedit setup // Delayed worldedit setup
TaskManager.IMP.later(() -> { TaskManager.taskManager().later(() -> {
try { try {
WEManager.IMP.addManagers(Fawe.this.implementation.getMaskManagers()); WEManager.weManager().addManagers(Fawe.this.implementation.getMaskManagers());
} catch (Throwable ignored) { } catch (Throwable ignored) {
} }
}, 0); }, 0);
TaskManager.IMP.repeat(timer, 1); TaskManager.taskManager().repeat(timer, 1);
} }
/** /**
* Get the implementation specific class. * Get the implementation specific class.
* @deprecated use {@link #platform()}
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Deprecated(forRemoval = true, since = "2.0.0")
public static <T extends IFawe> T imp() { public static <T extends IFawe> T imp() {
return instance != null ? (T) instance.implementation : null; return instance != null ? (T) instance.implementation : null;
} }
/**
* Get the implementation specific class.
* @since 2.0.0
*/
@SuppressWarnings("unchecked")
public static <T extends IFawe> T platform() {
return instance != null ? (T) instance.implementation : null;
}
/**
* Get the implementation independent class.
* @ use {@link #instance()}
*/
@Deprecated(forRemoval = true, since = "2.0.0")
public static Fawe get() {
return instance;
}
/** /**
* Get the implementation independent class. * Get the implementation independent class.
*/ */
public static Fawe get() { public static Fawe instance() {
return instance; return instance;
} }
@ -225,8 +246,8 @@ public class Fawe {
} }
public void onDisable() { public void onDisable() {
if (imp().getPreloader(false) != null) { if (platform().getPreloader(false) != null) {
imp().getPreloader(false).cancel(); platform().getPreloader(false).cancel();
} }
} }
@ -296,7 +317,7 @@ public class Fawe {
MainUtil.copyFile(MainUtil.getJarFile(), "lang/strings.json", null); MainUtil.copyFile(MainUtil.getJarFile(), "lang/strings.json", null);
// Setting up config.yml // Setting up config.yml
File file = new File(this.implementation.getDirectory(), "config.yml"); File file = new File(this.implementation.getDirectory(), "config.yml");
Settings.IMP.PLATFORM = implementation.getPlatform().replace("\"", ""); Settings.settings().PLATFORM = implementation.getPlatform().replace("\"", "");
try (InputStream stream = getClass().getResourceAsStream("/fawe.properties"); try (InputStream stream = getClass().getResourceAsStream("/fawe.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(stream))) { BufferedReader br = new BufferedReader(new InputStreamReader(stream))) {
String versionString = br.readLine(); String versionString = br.readLine();
@ -304,17 +325,17 @@ public class Fawe {
String dateString = br.readLine(); String dateString = br.readLine();
br.close(); br.close();
this.version = FaweVersion.tryParse(versionString, commitString, dateString); this.version = FaweVersion.tryParse(versionString, commitString, dateString);
Settings.IMP.DATE = new Date(100 + version.year, version.month, version.day).toString(); Settings.settings().DATE = new Date(100 + version.year, version.month, version.day).toString();
Settings.IMP.BUILD = "https://ci.athion.net/job/FastAsyncWorldEdit/" + version.build; Settings.settings().BUILD = "https://ci.athion.net/job/FastAsyncWorldEdit/" + version.build;
Settings.IMP.COMMIT = "https://github.com/IntellectualSites/FastAsyncWorldEdit/commit/" + Integer.toHexString(version.hash); Settings.settings().COMMIT = "https://github.com/IntellectualSites/FastAsyncWorldEdit/commit/" + Integer.toHexString(version.hash);
} catch (Throwable ignored) { } catch (Throwable ignored) {
} }
try { try {
Settings.IMP.reload(file); Settings.settings().reload(file);
} catch (Throwable e) { } catch (Throwable e) {
LOGGER.error("Failed to load config.", e); LOGGER.error("Failed to load config.", e);
} }
Settings.IMP.QUEUE.TARGET_SIZE = Math.max(Settings.IMP.QUEUE.TARGET_SIZE, Settings.IMP.QUEUE.PARALLEL_THREADS); Settings.settings().QUEUE.TARGET_SIZE = Math.max(Settings.settings().QUEUE.TARGET_SIZE, Settings.settings().QUEUE.PARALLEL_THREADS);
try { try {
byte[] in = new byte[0]; byte[] in = new byte[0];
byte[] compressed = LZ4Factory.fastestJavaInstance().fastCompressor().compress(in); byte[] compressed = LZ4Factory.fastestJavaInstance().fastCompressor().compress(in);
@ -332,14 +353,14 @@ public class Fawe {
assert (Zstd.decompress(ob, compressed) == 0); assert (Zstd.decompress(ob, compressed) == 0);
LOGGER.info("ZSTD Compression Binding loaded successfully"); LOGGER.info("ZSTD Compression Binding loaded successfully");
} catch (Throwable e) { } catch (Throwable e) {
if (Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL > 6 || Settings.IMP.HISTORY.COMPRESSION_LEVEL > 6) { if (Settings.settings().CLIPBOARD.COMPRESSION_LEVEL > 6 || Settings.settings().HISTORY.COMPRESSION_LEVEL > 6) {
Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL = Math.min(6, Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL); Settings.settings().CLIPBOARD.COMPRESSION_LEVEL = Math.min(6, Settings.settings().CLIPBOARD.COMPRESSION_LEVEL);
Settings.IMP.HISTORY.COMPRESSION_LEVEL = Math.min(6, Settings.IMP.HISTORY.COMPRESSION_LEVEL); Settings.settings().HISTORY.COMPRESSION_LEVEL = Math.min(6, Settings.settings().HISTORY.COMPRESSION_LEVEL);
LOGGER.error("ZSTD Compression Binding Not Found.\n" LOGGER.error("ZSTD Compression Binding Not Found.\n"
+ "FAWE will still work but compression won't work as well.", e); + "FAWE will still work but compression won't work as well.", e);
} }
} }
Settings.IMP.save(file); Settings.settings().save(file);
} }
public WorldEdit getWorldEdit() { public WorldEdit getWorldEdit() {
@ -347,7 +368,7 @@ public class Fawe {
} }
private void setupMemoryListener() { private void setupMemoryListener() {
if (Settings.IMP.MAX_MEMORY_PERCENT < 1 || Settings.IMP.MAX_MEMORY_PERCENT > 99) { if (Settings.settings().MAX_MEMORY_PERCENT < 1 || Settings.settings().MAX_MEMORY_PERCENT > 99) {
return; return;
} }
try { try {
@ -371,7 +392,7 @@ public class Fawe {
if (max < 0) { if (max < 0) {
continue; continue;
} }
final long alert = (max * Settings.IMP.MAX_MEMORY_PERCENT) / 100; final long alert = (max * Settings.settings().MAX_MEMORY_PERCENT) / 100;
mp.setUsageThreshold(alert); mp.setUsageThreshold(alert);
} }
} }

View File

@ -65,7 +65,7 @@ public class FaweAPI {
* @return TaskManager * @return TaskManager
*/ */
public static TaskManager getTaskManager() { public static TaskManager getTaskManager() {
return TaskManager.IMP; return TaskManager.taskManager();
} }
/** /**
@ -81,7 +81,7 @@ public class FaweAPI {
* @return the queue extent * @return the queue extent
*/ */
public static IQueueExtent<IQueueChunk> createQueue(World world, boolean autoQueue) { public static IQueueExtent<IQueueChunk> createQueue(World world, boolean autoQueue) {
IQueueExtent<IQueueChunk> queue = Fawe.get().getQueueHandler().getQueue(world); IQueueExtent<IQueueChunk> queue = Fawe.instance().getQueueHandler().getQueue(world);
if (!autoQueue) { if (!autoQueue) {
queue.disableQueue(); queue.disableQueue();
} }
@ -127,7 +127,7 @@ public class FaweAPI {
* @return Set of FaweMaskManager * @return Set of FaweMaskManager
*/ */
public static Set<FaweMaskManager> getMaskManagers() { public static Set<FaweMaskManager> getMaskManagers() {
return new HashSet<>(WEManager.IMP.getManagers()); return new HashSet<>(WEManager.weManager().getManagers());
} }
/** /**
@ -143,7 +143,7 @@ public class FaweAPI {
* Get a player's allowed WorldEdit region(s). * Get a player's allowed WorldEdit region(s).
*/ */
public static Region[] getRegions(Player player) { public static Region[] getRegions(Player player) {
return WEManager.IMP.getMask(player); return WEManager.weManager().getMask(player);
} }
/** /**
@ -155,7 +155,7 @@ public class FaweAPI {
* @return array of allowed regions if whitelist, else of disallowed regions. * @return array of allowed regions if whitelist, else of disallowed regions.
*/ */
public static Region[] getRegions(Player player, FaweMaskManager.MaskType type, boolean isWhiteList) { public static Region[] getRegions(Player player, FaweMaskManager.MaskType type, boolean isWhiteList) {
return WEManager.IMP.getMask(player, type, isWhiteList); return WEManager.weManager().getMask(player, type, isWhiteList);
} }
/** /**
@ -170,13 +170,13 @@ public class FaweAPI {
*/ */
public static void cancelEdit(AbstractDelegateExtent extent, Component reason) { public static void cancelEdit(AbstractDelegateExtent extent, Component reason) {
try { try {
WEManager.IMP.cancelEdit(extent, new FaweException(reason)); WEManager.weManager().cancelEdit(extent, new FaweException(reason));
} catch (WorldEditException ignored) { } catch (WorldEditException ignored) {
} }
} }
public static void addMaskManager(FaweMaskManager maskMan) { public static void addMaskManager(FaweMaskManager maskMan) {
WEManager.IMP.addManager(maskMan); WEManager.weManager().addManager(maskMan);
} }
/** /**
@ -186,7 +186,7 @@ public class FaweAPI {
if (!file.exists() || file.isDirectory()) { if (!file.exists() || file.isDirectory()) {
throw new IllegalArgumentException("Not a file!"); throw new IllegalArgumentException("Not a file!");
} }
if (Settings.IMP.HISTORY.USE_DISK) { if (Settings.settings().HISTORY.USE_DISK) {
throw new IllegalArgumentException("History on disk not enabled!"); throw new IllegalArgumentException("History on disk not enabled!");
} }
if (!file.getName().toLowerCase(Locale.ROOT).endsWith(".bd")) { if (!file.getName().toLowerCase(Locale.ROOT).endsWith(".bd")) {
@ -224,11 +224,10 @@ public class FaweAPI {
*/ */
public static List<DiskStorageHistory> getBDFiles(Location origin, UUID user, int radius, long timediff, boolean shallow) { public static List<DiskStorageHistory> getBDFiles(Location origin, UUID user, int radius, long timediff, boolean shallow) {
Extent extent = origin.getExtent(); Extent extent = origin.getExtent();
if (!(extent instanceof World)) { if (!(extent instanceof World world)) {
throw new IllegalArgumentException("Origin is not a valid world"); throw new IllegalArgumentException("Origin is not a valid world");
} }
World world = (World) extent; File history = MainUtil.getFile(Fawe.platform().getDirectory(), Settings.settings().PATHS.HISTORY + File.separator + world.getName());
File history = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + world.getName());
if (!history.exists()) { if (!history.exists()) {
return new ArrayList<>(); return new ArrayList<>();
} }
@ -352,12 +351,12 @@ public class FaweAPI {
World unwrapped = WorldWrapper.unwrap(world); World unwrapped = WorldWrapper.unwrap(world);
if (unwrapped instanceof IQueueExtent) { if (unwrapped instanceof IQueueExtent) {
queue = (IQueueExtent) unwrapped; queue = (IQueueExtent) unwrapped;
} else if (Settings.IMP.QUEUE.PARALLEL_THREADS > 1) { } else if (Settings.settings().QUEUE.PARALLEL_THREADS > 1) {
ParallelQueueExtent parallel = ParallelQueueExtent parallel =
new ParallelQueueExtent(Fawe.get().getQueueHandler(), world, true); new ParallelQueueExtent(Fawe.instance().getQueueHandler(), world, true);
queue = parallel.getExtent(); queue = parallel.getExtent();
} else { } else {
queue = Fawe.get().getQueueHandler().getQueue(world); queue = Fawe.instance().getQueueHandler().getQueue(world);
} }
} }
@ -372,7 +371,7 @@ public class FaweAPI {
} }
} }
if (mode != RelightMode.NONE) { if (mode != RelightMode.NONE) {
if (Settings.IMP.LIGHTING.REMOVE_FIRST) { if (Settings.settings().LIGHTING.REMOVE_FIRST) {
relighter.removeAndRelight(true); relighter.removeAndRelight(true);
} else { } else {
relighter.fixSkyLighting(); relighter.fixSkyLighting();

View File

@ -59,7 +59,15 @@ import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
public enum FaweCache implements Trimable { public enum FaweCache implements Trimable {
IMP; // singleton /**
* @deprecated Use {@link #INSTANCE} to get an instance.
*/
@Deprecated(forRemoval = true, since = "2.0.0")
IMP,
/**
* @since 2.0.0
*/
INSTANCE;// singleton
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
@ -301,7 +309,7 @@ public enum FaweCache implements Trimable {
// BlockStates // BlockStates
int bitsPerEntry = MathMan.log2nlz(num_palette - 1); int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
if (Settings.IMP.PROTOCOL_SUPPORT_FIX || num_palette != 1) { if (Settings.settings().PROTOCOL_SUPPORT_FIX || num_palette != 1) {
bitsPerEntry = Math.max(bitsPerEntry, 4); // Protocol support breaks <4 bits per entry bitsPerEntry = Math.max(bitsPerEntry, 4); // Protocol support breaks <4 bits per entry
} else { } else {
bitsPerEntry = Math.max(bitsPerEntry, 1); // For some reason minecraft needs 4096 bits to store 0 entries bitsPerEntry = Math.max(bitsPerEntry, 1); // For some reason minecraft needs 4096 bits to store 0 entries
@ -387,7 +395,7 @@ public enum FaweCache implements Trimable {
// BlockStates // BlockStates
int bitsPerEntry = MathMan.log2nlz(num_palette - 1); int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
if (Settings.IMP.PROTOCOL_SUPPORT_FIX || num_palette != 1) { if (Settings.settings().PROTOCOL_SUPPORT_FIX || num_palette != 1) {
bitsPerEntry = Math.max(bitsPerEntry, 4); // Protocol support breaks <4 bits per entry bitsPerEntry = Math.max(bitsPerEntry, 4); // Protocol support breaks <4 bits per entry
} else { } else {
bitsPerEntry = Math.max(bitsPerEntry, 1); // For some reason minecraft needs 4096 bits to store 0 entries bitsPerEntry = Math.max(bitsPerEntry, 1); // For some reason minecraft needs 4096 bits to store 0 entries
@ -568,7 +576,7 @@ public enum FaweCache implements Trimable {
Thread stuff Thread stuff
*/ */
public ThreadPoolExecutor newBlockingExecutor() { public ThreadPoolExecutor newBlockingExecutor() {
int nThreads = Settings.IMP.QUEUE.PARALLEL_THREADS; int nThreads = Settings.settings().QUEUE.PARALLEL_THREADS;
ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(nThreads, true); ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(nThreads, true);
return new ThreadPoolExecutor(nThreads, nThreads, return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS, queue, 0L, TimeUnit.MILLISECONDS, queue,
@ -609,7 +617,7 @@ public enum FaweCache implements Trimable {
lastException = hash; lastException = hash;
LOGGER.catching(throwable); LOGGER.catching(throwable);
count = 0; count = 0;
} else if (count < Settings.IMP.QUEUE.PARALLEL_THREADS) { } else if (count < Settings.settings().QUEUE.PARALLEL_THREADS) {
LOGGER.warn(throwable.getMessage()); LOGGER.warn(throwable.getMessage());
count++; count++;
} }

View File

@ -531,7 +531,7 @@ public class AnvilCommands {
// }); // });
// if (useData) { // if (useData) {
// for (long[] c : map) { // for (long[] c : map) {
// BaseBlock block = FaweCache.IMP.CACHE_BLOCK[(int) c[0]]; // BaseBlock block = FaweCache.INSTANCE.CACHE_BLOCK[(int) c[0]];
// String name = BlockType.fromID(block.getId()).getName(); // String name = BlockType.fromID(block.getId()).getName();
// String str = String.format("%-7s (%.3f%%) %s #%d:%d", // String str = String.format("%-7s (%.3f%%) %s #%d:%d",
// String.valueOf(c[1]), // String.valueOf(c[1]),

View File

@ -147,7 +147,7 @@
// CFISettings settings = getSettings(player).remove(); // CFISettings settings = getSettings(player).remove();
// generator.setPacketViewer(player); // generator.setPacketViewer(player);
// settings.setGenerator(generator).bind(); // settings.setGenerator(generator).bind();
// generator.setImageViewer(Fawe.imp().getImageViewer(player)); // generator.setImageViewer(Fawe.platform().getImageViewer(player));
// generator.update(); // generator.update();
// mainMenu(player); // mainMenu(player);
// } // }
@ -226,7 +226,7 @@
// World world = FaweAPI.getWorld(folder.getName()); // World world = FaweAPI.getWorld(folder.getName());
// if (world != null) { // if (world != null) {
// if (player.getWorld() != world) { // if (player.getWorld() != world) {
// TaskManager.IMP.sync(new RunnableVal<Object>() { // TaskManager.taskManager().sync(new RunnableVal<Object>() {
// @Override // @Override
// public void run(Object value) { // public void run(Object value) {
// Location spawn = new Location(world, world.getSpawnPosition().toVector3()); // Location spawn = new Location(world, world.getSpawnPosition().toVector3());
@ -425,7 +425,7 @@
// switch (argOpt.toLowerCase(Locale.ROOT)) { // switch (argOpt.toLowerCase(Locale.ROOT)) {
// case "true": // case "true":
// case "*": { // case "*": {
// generator.setTextureUtil(Fawe.get().getTextureUtil()); // generator.setTextureUtil(Fawe.instance().getTextureUtil());
// return; // return;
// } // }
// case "#clipboard": { // case "#clipboard": {
@ -453,7 +453,7 @@
// parserContext.setExtent(extent); // parserContext.setExtent(extent);
// Request.request().setExtent(extent); // Request.request().setExtent(extent);
// Mask mask = worldEdit.getMaskFactory().parseFromInput(argOpt, parserContext); // Mask mask = worldEdit.getMaskFactory().parseFromInput(argOpt, parserContext);
// TextureUtil tu = Fawe.get().getTextureUtil(); // TextureUtil tu = Fawe.instance().getTextureUtil();
// for (int typeId : tu.getValidBlockIds()) { // for (int typeId : tu.getValidBlockIds()) {
// BlockType type = BlockTypes.get(typeId); // BlockType type = BlockTypes.get(typeId);
// extent.init(0, 0, 0, type.getDefaultState().toBaseBlock()); // extent.init(0, 0, 0, type.getDefaultState().toBaseBlock());
@ -464,7 +464,7 @@
// break; // break;
// } // }
// } // }
// generator.setTextureUtil(new FilteredTextureUtil(Fawe.get().getTextureUtil(), blocks)); // generator.setTextureUtil(new FilteredTextureUtil(Fawe.instance().getTextureUtil(), blocks));
// coloring(player); // coloring(player);
// } // }
// //
@ -493,9 +493,9 @@
// public void complexity(Player player, int min, int max) throws FileNotFoundException { // public void complexity(Player player, int min, int max) throws FileNotFoundException {
// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); // HeightMapMCAGenerator gen = assertSettings(player).getGenerator();
// if (min == 0 && max == 100) { // if (min == 0 && max == 100) {
// gen.setTextureUtil(Fawe.get().getTextureUtil()); // gen.setTextureUtil(Fawe.instance().getTextureUtil());
// } else { // } else {
// gen.setTextureUtil(new CleanTextureUtil(Fawe.get().getTextureUtil(), min, max)); // gen.setTextureUtil(new CleanTextureUtil(Fawe.instance().getTextureUtil(), min, max));
// } // }
// coloring(player); // coloring(player);
// } // }
@ -1201,7 +1201,7 @@
// whiteOnly = true; // whiteOnly = true;
// maskArg = null; // maskArg = null;
// imageMaskArg = null; // imageMaskArg = null;
// generator.setTextureUtil(Fawe.get().getTextureUtil()); // generator.setTextureUtil(Fawe.instance().getTextureUtil());
// } // }
// //
// public void resetComponent() { // public void resetComponent() {

View File

@ -95,7 +95,7 @@ public class ListFilters {
} }
String firstArg = finalArg.substring(0, finalArg.length() - File.separator.length()); String firstArg = finalArg.substring(0, finalArg.length() - File.separator.length());
if (firstArg.length() > 3 && firstArg.length() <= 16) { if (firstArg.length() > 3 && firstArg.length() <= 16) {
UUID fromName = Fawe.imp().getUUID(finalArg); UUID fromName = Fawe.platform().getUUID(finalArg);
if (fromName != null) { if (fromName != null) {
newRoot = new File(root, finalArg); newRoot = new File(root, finalArg);
if (newRoot.exists()) { if (newRoot.exists()) {

View File

@ -45,7 +45,7 @@
// PlotPlayer player = PlotPlayer.get(actor.getName()); // PlotPlayer player = PlotPlayer.get(actor.getName());
// //
// actor.print("Claiming world"); // actor.print("Claiming world");
// Plot plot = TaskManager.IMP.sync(new RunnableVal<Plot>() { // Plot plot = TaskManager.taskManager().sync(new RunnableVal<Plot>() {
// @Override // @Override
// public void run(Plot o) { // public void run(Plot o) {
// int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() // int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount()
@ -73,7 +73,7 @@
// File folder = CFICommands.getFolder(plot.getWorldName()); // File folder = CFICommands.getFolder(plot.getWorldName());
// Boolean result = createTask.apply(folder); // Boolean result = createTask.apply(folder);
// if (result == Boolean.TRUE) { // if (result == Boolean.TRUE) {
// TaskManager.IMP.sync(() -> plot.teleportPlayer(player)); // TaskManager.taskManager().sync(() -> plot.teleportPlayer(player));
// } // }
// return; // return;
// } // }

View File

@ -90,7 +90,7 @@ public class BrushSettings {
// } // }
// if (settings.containsKey(SettingType.TRANSFORM.name())) { // if (settings.containsKey(SettingType.TRANSFORM.name())) {
// String transformArgs = (String) settings.get(SettingType.TRANSFORM.name()); // String transformArgs = (String) settings.get(SettingType.TRANSFORM.name());
// ResettableExtent extent = Fawe.get().getTransformParser().parseFromInput(transformArgs, parserContext); // ResettableExtent extent = Fawe.instance().getTransformParser().parseFromInput(transformArgs, parserContext);
// bs.setTransform(extent); // bs.setTransform(extent);
// bs.constructor.put(SettingType.TRANSFORM, transformArgs); // bs.constructor.put(SettingType.TRANSFORM, transformArgs);
// } // }

View File

@ -68,7 +68,7 @@ public class InspectBrush extends BrushTool {
player.print(Caption.of("fawe.error.no-perm", "worldedit.tool.inspect")); player.print(Caption.of("fawe.error.no-perm", "worldedit.tool.inspect"));
return false; return false;
} }
if (!Settings.IMP.HISTORY.USE_DATABASE) { if (!Settings.settings().HISTORY.USE_DATABASE) {
player.print(Caption.of( player.print(Caption.of(
"fawe.error.setting.disable", "fawe.error.setting.disable",
"history.use-database (Import with /history import )" "history.use-database (Import with /history import )"
@ -95,7 +95,7 @@ public class InspectBrush extends BrushTool {
int from = change.from; int from = change.from;
int to = change.to; int to = change.to;
UUID uuid = edit.getUUID(); UUID uuid = edit.getUUID();
String name = Fawe.imp().getName(uuid); String name = Fawe.platform().getName(uuid);
int index = edit.getIndex(); int index = edit.getIndex();
long age = System.currentTimeMillis() - edit.getBDFile().lastModified(); long age = System.currentTimeMillis() - edit.getBDFile().lastModified();
String ageFormatted = MainUtil.secToTime(age / 1000); String ageFormatted = MainUtil.secToTime(age / 1000);

View File

@ -19,12 +19,16 @@ import java.util.stream.Stream;
public class Settings extends Config { public class Settings extends Config {
/**
* @deprecated Use {@link #settings()} instead to get an instance.
*/
@Ignore @Ignore
@Deprecated(forRemoval = true, since = "2.0.0")
public static final Settings IMP = new Settings(); public static final Settings IMP = new Settings();
@Ignore
static Settings INSTANCE = new Settings();
@Ignore @Ignore
public boolean PROTOCOL_SUPPORT_FIX = false; public boolean PROTOCOL_SUPPORT_FIX = false;
@Comment("These first 6 aren't configurable") // This is a comment @Comment("These first 6 aren't configurable") // This is a comment
@Final // Indicates that this value isn't configurable @Final // Indicates that this value isn't configurable
public String ISSUES = "https://github.com/IntellectualSites/FastAsyncWorldEdit/issues"; public String ISSUES = "https://github.com/IntellectualSites/FastAsyncWorldEdit/issues";
@ -38,7 +42,6 @@ public class Settings extends Config {
public String COMMIT; // These values are set from FAWE before loading public String COMMIT; // These values are set from FAWE before loading
@Final @Final
public String PLATFORM; // These values are set from FAWE before loading public String PLATFORM; // These values are set from FAWE before loading
@Comment({ @Comment({
"Set true to enable WorldEdit restrictions per region (e.g. PlotSquared or WorldGuard).", "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", "To be allowed to WorldEdit in a region, users need the appropriate",
@ -51,7 +54,6 @@ public class Settings extends Config {
" - Disable with 100 or -1." " - Disable with 100 or -1."
}) })
public int MAX_MEMORY_PERCENT = 95; public int MAX_MEMORY_PERCENT = 95;
@Create @Create
public ENABLED_COMPONENTS ENABLED_COMPONENTS; public ENABLED_COMPONENTS ENABLED_COMPONENTS;
@Create @Create
@ -77,16 +79,178 @@ public class Settings extends Config {
@Create @Create
public ConfigBlock<LIMITS> LIMITS; public ConfigBlock<LIMITS> LIMITS;
private Settings() {
INSTANCE = this;
}
/**
* Gets an instance of Settings.
*
* @return an instance of Settings
* @since 2.0.0
*/
public static Settings settings() {
return INSTANCE;
}
public void reload(File file) {
load(file);
save(file);
}
public FaweLimit getLimit(Actor actor) {
FaweLimit limit;
if (actor.hasPermission("fawe.limit.*") || actor.hasPermission("fawe.bypass")) {
limit = FaweLimit.MAX.copy();
} else {
limit = new FaweLimit();
}
ArrayList<String> keys = new ArrayList<>(LIMITS.getSections());
if (keys.remove("default")) {
keys.add("default");
}
boolean limitFound = false;
for (String key : keys) {
if (actor.hasPermission("fawe.limit." + key) || !limitFound && key.equals("default")) {
limitFound = true;
LIMITS newLimit = LIMITS.get(key);
limit.MAX_ACTIONS = Math.max(
limit.MAX_ACTIONS,
newLimit.MAX_ACTIONS != -1 ? newLimit.MAX_ACTIONS : Integer.MAX_VALUE
);
limit.MAX_CHANGES = Math.max(
limit.MAX_CHANGES,
newLimit.MAX_CHANGES != -1 ? newLimit.MAX_CHANGES : Long.MAX_VALUE
);
limit.MAX_BLOCKSTATES = Math.max(
limit.MAX_BLOCKSTATES,
newLimit.MAX_BLOCKSTATES != -1 ? newLimit.MAX_BLOCKSTATES : Integer.MAX_VALUE
);
limit.MAX_CHECKS = Math.max(
limit.MAX_CHECKS,
newLimit.MAX_CHECKS != -1 ? newLimit.MAX_CHECKS : Long.MAX_VALUE
);
limit.MAX_ENTITIES = Math.max(
limit.MAX_ENTITIES,
newLimit.MAX_ENTITIES != -1 ? newLimit.MAX_ENTITIES : Integer.MAX_VALUE
);
limit.MAX_FAILS = Math.max(limit.MAX_FAILS, newLimit.MAX_FAILS != -1 ? newLimit.MAX_FAILS : Integer.MAX_VALUE);
limit.MAX_ITERATIONS = Math.max(
limit.MAX_ITERATIONS,
newLimit.MAX_ITERATIONS != -1 ? newLimit.MAX_ITERATIONS : Integer.MAX_VALUE
);
limit.MAX_HISTORY = Math.max(
limit.MAX_HISTORY,
newLimit.MAX_HISTORY_MB != -1 ? newLimit.MAX_HISTORY_MB : Integer.MAX_VALUE
);
limit.MAX_EXPRESSION_MS = Math.max(
limit.MAX_EXPRESSION_MS,
newLimit.MAX_EXPRESSION_MS != -1 ? newLimit.MAX_EXPRESSION_MS : Integer.MAX_VALUE
);
limit.INVENTORY_MODE = Math.min(limit.INVENTORY_MODE, newLimit.INVENTORY_MODE);
limit.SPEED_REDUCTION = Math.min(limit.SPEED_REDUCTION, newLimit.SPEED_REDUCTION);
limit.FAST_PLACEMENT |= newLimit.FAST_PLACEMENT;
limit.CONFIRM_LARGE &= newLimit.CONFIRM_LARGE;
limit.RESTRICT_HISTORY_TO_REGIONS &= newLimit.RESTRICT_HISTORY_TO_REGIONS;
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();
}
}
limit.UNIVERSAL_DISALLOWED_BLOCKS &= newLimit.UNIVERSAL_DISALLOWED_BLOCKS;
if (limit.DISALLOWED_BLOCKS == null) {
limit.DISALLOWED_BLOCKS = newLimit.DISALLOWED_BLOCKS.isEmpty() ? Collections.emptySet() : new HashSet<>(
newLimit.DISALLOWED_BLOCKS);
} else if (limit.DISALLOWED_BLOCKS.isEmpty() || newLimit.DISALLOWED_BLOCKS.isEmpty()) {
limit.DISALLOWED_BLOCKS = Collections.emptySet();
} else {
limit.DISALLOWED_BLOCKS = new HashSet<>(limit.DISALLOWED_BLOCKS);
limit.DISALLOWED_BLOCKS.retainAll(newLimit.DISALLOWED_BLOCKS
.stream()
.map(s -> s.contains(":") ? s.toLowerCase(Locale.ROOT) : ("minecraft:" + s).toLowerCase(Locale.ROOT))
.collect(Collectors.toSet()));
if (limit.DISALLOWED_BLOCKS.isEmpty()) {
limit.DISALLOWED_BLOCKS = Collections.emptySet();
}
}
if (limit.REMAP_PROPERTIES == null) {
limit.REMAP_PROPERTIES = newLimit.REMAP_PROPERTIES.isEmpty() ? Collections.emptySet() :
newLimit.REMAP_PROPERTIES.stream().flatMap(s -> {
String propertyStr = s.substring(0, s.indexOf('['));
List<Property<?>> properties =
BlockTypesCache.getAllProperties().get(propertyStr.toLowerCase(Locale.ROOT));
if (properties == null || properties.isEmpty()) {
return Stream.empty();
}
String[] mappings = s.substring(s.indexOf('[') + 1, s.indexOf(']')).split(",");
Set<PropertyRemap<?>> remaps = new HashSet<>();
for (Property<?> property : properties) {
for (String mapping : mappings) {
try {
String[] fromTo = mapping.split(":");
remaps.add(property.getRemap(
property.getValueFor(fromTo[0]),
property.getValueFor(fromTo[1])
));
} catch (IllegalArgumentException ignored) {
// This property is unlikely to be the one being targeted.
break;
}
}
}
return remaps.stream();
}).collect(Collectors.toSet());
} else if (limit.REMAP_PROPERTIES.isEmpty() || newLimit.REMAP_PROPERTIES.isEmpty()) {
limit.REMAP_PROPERTIES = Collections.emptySet();
} else {
limit.REMAP_PROPERTIES = new HashSet<>(limit.REMAP_PROPERTIES);
limit.REMAP_PROPERTIES.retainAll(newLimit.REMAP_PROPERTIES.stream().flatMap(s -> {
String propertyStr = s.substring(0, s.indexOf('['));
List<Property<?>> properties =
BlockTypesCache.getAllProperties().get(propertyStr.toLowerCase(Locale.ROOT));
if (properties == null || properties.isEmpty()) {
return Stream.empty();
}
String[] mappings = s.substring(s.indexOf('[') + 1, s.indexOf(']')).split(",");
Set<PropertyRemap<?>> remaps = new HashSet<>();
for (Property<?> property : properties) {
for (String mapping : mappings) {
try {
String[] fromTo = mapping.split(":");
remaps.add(property.getRemap(
property.getValueFor(fromTo[0]),
property.getValueFor(fromTo[1])
));
} catch (IllegalArgumentException ignored) {
// This property is unlikely to be the one being targeted.
break;
}
}
}
return remaps.stream();
}).collect(Collectors.toSet()));
if (limit.REMAP_PROPERTIES.isEmpty()) {
limit.REMAP_PROPERTIES = Collections.emptySet();
}
}
}
}
return limit;
}
@Comment("Enable or disable core components") @Comment("Enable or disable core components")
public static final class ENABLED_COMPONENTS { public static final class ENABLED_COMPONENTS {
public boolean COMMANDS = true; public boolean COMMANDS = true;
@Comment({
"Disable the FAWE-PlotSquared hook to take over most intense P2 queueing",
"Specific aspects can be turned on and off further below",
"Only disables/enables the hook with v4. For v6, see PlotSquared settings.yml"
})
public boolean PLOTSQUARED_V4_HOOK = true;
@Comment({"Show additional information in console. It helps us at IntellectualSites to find out more about an issue.", @Comment({"Show additional information in console. It helps us at IntellectualSites to find out more about an issue.",
"Leave it off if you don't need it, it can spam your console."}) "Leave it off if you don't need it, it can spam your console."})
public boolean DEBUG = false; public boolean DEBUG = false;
@ -341,12 +505,12 @@ public class Settings extends Config {
@Comment("This relates to how FAWE places chunks") @Comment("This relates to how FAWE places chunks")
public static class QUEUE { public static class QUEUE {
@Create
public static PROGRESS PROGRESS;
@Comment({ @Comment({
"This should equal the number of processors you have", "This should equal the number of processors you have",
}) })
public int PARALLEL_THREADS = Math.max(1, Runtime.getRuntime().availableProcessors()); public int PARALLEL_THREADS = Math.max(1, Runtime.getRuntime().availableProcessors());
@Create
public static PROGRESS PROGRESS;
@Comment({ @Comment({
"When doing edits that effect more than this many chunks:", "When doing edits that effect more than this many chunks:",
" - FAWE will start placing before all calculations are finished", " - FAWE will start placing before all calculations are finished",
@ -575,158 +739,4 @@ public class Settings extends Config {
} }
public void reload(File file) {
load(file);
save(file);
}
public FaweLimit getLimit(Actor actor) {
FaweLimit limit;
if (actor.hasPermission("fawe.limit.*") || actor.hasPermission("fawe.bypass")) {
limit = FaweLimit.MAX.copy();
} else {
limit = new FaweLimit();
}
ArrayList<String> keys = new ArrayList<>(LIMITS.getSections());
if (keys.remove("default")) {
keys.add("default");
}
boolean limitFound = false;
for (String key : keys) {
if (actor.hasPermission("fawe.limit." + key) || !limitFound && key.equals("default")) {
limitFound = true;
LIMITS newLimit = LIMITS.get(key);
limit.MAX_ACTIONS = Math.max(
limit.MAX_ACTIONS,
newLimit.MAX_ACTIONS != -1 ? newLimit.MAX_ACTIONS : Integer.MAX_VALUE
);
limit.MAX_CHANGES = Math.max(
limit.MAX_CHANGES,
newLimit.MAX_CHANGES != -1 ? newLimit.MAX_CHANGES : Long.MAX_VALUE
);
limit.MAX_BLOCKSTATES = Math.max(
limit.MAX_BLOCKSTATES,
newLimit.MAX_BLOCKSTATES != -1 ? newLimit.MAX_BLOCKSTATES : Integer.MAX_VALUE
);
limit.MAX_CHECKS = Math.max(
limit.MAX_CHECKS,
newLimit.MAX_CHECKS != -1 ? newLimit.MAX_CHECKS : Long.MAX_VALUE
);
limit.MAX_ENTITIES = Math.max(
limit.MAX_ENTITIES,
newLimit.MAX_ENTITIES != -1 ? newLimit.MAX_ENTITIES : Integer.MAX_VALUE
);
limit.MAX_FAILS = Math.max(limit.MAX_FAILS, newLimit.MAX_FAILS != -1 ? newLimit.MAX_FAILS : Integer.MAX_VALUE);
limit.MAX_ITERATIONS = Math.max(
limit.MAX_ITERATIONS,
newLimit.MAX_ITERATIONS != -1 ? newLimit.MAX_ITERATIONS : Integer.MAX_VALUE
);
limit.MAX_HISTORY = Math.max(
limit.MAX_HISTORY,
newLimit.MAX_HISTORY_MB != -1 ? newLimit.MAX_HISTORY_MB : Integer.MAX_VALUE
);
limit.MAX_EXPRESSION_MS = Math.max(
limit.MAX_EXPRESSION_MS,
newLimit.MAX_EXPRESSION_MS != -1 ? newLimit.MAX_EXPRESSION_MS : Integer.MAX_VALUE
);
limit.INVENTORY_MODE = Math.min(limit.INVENTORY_MODE, newLimit.INVENTORY_MODE);
limit.SPEED_REDUCTION = Math.min(limit.SPEED_REDUCTION, newLimit.SPEED_REDUCTION);
limit.FAST_PLACEMENT |= newLimit.FAST_PLACEMENT;
limit.CONFIRM_LARGE &= newLimit.CONFIRM_LARGE;
limit.RESTRICT_HISTORY_TO_REGIONS &= newLimit.RESTRICT_HISTORY_TO_REGIONS;
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();
}
}
limit.UNIVERSAL_DISALLOWED_BLOCKS &= newLimit.UNIVERSAL_DISALLOWED_BLOCKS;
if (limit.DISALLOWED_BLOCKS == null) {
limit.DISALLOWED_BLOCKS = newLimit.DISALLOWED_BLOCKS.isEmpty() ? Collections.emptySet() : new HashSet<>(
newLimit.DISALLOWED_BLOCKS);
} else if (limit.DISALLOWED_BLOCKS.isEmpty() || newLimit.DISALLOWED_BLOCKS.isEmpty()) {
limit.DISALLOWED_BLOCKS = Collections.emptySet();
} else {
limit.DISALLOWED_BLOCKS = new HashSet<>(limit.DISALLOWED_BLOCKS);
limit.DISALLOWED_BLOCKS.retainAll(newLimit.DISALLOWED_BLOCKS
.stream()
.map(s -> s.contains(":") ? s.toLowerCase(Locale.ROOT) : ("minecraft:" + s).toLowerCase(Locale.ROOT))
.collect(Collectors.toSet()));
if (limit.DISALLOWED_BLOCKS.isEmpty()) {
limit.DISALLOWED_BLOCKS = Collections.emptySet();
}
}
if (limit.REMAP_PROPERTIES == null) {
limit.REMAP_PROPERTIES = newLimit.REMAP_PROPERTIES.isEmpty() ? Collections.emptySet() :
newLimit.REMAP_PROPERTIES.stream().flatMap(s -> {
String propertyStr = s.substring(0, s.indexOf('['));
List<Property<?>> properties =
BlockTypesCache.getAllProperties().get(propertyStr.toLowerCase(Locale.ROOT));
if (properties == null || properties.isEmpty()) {
return Stream.empty();
}
String[] mappings = s.substring(s.indexOf('[') + 1, s.indexOf(']')).split(",");
Set<PropertyRemap<?>> remaps = new HashSet<>();
for (Property<?> property : properties) {
for (String mapping : mappings) {
try {
String[] fromTo = mapping.split(":");
remaps.add(property.getRemap(
property.getValueFor(fromTo[0]),
property.getValueFor(fromTo[1])
));
} catch (IllegalArgumentException ignored) {
// This property is unlikely to be the one being targeted.
break;
}
}
}
return remaps.stream();
}).collect(Collectors.toSet());
} else if (limit.REMAP_PROPERTIES.isEmpty() || newLimit.REMAP_PROPERTIES.isEmpty()) {
limit.REMAP_PROPERTIES = Collections.emptySet();
} else {
limit.REMAP_PROPERTIES = new HashSet<>(limit.REMAP_PROPERTIES);
limit.REMAP_PROPERTIES.retainAll(newLimit.REMAP_PROPERTIES.stream().flatMap(s -> {
String propertyStr = s.substring(0, s.indexOf('['));
List<Property<?>> properties =
BlockTypesCache.getAllProperties().get(propertyStr.toLowerCase(Locale.ROOT));
if (properties == null || properties.isEmpty()) {
return Stream.empty();
}
String[] mappings = s.substring(s.indexOf('[') + 1, s.indexOf(']')).split(",");
Set<PropertyRemap<?>> remaps = new HashSet<>();
for (Property<?> property : properties) {
for (String mapping : mappings) {
try {
String[] fromTo = mapping.split(":");
remaps.add(property.getRemap(
property.getValueFor(fromTo[0]),
property.getValueFor(fromTo[1])
));
} catch (IllegalArgumentException ignored) {
// This property is unlikely to be the one being targeted.
break;
}
}
}
return remaps.stream();
}).collect(Collectors.toSet()));
if (limit.REMAP_PROPERTIES.isEmpty()) {
limit.REMAP_PROPERTIES = Collections.emptySet();
}
}
}
}
return limit;
}
} }

View File

@ -44,14 +44,14 @@ public class RollbackDatabase extends AsyncNotifyQueue {
this.prefix = ""; this.prefix = "";
this.world = world; this.world = world;
this.dbLocation = MainUtil.getFile( this.dbLocation = MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HISTORY + File.separator + world.getName() + File.separator + "summary.db" Settings.settings().PATHS.HISTORY + File.separator + world.getName() + File.separator + "summary.db"
); );
connection = openConnection(); connection = openConnection();
try { try {
init().get(); init().get();
purge((int) TimeUnit.DAYS.toSeconds(Settings.IMP.HISTORY.DELETE_AFTER_DAYS)); purge((int) TimeUnit.DAYS.toSeconds(Settings.settings().HISTORY.DELETE_AFTER_DAYS));
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -284,8 +284,8 @@ public class RollbackDatabase extends AsyncNotifyQueue {
if (checkConnection()) { if (checkConnection()) {
return connection; return connection;
} }
if (!Fawe.imp().getDirectory().exists()) { if (!Fawe.platform().getDirectory().exists()) {
Fawe.imp().getDirectory().mkdirs(); Fawe.platform().getDirectory().mkdirs();
} }
if (!dbLocation.exists()) { if (!dbLocation.exists()) {
try { try {

View File

@ -27,7 +27,7 @@ public class LazyBaseEntity extends BaseEntity {
if (Fawe.isMainThread()) { if (Fawe.isMainThread()) {
setNbtData(tmp.get()); setNbtData(tmp.get());
} else { } else {
setNbtData(TaskManager.IMP.sync(tmp)); setNbtData(TaskManager.taskManager().sync(tmp));
} }
} }
return super.getNbtData(); return super.getNbtData();

View File

@ -166,7 +166,7 @@ public class ConsumeBindings extends Bindings {
if (argument.length() > 16) { if (argument.length() > 16) {
uuid = UUID.fromString(argument); uuid = UUID.fromString(argument);
} else { } else {
uuid = Fawe.imp().getUUID(argument); uuid = Fawe.platform().getUUID(argument);
} }
if (uuid == null) { if (uuid == null) {
throw new InputParseException(Caption.of("fawe.error.player.not.found", TextComponent.of(argument))); throw new InputParseException(Caption.of("fawe.error.player.not.found", TextComponent.of(argument)));

View File

@ -75,7 +75,7 @@ public abstract class FaweRegionExtent extends ResettableExtent implements IBatc
throws WorldEditException { throws WorldEditException {
if (!contains(x, y, z)) { if (!contains(x, y, z)) {
if (!limit.MAX_FAILS()) { if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.OUTSIDE_REGION); WEManager.weManager().cancelEditSafe(this, FaweCache.OUTSIDE_REGION);
} }
return false; return false;
} }
@ -86,7 +86,7 @@ public abstract class FaweRegionExtent extends ResettableExtent implements IBatc
public boolean setBiome(int x, int y, int z, BiomeType biome) { public boolean setBiome(int x, int y, int z, BiomeType biome) {
if (!contains(x, y, z)) { if (!contains(x, y, z)) {
if (!limit.MAX_FAILS()) { if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.OUTSIDE_REGION); WEManager.weManager().cancelEditSafe(this, FaweCache.OUTSIDE_REGION);
} }
return false; return false;
} }
@ -97,7 +97,7 @@ public abstract class FaweRegionExtent extends ResettableExtent implements IBatc
public BiomeType getBiome(BlockVector3 position) { public BiomeType getBiome(BlockVector3 position) {
if (!contains(position)) { if (!contains(position)) {
if (!limit.MAX_FAILS()) { if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.OUTSIDE_REGION); WEManager.weManager().cancelEditSafe(this, FaweCache.OUTSIDE_REGION);
} }
return null; return null;
} }
@ -108,7 +108,7 @@ public abstract class FaweRegionExtent extends ResettableExtent implements IBatc
public BiomeType getBiomeType(int x, int y, int z) { public BiomeType getBiomeType(int x, int y, int z) {
if (!contains(x, z)) { if (!contains(x, z)) {
if (!limit.MAX_FAILS()) { if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.OUTSIDE_REGION); WEManager.weManager().cancelEditSafe(this, FaweCache.OUTSIDE_REGION);
} }
return null; return null;
} }
@ -119,7 +119,7 @@ public abstract class FaweRegionExtent extends ResettableExtent implements IBatc
public BaseBlock getFullBlock(BlockVector3 position) { public BaseBlock getFullBlock(BlockVector3 position) {
if (!contains(position)) { if (!contains(position)) {
if (!limit.MAX_FAILS()) { if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.OUTSIDE_REGION); WEManager.weManager().cancelEditSafe(this, FaweCache.OUTSIDE_REGION);
} }
return BlockTypes.AIR.getDefaultState().toBaseBlock(); return BlockTypes.AIR.getDefaultState().toBaseBlock();
} }
@ -130,7 +130,7 @@ public abstract class FaweRegionExtent extends ResettableExtent implements IBatc
public BlockState getBlock(BlockVector3 position) { public BlockState getBlock(BlockVector3 position) {
if (!contains(position)) { if (!contains(position)) {
if (!limit.MAX_FAILS()) { if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.OUTSIDE_REGION); WEManager.weManager().cancelEditSafe(this, FaweCache.OUTSIDE_REGION);
} }
return BlockTypes.AIR.getDefaultState(); return BlockTypes.AIR.getDefaultState();
} }
@ -142,7 +142,7 @@ public abstract class FaweRegionExtent extends ResettableExtent implements IBatc
public Entity createEntity(Location location, BaseEntity entity) { public Entity createEntity(Location location, BaseEntity entity) {
if (!contains(location.getBlockX(), location.getBlockY(), location.getBlockZ())) { if (!contains(location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
if (!limit.MAX_FAILS()) { if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.OUTSIDE_REGION); WEManager.weManager().cancelEditSafe(this, FaweCache.OUTSIDE_REGION);
} }
return null; return null;
} }

View File

@ -29,7 +29,7 @@ public class MemoryCheckingExtent extends PassthroughExtent {
this.actor.print(Caption.of("fawe.info.worldedit.oom.admin")); this.actor.print(Caption.of("fawe.info.worldedit.oom.admin"));
} }
} }
WEManager.IMP.cancelEdit(this, FaweCache.LOW_MEMORY); WEManager.weManager().cancelEdit(this, FaweCache.LOW_MEMORY);
} }
return super.getExtent(); return super.getExtent();
} }

View File

@ -37,7 +37,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
return null; return null;
} }
if (!limit.MAX_ENTITIES()) { if (!limit.MAX_ENTITIES()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.MAX_ENTITIES); WEManager.weManager().cancelEditSafe(this, FaweCache.MAX_ENTITIES);
return null; return null;
} }
return super.createEntity(location, entity); return super.createEntity(location, entity);
@ -46,7 +46,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
@Override @Override
public BlockState getBlock(int x, int y, int z) { public BlockState getBlock(int x, int y, int z) {
if (!limit.MAX_CHECKS()) { if (!limit.MAX_CHECKS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.MAX_CHECKS); WEManager.weManager().cancelEditSafe(this, FaweCache.MAX_CHECKS);
return BlockTypes.AIR.getDefaultState(); return BlockTypes.AIR.getDefaultState();
} else { } else {
return extent.getBlock(x, y, z); return extent.getBlock(x, y, z);
@ -56,7 +56,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
@Override @Override
public BaseBlock getFullBlock(BlockVector3 pos) { public BaseBlock getFullBlock(BlockVector3 pos) {
if (!limit.MAX_CHECKS()) { if (!limit.MAX_CHECKS()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.MAX_CHECKS); WEManager.weManager().cancelEditSafe(this, FaweCache.MAX_CHECKS);
return BlockTypes.AIR.getDefaultState().toBaseBlock(); return BlockTypes.AIR.getDefaultState().toBaseBlock();
} else { } else {
return extent.getFullBlock(pos); return extent.getFullBlock(pos);
@ -80,18 +80,18 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
boolean hasNbt = block instanceof BaseBlock && block.hasNbtData(); boolean hasNbt = block instanceof BaseBlock && block.hasNbtData();
if (hasNbt) { if (hasNbt) {
if (!limit.MAX_BLOCKSTATES()) { if (!limit.MAX_BLOCKSTATES()) {
WEManager.IMP.cancelEdit(this, FaweCache.MAX_TILES); WEManager.weManager().cancelEdit(this, FaweCache.MAX_TILES);
return false; return false;
} else { } else {
if (!limit.MAX_CHANGES()) { if (!limit.MAX_CHANGES()) {
WEManager.IMP.cancelEdit(this, FaweCache.MAX_CHANGES); WEManager.weManager().cancelEdit(this, FaweCache.MAX_CHANGES);
return false; return false;
} }
return extent.setBlock(x, y, z, block); return extent.setBlock(x, y, z, block);
} }
} }
if (!limit.MAX_CHANGES()) { if (!limit.MAX_CHANGES()) {
WEManager.IMP.cancelEdit(this, FaweCache.MAX_CHANGES); WEManager.weManager().cancelEdit(this, FaweCache.MAX_CHANGES);
return false; return false;
} else { } else {
return extent.setBlock(x, y, z, block); return extent.setBlock(x, y, z, block);
@ -101,7 +101,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
@Override @Override
public boolean setBiome(BlockVector3 position, BiomeType biome) { public boolean setBiome(BlockVector3 position, BiomeType biome) {
if (!limit.MAX_CHANGES()) { if (!limit.MAX_CHANGES()) {
WEManager.IMP.cancelEditSafe(this, FaweCache.MAX_CHANGES); WEManager.weManager().cancelEditSafe(this, FaweCache.MAX_CHANGES);
return false; return false;
} }
return super.setBiome(position, biome); return super.setBiome(position, biome);

View File

@ -72,8 +72,8 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
this( this(
region.getDimensions(), region.getDimensions(),
MainUtil.getFile( MainUtil.getFile(
Fawe.get() != null ? Fawe.imp().getDirectory() : new File("."), Fawe.instance() != null ? Fawe.platform().getDirectory() : new File("."),
Settings.IMP.PATHS.CLIPBOARD + File.separator + uuid + ".bd" Settings.settings().PATHS.CLIPBOARD + File.separator + uuid + ".bd"
) )
); );
setOffset(region.getMinimumPoint()); setOffset(region.getMinimumPoint());
@ -84,8 +84,8 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
this( this(
dimensions, dimensions,
MainUtil.getFile( MainUtil.getFile(
Fawe.imp() != null ? Fawe.imp().getDirectory() : new File("."), Fawe.platform() != null ? Fawe.platform().getDirectory() : new File("."),
Settings.IMP.PATHS.CLIPBOARD + File.separator + UUID.randomUUID() + ".bd" Settings.settings().PATHS.CLIPBOARD + File.separator + UUID.randomUUID() + ".bd"
) )
); );
} }

View File

@ -54,7 +54,7 @@ public class MemoryOptimizedClipboard extends LinearClipboard {
private final int compressionLevel; private final int compressionLevel;
public MemoryOptimizedClipboard(Region region) { public MemoryOptimizedClipboard(Region region) {
this(region, Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL); this(region, Settings.settings().CLIPBOARD.COMPRESSION_LEVEL);
} }
public MemoryOptimizedClipboard(Region region, int compressionLevel) { public MemoryOptimizedClipboard(Region region, int compressionLevel) {

View File

@ -39,12 +39,12 @@ public abstract class ReadOnlyClipboard extends SimpleClipboard {
} }
public static ReadOnlyClipboard of(Extent extent, final Region region) { public static ReadOnlyClipboard of(Extent extent, final Region region) {
Fawe.get().getQueueHandler().unCache(); Fawe.instance().getQueueHandler().unCache();
return of(() -> extent, region); return of(() -> extent, region);
} }
public static ReadOnlyClipboard of(Extent extent, final Region region, boolean copyEntities, boolean copyBiomes) { public static ReadOnlyClipboard of(Extent extent, final Region region, boolean copyEntities, boolean copyBiomes) {
Fawe.get().getQueueHandler().unCache(); Fawe.instance().getQueueHandler().unCache();
return of(() -> extent, region, copyEntities, copyBiomes); return of(() -> extent, region, copyEntities, copyBiomes);
} }

View File

@ -327,7 +327,7 @@ public class FastSchematicReader extends NBTSchematicReader {
// tiles // tiles
if (tiles != null && !tiles.isEmpty()) { if (tiles != null && !tiles.isEmpty()) {
for (Map<String, Object> tileRaw : tiles) { for (Map<String, Object> tileRaw : tiles) {
CompoundTag tile = FaweCache.IMP.asTag(tileRaw); CompoundTag tile = FaweCache.INSTANCE.asTag(tileRaw);
int[] pos = tile.getIntArray("Pos"); int[] pos = tile.getIntArray("Pos");
int x; int x;
@ -372,7 +372,7 @@ public class FastSchematicReader extends NBTSchematicReader {
// entities // entities
if (entities != null && !entities.isEmpty()) { if (entities != null && !entities.isEmpty()) {
for (Map<String, Object> entRaw : entities) { for (Map<String, Object> entRaw : entities) {
Map<String, Tag> value = new HashMap<>(FaweCache.IMP.asTag(entRaw).getValue()); Map<String, Tag> value = new HashMap<>(FaweCache.INSTANCE.asTag(entRaw).getValue());
StringTag id = (StringTag) value.get("Id"); StringTag id = (StringTag) value.get("Id");
if (id == null) { if (id == null) {
id = (StringTag) value.get("id"); id = (StringTag) value.get("id");

View File

@ -123,7 +123,7 @@ public class FastSchematicWriter implements ClipboardWriter {
out1.writeNamedTag("WEOffsetX", offset.getBlockX()); out1.writeNamedTag("WEOffsetX", offset.getBlockX());
out1.writeNamedTag("WEOffsetY", offset.getBlockY()); out1.writeNamedTag("WEOffsetY", offset.getBlockY());
out1.writeNamedTag("WEOffsetZ", offset.getBlockZ()); out1.writeNamedTag("WEOffsetZ", offset.getBlockZ());
out1.writeNamedTag("FAWEVersion", Fawe.get().getVersion().build); out1.writeNamedTag("FAWEVersion", Fawe.instance().getVersion().build);
}); });
ByteArrayOutputStream blocksCompressed = new ByteArrayOutputStream(); ByteArrayOutputStream blocksCompressed = new ByteArrayOutputStream();

View File

@ -165,7 +165,7 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
if (width > WARN_SIZE || height > WARN_SIZE || length > WARN_SIZE) { if (width > WARN_SIZE || height > WARN_SIZE || length > WARN_SIZE) {
LOGGER.info("A structure longer than 32 is unsupported by minecraft (but probably still works)"); LOGGER.info("A structure longer than 32 is unsupported by minecraft (but probably still works)");
} }
Map<String, Object> structure = FaweCache.IMP.asMap("version", 1, "author", owner); Map<String, Object> structure = FaweCache.INSTANCE.asMap("version", 1, "author", owner);
// ignored: version / owner // ignored: version / owner
Int2ObjectArrayMap<Integer> indexes = new Int2ObjectArrayMap<>(); Int2ObjectArrayMap<Integer> indexes = new Int2ObjectArrayMap<>();
// Size // Size
@ -217,10 +217,10 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
point.getY() - min.getY(), point.getZ() - min.getZ() point.getY() - min.getY(), point.getZ() - min.getZ()
); );
if (!block.hasNbtData()) { if (!block.hasNbtData()) {
blocks.add(FaweCache.IMP.asMap("state", index, "pos", pos)); blocks.add(FaweCache.INSTANCE.asMap("state", index, "pos", pos));
} else { } else {
blocks.add( blocks.add(
FaweCache.IMP.asMap("state", index, "pos", pos, "nbt", block.getNbtData())); FaweCache.INSTANCE.asMap("state", index, "pos", pos, "nbt", block.getNbtData()));
} }
} }
} }
@ -240,14 +240,14 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
// Replace rotation data // Replace rotation data
nbtMap.put("Rotation", writeRotation(entity.getLocation())); nbtMap.put("Rotation", writeRotation(entity.getLocation()));
nbtMap.put("id", new StringTag(state.getType().getId())); nbtMap.put("id", new StringTag(state.getType().getId()));
Map<String, Object> entityMap = FaweCache.IMP.asMap("pos", pos, "blockPos", blockPos, "nbt", nbt); Map<String, Object> entityMap = FaweCache.INSTANCE.asMap("pos", pos, "blockPos", blockPos, "nbt", nbt);
entities.add(entityMap); entities.add(entityMap);
} }
} }
if (!entities.isEmpty()) { if (!entities.isEmpty()) {
structure.put("entities", entities); structure.put("entities", entities);
} }
out.writeNamedTag("", FaweCache.IMP.asTag(structure)); out.writeNamedTag("", FaweCache.INSTANCE.asTag(structure));
close(); close();
} }

View File

@ -26,7 +26,7 @@ public class PNGWriter implements ClipboardWriter {
public PNGWriter(OutputStream out) throws IOException { public PNGWriter(OutputStream out) throws IOException {
this.out = ImageIO.createImageOutputStream(out); this.out = ImageIO.createImageOutputStream(out);
this.tu = Fawe.get().getCachedTextureUtil(false, 0, 100); this.tu = Fawe.instance().getCachedTextureUtil(false, 0, 100);
} }
@Override @Override

View File

@ -203,7 +203,7 @@
// */ // */
// private void clean() { // private void clean() {
// if (chunks.size() > 225) { // if (chunks.size() > 225) {
// TaskManager.IMP.sync(() -> { // TaskManager.taskManager().sync(() -> {
// if (chunks.size() > 225) { // if (chunks.size() > 225) {
// synchronized (SchemVis.this) { // synchronized (SchemVis.this) {
// Location pos = player.toWorldEditPlayer().getLocation(); // Location pos = player.toWorldEditPlayer().getLocation();
@ -233,7 +233,7 @@
// * @param chunkZ // * @param chunkZ
// */ // */
// private void send(IQueueExtent packetQueue, int chunkX, int chunkZ) { // private void send(IQueueExtent packetQueue, int chunkX, int chunkZ) {
// TaskManager.IMP.getPublicForkJoinPool().submit(() -> { // TaskManager.taskManager().getPublicForkJoinPool().submit(() -> {
// try { // try {
// int OX = chunkOffset.getBlockX(); // int OX = chunkOffset.getBlockX();
// int OZ = chunkOffset.getBlockZ(); // int OZ = chunkOffset.getBlockZ();

View File

@ -71,7 +71,7 @@ public class CharFilterBlock extends ChunkFilterBlock {
maxLayer = this.get.getMaxSectionPosition(); maxLayer = this.get.getMaxSectionPosition();
this.layer = layer; this.layer = layer;
if (!iget.hasSection(layer)) { if (!iget.hasSection(layer)) {
getArr = FaweCache.IMP.EMPTY_CHAR_4096; getArr = FaweCache.INSTANCE.EMPTY_CHAR_4096;
} else { } else {
getArr = iget.load(layer); getArr = iget.load(layer);
} }

View File

@ -21,7 +21,7 @@ public abstract class ExtentBatchProcessorHolder extends BatchProcessorHolder im
@Override @Override
public Extent enableHistory(AbstractChangeSet changeSet) { public Extent enableHistory(AbstractChangeSet changeSet) {
if (Settings.IMP.HISTORY.SEND_BEFORE_HISTORY) { if (Settings.settings().HISTORY.SEND_BEFORE_HISTORY) {
return this.addPostProcessor(changeSet); return this.addPostProcessor(changeSet);
} else { } else {
return this.addProcessor(changeSet); return this.addProcessor(changeSet);

View File

@ -34,7 +34,7 @@ public class MultiBatchProcessor implements IBatchProcessor {
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
private final LoadingCache<Class<?>, Map<Long, Filter>> classToThreadIdToFilter = private final LoadingCache<Class<?>, Map<Long, Filter>> classToThreadIdToFilter =
FaweCache.IMP.createCache((Supplier<Map<Long, Filter>>) ConcurrentHashMap::new); FaweCache.INSTANCE.createCache((Supplier<Map<Long, Filter>>) ConcurrentHashMap::new);
// Array for lazy avoidance of concurrent modification exceptions and needless overcomplication of code (synchronisation is // Array for lazy avoidance of concurrent modification exceptions and needless overcomplication of code (synchronisation is
// not very important) // not very important)
private boolean[] faweExceptionReasonsUsed = new boolean[FaweException.Type.values().length]; private boolean[] faweExceptionReasonsUsed = new boolean[FaweException.Type.values().length];
@ -157,7 +157,7 @@ public class MultiBatchProcessor implements IBatchProcessor {
lastException = hash; lastException = hash;
exceptionCount = 0; exceptionCount = 0;
LOGGER.catching(e); LOGGER.catching(e);
} else if (exceptionCount < Settings.IMP.QUEUE.PARALLEL_THREADS) { } else if (exceptionCount < Settings.settings().QUEUE.PARALLEL_THREADS) {
exceptionCount++; exceptionCount++;
LOGGER.warn(message); LOGGER.warn(message);
} }

View File

@ -62,7 +62,7 @@ public class HeightmapProcessor implements IBatchProcessor {
continue; continue;
} }
char[] setSection = hasSectionSet ? set.loadIfPresent(layer) : null; char[] setSection = hasSectionSet ? set.loadIfPresent(layer) : null;
if (setSection == null || Arrays.equals(setSection, FaweCache.IMP.EMPTY_CHAR_4096) || if (setSection == null || Arrays.equals(setSection, FaweCache.INSTANCE.EMPTY_CHAR_4096) ||
Arrays.equals(setSection, AIR_LAYER)) { Arrays.equals(setSection, AIR_LAYER)) {
hasSectionSet = false; hasSectionSet = false;
} }
@ -86,7 +86,7 @@ public class HeightmapProcessor implements IBatchProcessor {
} else if (getSection == null) { } else if (getSection == null) {
getSection = get.load(layer); getSection = get.load(layer);
// skip empty layer // skip empty layer
if (Arrays.equals(getSection, FaweCache.IMP.EMPTY_CHAR_4096) if (Arrays.equals(getSection, FaweCache.INSTANCE.EMPTY_CHAR_4096)
|| Arrays.equals(getSection, AIR_LAYER)) { || Arrays.equals(getSection, AIR_LAYER)) {
hasSectionGet = false; hasSectionGet = false;
if (!hasSectionSet) { if (!hasSectionSet) {

View File

@ -77,7 +77,7 @@ public class NMSRelighter implements Relighter {
this.concurrentLightQueue = new ConcurrentHashMap<>(12); this.concurrentLightQueue = new ConcurrentHashMap<>(12);
this.maxY = queue.getMaxY(); this.maxY = queue.getMaxY();
this.minY = queue.getMinY(); this.minY = queue.getMinY();
this.relightMode = relightMode != null ? relightMode : RelightMode.valueOf(Settings.IMP.LIGHTING.MODE); this.relightMode = relightMode != null ? relightMode : RelightMode.valueOf(Settings.settings().LIGHTING.MODE);
this.lightingLock = new ReentrantLock(); this.lightingLock = new ReentrantLock();
} }
@ -911,11 +911,11 @@ public class NMSRelighter implements Relighter {
chunk.setBitMask(bitMask); chunk.setBitMask(bitMask);
iter.remove(); iter.remove();
} }
if (Settings.IMP.LIGHTING.ASYNC) { if (Settings.settings().LIGHTING.ASYNC) {
queue.flush(); queue.flush();
finished.set(true); finished.set(true);
} else { } else {
TaskManager.IMP.sync(new RunnableVal<>() { TaskManager.taskManager().sync(new RunnableVal<>() {
@Override @Override
public void run(Object value) { public void run(Object value) {
queue.flush(); queue.flush();
@ -943,16 +943,16 @@ public class NMSRelighter implements Relighter {
ChunkHolder<?> chunk = (ChunkHolder<?>) queue.getOrCreateChunk(x, z); ChunkHolder<?> chunk = (ChunkHolder<?>) queue.getOrCreateChunk(x, z);
chunk.setBitMask(bitMask); chunk.setBitMask(bitMask);
chunk.flushLightToGet(); chunk.flushLightToGet();
Fawe.imp().getPlatformAdapter().sendChunk(chunk.getOrCreateGet(), bitMask, true); Fawe.platform().getPlatformAdapter().sendChunk(chunk.getOrCreateGet(), bitMask, true);
iter.remove(); iter.remove();
} }
finished.set(true); finished.set(true);
} }
}; };
if (Settings.IMP.LIGHTING.ASYNC) { if (Settings.settings().LIGHTING.ASYNC) {
runnable.run(); runnable.run();
} else { } else {
TaskManager.IMP.sync(runnable); TaskManager.taskManager().sync(runnable);
} }
} }

View File

@ -25,9 +25,9 @@ public class RelightProcessor implements IBatchProcessor {
@Override @Override
public IChunkSet processSet(IChunk chunk, IChunkGet get, IChunkSet set) { public IChunkSet processSet(IChunk chunk, IChunkGet get, IChunkSet set) {
if (Settings.IMP.LIGHTING.MODE == 2) { if (Settings.settings().LIGHTING.MODE == 2) {
relighter.addChunk(chunk.getX(), chunk.getZ(), null, chunk.getBitMask()); relighter.addChunk(chunk.getX(), chunk.getZ(), null, chunk.getBitMask());
} else if (Settings.IMP.LIGHTING.MODE == 1) { } else if (Settings.settings().LIGHTING.MODE == 1) {
byte[] fix = new byte[get.getSectionCount()]; byte[] fix = new byte[get.getSectionCount()];
boolean relight = false; boolean relight = false;
for (int i = get.getMaxSectionPosition(); i >= get.getMinSectionPosition(); i--) { for (int i = get.getMaxSectionPosition(); i >= get.getMinSectionPosition(); i--) {

View File

@ -32,7 +32,7 @@ public class BufferedPattern extends AbstractPattern implements ResettablePatter
} }
actionTime = tmp; actionTime = tmp;
this.pattern = parent; this.pattern = parent;
this.timer = Fawe.get().getTimer(); this.timer = Fawe.instance().getTimer();
} }
@Override @Override

View File

@ -75,8 +75,8 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
private void init(UUID uuid, String worldName) { private void init(UUID uuid, String worldName) {
final File folder = MainUtil.getFile( final File folder = MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HISTORY + File.separator + worldName + File.separator + uuid Settings.settings().PATHS.HISTORY + File.separator + worldName + File.separator + uuid
); );
final int max = NEXT_INDEX.computeIfAbsent(worldName, _worldName -> new ConcurrentHashMap<>()) final int max = NEXT_INDEX.computeIfAbsent(worldName, _worldName -> new ConcurrentHashMap<>())
@ -111,8 +111,8 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
this.uuid = uuid; this.uuid = uuid;
this.index = i; this.index = i;
File folder = MainUtil.getFile( File folder = MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HISTORY + File.separator + getWorld().getName() + File.separator + uuid Settings.settings().PATHS.HISTORY + File.separator + getWorld().getName() + File.separator + uuid
); );
initFiles(folder); initFiles(folder);
} }
@ -120,7 +120,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
@Override @Override
public void delete() { public void delete() {
deleteFiles(); deleteFiles();
if (Settings.IMP.HISTORY.USE_DATABASE) { if (Settings.settings().HISTORY.USE_DATABASE) {
RollbackDatabase db = DBHandler.IMP.getDatabase(getWorld()); RollbackDatabase db = DBHandler.IMP.getDatabase(getWorld());
db.delete(uuid, index); db.delete(uuid, index);
} }

View File

@ -149,7 +149,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
} }
synchronized (this) { synchronized (this) {
setOrigin(x, z); setOrigin(x, z);
idsStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); idsStream = new FastByteArrayOutputStream(Settings.settings().HISTORY.BUFFER_SIZE);
idsStreamZip = getCompressedOS(idsStream); idsStreamZip = getCompressedOS(idsStream);
writeHeader(idsStreamZip, x, y, z); writeHeader(idsStreamZip, x, y, z);
return idsStreamZip; return idsStreamZip;
@ -170,7 +170,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
return biomeStreamZip; return biomeStreamZip;
} }
synchronized (this) { synchronized (this) {
biomeStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); biomeStream = new FastByteArrayOutputStream(Settings.settings().HISTORY.BUFFER_SIZE);
biomeStreamZip = getCompressedOS(biomeStream); biomeStreamZip = getCompressedOS(biomeStream);
return biomeStreamZip; return biomeStreamZip;
} }
@ -191,7 +191,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
if (entCStreamZip != null) { if (entCStreamZip != null) {
return entCStreamZip; return entCStreamZip;
} }
entCStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); entCStream = new FastByteArrayOutputStream(Settings.settings().HISTORY.BUFFER_SIZE);
return entCStreamZip = new NBTOutputStream(getCompressedOS(entCStream)); return entCStreamZip = new NBTOutputStream(getCompressedOS(entCStream));
} }
@ -200,7 +200,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
if (entRStreamZip != null) { if (entRStreamZip != null) {
return entRStreamZip; return entRStreamZip;
} }
entRStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); entRStream = new FastByteArrayOutputStream(Settings.settings().HISTORY.BUFFER_SIZE);
return entRStreamZip = new NBTOutputStream(getCompressedOS(entRStream)); return entRStreamZip = new NBTOutputStream(getCompressedOS(entRStream));
} }
@ -209,7 +209,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
if (tileCStreamZip != null) { if (tileCStreamZip != null) {
return tileCStreamZip; return tileCStreamZip;
} }
tileCStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); tileCStream = new FastByteArrayOutputStream(Settings.settings().HISTORY.BUFFER_SIZE);
return tileCStreamZip = new NBTOutputStream(getCompressedOS(tileCStream)); return tileCStreamZip = new NBTOutputStream(getCompressedOS(tileCStream));
} }
@ -218,7 +218,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
if (tileRStreamZip != null) { if (tileRStreamZip != null) {
return tileRStreamZip; return tileRStreamZip;
} }
tileRStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); tileRStream = new FastByteArrayOutputStream(Settings.settings().HISTORY.BUFFER_SIZE);
return tileRStreamZip = new NBTOutputStream(getCompressedOS(tileRStream)); return tileRStreamZip = new NBTOutputStream(getCompressedOS(tileRStream));
} }

View File

@ -64,7 +64,7 @@ public abstract class AbstractChangeSet implements ChangeSet, IBatchProcessor {
return; return;
} }
waitingAsync.incrementAndGet(); waitingAsync.incrementAndGet();
TaskManager.IMP.async(() -> { TaskManager.taskManager().async(() -> {
waitingAsync.decrementAndGet(); waitingAsync.decrementAndGet();
synchronized (waitingAsync) { synchronized (waitingAsync) {
waitingAsync.notifyAll(); waitingAsync.notifyAll();
@ -168,7 +168,7 @@ public abstract class AbstractChangeSet implements ChangeSet, IBatchProcessor {
char[] blocksGet; char[] blocksGet;
char[] tmp = get.load(layer); char[] tmp = get.load(layer);
if (tmp == null) { if (tmp == null) {
blocksGet = FaweCache.IMP.EMPTY_CHAR_4096; blocksGet = FaweCache.INSTANCE.EMPTY_CHAR_4096;
} else { } else {
System.arraycopy(tmp, 0, (blocksGet = new char[4096]), 0, 4096); System.arraycopy(tmp, 0, (blocksGet = new char[4096]), 0, 4096);
} }
@ -379,7 +379,7 @@ public abstract class AbstractChangeSet implements ChangeSet, IBatchProcessor {
wrappedTask.run(); wrappedTask.run();
return Futures.immediateCancelledFuture(); return Futures.immediateCancelledFuture();
} else { } else {
return Fawe.get().getQueueHandler().submit(wrappedTask); return Fawe.instance().getQueueHandler().submit(wrappedTask);
} }
} }

View File

@ -43,7 +43,7 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet {
protected FaweStreamPositionDelegate posDel; protected FaweStreamPositionDelegate posDel;
public FaweStreamChangeSet(World world) { public FaweStreamChangeSet(World world) {
this(world, Settings.IMP.HISTORY.COMPRESSION_LEVEL, Settings.IMP.HISTORY.STORE_REDO, Settings.IMP.HISTORY.SMALL_EDITS); this(world, Settings.settings().HISTORY.COMPRESSION_LEVEL, Settings.settings().HISTORY.STORE_REDO, Settings.settings().HISTORY.SMALL_EDITS);
} }
public FaweStreamChangeSet(World world, int compression, boolean storeRedo, boolean smallLoc) { public FaweStreamChangeSet(World world, int compression, boolean storeRedo, boolean smallLoc) {
@ -764,7 +764,7 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet {
} }
try (FaweInputStream fis = getBlockIS()) { try (FaweInputStream fis = getBlockIS()) {
if (!shallow) { if (!shallow) {
int amount = (Settings.IMP.HISTORY.BUFFER_SIZE - HEADER_SIZE) / 9; int amount = (Settings.settings().HISTORY.BUFFER_SIZE - HEADER_SIZE) / 9;
MutableFullBlockChange change = new MutableFullBlockChange(null, 0, false); MutableFullBlockChange change = new MutableFullBlockChange(null, 0, false);
for (int i = 0; i < amount; i++) { for (int i = 0; i < amount; i++) {
int x = posDel.readX(fis) + ox; int x = posDel.readX(fis) + ox;

View File

@ -14,7 +14,7 @@ public class MutableBlockVector3 extends BlockVector3 {
} }
public static MutableBlockVector3 get(int x, int y, int z) { public static MutableBlockVector3 get(int x, int y, int z) {
return FaweCache.IMP.MUTABLE_BLOCKVECTOR3.get().setComponents(x, y, z); return FaweCache.INSTANCE.MUTABLE_BLOCKVECTOR3.get().setComponents(x, y, z);
} }
public MutableBlockVector3() { public MutableBlockVector3() {

View File

@ -27,11 +27,11 @@ public class MutableVector3 extends Vector3 {
} }
public static MutableVector3 get(int x, int y, int z) { public static MutableVector3 get(int x, int y, int z) {
return FaweCache.IMP.MUTABLE_VECTOR3.get().setComponents(x, y, z); return FaweCache.INSTANCE.MUTABLE_VECTOR3.get().setComponents(x, y, z);
} }
public static MutableVector3 get(double x, double y, double z) { public static MutableVector3 get(double x, double y, double z) {
return FaweCache.IMP.MUTABLE_VECTOR3.get().setComponents(x, y, z); return FaweCache.INSTANCE.MUTABLE_VECTOR3.get().setComponents(x, y, z);
} }
@Override @Override

View File

@ -129,9 +129,9 @@ public interface IBlocks extends Trimable {
sectionWriter.writeShort(nonEmpty); // non empty sectionWriter.writeShort(nonEmpty); // non empty
FaweCache.Palette palette; FaweCache.Palette palette;
if (stretched) { if (stretched) {
palette = FaweCache.IMP.toPalette(0, ids); palette = FaweCache.INSTANCE.toPalette(0, ids);
} else { } else {
palette = FaweCache.IMP.toPaletteUnstretched(0, ids); palette = FaweCache.INSTANCE.toPaletteUnstretched(0, ids);
} }
sectionWriter.writeByte(palette.bitsPerEntry); // bits per block sectionWriter.writeByte(palette.bitsPerEntry); // bits per block

View File

@ -45,7 +45,7 @@ public class Flood {
} }
public synchronized void run(World world) { public synchronized void run(World world) {
QueueHandler queueHandler = Fawe.get().getQueueHandler(); QueueHandler queueHandler = Fawe.instance().getQueueHandler();
IQueueExtent<IQueueChunk> fq = queueHandler.getQueue(world); IQueueExtent<IQueueChunk> fq = queueHandler.getQueue(world);
while (!chunkQueues.isEmpty()) { while (!chunkQueues.isEmpty()) {
long firstKey = chunkQueues.firstLongKey(); long firstKey = chunkQueues.firstLongKey();

View File

@ -99,7 +99,7 @@ public class ParallelQueueExtent extends PassthroughExtent {
final Iterator<BlockVector2> chunksIter = chunks.iterator(); final Iterator<BlockVector2> chunksIter = chunks.iterator();
// Get a pool, to operate on the chunks in parallel // Get a pool, to operate on the chunks in parallel
final int size = Math.min(chunks.size(), Settings.IMP.QUEUE.PARALLEL_THREADS); final int size = Math.min(chunks.size(), Settings.settings().QUEUE.PARALLEL_THREADS);
if (size <= 1 && chunksIter.hasNext()) { if (size <= 1 && chunksIter.hasNext()) {
BlockVector2 pos = chunksIter.next(); BlockVector2 pos = chunksIter.next();
getExtent().apply(null, filter, region, pos.getX(), pos.getZ(), full); getExtent().apply(null, filter, region, pos.getX(), pos.getZ(), full);
@ -147,7 +147,7 @@ public class ParallelQueueExtent extends PassthroughExtent {
lastException = hash; lastException = hash;
exceptionCount = 0; exceptionCount = 0;
LOGGER.catching(e); LOGGER.catching(e);
} else if (exceptionCount < Settings.IMP.QUEUE.PARALLEL_THREADS) { } else if (exceptionCount < Settings.settings().QUEUE.PARALLEL_THREADS) {
exceptionCount++; exceptionCount++;
LOGGER.warn(message); LOGGER.warn(message);
} }

View File

@ -41,7 +41,7 @@ public abstract class QueueHandler implements Trimable, Runnable {
private final ForkJoinPool forkJoinPoolPrimary = new ForkJoinPool(); private final ForkJoinPool forkJoinPoolPrimary = new ForkJoinPool();
private final ForkJoinPool forkJoinPoolSecondary = new ForkJoinPool(); private final ForkJoinPool forkJoinPoolSecondary = new ForkJoinPool();
private final ThreadPoolExecutor blockingExecutor = FaweCache.IMP.newBlockingExecutor(); private final ThreadPoolExecutor blockingExecutor = FaweCache.INSTANCE.newBlockingExecutor();
private final ConcurrentLinkedQueue<FutureTask> syncTasks = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<FutureTask> syncTasks = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<FutureTask> syncWhenFree = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<FutureTask> syncWhenFree = new ConcurrentLinkedQueue<>();
@ -56,7 +56,7 @@ public abstract class QueueHandler implements Trimable, Runnable {
private double targetTPS = 18; private double targetTPS = 18;
public QueueHandler() { public QueueHandler() {
TaskManager.IMP.repeat(this, 1); TaskManager.taskManager().repeat(this, 1);
} }
@Override @Override
@ -87,14 +87,14 @@ public abstract class QueueHandler implements Trimable, Runnable {
private long getAllocate() { private long getAllocate() {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
targetTPS = 18 - Math.max(Settings.IMP.QUEUE.EXTRA_TIME_MS * 0.05, 0); targetTPS = 18 - Math.max(Settings.settings().QUEUE.EXTRA_TIME_MS * 0.05, 0);
long diff = 50 + this.last - (this.last = now); long diff = 50 + this.last - (this.last = now);
long absDiff = Math.abs(diff); long absDiff = Math.abs(diff);
if (diff == 0) { if (diff == 0) {
allocate = Math.min(50, allocate + 1); allocate = Math.min(50, allocate + 1);
} else if (diff < 0) { } else if (diff < 0) {
allocate = Math.max(5, allocate + diff); allocate = Math.max(5, allocate + diff);
} else if (!Fawe.get().getTimer().isAbove(targetTPS)) { } else if (!Fawe.instance().getTimer().isAbove(targetTPS)) {
allocate = Math.max(5, allocate - 1); allocate = Math.max(5, allocate - 1);
} }
return allocate - absDiff; return allocate - absDiff;

View File

@ -250,7 +250,7 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
} }
} }
return (V) Fawe.get().getQueueHandler().submit(chunk); return (V) Fawe.instance().getQueueHandler().submit(chunk);
} }
@Override @Override
@ -266,7 +266,7 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
if (aggressive) { if (aggressive) {
pollSubmissions(0, aggressive); pollSubmissions(0, aggressive);
} else { } else {
pollSubmissions(Settings.IMP.QUEUE.PARALLEL_THREADS, aggressive); pollSubmissions(Settings.settings().QUEUE.PARALLEL_THREADS, aggressive);
} }
} }
synchronized (this) { synchronized (this) {
@ -312,8 +312,8 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
// If queueing is enabled AND either of the following // If queueing is enabled AND either of the following
// - memory is low & queue size > num threads + 8 // - memory is low & queue size > num threads + 8
// - queue size > target size and primary queue has less than num threads submissions // - queue size > target size and primary queue has less than num threads submissions
if (enabledQueue && ((lowMem && size > Settings.IMP.QUEUE.PARALLEL_THREADS + 8) || (size > Settings.IMP.QUEUE.TARGET_SIZE && Fawe if (enabledQueue && ((lowMem && size > Settings.settings().QUEUE.PARALLEL_THREADS + 8) || (size > Settings.settings().QUEUE.TARGET_SIZE && Fawe
.get() .instance()
.getQueueHandler() .getQueueHandler()
.isUnderutilized()))) { .isUnderutilized()))) {
chunk = chunks.removeFirst(); chunk = chunks.removeFirst();
@ -321,9 +321,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
if (future != null && !future.isDone()) { if (future != null && !future.isDone()) {
final int targetSize; final int targetSize;
if (lowMem) { if (lowMem) {
targetSize = Settings.IMP.QUEUE.PARALLEL_THREADS + 8; targetSize = Settings.settings().QUEUE.PARALLEL_THREADS + 8;
} else { } else {
targetSize = Settings.IMP.QUEUE.TARGET_SIZE; targetSize = Settings.settings().QUEUE.TARGET_SIZE;
} }
pollSubmissions(targetSize, lowMem); pollSubmissions(targetSize, lowMem);
submissions.add(future); submissions.add(future);
@ -361,10 +361,10 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
* @param region region of chunks * @param region region of chunks
*/ */
public void preload(Region region) { public void preload(Region region) {
if (Settings.IMP.QUEUE.PRELOAD_CHUNK_COUNT > 1) { if (Settings.settings().QUEUE.PRELOAD_CHUNK_COUNT > 1) {
int loadCount = 0; int loadCount = 0;
for (BlockVector2 from : region.getChunks()) { for (BlockVector2 from : region.getChunks()) {
if (loadCount >= Settings.IMP.QUEUE.PRELOAD_CHUNK_COUNT) { if (loadCount >= Settings.settings().QUEUE.PRELOAD_CHUNK_COUNT) {
break; break;
} }
loadCount++; loadCount++;
@ -409,7 +409,7 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
lastException = hash; lastException = hash;
exceptionCount = 0; exceptionCount = 0;
LOGGER.catching(e); LOGGER.catching(e);
} else if (exceptionCount < Settings.IMP.QUEUE.PARALLEL_THREADS) { } else if (exceptionCount < Settings.settings().QUEUE.PARALLEL_THREADS) {
exceptionCount++; exceptionCount++;
LOGGER.warn(message); LOGGER.warn(message);
} }
@ -449,7 +449,7 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
lastException = hash; lastException = hash;
exceptionCount = 0; exceptionCount = 0;
LOGGER.catching(e); LOGGER.catching(e);
} else if (exceptionCount < Settings.IMP.QUEUE.PARALLEL_THREADS) { } else if (exceptionCount < Settings.settings().QUEUE.PARALLEL_THREADS) {
exceptionCount++; exceptionCount++;
LOGGER.warn(message); LOGGER.warn(message);
} }
@ -464,7 +464,7 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen
for (IQueueChunk chunk : chunks.values()) { for (IQueueChunk chunk : chunks.values()) {
final Future future = submitUnchecked(chunk); final Future future = submitUnchecked(chunk);
if (future != null && !future.isDone()) { if (future != null && !future.isDone()) {
pollSubmissions(Settings.IMP.QUEUE.PARALLEL_THREADS, true); pollSubmissions(Settings.settings().QUEUE.PARALLEL_THREADS, true);
submissions.add(future); submissions.add(future);
} }
} }

View File

@ -124,7 +124,7 @@ public class BitSetBlocks implements IChunkSet {
@Override @Override
public char[] load(int layer) { public char[] load(int layer) {
layer -= minSectionPosition; layer -= minSectionPosition;
char[] arr = FaweCache.IMP.SECTION_BITS_TO_CHAR.get(); char[] arr = FaweCache.INSTANCE.SECTION_BITS_TO_CHAR.get();
MemBlockSet.IRow nullRowY = row.getRow(layer); MemBlockSet.IRow nullRowY = row.getRow(layer);
if (nullRowY instanceof MemBlockSet.RowY) { if (nullRowY instanceof MemBlockSet.RowY) {
char value = blockState.getOrdinalChar(); char value = blockState.getOrdinalChar();

View File

@ -201,7 +201,7 @@ public abstract class CharBlocks implements IBlocks {
set(layer, index, value); set(layer, index, value);
} catch (ArrayIndexOutOfBoundsException exception) { } catch (ArrayIndexOutOfBoundsException exception) {
LOGGER.error("Tried setting block at coordinates (" + x + "," + y + "," + z + ")"); LOGGER.error("Tried setting block at coordinates (" + x + "," + y + "," + z + ")");
assert Fawe.imp() != null; assert Fawe.platform() != null;
LOGGER.error("Layer variable was = {}", layer, exception); LOGGER.error("Layer variable was = {}", layer, exception);
} }
} }

View File

@ -23,10 +23,10 @@ import java.util.stream.IntStream;
public class CharSetBlocks extends CharBlocks implements IChunkSet { public class CharSetBlocks extends CharBlocks implements IChunkSet {
private static final Pool<CharSetBlocks> POOL = FaweCache.IMP.registerPool( private static final Pool<CharSetBlocks> POOL = FaweCache.INSTANCE.registerPool(
CharSetBlocks.class, CharSetBlocks.class,
CharSetBlocks::new, CharSetBlocks::new,
Settings.IMP.QUEUE.POOL Settings.settings().QUEUE.POOL
); );
public static CharSetBlocks newInstance() { public static CharSetBlocks newInstance() {

View File

@ -124,7 +124,7 @@ public final class NullChunkGet implements IChunkGet {
@Nonnull @Nonnull
public char[] load(int layer) { public char[] load(int layer) {
return FaweCache.IMP.EMPTY_CHAR_4096; return FaweCache.INSTANCE.EMPTY_CHAR_4096;
} }
@Nullable @Nullable

View File

@ -32,10 +32,10 @@ import java.util.concurrent.Future;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> { public class ChunkHolder<T extends Future<T>> implements IQueueChunk<T> {
private static final Pool<ChunkHolder> POOL = FaweCache.IMP.registerPool( private static final Pool<ChunkHolder> POOL = FaweCache.INSTANCE.registerPool(
ChunkHolder.class, ChunkHolder.class,
ChunkHolder::new, ChunkHolder::new,
Settings.IMP.QUEUE.POOL Settings.settings().QUEUE.POOL
); );
public static ChunkHolder newInstance() { public static ChunkHolder newInstance() {

View File

@ -64,8 +64,8 @@ public class ChunkPacket implements Function<byte[], byte[]>, Supplier<byte[]> {
synchronized (this) { synchronized (this) {
if (sectionBytes == null) { if (sectionBytes == null) {
IBlocks tmpChunk = getChunk(); IBlocks tmpChunk = getChunk();
byte[] buf = FaweCache.IMP.BYTE_BUFFER_8192.get(); byte[] buf = FaweCache.INSTANCE.BYTE_BUFFER_8192.get();
sectionBytes = tmpChunk.toByteArray(buf, tmpChunk.getBitMask(), this.full, Fawe.imp().isChunksStretched()); sectionBytes = tmpChunk.toByteArray(buf, tmpChunk.getBitMask(), this.full, Fawe.platform().isChunksStretched());
} }
tmp = sectionBytes; tmp = sectionBytes;
} }
@ -85,14 +85,14 @@ public class ChunkPacket implements Function<byte[], byte[]>, Supplier<byte[]> {
@Override @Override
@Deprecated @Deprecated
public byte[] get() { public byte[] get() {
return apply(FaweCache.IMP.BYTE_BUFFER_8192.get()); return apply(FaweCache.INSTANCE.BYTE_BUFFER_8192.get());
} }
public CompoundTag getHeightMap() { public CompoundTag getHeightMap() {
HashMap<String, Object> map = new HashMap<>(); HashMap<String, Object> map = new HashMap<>();
map.put("MOTION_BLOCKING", new long[36]); map.put("MOTION_BLOCKING", new long[36]);
// TODO // TODO
return FaweCache.IMP.asTag(map); return FaweCache.INSTANCE.asTag(map);
} }
@Override @Override

View File

@ -31,7 +31,7 @@ public class AsyncPreloader implements Preloader, Runnable {
public AsyncPreloader() { public AsyncPreloader() {
this.update = new ConcurrentHashMap<>(); this.update = new ConcurrentHashMap<>();
TaskManager.IMP.laterAsync(this, 1); TaskManager.taskManager().laterAsync(this, 1);
} }
@Override @Override
@ -77,7 +77,7 @@ public class AsyncPreloader implements Preloader, Runnable {
existing.setKey(world); existing.setKey(world);
existing.setValue(ImmutableSet.copyOf(Iterables.limit( existing.setValue(ImmutableSet.copyOf(Iterables.limit(
region.getChunks(), region.getChunks(),
Settings.IMP.QUEUE.PRELOAD_CHUNK_COUNT Settings.settings().QUEUE.PRELOAD_CHUNK_COUNT
))); )));
} }
synchronized (update) { synchronized (update) {
@ -89,12 +89,12 @@ public class AsyncPreloader implements Preloader, Runnable {
@Override @Override
public void run() { public void run() {
FaweTimer timer = Fawe.get().getTimer(); FaweTimer timer = Fawe.instance().getTimer();
if (cancelled.get()) { if (cancelled.get()) {
return; return;
} }
if (update.isEmpty()) { if (update.isEmpty()) {
TaskManager.IMP.laterAsync(this, 1); TaskManager.taskManager().laterAsync(this, 1);
return; return;
} }
Iterator<Map.Entry<UUID, MutablePair<World, Set<BlockVector2>>>> plrIter = update.entrySet().iterator(); Iterator<Map.Entry<UUID, MutablePair<World, Set<BlockVector2>>>> plrIter = update.entrySet().iterator();
@ -118,7 +118,7 @@ public class AsyncPreloader implements Preloader, Runnable {
if (cancelled.get()) { if (cancelled.get()) {
return; return;
} }
TaskManager.IMP.laterAsync(this, 20); TaskManager.taskManager().laterAsync(this, 20);
} }
private void queueLoad(World world, BlockVector2 chunk) { private void queueLoad(World world, BlockVector2 chunk) {

View File

@ -29,7 +29,7 @@ public abstract class FaweMaskManager {
public abstract FaweMask getMask(final Player player, MaskType type, boolean isWhitelist); public abstract FaweMask getMask(final Player player, MaskType type, boolean isWhitelist);
public boolean isExclusive() { public boolean isExclusive() {
return Settings.IMP.REGION_RESTRICTIONS_OPTIONS.EXCLUSIVE_MANAGERS.contains(this.key); return Settings.settings().REGION_RESTRICTIONS_OPTIONS.EXCLUSIVE_MANAGERS.contains(this.key);
} }
public enum MaskType { public enum MaskType {
@ -39,7 +39,7 @@ public abstract class FaweMaskManager {
public static MaskType getDefaultMaskType() { public static MaskType getDefaultMaskType() {
try { try {
return MaskType return MaskType
.valueOf(Settings.IMP.REGION_RESTRICTIONS_OPTIONS.MODE.toUpperCase(Locale.ROOT)); .valueOf(Settings.settings().REGION_RESTRICTIONS_OPTIONS.MODE.toUpperCase(Locale.ROOT));
} catch (Exception ignored) { } catch (Exception ignored) {
return MEMBER; return MEMBER;
} }

View File

@ -115,7 +115,7 @@ public class MainUtil {
public static long getTotalSize(Path path) { public static long getTotalSize(Path path) {
final AtomicLong size = new AtomicLong(0); final AtomicLong size = new AtomicLong(0);
traverse(path, new RunnableVal2<Path, BasicFileAttributes>() { traverse(path, new RunnableVal2<>() {
@Override @Override
public void run(Path path, BasicFileAttributes attrs) { public void run(Path path, BasicFileAttributes attrs) {
size.addAndGet(attrs.size()); size.addAndGet(attrs.size());
@ -126,7 +126,7 @@ public class MainUtil {
public static void traverse(Path path, final BiConsumer<Path, BasicFileAttributes> onEach) { public static void traverse(Path path, final BiConsumer<Path, BasicFileAttributes> onEach) {
try { try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() { Files.walkFileTree(path, new SimpleFileVisitor<>() {
@Override @Override
public FileVisitResult public FileVisitResult
visitFile(Path file, BasicFileAttributes attrs) { visitFile(Path file, BasicFileAttributes attrs) {
@ -231,20 +231,19 @@ public class MainUtil {
} }
public static long getSize(ChangeSet changeSet) { public static long getSize(ChangeSet changeSet) {
if (changeSet instanceof FaweStreamChangeSet) { if (changeSet instanceof FaweStreamChangeSet fscs) {
FaweStreamChangeSet fscs = (FaweStreamChangeSet) changeSet;
return fscs.getSizeOnDisk() + fscs.getSizeInMemory(); return fscs.getSizeOnDisk() + fscs.getSizeInMemory();
// } else if (changeSet instanceof CPUOptimizedChangeSet) { // } else if (changeSet instanceof CPUOptimizedChangeSet) {
// return changeSet.size() + 32; // return changeSet.size() + 32;
} else if (changeSet != null) { } else if (changeSet != null) {
return changeSet.size() * 128; return changeSet.size() * 128L;
} else { } else {
return 0; return 0;
} }
} }
public static FaweOutputStream getCompressedOS(OutputStream os, int amount) throws IOException { public static FaweOutputStream getCompressedOS(OutputStream os, int amount) throws IOException {
return getCompressedOS(os, amount, Settings.IMP.HISTORY.BUFFER_SIZE); return getCompressedOS(os, amount, Settings.settings().HISTORY.BUFFER_SIZE);
} }
private static final LZ4Factory FACTORY = LZ4Factory.fastestInstance(); private static final LZ4Factory FACTORY = LZ4Factory.fastestInstance();
@ -350,7 +349,7 @@ public class MainUtil {
} }
public static FaweInputStream getCompressedIS(InputStream is) throws IOException { public static FaweInputStream getCompressedIS(InputStream is) throws IOException {
return getCompressedIS(is, Settings.IMP.HISTORY.BUFFER_SIZE); return getCompressedIS(is, Settings.settings().HISTORY.BUFFER_SIZE);
} }
public static FaweInputStream getCompressedIS(InputStream is, int buffer) throws IOException { public static FaweInputStream getCompressedIS(InputStream is, int buffer) throws IOException {
@ -381,7 +380,7 @@ public class MainUtil {
} }
public static URL upload(UUID uuid, String file, String extension, @Nonnull final RunnableVal<OutputStream> writeTask) { public static URL upload(UUID uuid, String file, String extension, @Nonnull final RunnableVal<OutputStream> writeTask) {
return upload(Settings.IMP.WEB.URL, uuid != null, uuid != null ? uuid.toString() : null, file, extension, writeTask); return upload(Settings.settings().WEB.URL, uuid != null, uuid != null ? uuid.toString() : null, file, extension, writeTask);
} }
public static URL upload( public static URL upload(
@ -413,16 +412,15 @@ public class MainUtil {
StandardCharsets.UTF_8 StandardCharsets.UTF_8
), true)) { ), true)) {
String crlf = "\r\n"; String crlf = "\r\n";
writer.append("--" + boundary).append(crlf); writer.append("--").append(boundary).append(crlf);
writer.append("Content-Disposition: form-data; name=\"param\"").append(crlf); writer.append("Content-Disposition: form-data; name=\"param\"").append(crlf);
writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(crlf); writer.append("Content-Type: text/plain; charset=").append(StandardCharsets.UTF_8.displayName()).append(crlf);
String param = "value"; String param = "value";
writer.append(crlf).append(param).append(crlf).flush(); writer.append(crlf).append(param).append(crlf).flush();
writer.append("--" + boundary).append(crlf); writer.append("--").append(boundary).append(crlf);
writer writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"").append(filename).append(String.valueOf('"'))
.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + filename + '"')
.append(crlf); .append(crlf);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)).append(crlf); writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(filename)).append(crlf);
writer.append("Content-Transfer-Encoding: binary").append(crlf); writer.append("Content-Transfer-Encoding: binary").append(crlf);
writer.append(crlf).flush(); writer.append(crlf).flush();
OutputStream nonClosable = new AbstractDelegateOutputStream(new BufferedOutputStream(output)) { OutputStream nonClosable = new AbstractDelegateOutputStream(new BufferedOutputStream(output)) {
@ -434,7 +432,7 @@ public class MainUtil {
writeTask.run(); writeTask.run();
nonClosable.flush(); nonClosable.flush();
writer.append(crlf).flush(); writer.append(crlf).flush();
writer.append("--" + boundary + "--").append(crlf).flush(); writer.append("--").append(boundary).append("--").append(crlf).flush();
} }
int responseCode = ((HttpURLConnection) con).getResponseCode(); int responseCode = ((HttpURLConnection) con).getResponseCode();
String content; String content;
@ -524,7 +522,7 @@ public class MainUtil {
try { try {
return getJarFile(Fawe.class); return getJarFile(Fawe.class);
} catch (MalformedURLException | URISyntaxException | SecurityException e) { } catch (MalformedURLException | URISyntaxException | SecurityException e) {
return new File(Fawe.imp().getDirectory().getParentFile(), "FastAsyncWorldEdit.jar"); return new File(Fawe.platform().getDirectory().getParentFile(), "FastAsyncWorldEdit.jar");
} }
} }
@ -598,7 +596,7 @@ public class MainUtil {
public static File copyFile(File jar, String resource, File output, String fileName) { public static File copyFile(File jar, String resource, File output, String fileName) {
try { try {
if (output == null) { if (output == null) {
output = Fawe.imp().getDirectory(); output = Fawe.platform().getDirectory();
} }
if (!output.exists()) { if (!output.exists()) {
output.mkdirs(); output.mkdirs();
@ -663,21 +661,19 @@ public class MainUtil {
continue; continue;
} }
switch (c) { switch (c) {
case '-': case '-' -> val = -val;
val = -val; case '.' -> {
break;
case '.':
res[index--] = val; res[index--] = val;
if (index == -1) { if (index == -1) {
return res; return res;
} }
val = 0; val = 0;
numIndex = 1; numIndex = 1;
break; }
default: default -> {
val = val + (c - 48) * numIndex; val = val + (c - 48) * numIndex;
numIndex *= 10; numIndex *= 10;
break; }
} }
} }
res[index] = val; res[index] = val;
@ -802,30 +798,30 @@ public class MainUtil {
int years = (int) (time / 33868800); int years = (int) (time / 33868800);
int time1 = years * 33868800; int time1 = years * 33868800;
time -= time1; time -= time1;
toreturn.append(years + "y "); toreturn.append(years).append("y ");
} }
if (time >= 604800) { if (time >= 604800) {
int weeks = (int) (time / 604800); int weeks = (int) (time / 604800);
time -= weeks * 604800; time -= weeks * 604800L;
toreturn.append(weeks + "w "); toreturn.append(weeks).append("w ");
} }
if (time >= 86400) { if (time >= 86400) {
int days = (int) (time / 86400); int days = (int) (time / 86400);
time -= days * 86400; time -= days * 86400L;
toreturn.append(days + "d "); toreturn.append(days).append("d ");
} }
if (time >= 3600) { if (time >= 3600) {
int hours = (int) (time / 3600); int hours = (int) (time / 3600);
time -= hours * 3600; time -= hours * 3600L;
toreturn.append(hours + "h "); toreturn.append(hours).append("h ");
} }
if (time >= 60) { if (time >= 60) {
int minutes = (int) (time / 60); int minutes = (int) (time / 60);
time -= minutes * 60; time -= minutes * 60L;
toreturn.append(minutes + "m "); toreturn.append(minutes).append("m ");
} }
if (toreturn.equals("") || time > 0) { if (toreturn.equals("") || time > 0) {
toreturn.append((time) + "s "); toreturn.append(time).append("s ");
} }
return toreturn.toString().trim(); return toreturn.toString().trim();
} }
@ -849,23 +845,23 @@ public class MainUtil {
case "wks": case "wks":
case "w": case "w":
time += 604800 * nums; time += 604800L * nums;
case "days": case "days":
case "day": case "day":
case "d": case "d":
time += 86400 * nums; time += 86400L * nums;
case "hour": case "hour":
case "hr": case "hr":
case "hrs": case "hrs":
case "hours": case "hours":
case "h": case "h":
time += 3600 * nums; time += 3600L * nums;
case "minutes": case "minutes":
case "minute": case "minute":
case "mins": case "mins":
case "min": case "min":
case "m": case "m":
time += 60 * nums; time += 60L * nums;
case "seconds": case "seconds":
case "second": case "second":
case "secs": case "secs":

View File

@ -44,7 +44,7 @@ public class MemUtil {
} }
final long heapFreeSize = Runtime.getRuntime().freeMemory(); final long heapFreeSize = Runtime.getRuntime().freeMemory();
final int size = (int) ((heapFreeSize * 100) / heapMaxSize); final int size = (int) ((heapFreeSize * 100) / heapMaxSize);
if (size > (100 - Settings.IMP.MAX_MEMORY_PERCENT)) { if (size > (100 - Settings.settings().MAX_MEMORY_PERCENT)) {
memoryPlentifulTask(); memoryPlentifulTask();
return Integer.MAX_VALUE; return Integer.MAX_VALUE;
} }

View File

@ -21,10 +21,31 @@ public abstract class TaskManager {
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
/**
* @deprecated Use {@link #taskManager()} to get an instance.
*/
@Deprecated(forRemoval = true, since = "2.0.0")
public static TaskManager IMP; public static TaskManager IMP;
static TaskManager INSTANCE;
private final ForkJoinPool pool = new ForkJoinPool(); private final ForkJoinPool pool = new ForkJoinPool();
protected TaskManager() {
INSTANCE = this;
}
/**
* Gets an instance of the TaskManager.
*
* @return an instance of the TaskManager
* @since 2.0.0
*/
public static TaskManager taskManager() {
if (INSTANCE == null) {
INSTANCE = Fawe.platform().getTaskManager();
}
return INSTANCE;
}
/** /**
* Run a repeating task on the main thread. * Run a repeating task on the main thread.
* *
@ -68,8 +89,8 @@ public abstract class TaskManager {
/** /**
* Run a bunch of tasks in parallel using the shared thread pool. * Run a bunch of tasks in parallel using the shared thread pool.
*/ */
public void parallel(Collection<Runnable> runnables) { public void parallel(Collection<Runnable> runables) {
for (Runnable run : runnables) { for (Runnable run : runables) {
pool.submit(run); pool.submit(run);
} }
pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS); pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
@ -87,7 +108,7 @@ public abstract class TaskManager {
return; return;
} }
if (numThreads == null) { if (numThreads == null) {
numThreads = Settings.IMP.QUEUE.PARALLEL_THREADS; numThreads = Settings.settings().QUEUE.PARALLEL_THREADS;
} }
if (numThreads <= 1) { if (numThreads <= 1) {
for (Runnable run : runnables) { for (Runnable run : runnables) {
@ -135,7 +156,7 @@ public abstract class TaskManager {
* Disable async catching for a specific task. * Disable async catching for a specific task.
*/ */
public void runUnsafe(Runnable run) { public void runUnsafe(Runnable run) {
QueueHandler queue = Fawe.get().getQueueHandler(); QueueHandler queue = Fawe.instance().getQueueHandler();
queue.startSet(true); queue.startSet(true);
try { try {
run.run(); run.run();
@ -256,7 +277,7 @@ public abstract class TaskManager {
synchronized (running) { synchronized (running) {
while (running.get()) { while (running.get()) {
running.wait(timeout); running.wait(timeout);
if (running.get() && System.currentTimeMillis() - start > Settings.IMP.QUEUE.DISCARD_AFTER_MS) { if (running.get() && System.currentTimeMillis() - start > Settings.settings().QUEUE.DISCARD_AFTER_MS) {
new RuntimeException("FAWE is taking a long time to execute a task (might just be a symptom): ").printStackTrace(); new RuntimeException("FAWE is taking a long time to execute a task (might just be a symptom): ").printStackTrace();
LOGGER.info("For full debug information use: /fawe threads"); LOGGER.info("For full debug information use: /fawe threads");
} }
@ -278,7 +299,7 @@ public abstract class TaskManager {
if (Fawe.isMainThread()) { if (Fawe.isMainThread()) {
run.run(); run.run();
} else { } else {
Fawe.get().getQueueHandler().sync(run); Fawe.instance().getQueueHandler().sync(run);
} }
} }
@ -293,7 +314,7 @@ public abstract class TaskManager {
return function.value; return function.value;
} }
try { try {
return Fawe.get().getQueueHandler().sync((Supplier<T>) function).get(); return Fawe.instance().getQueueHandler().sync((Supplier<T>) function).get();
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -309,7 +330,7 @@ public abstract class TaskManager {
return supplier.get(); return supplier.get();
} }
try { try {
return Fawe.get().getQueueHandler().sync(supplier).get(); return Fawe.instance().getQueueHandler().sync(supplier).get();
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -334,7 +355,7 @@ public abstract class TaskManager {
return function.get(); return function.get();
} }
try { try {
return Fawe.get().getQueueHandler().sync(function).get(); return Fawe.instance().getQueueHandler().sync(function).get();
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@ -340,7 +340,7 @@ public class TextureUtil implements TextureHolder {
* Do not use. Use {@link Fawe#getTextureUtil()} * Do not use. Use {@link Fawe#getTextureUtil()}
*/ */
public TextureUtil() throws FileNotFoundException { public TextureUtil() throws FileNotFoundException {
this(MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.TEXTURES)); this(MainUtil.getFile(Fawe.platform().getDirectory(), Settings.settings().PATHS.TEXTURES));
} }
/** /**
@ -351,12 +351,12 @@ public class TextureUtil implements TextureHolder {
if (!folder.exists()) { if (!folder.exists()) {
try { try {
LOGGER.info("Downloading asset jar from Mojang, please wait..."); LOGGER.info("Downloading asset jar from Mojang, please wait...");
new File(Fawe.imp().getDirectory() + "/" + Settings.IMP.PATHS.TEXTURES + "/").mkdirs(); new File(Fawe.platform().getDirectory() + "/" + Settings.settings().PATHS.TEXTURES + "/").mkdirs();
try (BufferedInputStream in = new BufferedInputStream( try (BufferedInputStream in = new BufferedInputStream(
new URL("https://launcher.mojang.com/v1/objects/7e46fb47609401970e2818989fa584fd467cd036/client.jar") new URL("https://launcher.mojang.com/v1/objects/7e46fb47609401970e2818989fa584fd467cd036/client.jar")
.openStream()); .openStream());
FileOutputStream fileOutputStream = new FileOutputStream( FileOutputStream fileOutputStream = new FileOutputStream(
Fawe.imp().getDirectory() + "/" + Settings.IMP.PATHS.TEXTURES + "/1.18.1.jar")) { Fawe.platform().getDirectory() + "/" + Settings.settings().PATHS.TEXTURES + "/1.18.1.jar")) {
byte[] dataBuffer = new byte[1024]; byte[] dataBuffer = new byte[1024];
int bytesRead; int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
@ -395,7 +395,7 @@ public class TextureUtil implements TextureHolder {
} }
public static TextureUtil fromBlocks(Set<BlockType> blocks) throws FileNotFoundException { public static TextureUtil fromBlocks(Set<BlockType> blocks) throws FileNotFoundException {
return new FilteredTextureUtil(Fawe.get().getTextureUtil(), blocks); return new FilteredTextureUtil(Fawe.instance().getTextureUtil(), blocks);
} }
public static TextureUtil fromMask(Mask mask) throws FileNotFoundException { public static TextureUtil fromMask(Mask mask) throws FileNotFoundException {
@ -404,7 +404,7 @@ public class TextureUtil implements TextureHolder {
SingleFilterBlock extent = new SingleFilterBlock(); SingleFilterBlock extent = new SingleFilterBlock();
new MaskTraverser(mask).reset(extent); new MaskTraverser(mask).reset(extent);
TextureUtil tu = Fawe.get().getTextureUtil(); TextureUtil tu = Fawe.instance().getTextureUtil();
for (int typeId : tu.getValidBlockIds()) { for (int typeId : tu.getValidBlockIds()) {
BlockType block = BlockTypes.get(typeId); BlockType block = BlockTypes.get(typeId);
extent.init(0, 0, 0, block.getDefaultState().toBaseBlock()); extent.init(0, 0, 0, block.getDefaultState().toBaseBlock());
@ -807,13 +807,13 @@ public class TextureUtil implements TextureHolder {
// Get all the jar files // Get all the jar files
File[] files = folder.listFiles((dir, name) -> name.endsWith(".jar")); File[] files = folder.listFiles((dir, name) -> name.endsWith(".jar"));
if (files.length == 0) { if (files.length == 0) {
new File(Fawe.imp().getDirectory() + "/" + Settings.IMP.PATHS.TEXTURES + "/") new File(Fawe.platform().getDirectory() + "/" + Settings.settings().PATHS.TEXTURES + "/")
.mkdirs(); .mkdirs();
try (BufferedInputStream in = new BufferedInputStream( try (BufferedInputStream in = new BufferedInputStream(
new URL("https://launcher.mojang.com/v1/objects/7e46fb47609401970e2818989fa584fd467cd036/client.jar") new URL("https://launcher.mojang.com/v1/objects/7e46fb47609401970e2818989fa584fd467cd036/client.jar")
.openStream()); .openStream());
FileOutputStream fileOutputStream = new FileOutputStream( FileOutputStream fileOutputStream = new FileOutputStream(
Fawe.imp().getDirectory() + "/" + Settings.IMP.PATHS.TEXTURES + "/1.18.1.jar")) { Fawe.platform().getDirectory() + "/" + Settings.settings().PATHS.TEXTURES + "/1.18.1.jar")) {
byte[] dataBuffer = new byte[1024]; byte[] dataBuffer = new byte[1024];
int bytesRead; int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {

View File

@ -27,14 +27,14 @@ public class UpdateNotification {
* Check whether a new build with a higher build number than the current build is available. * Check whether a new build with a higher build number than the current build is available.
*/ */
public static void doUpdateCheck() { public static void doUpdateCheck() {
if (Settings.IMP.ENABLED_COMPONENTS.UPDATE_NOTIFICATIONS) { if (Settings.settings().ENABLED_COMPONENTS.UPDATE_NOTIFICATIONS) {
try { try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder db = dbf.newDocumentBuilder(); DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL("https://ci.athion.net/job/FastAsyncWorldEdit/api/xml/").openStream()); Document doc = db.parse(new URL("https://ci.athion.net/job/FastAsyncWorldEdit/api/xml/").openStream());
faweVersion = doc.getElementsByTagName("lastSuccessfulBuild").item(0).getFirstChild().getTextContent(); faweVersion = doc.getElementsByTagName("lastSuccessfulBuild").item(0).getFirstChild().getTextContent();
FaweVersion faweVersion = Fawe.get().getVersion(); FaweVersion faweVersion = Fawe.instance().getVersion();
if (faweVersion.build == 0) { if (faweVersion.build == 0) {
LOGGER.warn("You are using a snapshot or a custom version of FAWE. This is not an official build distributed " + LOGGER.warn("You are using a snapshot or a custom version of FAWE. This is not an official build distributed " +
"via https://www.spigotmc.org/resources/13932/"); "via https://www.spigotmc.org/resources/13932/");
@ -66,9 +66,9 @@ public class UpdateNotification {
* @param actor The player to notify. * @param actor The player to notify.
*/ */
public static void doUpdateNotification(Actor actor) { public static void doUpdateNotification(Actor actor) {
if (Settings.IMP.ENABLED_COMPONENTS.UPDATE_NOTIFICATIONS) { if (Settings.settings().ENABLED_COMPONENTS.UPDATE_NOTIFICATIONS) {
if (actor.hasPermission("fawe.admin") && UpdateNotification.hasUpdate) { if (actor.hasPermission("fawe.admin") && UpdateNotification.hasUpdate) {
FaweVersion faweVersion = Fawe.get().getVersion(); FaweVersion faweVersion = Fawe.instance().getVersion();
int versionDifference = Integer.parseInt(UpdateNotification.faweVersion) - faweVersion.build; int versionDifference = Integer.parseInt(UpdateNotification.faweVersion) - faweVersion.build;
actor.print(Caption.of( actor.print(Caption.of(
"fawe.info.update-available", "fawe.info.update-available",

View File

@ -26,10 +26,28 @@ import java.util.Set;
public class WEManager { public class WEManager {
public static final WEManager IMP = new WEManager();
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
private static WEManager INSTANCE;
/**
* @deprecated Use {@link #weManager()} instead.
*/
@Deprecated(forRemoval = true, since = "2.0.0")
private final WEManager IMP = new WEManager();
private final ArrayDeque<FaweMaskManager> managers = new ArrayDeque<>(); private final ArrayDeque<FaweMaskManager> managers = new ArrayDeque<>();
private WEManager() {
INSTANCE = this;
}
/**
* Get an instance of the WEManager.
*
* @return an instance of the WEManager
*/
public static WEManager weManager() {
return INSTANCE;
}
public ArrayDeque<FaweMaskManager> getManagers() { public ArrayDeque<FaweMaskManager> getManagers() {
return managers; return managers;
} }
@ -81,7 +99,7 @@ public class WEManager {
* @return array of allowed regions if whitelist, else of disallowed regions. * @return array of allowed regions if whitelist, else of disallowed regions.
*/ */
public Region[] getMask(Player player, FaweMaskManager.MaskType type, final boolean isWhitelist) { public Region[] getMask(Player player, FaweMaskManager.MaskType type, final boolean isWhitelist) {
if (!Settings.IMP.REGION_RESTRICTIONS || player.hasPermission("fawe.bypass") || player.hasPermission("fawe.bypass.regions")) { if (!Settings.settings().REGION_RESTRICTIONS || player.hasPermission("fawe.bypass") || player.hasPermission("fawe.bypass.regions")) {
return new Region[]{RegionWrapper.GLOBAL()}; return new Region[]{RegionWrapper.GLOBAL()};
} }
Location loc = player.getLocation(); Location loc = player.getLocation();

View File

@ -22,7 +22,7 @@ import java.util.Set;
public final class MemBlockSet extends BlockSet { public final class MemBlockSet extends BlockSet {
public static final int BITS_PER_WORD = 6; public static final int BITS_PER_WORD = 6;
public static final int WORDS = FaweCache.IMP.BLOCKS_PER_LAYER >> BITS_PER_WORD; public static final int WORDS = FaweCache.INSTANCE.BLOCKS_PER_LAYER >> BITS_PER_WORD;
public static final IRow NULL_ROW_X = new NullRowX(); public static final IRow NULL_ROW_X = new NullRowX();
public static final IRow NULL_ROW_Z = new NullRowZ(); public static final IRow NULL_ROW_Z = new NullRowZ();
public static final IRow NULL_ROW_Y = new NullRowY(); public static final IRow NULL_ROW_Y = new NullRowY();

View File

@ -212,8 +212,8 @@ public class ImageUtil {
if (arg.startsWith("file:/")) { if (arg.startsWith("file:/")) {
arg = arg.replaceFirst("file:/+", ""); arg = arg.replaceFirst("file:/+", "");
File file = MainUtil.getFile(MainUtil.getFile( File file = MainUtil.getFile(MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HEIGHTMAP Settings.settings().PATHS.HEIGHTMAP
), arg); ), arg);
return MainUtil.readImage(file); return MainUtil.readImage(file);
} }
@ -234,8 +234,8 @@ public class ImageUtil {
if (arg.startsWith("file:/")) { if (arg.startsWith("file:/")) {
arg = arg.replaceFirst("file:/+", ""); arg = arg.replaceFirst("file:/+", "");
File file = MainUtil.getFile(MainUtil.getFile( File file = MainUtil.getFile(MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HEIGHTMAP Settings.settings().PATHS.HEIGHTMAP
), arg); ), arg);
if (!file.exists()) { if (!file.exists()) {
throw new InputParseException(Caption.of( throw new InputParseException(Caption.of(

View File

@ -17,8 +17,8 @@ public class DefaultProgressTracker implements BiConsumer<DefaultProgressTracker
private final Player player; private final Player player;
private final long start; private final long start;
private int delay = Settings.IMP.QUEUE.PROGRESS.DELAY; private int delay = Settings.settings().QUEUE.PROGRESS.DELAY;
private int interval = Settings.IMP.QUEUE.PROGRESS.INTERVAL; private int interval = Settings.settings().QUEUE.PROGRESS.INTERVAL;
public DefaultProgressTracker(Player player) { public DefaultProgressTracker(Player player) {
this.start = System.currentTimeMillis(); this.start = System.currentTimeMillis();
@ -92,14 +92,14 @@ public class DefaultProgressTracker implements BiConsumer<DefaultProgressTracker
} }
private void done() { private void done() {
TaskManager.IMP.task(this::doneTask); TaskManager.taskManager().task(this::doneTask);
} }
private long lastTick = 0; private long lastTick = 0;
private void send() { private void send() {
// Run on main thread // Run on main thread
TaskManager.IMP.task(this::sendTask); TaskManager.taskManager().task(this::sendTask);
} }
public void doneTask() { public void doneTask() {

View File

@ -59,7 +59,7 @@ public class AsyncNotifyQueue implements Closeable {
} }
return null; return null;
}; };
self[0] = Fawe.get().getQueueHandler().async(wrapped); self[0] = Fawe.instance().getQueueHandler().async(wrapped);
return self[0]; return self[0];
} }

View File

@ -19,7 +19,7 @@ public abstract class SingleThreadIntervalQueue<T> {
this.task = new Runnable() { this.task = new Runnable() {
@Override @Override
public void run() { public void run() {
long allowedTick = Fawe.get().getTimer().getTick() - 1; long allowedTick = Fawe.instance().getTimer().getTick() - 1;
Iterator<Map.Entry<T, Long>> iter = objMap.entrySet().iterator(); Iterator<Map.Entry<T, Long>> iter = objMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<T, Long> entry = iter.next(); Map.Entry<T, Long> entry = iter.next();
@ -32,7 +32,7 @@ public abstract class SingleThreadIntervalQueue<T> {
} }
synchronized (objMap) { synchronized (objMap) {
if (!objMap.isEmpty()) { if (!objMap.isEmpty()) {
TaskManager.IMP.laterAsync(this, interval); TaskManager.taskManager().laterAsync(this, interval);
} else { } else {
queued.set(false); queued.set(false);
} }
@ -51,10 +51,10 @@ public abstract class SingleThreadIntervalQueue<T> {
public void queue(T obj) { public void queue(T obj) {
synchronized (objMap) { synchronized (objMap) {
objMap.put(obj, Fawe.get().getTimer().getTick()); objMap.put(obj, Fawe.instance().getTimer().getTick());
if (!queued.get()) { if (!queued.get()) {
queued.set(true); queued.set(true);
TaskManager.IMP.laterAsync(task, 3); TaskManager.taskManager().laterAsync(task, 3);
} }
} }
} }

View File

@ -97,7 +97,7 @@ public interface SimpleWorld extends World {
@Override @Override
default boolean queueBlockBreakEffect(Platform server, BlockVector3 position, BlockType blockType, double priority) { default boolean queueBlockBreakEffect(Platform server, BlockVector3 position, BlockType blockType, double priority) {
Fawe.get().getQueueHandler().sync((Supplier<Boolean>) () -> playEffect( Fawe.instance().getQueueHandler().sync((Supplier<Boolean>) () -> playEffect(
position, position,
2001, 2001,
blockType.getLegacyCombinedId() >> 4 blockType.getLegacyCombinedId() >> 4

View File

@ -38,7 +38,7 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public void findFreePosition(Location searchPos) { public void findFreePosition(Location searchPos) {
TaskManager.IMP.sync(new RunnableVal<Boolean>() { TaskManager.taskManager().sync(new RunnableVal<Boolean>() {
@Override @Override
public void run(Boolean value) { public void run(Boolean value) {
getBasePlayer().findFreePosition(searchPos); getBasePlayer().findFreePosition(searchPos);
@ -48,7 +48,7 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public void setOnGround(Location searchPos) { public void setOnGround(Location searchPos) {
TaskManager.IMP.sync(new RunnableVal<Boolean>() { TaskManager.taskManager().sync(new RunnableVal<Boolean>() {
@Override @Override
public void run(Boolean value) { public void run(Boolean value) {
getBasePlayer().setOnGround(searchPos); getBasePlayer().setOnGround(searchPos);
@ -58,7 +58,7 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public void findFreePosition() { public void findFreePosition() {
TaskManager.IMP.sync(new RunnableVal<Boolean>() { TaskManager.taskManager().sync(new RunnableVal<Boolean>() {
@Override @Override
public void run(Boolean value) { public void run(Boolean value) {
getBasePlayer().findFreePosition(); getBasePlayer().findFreePosition();
@ -68,12 +68,12 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public boolean ascendLevel() { public boolean ascendLevel() {
return TaskManager.IMP.sync(() -> getBasePlayer().ascendLevel()); return TaskManager.taskManager().sync(() -> getBasePlayer().ascendLevel());
} }
@Override @Override
public boolean descendLevel() { public boolean descendLevel() {
return TaskManager.IMP.sync(() -> getBasePlayer().descendLevel()); return TaskManager.taskManager().sync(() -> getBasePlayer().descendLevel());
} }
@Override @Override
@ -155,7 +155,7 @@ public class AsyncPlayer extends PlayerProxy {
unwrap(getBasePlayer())).build(); unwrap(getBasePlayer())).build();
edit.setBlock(BlockVector3.at(x, y - 1, z), BlockTypes.GLASS); edit.setBlock(BlockVector3.at(x, y - 1, z), BlockTypes.GLASS);
edit.flushQueue(); edit.flushQueue();
LocalSession session = Fawe.get().getWorldEdit().getSessionManager().get(this); LocalSession session = Fawe.instance().getWorldEdit().getSessionManager().get(this);
if (session != null) { if (session != null) {
session.remember(edit, true, getBasePlayer().getLimit().MAX_HISTORY); session.remember(edit, true, getBasePlayer().getLimit().MAX_HISTORY);
} }
@ -173,12 +173,12 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public void setPosition(Vector3 pos, float pitch, float yaw) { public void setPosition(Vector3 pos, float pitch, float yaw) {
Fawe.get().getQueueHandler().sync(() -> super.setPosition(pos, pitch, yaw)); Fawe.instance().getQueueHandler().sync(() -> super.setPosition(pos, pitch, yaw));
} }
@Override @Override
public Location getBlockTrace(int range, boolean useLastBlock) { public Location getBlockTrace(int range, boolean useLastBlock) {
return TaskManager.IMP.sync(() -> { return TaskManager.taskManager().sync(() -> {
TargetBlock tb = new TargetBlock(AsyncPlayer.this, range, 0.2D); TargetBlock tb = new TargetBlock(AsyncPlayer.this, range, 0.2D);
return useLastBlock ? tb.getAnyTargetBlock() : tb.getTargetBlock(); return useLastBlock ? tb.getAnyTargetBlock() : tb.getTargetBlock();
}); });
@ -186,7 +186,7 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public Location getBlockTraceFace(int range, boolean useLastBlock) { public Location getBlockTraceFace(int range, boolean useLastBlock) {
return TaskManager.IMP.sync(() -> { return TaskManager.taskManager().sync(() -> {
TargetBlock tb = new TargetBlock(AsyncPlayer.this, range, 0.2D); TargetBlock tb = new TargetBlock(AsyncPlayer.this, range, 0.2D);
return useLastBlock ? tb.getAnyTargetBlockFace() : tb.getTargetBlockFace(); return useLastBlock ? tb.getAnyTargetBlockFace() : tb.getTargetBlockFace();
}); });
@ -194,7 +194,7 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public Location getSolidBlockTrace(int range) { public Location getSolidBlockTrace(int range) {
return TaskManager.IMP.sync(() -> { return TaskManager.taskManager().sync(() -> {
TargetBlock tb = new TargetBlock(AsyncPlayer.this, range, 0.2D); TargetBlock tb = new TargetBlock(AsyncPlayer.this, range, 0.2D);
return tb.getSolidTargetBlock(); return tb.getSolidTargetBlock();
}); });
@ -207,7 +207,7 @@ public class AsyncPlayer extends PlayerProxy {
@Override @Override
public boolean passThroughForwardWall(int range) { public boolean passThroughForwardWall(int range) {
return TaskManager.IMP.sync(() -> { return TaskManager.taskManager().sync(() -> {
int searchDist = 0; int searchDist = 0;
TargetBlock hitBlox = new TargetBlock(AsyncPlayer.this, range, 0.2); TargetBlock hitBlox = new TargetBlock(AsyncPlayer.this, range, 0.2);
Extent world = getLocation().getExtent(); Extent world = getLocation().getExtent();

View File

@ -238,7 +238,7 @@ public class WorldWrapper extends AbstractWorld {
@Override @Override
public void simulateBlockMine(BlockVector3 pt) { public void simulateBlockMine(BlockVector3 pt) {
TaskManager.IMP.sync(new RunnableVal<Object>() { TaskManager.taskManager().sync(new RunnableVal<Object>() {
@Override @Override
public void run(Object value) { public void run(Object value) {
parent.simulateBlockMine(pt); parent.simulateBlockMine(pt);
@ -249,7 +249,7 @@ public class WorldWrapper extends AbstractWorld {
//FAWE start //FAWE start
@Override @Override
public Collection<BaseItemStack> getBlockDrops(final BlockVector3 position) { public Collection<BaseItemStack> getBlockDrops(final BlockVector3 position) {
return TaskManager.IMP.sync(() -> parent.getBlockDrops(position)); return TaskManager.taskManager().sync(() -> parent.getBlockDrops(position));
} }
//FAWE end //FAWE end
@ -266,7 +266,7 @@ public class WorldWrapper extends AbstractWorld {
@Override @Override
public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws
MaxChangedBlocksException { MaxChangedBlocksException {
return TaskManager.IMP.sync(() -> { return TaskManager.taskManager().sync(() -> {
try { try {
return parent.generateTree(type, editSession, position); return parent.generateTree(type, editSession, position);
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
@ -307,12 +307,12 @@ public class WorldWrapper extends AbstractWorld {
@Override @Override
public List<? extends Entity> getEntities(Region region) { public List<? extends Entity> getEntities(Region region) {
return TaskManager.IMP.sync(() -> parent.getEntities(region)); return TaskManager.taskManager().sync(() -> parent.getEntities(region));
} }
@Override @Override
public List<? extends Entity> getEntities() { public List<? extends Entity> getEntities() {
return TaskManager.IMP.sync(parent::getEntities); return TaskManager.taskManager().sync(parent::getEntities);
} }
@Override @Override

View File

@ -1289,7 +1289,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable {
// Don't relight twice! // Don't relight twice!
if (!relighter.isFinished() && relighter.getLock().tryLock()) { if (!relighter.isFinished() && relighter.getLock().tryLock()) {
try { try {
if (Settings.IMP.LIGHTING.REMOVE_FIRST) { if (Settings.settings().LIGHTING.REMOVE_FIRST) {
relighter.removeAndRelight(true); relighter.removeAndRelight(true);
} else { } else {
relighter.fixLightingSafe(true); relighter.fixLightingSafe(true);
@ -1305,14 +1305,14 @@ public class EditSession extends PassthroughExtent implements AutoCloseable {
} }
// Cancel any preloader associated with the actor if present // Cancel any preloader associated with the actor if present
if (getActor() instanceof Player) { if (getActor() instanceof Player) {
Preloader preloader = Fawe.imp().getPreloader(false); Preloader preloader = Fawe.platform().getPreloader(false);
if (preloader != null) { if (preloader != null) {
preloader.cancel(getActor()); preloader.cancel(getActor());
} }
} }
// Enqueue it // Enqueue it
if (getChangeSet() != null) { if (getChangeSet() != null) {
if (Settings.IMP.HISTORY.COMBINE_STAGES) { if (Settings.settings().HISTORY.COMBINE_STAGES) {
((AbstractChangeSet) getChangeSet()).closeAsync(); ((AbstractChangeSet) getChangeSet()).closeAsync();
} else { } else {
try { try {
@ -3649,7 +3649,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable {
} }
if (containsAny) { if (containsAny) {
changes++; changes++;
TaskManager.IMP.sync(new RunnableVal<Object>() { TaskManager.taskManager().sync(new RunnableVal<Object>() {
@Override @Override
public void run(Object value) { public void run(Object value) {
regenerateChunk(cx, cz, biome, seed); regenerateChunk(cx, cz, biome, seed);

View File

@ -303,7 +303,7 @@ public final class EditSessionBuilder {
*/ */
public EditSessionBuilder changeSet(boolean disk, @Nullable UUID uuid) { public EditSessionBuilder changeSet(boolean disk, @Nullable UUID uuid) {
if (disk) { if (disk) {
if (Settings.IMP.HISTORY.USE_DATABASE) { if (Settings.settings().HISTORY.USE_DATABASE) {
this.changeSet = new RollbackOptimizedHistory(world, uuid); this.changeSet = new RollbackOptimizedHistory(world, uuid);
} else { } else {
this.changeSet = new DiskStorageHistory(world, uuid); this.changeSet = new DiskStorageHistory(world, uuid);
@ -437,7 +437,7 @@ public final class EditSessionBuilder {
} }
if (fastMode == null) { if (fastMode == null) {
if (actor == null) { if (actor == null) {
fastMode = !Settings.IMP.HISTORY.ENABLE_FOR_CONSOLE; fastMode = !Settings.settings().HISTORY.ENABLE_FOR_CONSOLE;
} else { } else {
fastMode = actor.getSession().hasFastMode(); fastMode = actor.getSession().hasFastMode();
} }
@ -466,12 +466,12 @@ public final class EditSessionBuilder {
wnaMode = false; wnaMode = false;
if (unwrapped instanceof IQueueExtent) { if (unwrapped instanceof IQueueExtent) {
extent = queue = (IQueueExtent) unwrapped; extent = queue = (IQueueExtent) unwrapped;
} else if (Settings.IMP.QUEUE.PARALLEL_THREADS > 1 && !Fawe.isMainThread()) { } else if (Settings.settings().QUEUE.PARALLEL_THREADS > 1 && !Fawe.isMainThread()) {
ParallelQueueExtent parallel = new ParallelQueueExtent(Fawe.get().getQueueHandler(), world, fastMode); ParallelQueueExtent parallel = new ParallelQueueExtent(Fawe.instance().getQueueHandler(), world, fastMode);
queue = parallel.getExtent(); queue = parallel.getExtent();
extent = parallel; extent = parallel;
} else { } else {
extent = queue = Fawe.get().getQueueHandler().getQueue(world); extent = queue = Fawe.instance().getQueueHandler().getQueue(world);
} }
} else { } else {
wnaMode = true; wnaMode = true;
@ -480,7 +480,7 @@ public final class EditSessionBuilder {
if (combineStages == null) { if (combineStages == null) {
combineStages = combineStages =
// If it's enabled in the settings // If it's enabled in the settings
Settings.IMP.HISTORY.COMBINE_STAGES Settings.settings().HISTORY.COMBINE_STAGES
// If fast placement is disabled, it's slower to perform a copy on each chunk // If fast placement is disabled, it's slower to perform a copy on each chunk
&& this.limit.FAST_PLACEMENT && this.limit.FAST_PLACEMENT
// If the edit uses items from the inventory we can't use a delayed task // If the edit uses items from the inventory we can't use a delayed task
@ -490,17 +490,17 @@ public final class EditSessionBuilder {
this.bypassHistory = this.extent = wrapExtent(bypassAll, eventBus, event, EditSession.Stage.BEFORE_REORDER); this.bypassHistory = this.extent = wrapExtent(bypassAll, eventBus, event, EditSession.Stage.BEFORE_REORDER);
if (!this.fastMode || changeSet != null) { if (!this.fastMode || changeSet != null) {
if (changeSet == null) { if (changeSet == null) {
if (Settings.IMP.HISTORY.USE_DISK) { if (Settings.settings().HISTORY.USE_DISK) {
UUID uuid = actor == null ? Identifiable.CONSOLE : actor.getUniqueId(); UUID uuid = actor == null ? Identifiable.CONSOLE : actor.getUniqueId();
if (Settings.IMP.HISTORY.USE_DATABASE) { if (Settings.settings().HISTORY.USE_DATABASE) {
changeSet = new RollbackOptimizedHistory(world, uuid); changeSet = new RollbackOptimizedHistory(world, uuid);
} else { } else {
changeSet = new DiskStorageHistory(world, uuid); changeSet = new DiskStorageHistory(world, uuid);
} }
// } else if (combineStages && Settings.IMP.HISTORY.COMPRESSION_LEVEL == 0) { // } else if (combineStages && Settings.settings().HISTORY.COMPRESSION_LEVEL == 0) {
// changeSet = new CPUOptimizedChangeSet(world); // changeSet = new CPUOptimizedChangeSet(world);
} else { } else {
if (combineStages && Settings.IMP.HISTORY.COMPRESSION_LEVEL == 0) { if (combineStages && Settings.settings().HISTORY.COMPRESSION_LEVEL == 0) {
//TODO add CPUOptimizedChangeSet //TODO add CPUOptimizedChangeSet
} }
changeSet = new MemoryOptimizedHistory(world); changeSet = new MemoryOptimizedHistory(world);
@ -528,7 +528,7 @@ public final class EditSessionBuilder {
} }
} }
} }
if (allowedRegions == null && Settings.IMP.REGION_RESTRICTIONS) { if (allowedRegions == null && Settings.settings().REGION_RESTRICTIONS) {
if (actor != null && !actor.hasPermission("fawe.bypass") && !actor.hasPermission("fawe.bypass.regions")) { if (actor != null && !actor.hasPermission("fawe.bypass") && !actor.hasPermission("fawe.bypass.regions")) {
if (actor instanceof Player) { if (actor instanceof Player) {
Player player = (Player) actor; Player player = (Player) actor;
@ -536,7 +536,7 @@ public final class EditSessionBuilder {
} }
} }
} }
if (disallowedRegions == null && Settings.IMP.REGION_RESTRICTIONS && Settings.IMP.REGION_RESTRICTIONS_OPTIONS.ALLOW_BLACKLISTS) { if (disallowedRegions == null && Settings.settings().REGION_RESTRICTIONS && Settings.settings().REGION_RESTRICTIONS_OPTIONS.ALLOW_BLACKLISTS) {
if (actor != null && !actor.hasPermission("fawe.bypass") && !actor.hasPermission("fawe.bypass.regions")) { if (actor != null && !actor.hasPermission("fawe.bypass") && !actor.hasPermission("fawe.bypass.regions")) {
if (actor instanceof Player) { if (actor instanceof Player) {
Player player = (Player) actor; Player player = (Player) actor;
@ -562,7 +562,7 @@ public final class EditSessionBuilder {
} }
// There's no need to do lighting (and it'll also just be a pain to implement) if we're not placing chunks // There's no need to do lighting (and it'll also just be a pain to implement) if we're not placing chunks
if (placeChunks) { if (placeChunks) {
if (((relightMode != null && relightMode != RelightMode.NONE) || (relightMode == null && Settings.IMP.LIGHTING.MODE > 0))) { if (((relightMode != null && relightMode != RelightMode.NONE) || (relightMode == null && Settings.settings().LIGHTING.MODE > 0))) {
relighter = WorldEdit.getInstance().getPlatformManager() relighter = WorldEdit.getInstance().getPlatformManager()
.queryCapability(Capability.WORLD_EDITING) .queryCapability(Capability.WORLD_EDITING)
.getRelighterFactory().createRelighter(relightMode, world, queue); .getRelighterFactory().createRelighter(relightMode, world, queue);
@ -704,13 +704,13 @@ public final class EditSessionBuilder {
} }
if (toReturn != extent) { if (toReturn != extent) {
String className = toReturn.getClass().getName().toLowerCase(Locale.ROOT); String className = toReturn.getClass().getName().toLowerCase(Locale.ROOT);
for (String allowed : Settings.IMP.EXTENT.ALLOWED_PLUGINS) { for (String allowed : Settings.settings().EXTENT.ALLOWED_PLUGINS) {
if (className.contains(allowed.toLowerCase(Locale.ROOT))) { if (className.contains(allowed.toLowerCase(Locale.ROOT))) {
this.wrapped = true; this.wrapped = true;
return toReturn; return toReturn;
} }
} }
if (Settings.IMP.EXTENT.DEBUG) { if (Settings.settings().EXTENT.DEBUG) {
if (event.getActor() != null) { if (event.getActor() != null) {
event.getActor().printDebug(TextComponent.of("Potentially unsafe extent blocked: " + toReturn event.getActor().printDebug(TextComponent.of("Potentially unsafe extent blocked: " + toReturn
.getClass() .getClass()

View File

@ -225,7 +225,7 @@ public class LocalSession implements TextureHolder {
if (world == null || uuid == null) { if (world == null || uuid == null) {
return false; return false;
} }
if (Settings.IMP.HISTORY.USE_DISK) { if (Settings.settings().HISTORY.USE_DISK) {
MAX_HISTORY_SIZE = Integer.MAX_VALUE; MAX_HISTORY_SIZE = Integer.MAX_VALUE;
} }
world = WorldWrapper.unwrap(world); world = WorldWrapper.unwrap(world);
@ -248,8 +248,8 @@ public class LocalSession implements TextureHolder {
private boolean loadHistoryChangeSets(UUID uuid, World world) { private boolean loadHistoryChangeSets(UUID uuid, World world) {
SparseBitSet set = new SparseBitSet(); SparseBitSet set = new SparseBitSet();
final File folder = MainUtil.getFile( final File folder = MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HISTORY + File.separator + world.getName() + File.separator + uuid Settings.settings().PATHS.HISTORY + File.separator + world.getName() + File.separator + uuid
); );
if (folder.isDirectory()) { if (folder.isDirectory()) {
folder.listFiles(pathname -> { folder.listFiles(pathname -> {
@ -282,12 +282,12 @@ public class LocalSession implements TextureHolder {
} }
private void loadHistoryNegativeIndex(UUID uuid, World world) { private void loadHistoryNegativeIndex(UUID uuid, World world) {
if (!Settings.IMP.HISTORY.USE_DISK) { if (!Settings.settings().HISTORY.USE_DISK) {
return; return;
} }
File file = MainUtil.getFile( File file = MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HISTORY + File.separator + world.getName() + File.separator + uuid + File.separator + "index" Settings.settings().PATHS.HISTORY + File.separator + world.getName() + File.separator + uuid + File.separator + "index"
); );
if (file.exists()) { if (file.exists()) {
try (FaweInputStream is = new FaweInputStream(new FileInputStream(file))) { try (FaweInputStream is = new FaweInputStream(new FileInputStream(file))) {
@ -301,12 +301,12 @@ public class LocalSession implements TextureHolder {
} }
private void saveHistoryNegativeIndex(UUID uuid, World world) { private void saveHistoryNegativeIndex(UUID uuid, World world) {
if (world == null || !Settings.IMP.HISTORY.USE_DISK) { if (world == null || !Settings.settings().HISTORY.USE_DISK) {
return; return;
} }
File file = MainUtil.getFile( File file = MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HISTORY + File.separator + world.getName() + File.separator + uuid + File.separator + "index" Settings.settings().PATHS.HISTORY + File.separator + world.getName() + File.separator + uuid + File.separator + "index"
); );
if (getHistoryNegativeIndex() != 0) { if (getHistoryNegativeIndex() != 0) {
try { try {
@ -450,8 +450,8 @@ public class LocalSession implements TextureHolder {
} }
if (o instanceof Integer) { if (o instanceof Integer) {
File folder = MainUtil.getFile( File folder = MainUtil.getFile(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HISTORY + File.separator + currentWorld.getName() + File.separator + uuid Settings.settings().PATHS.HISTORY + File.separator + currentWorld.getName() + File.separator + uuid
); );
File specific = new File(folder, o.toString()); File specific = new File(folder, o.toString());
if (specific.isDirectory()) { if (specific.isDirectory()) {
@ -467,7 +467,7 @@ public class LocalSession implements TextureHolder {
public void remember(Identifiable player, World world, ChangeSet changeSet, FaweLimit limit) { public void remember(Identifiable player, World world, ChangeSet changeSet, FaweLimit limit) {
historyWriteLock.lock(); historyWriteLock.lock();
try { try {
if (Settings.IMP.HISTORY.USE_DISK) { if (Settings.settings().HISTORY.USE_DISK) {
LocalSession.MAX_HISTORY_SIZE = Integer.MAX_VALUE; LocalSession.MAX_HISTORY_SIZE = Integer.MAX_VALUE;
} }
if (changeSet.size() == 0) { if (changeSet.size() == 0) {
@ -500,7 +500,7 @@ public class LocalSession implements TextureHolder {
} }
if (limit != null) { if (limit != null) {
int limitMb = limit.MAX_HISTORY; int limitMb = limit.MAX_HISTORY;
while (((!Settings.IMP.HISTORY.USE_DISK && history.size() > MAX_HISTORY_SIZE) || (historySize >> 20) > limitMb) && history while (((!Settings.settings().HISTORY.USE_DISK && history.size() > MAX_HISTORY_SIZE) || (historySize >> 20) > limitMb) && history
.size() > 1) { .size() > 1) {
ChangeSet item = (ChangeSet) history.remove(0); ChangeSet item = (ChangeSet) history.remove(0);
item.delete(); item.delete();
@ -516,7 +516,7 @@ public class LocalSession implements TextureHolder {
public void remember(EditSession editSession, boolean append, int limitMb) { public void remember(EditSession editSession, boolean append, int limitMb) {
historyWriteLock.lock(); historyWriteLock.lock();
try { try {
if (Settings.IMP.HISTORY.USE_DISK) { if (Settings.settings().HISTORY.USE_DISK) {
LocalSession.MAX_HISTORY_SIZE = Integer.MAX_VALUE; LocalSession.MAX_HISTORY_SIZE = Integer.MAX_VALUE;
} }
// It should have already been flushed, but just in case! // It should have already been flushed, but just in case!
@ -564,7 +564,7 @@ public class LocalSession implements TextureHolder {
} else { } else {
history.add(0, changeSet); history.add(0, changeSet);
} }
while (((!Settings.IMP.HISTORY.USE_DISK && history.size() > MAX_HISTORY_SIZE) || (historySize >> 20) > limitMb) && history while (((!Settings.settings().HISTORY.USE_DISK && history.size() > MAX_HISTORY_SIZE) || (historySize >> 20) > limitMb) && history
.size() > 1) { .size() > 1) {
ChangeSet item = (ChangeSet) history.remove(0); ChangeSet item = (ChangeSet) history.remove(0);
item.delete(); item.delete();
@ -1146,7 +1146,7 @@ public class LocalSession implements TextureHolder {
@Nullable @Nullable
public Tool getTool(Player player) { public Tool getTool(Player player) {
loadDefaults(player, false); loadDefaults(player, false);
if (!Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES && tools.isEmpty()) { if (!Settings.settings().EXPERIMENTAL.PERSISTENT_BRUSHES && tools.isEmpty()) {
return null; return null;
} }
BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); BaseItem item = player.getItemInHand(HandSide.MAIN_HAND);
@ -1157,7 +1157,7 @@ public class LocalSession implements TextureHolder {
public Tool getTool(BaseItem item, Player player) { public Tool getTool(BaseItem item, Player player) {
loadDefaults(player, false); loadDefaults(player, false);
if (Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES && item.getNativeItem() != null) { if (Settings.settings().EXPERIMENTAL.PERSISTENT_BRUSHES && item.getNativeItem() != null) {
BrushTool tool = BrushCache.getTool(player, this, item); BrushTool tool = BrushCache.getTool(player, this, item);
if (tool != null) { if (tool != null) {
return tool; return tool;
@ -1303,7 +1303,7 @@ public class LocalSession implements TextureHolder {
} }
Tool previous; Tool previous;
if (player != null && (tool instanceof BrushTool || tool == null) && Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES && item.getNativeItem() != null) { if (player != null && (tool instanceof BrushTool || tool == null) && Settings.settings().EXPERIMENTAL.PERSISTENT_BRUSHES && item.getNativeItem() != null) {
previous = BrushCache.getCachedTool(item); previous = BrushCache.getCachedTool(item);
BrushCache.setTool(item, (BrushTool) tool); BrushCache.setTool(item, (BrushTool) tool);
if (tool != null) { if (tool != null) {
@ -1782,7 +1782,7 @@ public class LocalSession implements TextureHolder {
TextureUtil tmp = texture; TextureUtil tmp = texture;
if (tmp == null) { if (tmp == null) {
synchronized (this) { synchronized (this) {
tmp = Fawe.get().getCachedTextureUtil(true, 0, 100); tmp = Fawe.instance().getCachedTextureUtil(true, 0, 100);
this.texture = tmp; this.texture = tmp;
} }
} }

View File

@ -860,8 +860,8 @@ public class BrushCommands {
} }
String filenamePng = filename.endsWith(".png") ? filename : filename + ".png"; String filenamePng = filename.endsWith(".png") ? filename : filename + ".png";
File file = new File( File file = new File(
Fawe.imp().getDirectory(), Fawe.platform().getDirectory(),
Settings.IMP.PATHS.HEIGHTMAP + File.separator + filenamePng Settings.settings().PATHS.HEIGHTMAP + File.separator + filenamePng
); );
if (file.exists()) { if (file.exists()) {
return new FileInputStream(file); return new FileInputStream(file);
@ -936,7 +936,7 @@ public class BrushCommands {
if (tool != null) { if (tool != null) {
root |= name.startsWith("../"); root |= name.startsWith("../");
name = FileSystems.getDefault().getPath(name).getFileName().toString(); name = FileSystems.getDefault().getPath(name).getFileName().toString();
File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); File folder = MainUtil.getFile(Fawe.platform().getDirectory(), "brushes");
name = name.endsWith(".jsgz") ? name : name + ".jsgz"; name = name.endsWith(".jsgz") ? name : name + ".jsgz";
File file; File file;
if (root && player.hasPermission("worldedit.brush.save.other")) { if (root && player.hasPermission("worldedit.brush.save.other")) {
@ -971,7 +971,7 @@ public class BrushCommands {
public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name) public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name)
throws WorldEditException, IOException { throws WorldEditException, IOException {
name = FileSystems.getDefault().getPath(name).getFileName().toString(); name = FileSystems.getDefault().getPath(name).getFileName().toString();
File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); File folder = MainUtil.getFile(Fawe.platform().getDirectory(), "brushes");
name = name.endsWith(".jsgz") ? name : name + ".jsgz"; name = name.endsWith(".jsgz") ? name : name + ".jsgz";
File file = new File(folder, player.getUniqueId() + File.separator + name); File file = new File(folder, player.getUniqueId() + File.separator + name);
if (!file.exists()) { if (!file.exists()) {
@ -1006,7 +1006,7 @@ public class BrushCommands {
int page int page
) throws WorldEditException { ) throws WorldEditException {
String baseCmd = "/brush loadbrush"; String baseCmd = "/brush loadbrush";
File dir = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); File dir = MainUtil.getFile(Fawe.platform().getDirectory(), "brushes");
// TODO NOT IMPLEMENTED // TODO NOT IMPLEMENTED
// UtilityCommands.list(dir, actor, args, page, null, true, baseCmd); // UtilityCommands.list(dir, actor, args, page, null, true, baseCmd);
} }
@ -1310,7 +1310,7 @@ public class BrushCommands {
worldEdit.checkMaxBrushRadius(radius); worldEdit.checkMaxBrushRadius(radius);
//FAWE start //FAWE start
FaweLimit limit = Settings.IMP.getLimit(player); FaweLimit limit = Settings.settings().getLimit(player);
iterations = Math.min(limit.MAX_ITERATIONS, iterations); iterations = Math.min(limit.MAX_ITERATIONS, iterations);
//FAWE end //FAWE end
@ -1345,7 +1345,7 @@ public class BrushCommands {
worldEdit.checkMaxBrushRadius(radius); worldEdit.checkMaxBrushRadius(radius);
//FAWE start //FAWE start
FaweLimit limit = Settings.IMP.getLimit(player); FaweLimit limit = Settings.settings().getLimit(player);
iterations = Math.min(limit.MAX_ITERATIONS, iterations); iterations = Math.min(limit.MAX_ITERATIONS, iterations);
//FAWE end //FAWE end

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