Remove FAWE-Piston

Disables a lot of previous functionality in FAWE until replacements can be made. This commit was untested and may cause major issues.
This commit is contained in:
MattBDev 2020-02-05 00:37:42 -05:00
parent 3452fd5a63
commit 75653087b9
46 changed files with 3643 additions and 3867 deletions

View File

@ -8,18 +8,6 @@ plugins {
repositories {
jcenter()
gradlePluginPortal()
// maven {
// name = "Forge Maven"
// url = uri("https://files.minecraftforge.net/maven")
// }
// maven {
// name = "Fabric"
// url = uri("https://maven.fabricmc.net/")
// }
// maven {
// name = "sponge"
// url = uri("https://repo.spongepowered.org/maven")
// }
}
configurations.all {
@ -43,15 +31,10 @@ val mixinVersion: String = properties.getProperty("mixin.version")
dependencies {
implementation(gradleApi())
// implementation("gradle.plugin.net.minecrell:licenser:0.4.1")
implementation("org.ajoberstar.grgit:grgit-gradle:3.1.1")
implementation("com.github.jengelman.gradle.plugins:shadow:5.1.0")
implementation("net.ltgt.apt-eclipse:net.ltgt.apt-eclipse.gradle.plugin:0.21")
implementation("net.ltgt.apt-idea:net.ltgt.apt-idea.gradle.plugin:0.21")
implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.9.7")
// implementation("gradle.plugin.org.spongepowered:spongegradle:0.9.0")
// implementation("net.minecraftforge.gradle:ForgeGradle:3.0.143")
// implementation("net.fabricmc:fabric-loom:$loomVersion")
// implementation("net.fabricmc:sponge-mixin:$mixinVersion")
implementation("gradle.plugin.com.mendhak.gradlecrowdin:plugin:0.1.0")
}

View File

@ -13,7 +13,6 @@ fun Project.applyCommonConfiguration() {
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") }
maven { url = uri("http://empcraft.com/maven2") }
maven { url = uri("https://repo.destroystokyo.com/repository/maven-public") }
maven { url = uri("https://ci.athion.net/job/FAWE-Piston/ws/") }
ivy { url = uri("https://ci.athion.net/job")
patternLayout {
artifact("/[organisation]/[revision]/artifact/[module].[ext]")

View File

@ -3,7 +3,7 @@ import org.gradle.api.Project
object Versions {
const val TEXT = "3.0.1"
const val TEXT_EXTRAS = "3.0.2"
const val PISTON = "0.5.3-SNAPSHOT"
const val PISTON = "0.5.2"
const val AUTO_VALUE = "1.6.5"
const val JUNIT = "5.5.0"
const val MOCKITO = "3.0.0"

View File

@ -2,7 +2,6 @@ package com.boydti.fawe.bukkit.listener;
import com.boydti.fawe.beta.IQueueExtent;
import com.boydti.fawe.bukkit.util.image.BukkitImageViewer;
import com.boydti.fawe.command.CFICommands;
import com.boydti.fawe.object.brush.BrushSettings;
import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator;
import com.boydti.fawe.util.EditSessionBuilder;
@ -57,31 +56,32 @@ public class BukkitImageListener implements Listener {
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerInteractEntity(AsyncPlayerChatEvent event) {
Set<Player> recipients = event.getRecipients();
Iterator<Player> iter = recipients.iterator();
while (iter.hasNext()) {
Player player = iter.next();
BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player);
CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings");
if (player.equals(event.getPlayer()) || !bukkitPlayer.hasMeta() || settings == null || !settings.hasGenerator()) {
continue;
}
String name = player.getName().toLowerCase();
if (!event.getMessage().toLowerCase().contains(name)) {
ArrayDeque<String> buffered = bukkitPlayer.getMeta("CFIBufferedMessages");
if (buffered == null) {
bukkitPlayer.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>());
}
String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(),
event.getMessage());
buffered.add(full);
iter.remove();
}
}
}
//TODO Fix along with CFI code 2020-02-04
// @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
// public void onPlayerInteractEntity(AsyncPlayerChatEvent event) {
// Set<Player> recipients = event.getRecipients();
// Iterator<Player> iter = recipients.iterator();
// while (iter.hasNext()) {
// Player player = iter.next();
// BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player);
// CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings");
// if (player.equals(event.getPlayer()) || !bukkitPlayer.hasMeta() || settings == null || !settings.hasGenerator()) {
// continue;
// }
//
// String name = player.getName().toLowerCase();
// if (!event.getMessage().toLowerCase().contains(name)) {
// ArrayDeque<String> buffered = bukkitPlayer.getMeta("CFIBufferedMessages");
// if (buffered == null) {
// bukkitPlayer.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>());
// }
// String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(),
// event.getMessage());
// buffered.add(full);
// iter.remove();
// }
// }
// }
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onHangingBreakByEntity(HangingBreakByEntityEvent event) {
@ -184,126 +184,127 @@ public class BukkitImageListener implements Listener {
}
private void handleInteract(Event event, Player player, Entity entity, boolean primary) {
if (!(entity instanceof ItemFrame)) {
return;
}
ItemFrame itemFrame = (ItemFrame) entity;
BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player);
CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings");
HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator();
BukkitImageViewer viewer = get(generator);
if (viewer == null) {
return;
}
if (itemFrame.getRotation() != Rotation.NONE) {
itemFrame.setRotation(Rotation.NONE);
}
LocalSession session = bukkitPlayer.getSession();
BrushTool tool;
try {
tool = session.getBrushTool(bukkitPlayer, false);
} catch (InvalidToolBindException e) {
return;
}
ItemFrame[][] frames = viewer.getItemFrames();
if (frames == null || tool == null) {
viewer.selectFrame(itemFrame);
player.updateInventory();
TaskManager.IMP.laterAsync(() -> viewer.view(generator), 1);
return;
}
BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary();
Brush brush = context.getBrush();
if (brush == null) {
return;
}
tool.setContext(context);
if (event instanceof Cancellable) {
((Cancellable) event).setCancelled(true);
}
Location target = itemFrame.getLocation();
Location source = player.getLocation();
double yawRad = Math.toRadians(source.getYaw() + 90d);
double pitchRad = Math.toRadians(-source.getPitch());
double a = Math.cos(pitchRad);
double xRat = Math.cos(yawRad) * a;
double zRat = Math.sin(yawRad) * a;
BlockFace facing = itemFrame.getFacing();
double thickness = 1 / 32D + 1 / 128D;
double modX = facing.getModX();
double modZ = facing.getModZ();
double dx = source.getX() - target.getX() - modX * thickness;
double dy = source.getY() + player.getEyeHeight() - target.getY();
double dz = source.getZ() - target.getZ() - modZ * thickness;
double offset;
double localX;
if (modX != 0) {
offset = dx / xRat;
localX = (-modX) * (dz - offset * zRat);
} else {
offset = dz / zRat;
localX = (modZ) * (dx - offset * xRat);
}
double localY = dy - offset * Math.sin(pitchRad);
int localPixelX = (int) ((localX + 0.5) * 128);
int localPixelY = (int) ((localY + 0.5) * 128);
UUID uuid = itemFrame.getUniqueId();
for (int blockX = 0; blockX < frames.length; blockX++) {
for (int blockY = 0; blockY < frames[0].length; blockY++) {
if (uuid.equals(frames[blockX][blockY].getUniqueId())) {
int pixelX = localPixelX + blockX * 128;
int pixelY = (128 * frames[0].length) - (localPixelY + blockY * 128 + 1);
int width = generator.getWidth();
int length = generator.getLength();
int worldX = (int) (pixelX * width / (frames.length * 128d));
int worldZ = (int) (pixelY * length / (frames[0].length * 128d));
if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) {
return;
}
bukkitPlayer.runAction(() -> {
BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ);
viewer.refresh();
int topY = generator
.getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255,
0, 255);
wPos = wPos.withY(topY);
EditSession es = new EditSessionBuilder(bukkitPlayer.getWorld()).player(bukkitPlayer)
.combineStages(false).autoQueue(false).blockBag(null).limitUnlimited()
.build();
ExtentTraverser last = new ExtentTraverser(es.getExtent()).last();
Extent extent = last.get();
if (extent instanceof IQueueExtent) {
last = last.previous();
}
last.setNext(generator);
try {
brush.build(es, wPos, context.getMaterial(), context.getSize());
} catch (WorldEditException e) {
e.printStackTrace();
}
es.flushQueue();
viewer.view(generator);
}, true, true);
return;
}
}
}
//todo fix with cfi code 2020-02-04
// if (!(entity instanceof ItemFrame)) {
// return;
// }
// ItemFrame itemFrame = (ItemFrame) entity;
//
// BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player);
// CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings");
// HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator();
// BukkitImageViewer viewer = get(generator);
// if (viewer == null) {
// return;
// }
//
// if (itemFrame.getRotation() != Rotation.NONE) {
// itemFrame.setRotation(Rotation.NONE);
// }
//
// LocalSession session = bukkitPlayer.getSession();
// BrushTool tool;
// try {
// tool = session.getBrushTool(bukkitPlayer, false);
// } catch (InvalidToolBindException e) {
// return;
// }
//
// ItemFrame[][] frames = viewer.getItemFrames();
// if (frames == null || tool == null) {
// viewer.selectFrame(itemFrame);
// player.updateInventory();
// TaskManager.IMP.laterAsync(() -> viewer.view(generator), 1);
// return;
// }
//
// BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary();
// Brush brush = context.getBrush();
// if (brush == null) {
// return;
// }
// tool.setContext(context);
//
// if (event instanceof Cancellable) {
// ((Cancellable) event).setCancelled(true);
// }
//
// Location target = itemFrame.getLocation();
// Location source = player.getLocation();
//
// double yawRad = Math.toRadians(source.getYaw() + 90d);
// double pitchRad = Math.toRadians(-source.getPitch());
//
// double a = Math.cos(pitchRad);
// double xRat = Math.cos(yawRad) * a;
// double zRat = Math.sin(yawRad) * a;
//
// BlockFace facing = itemFrame.getFacing();
// double thickness = 1 / 32D + 1 / 128D;
// double modX = facing.getModX();
// double modZ = facing.getModZ();
// double dx = source.getX() - target.getX() - modX * thickness;
// double dy = source.getY() + player.getEyeHeight() - target.getY();
// double dz = source.getZ() - target.getZ() - modZ * thickness;
//
// double offset;
// double localX;
// if (modX != 0) {
// offset = dx / xRat;
// localX = (-modX) * (dz - offset * zRat);
// } else {
// offset = dz / zRat;
// localX = (modZ) * (dx - offset * xRat);
// }
// double localY = dy - offset * Math.sin(pitchRad);
// int localPixelX = (int) ((localX + 0.5) * 128);
// int localPixelY = (int) ((localY + 0.5) * 128);
//
// UUID uuid = itemFrame.getUniqueId();
// for (int blockX = 0; blockX < frames.length; blockX++) {
// for (int blockY = 0; blockY < frames[0].length; blockY++) {
// if (uuid.equals(frames[blockX][blockY].getUniqueId())) {
// int pixelX = localPixelX + blockX * 128;
// int pixelY = (128 * frames[0].length) - (localPixelY + blockY * 128 + 1);
//
// int width = generator.getWidth();
// int length = generator.getLength();
// int worldX = (int) (pixelX * width / (frames.length * 128d));
// int worldZ = (int) (pixelY * length / (frames[0].length * 128d));
//
// if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) {
// return;
// }
//
// bukkitPlayer.runAction(() -> {
// BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ);
// viewer.refresh();
// int topY = generator
// .getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255,
// 0, 255);
// wPos = wPos.withY(topY);
//
// EditSession es = new EditSessionBuilder(bukkitPlayer.getWorld()).player(bukkitPlayer)
// .combineStages(false).autoQueue(false).blockBag(null).limitUnlimited()
// .build();
// ExtentTraverser last = new ExtentTraverser(es.getExtent()).last();
// Extent extent = last.get();
// if (extent instanceof IQueueExtent) {
// last = last.previous();
// }
// last.setNext(generator);
// try {
// brush.build(es, wPos, context.getMaterial(), context.getSize());
// } catch (WorldEditException e) {
// e.printStackTrace();
// }
// es.flushQueue();
// viewer.view(generator);
// }, true, true);
//
// return;
// }
// }
// }
}
}

View File

@ -1,7 +1,6 @@
package com.boydti.fawe.bukkit.listener;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.command.CFICommands;
import com.boydti.fawe.object.RunnableVal3;
import com.boydti.fawe.object.brush.visualization.VirtualWorld;
import com.comphenix.protocol.PacketType;
@ -262,10 +261,10 @@ public class CFIPacketListener implements Listener {
BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player);
VirtualWorld vw = bukkitPlayer.getSession().getVirtualWorld();
if (vw != null) return vw;
CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings");
if (settings != null && settings.hasGenerator() && settings.getGenerator().hasPacketViewer()) {
return settings.getGenerator();
}
// CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings");
// if (settings != null && settings.hasGenerator() && settings.getGenerator().hasPacketViewer()) {
// return settings.getGenerator();
// }
return null;
}

View File

@ -15,7 +15,6 @@ import com.boydti.fawe.util.TextureUtil;
import com.boydti.fawe.util.WEManager;
import com.github.luben.zstd.util.Native;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.factory.DefaultTransformParser;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.session.request.Request;
import java.io.BufferedReader;
@ -92,7 +91,8 @@ public class Fawe {
private FaweVersion version;
private VisualQueue visualQueue;
private TextureUtil textures;
private DefaultTransformParser transformParser;
// TODO: Ping @MattBDev to reimplement 2020-02-04
// private DefaultTransformParser transformParser;
private QueueHandler queueHandler;
@ -184,7 +184,8 @@ public class Fawe {
// Delayed worldedit setup
TaskManager.IMP.later(() -> {
try {
transformParser = new DefaultTransformParser(getWorldEdit());
// TODO: Ping @MattBDev to reimplement 2020-02-04
// transformParser = new DefaultTransformParser(getWorldEdit());
visualQueue = new VisualQueue(3);
WEManager.IMP.managers.addAll(Fawe.this.IMP.getMaskManagers());
WEManager.IMP.managers.add(new PlotSquaredFeature());
@ -208,10 +209,11 @@ public class Fawe {
}
return queueHandler;
}
public DefaultTransformParser getTransformParser() {
return transformParser;
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// public DefaultTransformParser getTransformParser() {
// return transformParser;
// }
public TextureUtil getCachedTextureUtil(boolean randomize, int min, int max) {
// TODO NOT IMPLEMENTED - optimize this by caching the default true/0/100 texture util

View File

@ -1,88 +1,89 @@
package com.boydti.fawe.command;
import static com.sk89q.worldedit.util.formatting.text.TextComponent.newline;
import com.boydti.fawe.command.CFICommands.CFISettings;
import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator;
import com.boydti.fawe.object.changeset.CFIChangeSet;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.Key;
public class CFICommand extends CommandProcessor<Object, Object> {
public CFICommand(CommandManager manager) {
super(manager);
}
@Override
public List<String> preprocess(InjectedValueAccess context, List<String> args) {
Player player = context.injectedValue(Key.of(Player.class)).orElseThrow(() -> new IllegalStateException("No player"));
CFICommands.CFISettings settings = CFICommands.getSettings(player);
settings.popMessages(player);
args = dispatch(player, settings, args, context);
HeightMapMCAGenerator gen = settings.getGenerator();
if (gen != null && gen.isModified()) {
try {
gen.update();
CFIChangeSet set = new CFIChangeSet(gen, player.getUniqueId());
LocalSession session = player.getSession();
session.remember(player, gen, set, player.getLimit());
} catch (IOException e) {
throw new StopExecutionException(TextComponent.of(e.getMessage()));
}
}
return args;
}
@Override
public Object process(InjectedValueAccess context, List<String> args, Object result) {
return result;
}
private List<String> dispatch(Player player, CFISettings settings, List<String> args, InjectedValueAccess context) {
if (!settings.hasGenerator()) {
if (args.size() == 0) {
String hmCmd = "/cfi ";
if (settings.image == null) {
hmCmd += "image";
} else {
hmCmd = "heightmap" + " " + settings.imageArg;
}
TextComponent build = TextComponent.builder("What do you want to use as the base?")
.append(newline())
.append("[HeightMap]")/* TODO .cmdTip(hmCmd).*/.append(" - A heightmap like ")
.append("[this]")//TODO .linkTip("http://i.imgur.com/qCd30MR.jpg")
.append(newline())
.append("[Empty]")//TODO .cmdTip(CFICommands.alias() + " empty")
.append("- An empty map of a specific size").build();
player.print(build);
} else {
args = new ArrayList<>(args);
switch (args.size()) {
case 1:
args.add(0, "heightmap");
break;
case 2:
args.add(0, "empty");
break;
}
return args;
}
} else {
if (args.isEmpty()) {
settings.setCategory(null);
CFICommands.mainMenu(player);
return null;
}
}
return args;
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
//package com.boydti.fawe.command;
//
//import static com.sk89q.worldedit.util.formatting.text.TextComponent.newline;
//
//import com.boydti.fawe.command.CFICommands.CFISettings;
//import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator;
//import com.boydti.fawe.object.changeset.CFIChangeSet;
//import com.sk89q.worldedit.LocalSession;
//import com.sk89q.worldedit.entity.Player;
//import com.sk89q.worldedit.util.formatting.text.TextComponent;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//import org.enginehub.piston.CommandManager;
//import org.enginehub.piston.exception.StopExecutionException;
//import org.enginehub.piston.inject.InjectedValueAccess;
//import org.enginehub.piston.inject.Key;
//
//public class CFICommand extends CommandProcessor<Object, Object> {
//
// public CFICommand(CommandManager manager) {
// super(manager);
// }
//
// @Override
// public List<String> preprocess(InjectedValueAccess context, List<String> args) {
// Player player = context.injectedValue(Key.of(Player.class)).orElseThrow(() -> new IllegalStateException("No player"));
// CFICommands.CFISettings settings = CFICommands.getSettings(player);
// settings.popMessages(player);
// args = dispatch(player, settings, args, context);
// HeightMapMCAGenerator gen = settings.getGenerator();
// if (gen != null && gen.isModified()) {
// try {
// gen.update();
// CFIChangeSet set = new CFIChangeSet(gen, player.getUniqueId());
// LocalSession session = player.getSession();
// session.remember(player, gen, set, player.getLimit());
// } catch (IOException e) {
// throw new StopExecutionException(TextComponent.of(e.getMessage()));
// }
// }
// return args;
// }
//
// @Override
// public Object process(InjectedValueAccess context, List<String> args, Object result) {
// return result;
// }
//
// private List<String> dispatch(Player player, CFISettings settings, List<String> args, InjectedValueAccess context) {
// if (!settings.hasGenerator()) {
// if (args.size() == 0) {
// String hmCmd = "/cfi ";
// if (settings.image == null) {
// hmCmd += "image";
// } else {
// hmCmd = "heightmap" + " " + settings.imageArg;
// }
// TextComponent build = TextComponent.builder("What do you want to use as the base?")
// .append(newline())
// .append("[HeightMap]")/* TODO .cmdTip(hmCmd).*/.append(" - A heightmap like ")
// .append("[this]")//TODO .linkTip("http://i.imgur.com/qCd30MR.jpg")
// .append(newline())
// .append("[Empty]")//TODO .cmdTip(CFICommands.alias() + " empty")
// .append("- An empty map of a specific size").build();
// player.print(build);
// } else {
// args = new ArrayList<>(args);
// switch (args.size()) {
// case 1:
// args.add(0, "heightmap");
// break;
// case 2:
// args.add(0, "empty");
// break;
// }
// return args;
// }
// } else {
// if (args.isEmpty()) {
// settings.setCategory(null);
// CFICommands.mainMenu(player);
// return null;
// }
// }
// return args;
// }
//}

View File

@ -1,93 +0,0 @@
package com.boydti.fawe.command;
import com.google.common.collect.ImmutableSet;
import org.enginehub.piston.Command;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.CommandParseResult;
import org.enginehub.piston.converter.ArgumentConverter;
import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.suggestion.Suggestion;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;
public abstract class CommandProcessor<I, O> implements CommandManager {
private final CommandManager parent;
public CommandProcessor(CommandManager parent) {
this.parent = parent;
}
@Override
public final Command.Builder newCommand(String s) {
return parent.newCommand(s);
}
@Override
public final void register(Command command) {
parent.register(command);
}
@Override
public final void register(String name, Consumer<Command.Builder> registrationProcess) {
parent.register(name, registrationProcess);
}
@Override
public final void registerManager(CommandManager manager) {
parent.registerManager(manager);
}
@Override
public final Stream<Command> getAllCommands() {
return parent.getAllCommands();
}
@Override
public final boolean containsCommand(String name) {
return parent.containsCommand(name);
}
@Override
public final Optional<Command> getCommand(String s) {
return parent.getCommand(s);
}
@Override
public final ImmutableSet<Suggestion> getSuggestions(InjectedValueAccess injectedValueAccess, List<String> list) {
return parent.getSuggestions(injectedValueAccess, list);
}
@Override
public final CommandParseResult parse(InjectedValueAccess injectedValueAccess, List<String> list) {
return parent.parse(injectedValueAccess, list);
}
@Override
public final Object execute(InjectedValueAccess context, List<String> args) {
args = preprocess(context, args);
if (args != null) {
Object result = parent.execute(context, args);
return process(context, args, result); // TODO NOT IMPLEMENTED (recompile piston)
} else {
return null;
}
}
@Override
public final <T> void registerConverter(Key<T> key, ArgumentConverter<T> argumentConverter) {
parent.registerConverter(key, argumentConverter);
}
@Override
public final <T> Optional<ArgumentConverter<T>> getConverter(Key<T> key) {
return parent.getConverter(key);
}
public abstract List<String> preprocess(InjectedValueAccess context, List<String> args);
public abstract Object process(InjectedValueAccess context, List<String> args, Object result);
}

View File

@ -1,113 +1,114 @@
package com.boydti.fawe.command;
import com.boydti.fawe.util.StringMan;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.internal.registry.InputParser;
import org.enginehub.piston.inject.InjectedValueAccess;
import java.util.*;
public abstract class FaweParser<T> extends InputParser<T> {
private final String prefix;
protected FaweParser(WorldEdit worldEdit, String prefix) {
super(worldEdit);
this.prefix = prefix;
}
public PlatformCommandManager getPlatform() {
return PlatformCommandManager.getInstance();
}
public T parse(String input, ParserContext context) {
input = prefix + " " + input;
InjectedValueAccess injected = context.getInjected();
if (injected != null) {
return getPlatform().parseCommand(input, injected);
} else {
return getPlatform().parseCommand(input, context.getActor());
}
}
public T catchSuggestion(String currentInput, String nextInput, ParserContext context) throws InputParseException {
try {
return parseFromInput(nextInput, context);
} catch (SuggestInputParseException e) {
e.prepend(currentInput.substring(0, currentInput.length() - nextInput.length()));
throw e;
}
}
protected static class ParseEntry {
public boolean and;
public String input;
public String full;
public ParseEntry(String full, String input, boolean type) {
this.full = full;
this.input = input;
this.and = type;
}
@Override
public String toString() {
return input + " | " + and;
}
}
public static List<Map.Entry<ParseEntry, List<String>>> parse(String toParse) throws InputParseException {
List<Map.Entry<ParseEntry, List<String>>> keys = new ArrayList<>();
List<String> inputs = new ArrayList<>();
List<Boolean> and = new ArrayList<>();
int last = 0;
outer:
for (int i = 0; i < toParse.length(); i++) {
char c = toParse.charAt(i);
switch (c) {
case ',':
case '&':
String result = toParse.substring(last, i);
if (!result.isEmpty()) {
inputs.add(result);
and.add(c == '&');
} else {
throw new InputParseException("Invalid dangling character " + c);
}
last = i + 1;
continue outer;
default:
if (c == '[' && StringMan.getMatchingBracket(c) != c) {
int next = StringMan.findMatchingBracket(toParse, i);
if (next != -1) {
i = next;
} else {
toParse += "]";
i = toParse.length();
}
continue outer;
}
}
}
inputs.add(toParse.substring(last));
for (int i = 0; i < inputs.size(); i++) {
String full = inputs.get(i);
String command = full;
List<String> args = new ArrayList<>();
while (!command.isEmpty() && command.charAt(command.length() - 1) == ']') {
int startPos = StringMan.findMatchingBracket(command, command.length() - 1);
if (startPos == -1) break;
String arg = command.substring(startPos + 1, command.length() - 1);
args.add(arg);
command = full.substring(0, startPos);
}
Collections.reverse(args);
ParseEntry entry = new ParseEntry(full, command, i > 0 ? and.get(i - 1) : false);
keys.add(new AbstractMap.SimpleEntry<>(entry, args));
}
return keys;
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
//package com.boydti.fawe.command;
//
//import com.boydti.fawe.util.StringMan;
//import com.sk89q.worldedit.WorldEdit;
//import com.sk89q.worldedit.extension.input.InputParseException;
//import com.sk89q.worldedit.extension.input.ParserContext;
//import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
//import com.sk89q.worldedit.internal.registry.InputParser;
//import org.enginehub.piston.inject.InjectedValueAccess;
//
//import java.util.*;
//
//public abstract class FaweParser<T> extends InputParser<T> {
//
// private final String prefix;
//
// protected FaweParser(WorldEdit worldEdit, String prefix) {
// super(worldEdit);
// this.prefix = prefix;
// }
//
// public PlatformCommandManager getPlatform() {
// return PlatformCommandManager.getInstance();
// }
//
// public T parse(String input, ParserContext context) {
// input = prefix + " " + input;
// InjectedValueAccess injected = context.getInjected();
// if (injected != null) {
// return getPlatform().parseCommand(input, injected);
// } else {
// return getPlatform().parseCommand(input, context.getActor());
// }
// }
//
// public T catchSuggestion(String currentInput, String nextInput, ParserContext context) throws InputParseException {
// try {
// return parseFromInput(nextInput, context);
// } catch (SuggestInputParseException e) {
// e.prepend(currentInput.substring(0, currentInput.length() - nextInput.length()));
// throw e;
// }
// }
//
// protected static class ParseEntry {
// public boolean and;
// public String input;
// public String full;
//
// public ParseEntry(String full, String input, boolean type) {
// this.full = full;
// this.input = input;
// this.and = type;
// }
//
// @Override
// public String toString() {
// return input + " | " + and;
// }
// }
//
// public static List<Map.Entry<ParseEntry, List<String>>> parse(String toParse) throws InputParseException {
// List<Map.Entry<ParseEntry, List<String>>> keys = new ArrayList<>();
// List<String> inputs = new ArrayList<>();
// List<Boolean> and = new ArrayList<>();
// int last = 0;
// outer:
// for (int i = 0; i < toParse.length(); i++) {
// char c = toParse.charAt(i);
// switch (c) {
// case ',':
// case '&':
// String result = toParse.substring(last, i);
// if (!result.isEmpty()) {
// inputs.add(result);
// and.add(c == '&');
// } else {
// throw new InputParseException("Invalid dangling character " + c);
// }
// last = i + 1;
// continue outer;
// default:
// if (c == '[' && StringMan.getMatchingBracket(c) != c) {
// int next = StringMan.findMatchingBracket(toParse, i);
// if (next != -1) {
// i = next;
// } else {
// toParse += "]";
// i = toParse.length();
// }
// continue outer;
// }
// }
// }
// inputs.add(toParse.substring(last));
// for (int i = 0; i < inputs.size(); i++) {
// String full = inputs.get(i);
// String command = full;
// List<String> args = new ArrayList<>();
// while (!command.isEmpty() && command.charAt(command.length() - 1) == ']') {
// int startPos = StringMan.findMatchingBracket(command, command.length() - 1);
// if (startPos == -1) break;
// String arg = command.substring(startPos + 1, command.length() - 1);
// args.add(arg);
// command = full.substring(0, startPos);
// }
// Collections.reverse(args);
// ParseEntry entry = new ParseEntry(full, command, i > 0 ? and.get(i - 1) : false);
// keys.add(new AbstractMap.SimpleEntry<>(entry, args));
// }
// return keys;
// }
//}

View File

@ -1,82 +1,83 @@
package com.boydti.fawe.command;
import com.boydti.fawe.command.CFICommands.CFISettings;
import com.boydti.fawe.object.RunnableVal;
import com.boydti.fawe.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.commands.Auto;
import com.github.intellectualsites.plotsquared.plot.config.Captions;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager;
import com.sk89q.worldedit.extension.platform.Actor;
import java.io.File;
import java.io.IOException;
import java.util.function.Function;
public class PlotLoader {
@Deprecated
public static void autoClaimFromDatabase(PlotPlayer player, PlotArea area, PlotId start,
com.github.intellectualsites.plotsquared.plot.object.RunnableVal<Plot> whenDone) {
final Plot plot = area.getNextFreePlot(player, start);
if (plot == null) {
whenDone.run(null);
return;
}
whenDone.value = plot;
plot.owner = player.getUUID();
DBFunc.createPlotSafe(plot, whenDone,
() -> autoClaimFromDatabase(player, area, plot.getId(), whenDone));
}
public void load(Actor actor, CFISettings settings, Function<File, Boolean> createTask) throws IOException {
PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
if (manager instanceof SinglePlotAreaManager) {
SinglePlotAreaManager sManager = (SinglePlotAreaManager) manager;
SinglePlotArea area = sManager.getArea();
PlotPlayer player = PlotPlayer.get(actor.getName());
actor.print("Claiming world");
Plot plot = TaskManager.IMP.sync(new RunnableVal<Plot>() {
@Override
public void run(Plot o) {
int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount()
: player.getPlotCount(area.worldname);
int diff = player.getAllowedPlots() - currentPlots;
if (diff < 1) {
Captions.CANT_CLAIM_MORE_PLOTS_NUM.send(player, -diff);
return;
}
if (area.getMeta("lastPlot") == null) {
area.setMeta("lastPlot", new PlotId(0, 0));
}
PlotId lastId = (PlotId) area.getMeta("lastPlot");
do {
lastId = Auto.getNextPlotId(lastId, 1);
} while (!area.canClaim(player, lastId, lastId));
area.setMeta("lastPlot", lastId);
this.value = area.getPlot(lastId);
this.value.setOwner(player.getUUID());
}
});
if (plot != null) {
File folder = CFICommands.getFolder(plot.getWorldName());
Boolean result = createTask.apply(folder);
if (result == Boolean.TRUE) {
TaskManager.IMP.sync(() -> plot.teleportPlayer(player));
}
return;
}
}
createTask.apply(null);
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
//package com.boydti.fawe.command;
//
//import com.boydti.fawe.command.CFICommands.CFISettings;
//import com.boydti.fawe.object.RunnableVal;
//import com.boydti.fawe.util.TaskManager;
//import com.github.intellectualsites.plotsquared.plot.PlotSquared;
//import com.github.intellectualsites.plotsquared.plot.commands.Auto;
//import com.github.intellectualsites.plotsquared.plot.config.Captions;
//import com.github.intellectualsites.plotsquared.plot.config.Settings;
//import com.github.intellectualsites.plotsquared.plot.database.DBFunc;
//import com.github.intellectualsites.plotsquared.plot.object.Plot;
//import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
//import com.github.intellectualsites.plotsquared.plot.object.PlotId;
//import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
//import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager;
//import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea;
//import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager;
//import com.sk89q.worldedit.extension.platform.Actor;
//import java.io.File;
//import java.io.IOException;
//import java.util.function.Function;
//
//public class PlotLoader {
//
// @Deprecated
// public static void autoClaimFromDatabase(PlotPlayer player, PlotArea area, PlotId start,
// com.github.intellectualsites.plotsquared.plot.object.RunnableVal<Plot> whenDone) {
// final Plot plot = area.getNextFreePlot(player, start);
// if (plot == null) {
// whenDone.run(null);
// return;
// }
// whenDone.value = plot;
// plot.owner = player.getUUID();
// DBFunc.createPlotSafe(plot, whenDone,
// () -> autoClaimFromDatabase(player, area, plot.getId(), whenDone));
// }
//
// public void load(Actor actor, CFISettings settings, Function<File, Boolean> createTask) throws IOException {
// PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
// if (manager instanceof SinglePlotAreaManager) {
// SinglePlotAreaManager sManager = (SinglePlotAreaManager) manager;
// SinglePlotArea area = sManager.getArea();
// PlotPlayer player = PlotPlayer.get(actor.getName());
//
// actor.print("Claiming world");
// Plot plot = TaskManager.IMP.sync(new RunnableVal<Plot>() {
// @Override
// public void run(Plot o) {
// int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount()
// : player.getPlotCount(area.worldname);
// int diff = player.getAllowedPlots() - currentPlots;
// if (diff < 1) {
// Captions.CANT_CLAIM_MORE_PLOTS_NUM.send(player, -diff);
// return;
// }
//
// if (area.getMeta("lastPlot") == null) {
// area.setMeta("lastPlot", new PlotId(0, 0));
// }
// PlotId lastId = (PlotId) area.getMeta("lastPlot");
// do {
// lastId = Auto.getNextPlotId(lastId, 1);
// } while (!area.canClaim(player, lastId, lastId));
// area.setMeta("lastPlot", lastId);
// this.value = area.getPlot(lastId);
// this.value.setOwner(player.getUUID());
// }
// });
// if (plot != null) {
//
// File folder = CFICommands.getFolder(plot.getWorldName());
// Boolean result = createTask.apply(folder);
// if (result == Boolean.TRUE) {
// TaskManager.IMP.sync(() -> plot.teleportPlayer(player));
// }
// return;
// }
// }
// createTask.apply(null);
// }
//}

View File

@ -58,65 +58,66 @@ public class BrushSettings {
this.constructor.put(SettingType.PERMISSIONS, permissions);
}
public static BrushSettings get(BrushTool tool, Player player, LocalSession session, Map<String, Object> settings) throws InputParseException {
PlatformCommandManager manager = PlatformCommandManager.getInstance();
String constructor = (String) settings.get(SettingType.BRUSH.name());
if (constructor == null) {
return new BrushSettings();
}
BrushSettings bs = manager.parseCommand(constructor, player);
bs.constructor.put(SettingType.BRUSH, constructor);
if (settings.containsKey(SettingType.PERMISSIONS.name())) {
bs.permissions.addAll((Collection<? extends String>) settings.get(SettingType.PERMISSIONS.name()));
}
if (settings.containsKey(SettingType.SIZE.name())) {
try {
bs.size = Expression.compile((String) settings.getOrDefault(SettingType.SIZE.name(), -1));
bs.size.optimize();
} catch (ExpressionException e) {
throw new RuntimeException(e);
}
}
ParserContext parserContext = new ParserContext();
parserContext.setActor(player);
parserContext.setWorld(player.getWorld());
parserContext.setSession(session);
if (settings.containsKey(SettingType.MASK.name())) {
String maskArgs = (String) settings.get(SettingType.MASK.name());
Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext);
bs.setMask(mask);
bs.constructor.put(SettingType.MASK, maskArgs);
}
if (settings.containsKey(SettingType.SOURCE_MASK.name())) {
String maskArgs = (String) settings.get(SettingType.SOURCE_MASK.name());
Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext);
bs.setSourceMask(mask);
bs.constructor.put(SettingType.SOURCE_MASK, maskArgs);
}
if (settings.containsKey(SettingType.TRANSFORM.name())) {
String transformArgs = (String) settings.get(SettingType.TRANSFORM.name());
ResettableExtent extent = Fawe.get().getTransformParser().parseFromInput(transformArgs, parserContext);
bs.setTransform(extent);
bs.constructor.put(SettingType.TRANSFORM, transformArgs);
}
if (settings.containsKey(SettingType.FILL.name())) {
String fillArgs = (String) settings.get(SettingType.FILL.name());
Pattern pattern = WorldEdit.getInstance().getPatternFactory().parseFromInput(fillArgs, parserContext);
bs.setFill(pattern);
bs.constructor.put(SettingType.FILL, fillArgs);
}
if (settings.containsKey(SettingType.SCROLL_ACTION.name())) {
String actionArgs = (String) settings.get(SettingType.SCROLL_ACTION.name());
Scroll action = Scroll.fromArguments(tool, player, session, actionArgs, false);
if (action != null) {
bs.setScrollAction(action);
bs.constructor.put(SettingType.SCROLL_ACTION, actionArgs);
}
}
return bs;
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// public static BrushSettings get(BrushTool tool, Player player, LocalSession session, Map<String, Object> settings) throws InputParseException {
// PlatformCommandManager manager = PlatformCommandManager.getInstance();
// String constructor = (String) settings.get(SettingType.BRUSH.name());
// if (constructor == null) {
// return new BrushSettings();
// }
// BrushSettings bs = manager.parseCommand(constructor, player);
// bs.constructor.put(SettingType.BRUSH, constructor);
// if (settings.containsKey(SettingType.PERMISSIONS.name())) {
// bs.permissions.addAll((Collection<? extends String>) settings.get(SettingType.PERMISSIONS.name()));
// }
// if (settings.containsKey(SettingType.SIZE.name())) {
// try {
// bs.size = Expression.compile((String) settings.getOrDefault(SettingType.SIZE.name(), -1));
// bs.size.optimize();
// } catch (ExpressionException e) {
// throw new RuntimeException(e);
// }
// }
//
// ParserContext parserContext = new ParserContext();
// parserContext.setActor(player);
// parserContext.setWorld(player.getWorld());
// parserContext.setSession(session);
//
// if (settings.containsKey(SettingType.MASK.name())) {
// String maskArgs = (String) settings.get(SettingType.MASK.name());
// Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext);
// bs.setMask(mask);
// bs.constructor.put(SettingType.MASK, maskArgs);
// }
// if (settings.containsKey(SettingType.SOURCE_MASK.name())) {
// String maskArgs = (String) settings.get(SettingType.SOURCE_MASK.name());
// Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext);
// bs.setSourceMask(mask);
// bs.constructor.put(SettingType.SOURCE_MASK, maskArgs);
// }
// if (settings.containsKey(SettingType.TRANSFORM.name())) {
// String transformArgs = (String) settings.get(SettingType.TRANSFORM.name());
// ResettableExtent extent = Fawe.get().getTransformParser().parseFromInput(transformArgs, parserContext);
// bs.setTransform(extent);
// bs.constructor.put(SettingType.TRANSFORM, transformArgs);
// }
// if (settings.containsKey(SettingType.FILL.name())) {
// String fillArgs = (String) settings.get(SettingType.FILL.name());
// Pattern pattern = WorldEdit.getInstance().getPatternFactory().parseFromInput(fillArgs, parserContext);
// bs.setFill(pattern);
// bs.constructor.put(SettingType.FILL, fillArgs);
// }
// if (settings.containsKey(SettingType.SCROLL_ACTION.name())) {
// String actionArgs = (String) settings.get(SettingType.SCROLL_ACTION.name());
// Scroll action = Scroll.fromArguments(tool, player, session, actionArgs, false);
// if (action != null) {
// bs.setScrollAction(action);
// bs.constructor.put(SettingType.SCROLL_ACTION, actionArgs);
// }
// }
// return bs;
// }
public BrushSettings setBrush(Brush brush) {
Brush tmp = this.brush;

View File

@ -41,23 +41,24 @@ public final class BrushCache {
CompoundTag nbt = item.getNbtData();
if (nbt == null) return null;
StringTag json = (StringTag) nbt.getValue().get("weBrushJson");
if (json != null) {
try {
if (RECURSION.get() != null) return null;
RECURSION.set(true);
BrushTool tool = BrushTool.fromString(player, session, json.getValue());
tool.setHolder(item);
brushCache.put(key, tool);
return tool;
} catch (Exception throwable) {
getLogger(BrushCache.class).debug("Invalid brush for " + player + " holding " + item.getType() + ": " + json.getValue(), throwable);
item.setNbtData(null);
brushCache.remove(key);
} finally {
RECURSION.remove();
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// if (json != null) {
// try {
// if (RECURSION.get() != null) return null;
// RECURSION.set(true);
//
// BrushTool tool = BrushTool.fromString(player, session, json.getValue());
// tool.setHolder(item);
// brushCache.put(key, tool);
// return tool;
// } catch (Exception throwable) {
// getLogger(BrushCache.class).debug("Invalid brush for " + player + " holding " + item.getType() + ": " + json.getValue(), throwable);
// item.setNbtData(null);
// brushCache.remove(key);
// } finally {
// RECURSION.remove();
// }
// }
return null;
}

View File

@ -155,6 +155,15 @@ public class BrushCommands {
this.worldEdit = worldEdit;
}
@Command(
name = "none",
aliases = "unbind",
desc = "Unbind a bound brush from your current item"
)
void none(Player player, LocalSession session) throws WorldEditException {
ToolCommands.setToolNone(player, session, true);
}
@Command(
name = "blendball",
aliases = {"bb", "blend"},
@ -984,38 +993,39 @@ public class BrushCommands {
}
}
@Command(
name = "loadbrush",
aliases = {"load"},
desc = "Load a brush"
)
@CommandPermissions("worldedit.brush.load")
public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name)
throws WorldEditException, IOException {
name = FileSystems.getDefault().getPath(name).getFileName().toString();
File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes");
name = name.endsWith(".jsgz") ? name : name + ".jsgz";
File file = new File(folder, player.getUniqueId() + File.separator + name);
if (!file.exists()) {
file = new File(folder, name);
}
if (!file.exists()) {
File[] files = folder.listFiles(pathname -> false);
player.print(Caption.of("fawe.error.brush.not.found" , name));
return;
}
try (DataInputStream in = new DataInputStream(
new GZIPInputStream(new FileInputStream(file)))) {
String json = in.readUTF();
BrushTool tool = BrushTool.fromString(player, session, json);
BaseItem item = player.getItemInHand(HandSide.MAIN_HAND);
session.setTool(item, tool, player);
player.print(Caption.of("fawe.worldedit.brush.brush.equipped" , name));
} catch (Throwable e) {
e.printStackTrace();
player.printError(TranslatableComponent.of("fawe.error.brush.incompatible"));
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// @Command(
// name = "loadbrush",
// aliases = {"load"},
// desc = "Load a brush"
// )
// @CommandPermissions("worldedit.brush.load")
// public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name)
// throws WorldEditException, IOException {
// name = FileSystems.getDefault().getPath(name).getFileName().toString();
// File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes");
// name = name.endsWith(".jsgz") ? name : name + ".jsgz";
// File file = new File(folder, player.getUniqueId() + File.separator + name);
// if (!file.exists()) {
// file = new File(folder, name);
// }
// if (!file.exists()) {
// File[] files = folder.listFiles(pathname -> false);
// player.print(Caption.of("fawe.error.brush.not.found" , name));
// return;
// }
// try (DataInputStream in = new DataInputStream(
// new GZIPInputStream(new FileInputStream(file)))) {
// String json = in.readUTF();
// BrushTool tool = BrushTool.fromString(player, session, json);
// BaseItem item = player.getItemInHand(HandSide.MAIN_HAND);
// session.setTool(item, tool, player);
// player.print(Caption.of("fawe.worldedit.brush.brush.equipped" , name));
// } catch (Throwable e) {
// e.printStackTrace();
// player.printError(TranslatableComponent.of("fawe.error.brush.incompatible"));
// }
// }
@Command(
name = "/listbrush",

View File

@ -1,448 +1,449 @@
package com.sk89q.worldedit.command;
import com.boydti.fawe.object.mask.AdjacentAnyMask;
import com.boydti.fawe.object.mask.AdjacentMask;
import com.boydti.fawe.object.mask.AngleMask;
import com.boydti.fawe.object.mask.BiomeMask;
import com.boydti.fawe.object.mask.BlockLightMask;
import com.boydti.fawe.object.mask.BrightnessMask;
import com.boydti.fawe.object.mask.DataMask;
import com.boydti.fawe.object.mask.ExtremaMask;
import com.boydti.fawe.object.mask.IdDataMask;
import com.boydti.fawe.object.mask.IdMask;
import com.boydti.fawe.object.mask.LightMask;
import com.boydti.fawe.object.mask.OpacityMask;
import com.boydti.fawe.object.mask.ROCAngleMask;
import com.boydti.fawe.object.mask.RadiusMask;
import com.boydti.fawe.object.mask.RandomMask;
import com.boydti.fawe.object.mask.SimplexMask;
import com.boydti.fawe.object.mask.SkyLightMask;
import com.boydti.fawe.object.mask.SurfaceMask;
import com.boydti.fawe.object.mask.WallMask;
import com.boydti.fawe.object.mask.XAxisMask;
import com.boydti.fawe.object.mask.YAxisMask;
import com.boydti.fawe.object.mask.ZAxisMask;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.mask.BlockMaskBuilder;
import com.sk89q.worldedit.function.mask.ExistingBlockMask;
import com.sk89q.worldedit.function.mask.ExpressionMask;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.MaskIntersection;
import com.sk89q.worldedit.function.mask.MaskUnion;
import com.sk89q.worldedit.function.mask.Masks;
import com.sk89q.worldedit.function.mask.OffsetMask;
import com.sk89q.worldedit.function.mask.RegionMask;
import com.sk89q.worldedit.function.mask.SolidBlockMask;
import com.sk89q.worldedit.internal.expression.Expression;
import com.sk89q.worldedit.internal.expression.ExpressionEnvironment;
import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment;
import com.sk89q.worldedit.session.request.RequestSelection;
import com.sk89q.worldedit.world.biome.BiomeType;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.Switch;
//@Command(aliases = {"masks"},
// desc = "Help for the various masks. [More Info](https://git.io/v9r4K)",
// descFooter = "Masks determine if a block can be placed\n" +
// " - Use [brackets] for arguments\n" +
// " - Use , to OR multiple\n" +
// " - Use & to AND multiple\n" +
// "e.g. >[stone,dirt],#light[0][5],$jungle\n" +
// "More Info: https://git.io/v9r4K"
// TODO: Ping @MattBDev to reimplement (or remove because this class is stupid) 2020-02-04
//package com.sk89q.worldedit.command;
//
//import com.boydti.fawe.object.mask.AdjacentAnyMask;
//import com.boydti.fawe.object.mask.AdjacentMask;
//import com.boydti.fawe.object.mask.AngleMask;
//import com.boydti.fawe.object.mask.BiomeMask;
//import com.boydti.fawe.object.mask.BlockLightMask;
//import com.boydti.fawe.object.mask.BrightnessMask;
//import com.boydti.fawe.object.mask.DataMask;
//import com.boydti.fawe.object.mask.ExtremaMask;
//import com.boydti.fawe.object.mask.IdDataMask;
//import com.boydti.fawe.object.mask.IdMask;
//import com.boydti.fawe.object.mask.LightMask;
//import com.boydti.fawe.object.mask.OpacityMask;
//import com.boydti.fawe.object.mask.ROCAngleMask;
//import com.boydti.fawe.object.mask.RadiusMask;
//import com.boydti.fawe.object.mask.RandomMask;
//import com.boydti.fawe.object.mask.SimplexMask;
//import com.boydti.fawe.object.mask.SkyLightMask;
//import com.boydti.fawe.object.mask.SurfaceMask;
//import com.boydti.fawe.object.mask.WallMask;
//import com.boydti.fawe.object.mask.XAxisMask;
//import com.boydti.fawe.object.mask.YAxisMask;
//import com.boydti.fawe.object.mask.ZAxisMask;
//import com.sk89q.worldedit.IncompleteRegionException;
//import com.sk89q.worldedit.LocalSession;
//import com.sk89q.worldedit.WorldEdit;
//import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
//import com.sk89q.worldedit.entity.Player;
//import com.sk89q.worldedit.extent.Extent;
//import com.sk89q.worldedit.function.mask.BlockMaskBuilder;
//import com.sk89q.worldedit.function.mask.ExistingBlockMask;
//import com.sk89q.worldedit.function.mask.ExpressionMask;
//import com.sk89q.worldedit.function.mask.Mask;
//import com.sk89q.worldedit.function.mask.MaskIntersection;
//import com.sk89q.worldedit.function.mask.MaskUnion;
//import com.sk89q.worldedit.function.mask.Masks;
//import com.sk89q.worldedit.function.mask.OffsetMask;
//import com.sk89q.worldedit.function.mask.RegionMask;
//import com.sk89q.worldedit.function.mask.SolidBlockMask;
//import com.sk89q.worldedit.internal.expression.Expression;
//import com.sk89q.worldedit.internal.expression.ExpressionEnvironment;
//import com.sk89q.worldedit.internal.expression.ExpressionException;
//import com.sk89q.worldedit.math.BlockVector3;
//import com.sk89q.worldedit.math.Vector3;
//import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment;
//import com.sk89q.worldedit.session.request.RequestSelection;
//import com.sk89q.worldedit.world.biome.BiomeType;
//import org.enginehub.piston.annotation.Command;
//import org.enginehub.piston.annotation.CommandContainer;
//import org.enginehub.piston.annotation.param.Arg;
//import org.enginehub.piston.annotation.param.Switch;
//
////@Command(aliases = {"masks"},
//// desc = "Help for the various masks. [More Info](https://git.io/v9r4K)",
//// descFooter = "Masks determine if a block can be placed\n" +
//// " - Use [brackets] for arguments\n" +
//// " - Use , to OR multiple\n" +
//// " - Use & to AND multiple\n" +
//// "e.g. >[stone,dirt],#light[0][5],$jungle\n" +
//// "More Info: https://git.io/v9r4K"
////)
//@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class)
//public class MaskCommands {
// private final WorldEdit worldEdit;
//
// public MaskCommands(WorldEdit worldEdit) {
// this.worldEdit = worldEdit;
// }
//
// @Command(
// name = "#simplex",
// desc = "Use simplex noise as the mask"
// )
// public Mask simplex(@Arg(desc = "double scale") double scale, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
// scale = 1d / Math.max(1, scale);
// minInt = (minInt - 50) / 50;
// maxInt = (maxInt - 50) / 50;
// return new SimplexMask(scale, minInt, maxInt);
// }
//
// @Command(
// name = "#light",
// desc = "Restrict to specific light levels"
// )
// public Mask light(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
// return new LightMask(extent, (int) minInt, (int) maxInt);
// }
//
// @Command(
// name = "#false",
// desc = "Always false"
// )
// public Mask falseMask(Extent extent) {
// return Masks.alwaysFalse();
// }
//
// @Command(
// name = "#true",
// desc = "Always true"
// )
// public Mask trueMask(Extent extent) {
// return Masks.alwaysTrue();
// }
//
// @Command(
// name = "#skylight",
// desc = "Restrict to specific sky light levels"
// )
// public Mask skylight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
// return new SkyLightMask(extent, (int) minInt, (int) maxInt);
// }
//
// @Command(
// name = "#blocklight",
// aliases = {"#emittedlight"},
// desc = "Restrict to specific block light levels"
// )
// public Mask blocklight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
// return new BlockLightMask(extent, (int) minInt, (int) maxInt);
// }
//
// @Command(
// name = "#opacity",
// desc = "Restrict to specific opacity levels"
// )
// public Mask opacity(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
// return new OpacityMask(extent, (int) minInt, (int) maxInt);
// }
//
// @Command(
// name = "#brightness",
// desc = "Restrict to specific block brightness"
// )
// public Mask brightness(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
// return new BrightnessMask(extent, (int) minInt, (int) maxInt);
// }
//
// @Command(
// name = "#offset",
// desc = "Offset a mask"
// )
// public Mask offset(@Arg(desc = "double x") double x, @Arg(desc = "double y") double y, @Arg(desc = "double z") double z, @Arg(desc = "Mask") Mask mask) {
// return new OffsetMask(mask, BlockVector3.at(x, y, z));
// }
//
// @Command(
// name = "#haslight",
// desc = "Restricts to blocks with light (sky or emitted)"
// )
// public Mask haslight(Extent extent) {
// return new LightMask(extent, 1, Integer.MAX_VALUE);
// }
//
// @Command(
// name = "#nolight",
// desc = "Restrict to blocks without light (sky or emitted)"
// )
// public Mask nolight(Extent extent) {
// return new LightMask(extent, 0, 0);
// }
//
// @Command(
// name = "#existing",
// desc = "If there is a non air block"
// )
// public Mask existing(Extent extent) {
// return new ExistingBlockMask(extent);
// }
//
// @Command(
// name = "#solid",
// desc = "If there is a solid block"
// )
// public Mask solid(Extent extent) {
// return new SolidBlockMask(extent);
// }
//
// @Command(
// name = "#liquid",
// desc = "If there is a solid block"
// )
// public Mask liquid(Extent extent) {
// return new BlockMaskBuilder().addAll(b -> b.getMaterial().isLiquid()).build(extent);
// }
//
// @Command(
// name = "#dregion",
// aliases = {"#dselection", "#dsel"},
// desc = "inside the player's selection"
// )
// public Mask dregion() {
// return new RegionMask(new RequestSelection());
// }
//
// @Command(
// name = "#region",
// aliases = {"#selection", "#sel"},
// desc = "inside the provided selection"
// )
// public Mask selection(Player player, LocalSession session) throws IncompleteRegionException {
// return new RegionMask(session.getSelection(player.getWorld()).clone());
// }
//
// @Command(
// name = "#xaxis",
// desc = "Restrict to initial x axis"
// )
// public Mask xaxis() {
// return new XAxisMask();
// }
//
// @Command(
// name = "#yaxis",
// desc = "Restrict to initial y axis"
// )
// public Mask yaxis() {
// return new YAxisMask();
// }
//
// @Command(
// name = "#zaxis",
// desc = "Restrict to initial z axis"
// )
// public Mask zaxis() {
// return new ZAxisMask();
// }
//
// @Command(
// name = "#id",
// desc = "Restrict to initial id"
// )
// public Mask id(Extent extent) {
// return new IdMask(extent);
// }
//
// @Command(
// name = "#data",
// desc = "Restrict to initial data"
// )
// public Mask data(Extent extent) {
// return new DataMask(extent);
// }
//
// @Command(
// name = "#iddata",
// desc = "Restrict to initial block id and data"
// )
// public Mask iddata(Extent extent) {
// return new IdDataMask(extent);
// }
//
// @Command(
// name = "#air",
// desc = "Restrict to types of air"
// )
// public Mask air(Extent extent) {
// return new BlockMaskBuilder().addAll(b -> b.getMaterial().isAir()).build(extent);
// }
//
// @Command(
// name = "#wall",
// desc = "Restrict to walls (any block n,e,s,w of air)"
// )
// public Mask wall(Extent extent) {
// Mask blockMask = air(extent);
// return new MaskUnion(new ExistingBlockMask(extent), new WallMask(blockMask, 1, 8));
// }
//
// @Command(
// name = "#surface",
// desc = "Restrict to surfaces (any solid block touching air)"
// )
// public Mask surface(Extent extent) {
// return new SurfaceMask(extent);
// }
//
// @Command(
// name = "\\",
// aliases = {"/", "#angle", "#\\", "#/"},
// desc = "Restrict to specific terrain angle",
// descFooter = "Restrict to specific terrain angle\n" +
// "The -o flag will only overlay\n" +
// "Example: /[0d][45d]\n" +
// "Explanation: Allows any block where the adjacent block is between 0 and 45 degrees.\n" +
// "Example: /[3][20]\n" +
// "Explanation: Allows any block where the adjacent block is between 3 and 20 blocks below"
//)
@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class MaskCommands {
private final WorldEdit worldEdit;
public MaskCommands(WorldEdit worldEdit) {
this.worldEdit = worldEdit;
}
@Command(
name = "#simplex",
desc = "Use simplex noise as the mask"
)
public Mask simplex(@Arg(desc = "double scale") double scale, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
scale = 1d / Math.max(1, scale);
minInt = (minInt - 50) / 50;
maxInt = (maxInt - 50) / 50;
return new SimplexMask(scale, minInt, maxInt);
}
@Command(
name = "#light",
desc = "Restrict to specific light levels"
)
public Mask light(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
return new LightMask(extent, (int) minInt, (int) maxInt);
}
@Command(
name = "#false",
desc = "Always false"
)
public Mask falseMask(Extent extent) {
return Masks.alwaysFalse();
}
@Command(
name = "#true",
desc = "Always true"
)
public Mask trueMask(Extent extent) {
return Masks.alwaysTrue();
}
@Command(
name = "#skylight",
desc = "Restrict to specific sky light levels"
)
public Mask skylight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
return new SkyLightMask(extent, (int) minInt, (int) maxInt);
}
@Command(
name = "#blocklight",
aliases = {"#emittedlight"},
desc = "Restrict to specific block light levels"
)
public Mask blocklight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
return new BlockLightMask(extent, (int) minInt, (int) maxInt);
}
@Command(
name = "#opacity",
desc = "Restrict to specific opacity levels"
)
public Mask opacity(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
return new OpacityMask(extent, (int) minInt, (int) maxInt);
}
@Command(
name = "#brightness",
desc = "Restrict to specific block brightness"
)
public Mask brightness(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) {
return new BrightnessMask(extent, (int) minInt, (int) maxInt);
}
@Command(
name = "#offset",
desc = "Offset a mask"
)
public Mask offset(@Arg(desc = "double x") double x, @Arg(desc = "double y") double y, @Arg(desc = "double z") double z, @Arg(desc = "Mask") Mask mask) {
return new OffsetMask(mask, BlockVector3.at(x, y, z));
}
@Command(
name = "#haslight",
desc = "Restricts to blocks with light (sky or emitted)"
)
public Mask haslight(Extent extent) {
return new LightMask(extent, 1, Integer.MAX_VALUE);
}
@Command(
name = "#nolight",
desc = "Restrict to blocks without light (sky or emitted)"
)
public Mask nolight(Extent extent) {
return new LightMask(extent, 0, 0);
}
@Command(
name = "#existing",
desc = "If there is a non air block"
)
public Mask existing(Extent extent) {
return new ExistingBlockMask(extent);
}
@Command(
name = "#solid",
desc = "If there is a solid block"
)
public Mask solid(Extent extent) {
return new SolidBlockMask(extent);
}
@Command(
name = "#liquid",
desc = "If there is a solid block"
)
public Mask liquid(Extent extent) {
return new BlockMaskBuilder().addAll(b -> b.getMaterial().isLiquid()).build(extent);
}
@Command(
name = "#dregion",
aliases = {"#dselection", "#dsel"},
desc = "inside the player's selection"
)
public Mask dregion() {
return new RegionMask(new RequestSelection());
}
@Command(
name = "#region",
aliases = {"#selection", "#sel"},
desc = "inside the provided selection"
)
public Mask selection(Player player, LocalSession session) throws IncompleteRegionException {
return new RegionMask(session.getSelection(player.getWorld()).clone());
}
@Command(
name = "#xaxis",
desc = "Restrict to initial x axis"
)
public Mask xaxis() {
return new XAxisMask();
}
@Command(
name = "#yaxis",
desc = "Restrict to initial y axis"
)
public Mask yaxis() {
return new YAxisMask();
}
@Command(
name = "#zaxis",
desc = "Restrict to initial z axis"
)
public Mask zaxis() {
return new ZAxisMask();
}
@Command(
name = "#id",
desc = "Restrict to initial id"
)
public Mask id(Extent extent) {
return new IdMask(extent);
}
@Command(
name = "#data",
desc = "Restrict to initial data"
)
public Mask data(Extent extent) {
return new DataMask(extent);
}
@Command(
name = "#iddata",
desc = "Restrict to initial block id and data"
)
public Mask iddata(Extent extent) {
return new IdDataMask(extent);
}
@Command(
name = "#air",
desc = "Restrict to types of air"
)
public Mask air(Extent extent) {
return new BlockMaskBuilder().addAll(b -> b.getMaterial().isAir()).build(extent);
}
@Command(
name = "#wall",
desc = "Restrict to walls (any block n,e,s,w of air)"
)
public Mask wall(Extent extent) {
Mask blockMask = air(extent);
return new MaskUnion(new ExistingBlockMask(extent), new WallMask(blockMask, 1, 8));
}
@Command(
name = "#surface",
desc = "Restrict to surfaces (any solid block touching air)"
)
public Mask surface(Extent extent) {
return new SurfaceMask(extent);
}
@Command(
name = "\\",
aliases = {"/", "#angle", "#\\", "#/"},
desc = "Restrict to specific terrain angle",
descFooter = "Restrict to specific terrain angle\n" +
"The -o flag will only overlay\n" +
"Example: /[0d][45d]\n" +
"Explanation: Allows any block where the adjacent block is between 0 and 45 degrees.\n" +
"Example: /[3][20]\n" +
"Explanation: Allows any block where the adjacent block is between 3 and 20 blocks below"
)
public Mask angle(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "1") int distanceOpt) throws ExpressionException {
double y1, y2;
boolean override;
if (maxStr.endsWith("d")) {
double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate();
double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate();
y1 = Math.tan(y1d * (Math.PI / 180));
y2 = Math.tan(y2d * (Math.PI / 180));
} else {
y1 = Expression.compile(minStr).evaluate();
y2 = Expression.compile(maxStr).evaluate();
}
return new AngleMask(extent, y1, y2, overlay, distanceOpt);
}
@Command(
name = "(",
aliases = {")", "#roc", "#(", "#)"},
desc = "Restrict to near specific terrain slope rate of change",
descFooter = "Restrict to near specific terrain slope rate of change\n" +
"The -o flag will only overlay\n" +
"Example: ([0d][45d][5]\n" +
"Explanation: Restrict near where the angle changes between 0-45 degrees within 5 blocks\n" +
"Note: Use negatives for decreasing slope"
)
public Mask roc(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException {
double y1, y2;
boolean override;
if (maxStr.endsWith("d")) {
double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate();
double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate();
y1 = Math.tan(y1d * (Math.PI / 180));
y2 = Math.tan(y2d * (Math.PI / 180));
} else {
y1 = Expression.compile(minStr).evaluate();
y2 = Expression.compile(maxStr).evaluate();
}
return new ROCAngleMask(extent, y1, y2, overlay, distanceOpt);
}
@Command(
name = "^",
aliases = {"#extrema", "#^"},
desc = "Restrict to near specific terrain extrema",
descFooter = "Restrict to near specific terrain extrema\n" +
"The -o flag will only overlay\n" +
"Example: ([0d][45d][5]\n" +
"Explanation: Restrict to near 45 degrees of local maxima\n" +
"Note: Use negatives for local minima"
)
public Mask extrema(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException {
double y1, y2;
boolean override;
if (maxStr.endsWith("d")) {
double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate();
double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate();
y1 = Math.tan(y1d * (Math.PI / 180));
y2 = Math.tan(y2d * (Math.PI / 180));
} else {
y1 = Expression.compile(minStr).evaluate();
y2 = Expression.compile(maxStr).evaluate();
}
return new ExtremaMask(extent, y1, y2, overlay, distanceOpt);
}
@Command(
name = "{",
aliases = {"#{"},
desc = "Restricts blocks to within a specific radius range of the initial block"
)
public Mask radius(@Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException {
return new RadiusMask((int) minInt, (int) maxInt);
}
@Command(
name = "|",
aliases = {"#|", "#side"},
desc = "sides with a specific number of other blocks"
)
public Mask wall(@Arg(desc = "Mask") Mask mask, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException {
return new WallMask(mask, (int) minInt, (int) maxInt);
}
@Command(
name = "~",
aliases = {"#~", "#adjacent"},
desc = "Adjacent to a specific number of other blocks"
)
public Mask adjacent(@Arg(desc = "Mask") Mask mask, @Arg(name = "min", desc = "double", def = "-1") double min, @Arg(name = "max", desc = "double", def = "-1") double max) throws ExpressionException {
if (min == -1 && max == -1) {
min = 1;
max = 8;
} else if (max == -1) max = min;
if (max >= 8 && min == 1) {
return new AdjacentAnyMask(mask);
}
return new AdjacentMask(mask, (int) min, (int) max);
}
@Command(
name = "<",
aliases = {"#<", "#below"},
desc = "below a specific block"
)
public Mask below(@Arg(desc = "Mask") Mask mask) throws ExpressionException {
OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, 1, 0));
return new MaskIntersection(offsetMask, Masks.negate(mask));
}
@Command(
name = ">",
aliases = {"#>", "#above"},
desc = "above a specific block"
)
public Mask above(@Arg(desc = "Mask") Mask mask) throws ExpressionException {
OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, -1, 0));
return new MaskIntersection(offsetMask, Masks.negate(mask));
}
@Command(
name = "$",
aliases = {"#biome", "#$"},
desc = "in a specific biome",
descFooter = "in a specific biome. For a list of biomes use //biomelist"
)
public Mask biome(Extent extent, @Arg(desc = "BiomeType") BiomeType biome) throws ExpressionException {
return new BiomeMask(extent, biome);
}
@Command(
name = "%",
aliases = {"#%", "#percent"},
desc = "percentage chance"
)
public Mask random(@Arg(desc = "double chance") double chance) throws ExpressionException {
chance = chance / 100;
return new RandomMask(chance);
}
@Command(
name = "=",
aliases = {"#=", "#expression"},
desc = "expression mask"
)
public Mask expression(Extent extent, @Arg(desc = "String expression") String input) throws ExpressionException {
Expression exp = Expression.compile(input, "x", "y", "z");
ExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO);
exp.setEnvironment(env);
return new ExpressionMask(exp);
}
@Command(
name = "!",
aliases = {"#not", "#negate", "#!"},
desc = "Negate another mask"
)
public Mask negate(@Arg(desc = "Mask") Mask mask) throws ExpressionException {
return Masks.negate(mask);
}
}
// public Mask angle(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "1") int distanceOpt) throws ExpressionException {
// double y1, y2;
// boolean override;
// if (maxStr.endsWith("d")) {
// double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate();
// double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate();
// y1 = Math.tan(y1d * (Math.PI / 180));
// y2 = Math.tan(y2d * (Math.PI / 180));
// } else {
// y1 = Expression.compile(minStr).evaluate();
// y2 = Expression.compile(maxStr).evaluate();
// }
// return new AngleMask(extent, y1, y2, overlay, distanceOpt);
// }
//
// @Command(
// name = "(",
// aliases = {")", "#roc", "#(", "#)"},
// desc = "Restrict to near specific terrain slope rate of change",
// descFooter = "Restrict to near specific terrain slope rate of change\n" +
// "The -o flag will only overlay\n" +
// "Example: ([0d][45d][5]\n" +
// "Explanation: Restrict near where the angle changes between 0-45 degrees within 5 blocks\n" +
// "Note: Use negatives for decreasing slope"
//)
// public Mask roc(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException {
// double y1, y2;
// boolean override;
// if (maxStr.endsWith("d")) {
// double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate();
// double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate();
// y1 = Math.tan(y1d * (Math.PI / 180));
// y2 = Math.tan(y2d * (Math.PI / 180));
// } else {
// y1 = Expression.compile(minStr).evaluate();
// y2 = Expression.compile(maxStr).evaluate();
// }
// return new ROCAngleMask(extent, y1, y2, overlay, distanceOpt);
// }
//
// @Command(
// name = "^",
// aliases = {"#extrema", "#^"},
// desc = "Restrict to near specific terrain extrema",
// descFooter = "Restrict to near specific terrain extrema\n" +
// "The -o flag will only overlay\n" +
// "Example: ([0d][45d][5]\n" +
// "Explanation: Restrict to near 45 degrees of local maxima\n" +
// "Note: Use negatives for local minima"
//)
// public Mask extrema(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException {
// double y1, y2;
// boolean override;
// if (maxStr.endsWith("d")) {
// double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate();
// double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate();
// y1 = Math.tan(y1d * (Math.PI / 180));
// y2 = Math.tan(y2d * (Math.PI / 180));
// } else {
// y1 = Expression.compile(minStr).evaluate();
// y2 = Expression.compile(maxStr).evaluate();
// }
// return new ExtremaMask(extent, y1, y2, overlay, distanceOpt);
// }
//
// @Command(
// name = "{",
// aliases = {"#{"},
// desc = "Restricts blocks to within a specific radius range of the initial block"
//)
// public Mask radius(@Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException {
// return new RadiusMask((int) minInt, (int) maxInt);
// }
//
// @Command(
// name = "|",
// aliases = {"#|", "#side"},
// desc = "sides with a specific number of other blocks"
//)
// public Mask wall(@Arg(desc = "Mask") Mask mask, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException {
// return new WallMask(mask, (int) minInt, (int) maxInt);
// }
//
// @Command(
// name = "~",
// aliases = {"#~", "#adjacent"},
// desc = "Adjacent to a specific number of other blocks"
//)
// public Mask adjacent(@Arg(desc = "Mask") Mask mask, @Arg(name = "min", desc = "double", def = "-1") double min, @Arg(name = "max", desc = "double", def = "-1") double max) throws ExpressionException {
// if (min == -1 && max == -1) {
// min = 1;
// max = 8;
// } else if (max == -1) max = min;
// if (max >= 8 && min == 1) {
// return new AdjacentAnyMask(mask);
// }
// return new AdjacentMask(mask, (int) min, (int) max);
// }
//
// @Command(
// name = "<",
// aliases = {"#<", "#below"},
// desc = "below a specific block"
//)
// public Mask below(@Arg(desc = "Mask") Mask mask) throws ExpressionException {
// OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, 1, 0));
// return new MaskIntersection(offsetMask, Masks.negate(mask));
// }
//
// @Command(
// name = ">",
// aliases = {"#>", "#above"},
// desc = "above a specific block"
//)
// public Mask above(@Arg(desc = "Mask") Mask mask) throws ExpressionException {
// OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, -1, 0));
// return new MaskIntersection(offsetMask, Masks.negate(mask));
// }
//
// @Command(
// name = "$",
// aliases = {"#biome", "#$"},
// desc = "in a specific biome",
// descFooter = "in a specific biome. For a list of biomes use //biomelist"
//)
// public Mask biome(Extent extent, @Arg(desc = "BiomeType") BiomeType biome) throws ExpressionException {
// return new BiomeMask(extent, biome);
// }
//
// @Command(
// name = "%",
// aliases = {"#%", "#percent"},
// desc = "percentage chance"
//)
// public Mask random(@Arg(desc = "double chance") double chance) throws ExpressionException {
// chance = chance / 100;
// return new RandomMask(chance);
// }
//
// @Command(
// name = "=",
// aliases = {"#=", "#expression"},
// desc = "expression mask"
//)
// public Mask expression(Extent extent, @Arg(desc = "String expression") String input) throws ExpressionException {
// Expression exp = Expression.compile(input, "x", "y", "z");
// ExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO);
// exp.setEnvironment(env);
// return new ExpressionMask(exp);
// }
//
// @Command(
// name = "!",
// aliases = {"#not", "#negate", "#!"},
// desc = "Negate another mask"
//)
// public Mask negate(@Arg(desc = "Mask") Mask mask) throws ExpressionException {
// return Masks.negate(mask);
// }
//}

View File

@ -1,403 +1,404 @@
package com.sk89q.worldedit.command;
import com.boydti.fawe.object.DataAnglePattern;
import com.boydti.fawe.object.clipboard.MultiClipboardHolder;
import com.boydti.fawe.object.collection.RandomCollection;
import com.boydti.fawe.object.pattern.AngleColorPattern;
import com.boydti.fawe.object.pattern.AverageColorPattern;
import com.boydti.fawe.object.pattern.BiomePattern;
import com.boydti.fawe.object.pattern.BufferedPattern;
import com.boydti.fawe.object.pattern.BufferedPattern2D;
import com.boydti.fawe.object.pattern.DataPattern;
import com.boydti.fawe.object.pattern.DesaturatePattern;
import com.boydti.fawe.object.pattern.ExistingPattern;
import com.boydti.fawe.object.pattern.ExpressionPattern;
import com.boydti.fawe.object.pattern.FullClipboardPattern;
import com.boydti.fawe.object.pattern.IdDataMaskPattern;
import com.boydti.fawe.object.pattern.IdPattern;
import com.boydti.fawe.object.pattern.Linear2DBlockPattern;
import com.boydti.fawe.object.pattern.Linear3DBlockPattern;
import com.boydti.fawe.object.pattern.LinearBlockPattern;
import com.boydti.fawe.object.pattern.MaskedPattern;
import com.boydti.fawe.object.pattern.NoXPattern;
import com.boydti.fawe.object.pattern.NoYPattern;
import com.boydti.fawe.object.pattern.NoZPattern;
import com.boydti.fawe.object.pattern.OffsetPattern;
import com.boydti.fawe.object.pattern.PropertyPattern;
import com.boydti.fawe.object.pattern.RandomFullClipboardPattern;
import com.boydti.fawe.object.pattern.RandomOffsetPattern;
import com.boydti.fawe.object.pattern.RelativePattern;
import com.boydti.fawe.object.pattern.SaturatePattern;
import com.boydti.fawe.object.pattern.ShadePattern;
import com.boydti.fawe.object.pattern.SolidRandomOffsetPattern;
import com.boydti.fawe.object.pattern.SurfaceRandomOffsetPattern;
import com.boydti.fawe.object.random.SimplexRandom;
import com.boydti.fawe.util.ColorUtil;
import com.boydti.fawe.util.TextureUtil;
import com.sk89q.worldedit.EmptyClipboardException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.pattern.ClipboardPattern;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.RandomPattern;
import com.sk89q.worldedit.internal.expression.Expression;
import com.sk89q.worldedit.internal.expression.ExpressionException;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment;
import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.world.biome.BiomeType;
import java.awt.Color;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.jetbrains.annotations.Range;
//@Command(aliases = {"patterns"},
// desc = "Help for the various patterns. [More Info](https://git.io/vSPmA)",
// descFooter = "Patterns determine what blocks are placed\n" +
// " - Use [brackets] for arguments\n" +
// " - Use , to OR multiple\n" +
// "e.g., #surfacespread[10][#existing],andesite\n" +
// "More Info: https://git.io/vSPmA"
// TODO: Ping @MattBDev to reimplement 2020-02-04
//package com.sk89q.worldedit.command;
//
//import com.boydti.fawe.object.DataAnglePattern;
//import com.boydti.fawe.object.clipboard.MultiClipboardHolder;
//import com.boydti.fawe.object.collection.RandomCollection;
//import com.boydti.fawe.object.pattern.AngleColorPattern;
//import com.boydti.fawe.object.pattern.AverageColorPattern;
//import com.boydti.fawe.object.pattern.BiomePattern;
//import com.boydti.fawe.object.pattern.BufferedPattern;
//import com.boydti.fawe.object.pattern.BufferedPattern2D;
//import com.boydti.fawe.object.pattern.DataPattern;
//import com.boydti.fawe.object.pattern.DesaturatePattern;
//import com.boydti.fawe.object.pattern.ExistingPattern;
//import com.boydti.fawe.object.pattern.ExpressionPattern;
//import com.boydti.fawe.object.pattern.FullClipboardPattern;
//import com.boydti.fawe.object.pattern.IdDataMaskPattern;
//import com.boydti.fawe.object.pattern.IdPattern;
//import com.boydti.fawe.object.pattern.Linear2DBlockPattern;
//import com.boydti.fawe.object.pattern.Linear3DBlockPattern;
//import com.boydti.fawe.object.pattern.LinearBlockPattern;
//import com.boydti.fawe.object.pattern.MaskedPattern;
//import com.boydti.fawe.object.pattern.NoXPattern;
//import com.boydti.fawe.object.pattern.NoYPattern;
//import com.boydti.fawe.object.pattern.NoZPattern;
//import com.boydti.fawe.object.pattern.OffsetPattern;
//import com.boydti.fawe.object.pattern.PropertyPattern;
//import com.boydti.fawe.object.pattern.RandomFullClipboardPattern;
//import com.boydti.fawe.object.pattern.RandomOffsetPattern;
//import com.boydti.fawe.object.pattern.RelativePattern;
//import com.boydti.fawe.object.pattern.SaturatePattern;
//import com.boydti.fawe.object.pattern.ShadePattern;
//import com.boydti.fawe.object.pattern.SolidRandomOffsetPattern;
//import com.boydti.fawe.object.pattern.SurfaceRandomOffsetPattern;
//import com.boydti.fawe.object.random.SimplexRandom;
//import com.boydti.fawe.util.ColorUtil;
//import com.boydti.fawe.util.TextureUtil;
//import com.sk89q.worldedit.EmptyClipboardException;
//import com.sk89q.worldedit.LocalSession;
//import com.sk89q.worldedit.entity.Player;
//import com.sk89q.worldedit.extension.input.InputParseException;
//import com.sk89q.worldedit.extension.platform.Actor;
//import com.sk89q.worldedit.extent.Extent;
//import com.sk89q.worldedit.extent.clipboard.Clipboard;
//import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats;
//import com.sk89q.worldedit.function.mask.Mask;
//import com.sk89q.worldedit.function.pattern.ClipboardPattern;
//import com.sk89q.worldedit.function.pattern.Pattern;
//import com.sk89q.worldedit.function.pattern.RandomPattern;
//import com.sk89q.worldedit.internal.expression.Expression;
//import com.sk89q.worldedit.internal.expression.ExpressionException;
//import com.sk89q.worldedit.math.Vector3;
//import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment;
//import com.sk89q.worldedit.session.ClipboardHolder;
//import com.sk89q.worldedit.world.biome.BiomeType;
//import java.awt.Color;
//import java.io.IOException;
//import java.util.Collections;
//import java.util.List;
//import java.util.Set;
//import org.enginehub.piston.annotation.Command;
//import org.enginehub.piston.annotation.CommandContainer;
//import org.enginehub.piston.annotation.param.Arg;
//import org.jetbrains.annotations.Range;
//
////@Command(aliases = {"patterns"},
//// desc = "Help for the various patterns. [More Info](https://git.io/vSPmA)",
//// descFooter = "Patterns determine what blocks are placed\n" +
//// " - Use [brackets] for arguments\n" +
//// " - Use , to OR multiple\n" +
//// "e.g., #surfacespread[10][#existing],andesite\n" +
//// "More Info: https://git.io/vSPmA"
////)
//@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class)
//public class PatternCommands {
//
// @Command(
// name = "#existing",
// aliases = {"#*", "*", ".*"},
// desc = "Use the block that is already there"
// )
// public Pattern existing(Extent extent, @Arg(desc = "String", def = "") String properties) { // TODO FIXME , @Arg(name = "properties", desc = "String", def = "") String properties
// if (properties == null) return new ExistingPattern(extent);
// return new PropertyPattern(extent).addRegex(".*[" + properties + "]");
// }
//
// @Command(
// name = "#clipboard",
// aliases = {"#copy"},
// desc = "Use the blocks in your clipboard as the pattern")
// public Pattern clipboard(LocalSession session) throws EmptyClipboardException {
// ClipboardHolder holder = session.getClipboard();
// Clipboard clipboard = holder.getClipboard();
// return new ClipboardPattern(clipboard);
// }
//
// @Command(
// name = "#simplex",
// desc = "Use simplex noise to randomize blocks. Tutorial: https://imgur.com/a/rwVAE"
//)
@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class PatternCommands {
@Command(
name = "#existing",
aliases = {"#*", "*", ".*"},
desc = "Use the block that is already there"
)
public Pattern existing(Extent extent, @Arg(desc = "String", def = "") String properties) { // TODO FIXME , @Arg(name = "properties", desc = "String", def = "") String properties
if (properties == null) return new ExistingPattern(extent);
return new PropertyPattern(extent).addRegex(".*[" + properties + "]");
}
@Command(
name = "#clipboard",
aliases = {"#copy"},
desc = "Use the blocks in your clipboard as the pattern")
public Pattern clipboard(LocalSession session) throws EmptyClipboardException {
ClipboardHolder holder = session.getClipboard();
Clipboard clipboard = holder.getClipboard();
return new ClipboardPattern(clipboard);
}
@Command(
name = "#simplex",
desc = "Use simplex noise to randomize blocks. Tutorial: https://imgur.com/a/rwVAE"
)
public Pattern simplex(@Arg(desc = "scale factor") double scale, @Arg(desc = "Pattern") Pattern other) {
if (other instanceof RandomPattern) {
scale = (1d / Math.max(1, scale));
RandomCollection<Pattern> collection = ((RandomPattern) other).getCollection();
collection.setRandom(new SimplexRandom(scale));
}
return other;
}
@Command(
name = "#color",
desc = "Use the block closest to a specific color"
)
public Pattern color(TextureUtil textureUtil, @Arg(desc = "String color") String color) {
Color colorObj = ColorUtil.parseColor(color);
return textureUtil.getNearestBlock(colorObj.getRGB()).getDefaultState();
}
@Command(
name = "#anglecolor",
desc = "A darker block based on the existing terrain angle"
)
public Pattern anglecolor(Extent extent, LocalSession session, @Arg(desc = "int", def = "1") int distance) {
return new AngleColorPattern(extent, session, distance);
}
@Command(
name = "#angledata",
desc = "Block data based on the existing terrain angle"
)
public Pattern angledata(Extent extent, @Arg(desc = "int", def = "1") int distance) {
return new DataAnglePattern(extent, distance);
}
@Command(
name = "#saturate",
desc = "Saturate the existing block with a color"
)
public Pattern saturate(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) {
Color color = ColorUtil.parseColor(colorStr);
return new SaturatePattern(extent, color.getRGB(), session);
}
@Command(
name = "#averagecolor",
desc = "Average between the existing block and a color"
)
public Pattern averagecolor(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) {
Color color = ColorUtil.parseColor(colorStr);
return new AverageColorPattern(extent, color.getRGB(), session);
}
@Command(
name = "#desaturate",
desc = "Desaturated color of the existing block"
)
public Pattern desaturate(Extent extent, LocalSession session, @Arg(desc = "double", def = "100") double percent) {
return new DesaturatePattern(extent, percent / 100d, session);
}
@Command(
name = "#lighten",
desc = "Lighten the existing block"
)
public Pattern lighten(Extent extent, TextureUtil util) {
return new ShadePattern(extent, false, util);
}
@Command(
name = "#darken",
desc = "Darken the existing block"
)
public Pattern darken(Extent extent, TextureUtil util) {
return new ShadePattern(extent, true, util);
}
@Command(
name = "#fullcopy",
desc = "Places your full clipboard at each block"
)
public Pattern fullcopy(Player player, Extent extent, LocalSession session, @Arg(desc = "String", def = "#copy") String location, @Arg(desc = "boolean", def = "false") boolean rotate, @Arg(desc = "boolean", def = "false") boolean flip) throws EmptyClipboardException, InputParseException, IOException {
List<ClipboardHolder> clipboards;
switch (location.toLowerCase()) {
case "#copy":
case "#clipboard":
ClipboardHolder clipboard = session.getExistingClipboard();
if (clipboard == null) {
throw new InputParseException("To use #fullcopy, please first copy something to your clipboard");
}
if (!rotate && !flip) {
return new FullClipboardPattern(extent, clipboard.getClipboard());
}
clipboards = Collections.singletonList(clipboard);
break;
default:
MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, location, null, true);
clipboards = multi != null ? multi.getHolders() : null;
break;
}
if (clipboards == null) {
throw new InputParseException("#fullcopy:<source>");
}
return new RandomFullClipboardPattern(extent, clipboards, rotate, flip);
}
@Command(
name = "#buffer",
desc = "Only place a block once while a pattern is in use",
descFooter = "Only place a block once while a pattern is in use\n" +
"Use with a brush when you don't want to apply to the same spot twice"
)
public Pattern buffer(Actor actor, @Arg(desc = "Pattern")Pattern pattern) {
return new BufferedPattern(actor, pattern);
}
@Command(
name = "#buffer2d",
desc = "Only place a block once in a column while a pattern is in use"
)
public Pattern buffer2d(Actor actor, @Arg(desc = "Pattern")Pattern pattern) {
return new BufferedPattern2D(actor, pattern);
}
@Command(
name = "#iddatamask",
desc = "Use the pattern's id and the existing blocks data with the provided mask",
descFooter = "Use the pattern's id and the existing blocks data with the provided mask\n" +
" - Use to replace slabs or where the data values needs to be shifted instead of set"
)
public Pattern iddatamask(Extent extent, @Range(from = 0, to = 15) @Arg(desc = "bit mask") int bitmask, @Arg(desc = "Pattern")Pattern pattern) {
return new IdDataMaskPattern(extent, pattern, bitmask);
}
@Command(
name = "#id",
desc = "Only change the block id"
)
public Pattern id(Extent extent, @Arg(desc = "Pattern")Pattern pattern) {
return new IdPattern(extent, pattern);
}
@Command(
name = "#data",
desc = "Only change the block data"
)
public Pattern data(Extent extent, @Arg(desc = "Pattern")Pattern pattern) {
return new DataPattern(extent, pattern);
}
@Command(
name = "#biome",
aliases = {"$"},
desc = "Set the biome"
)
public Pattern biome(Extent extent, @Arg(desc = "Biome type") BiomeType biome) {
return new BiomePattern(extent, biome);
}
@Command(
name = "#relative",
aliases = {"#~", "#r", "#rel"},
desc = "Offset the pattern to where you click"
)
public Pattern relative(@Arg(desc = "Pattern")Pattern pattern) {
return new RelativePattern(pattern);
}
@Command(
name = "#!x",
aliases = {"#nx", "#nox"},
desc = "The pattern will not be provided the x axis info",
descFooter = "The pattern will not be provided the z axis info.\n" +
"Example: #!x[#!z[#~[#l3d[pattern]]]]"
)
public Pattern nox(@Arg(desc = "Pattern")Pattern pattern) {
return new NoXPattern(pattern);
}
@Command(
name = "#!y",
aliases = {"#ny", "#noy"},
desc = "The pattern will not be provided the y axis info"
)
public Pattern noy(@Arg(desc = "Pattern")Pattern pattern) {
return new NoYPattern(pattern);
}
@Command(
name = "#!z",
aliases = {"#nz", "#noz"},
desc = "The pattern will not be provided the z axis info"
)
public Pattern noz(@Arg(desc = "Pattern")Pattern pattern) {
return new NoZPattern(pattern);
}
@Command(
name = "#mask",
desc = "Apply a pattern depending on a mask"
)
public Pattern mask(@Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern")Pattern pass, @Arg(desc = "Pattern")Pattern fail) {
return new MaskedPattern(mask, pass, fail);
}
@Command(
name = "#offset",
desc = "Offset a pattern"
)
public Pattern offset(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) {
return new OffsetPattern(pattern, (int) x, (int) y, (int) z);
}
@Command(
name = "#surfacespread",
desc = "Applies to only blocks on a surface. Selects a block from provided pattern with a given randomized offset `[0, <distance>)`. e.g., Use `#existing` to randomly offset blocks in the world, or `#copy` to offset blocks in your clipboard"
)
public Pattern surfacespread(@Arg(desc = "spread distance (blocks)") double distance, @Arg(desc = "Pattern")Pattern pattern) {
return new SurfaceRandomOffsetPattern(pattern, (int) distance);
}
@Command(
name = "#solidspread",
desc = "Randomly spread solid blocks"
)
public Pattern solidspread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) {
return new SolidRandomOffsetPattern(pattern, (int) x, (int) y, (int) z);
}
@Command(
name = "#spread",
aliases = {"#randomoffset"},
desc = "Randomly spread blocks"
)
public Pattern spread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) {
return new RandomOffsetPattern(pattern, (int) x, (int) y, (int) z);
}
@Command(
name = "#linear",
aliases = {"#l"},
desc = "Sequentially set blocks from a list of patterns"
)
public Pattern linear(@Arg(desc = "Pattern") Pattern other) {
if (other instanceof RandomPattern) {
Set<Pattern> patterns = ((RandomPattern) other).getPatterns();
return new LinearBlockPattern(patterns.toArray(new Pattern[patterns.size()]));
}
return other;
}
@Command(
name = "#linear3d",
aliases = {"#l3d"},
desc = "Use the x,y,z coordinate to pick a block from the list"
)
public Pattern linear3d(@Arg(desc = "Pattern") Pattern other) {
if (other instanceof RandomPattern) {
Set<Pattern> patterns = ((RandomPattern) other).getPatterns();
return new Linear3DBlockPattern(patterns.toArray(new Pattern[patterns.size()]));
}
return other;
}
@Command(
name = "#linear2d",
aliases = {"#l2d"},
desc = "Use the x,z coordinate to pick a block from the list"
)
public Pattern linear2d(@Arg(desc = "Pattern") Pattern other) {
if (other instanceof RandomPattern) {
Set<Pattern> patterns = ((RandomPattern) other).getPatterns();
return new Linear2DBlockPattern(patterns.toArray(new Pattern[patterns.size()]));
}
return other;
}
@Command(
name = "=",
aliases = {"#=", "#expression"},
desc = "Expression pattern: http://wiki.sk89q.com/wiki/WorldEdit/Expression_syntax"
)
public Pattern expression(Extent extent, @Arg(desc = "Expression") String input) throws ExpressionException {
Expression exp = Expression.compile(input, "x", "y", "z");
WorldEditExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO);
exp.setEnvironment(env);
return new ExpressionPattern(exp);
}
}
// public Pattern simplex(@Arg(desc = "scale factor") double scale, @Arg(desc = "Pattern") Pattern other) {
// if (other instanceof RandomPattern) {
// scale = (1d / Math.max(1, scale));
// RandomCollection<Pattern> collection = ((RandomPattern) other).getCollection();
// collection.setRandom(new SimplexRandom(scale));
// }
// return other;
// }
//
// @Command(
// name = "#color",
// desc = "Use the block closest to a specific color"
//)
// public Pattern color(TextureUtil textureUtil, @Arg(desc = "String color") String color) {
// Color colorObj = ColorUtil.parseColor(color);
// return textureUtil.getNearestBlock(colorObj.getRGB()).getDefaultState();
// }
//
// @Command(
// name = "#anglecolor",
// desc = "A darker block based on the existing terrain angle"
//)
// public Pattern anglecolor(Extent extent, LocalSession session, @Arg(desc = "int", def = "1") int distance) {
// return new AngleColorPattern(extent, session, distance);
// }
//
// @Command(
// name = "#angledata",
// desc = "Block data based on the existing terrain angle"
// )
// public Pattern angledata(Extent extent, @Arg(desc = "int", def = "1") int distance) {
// return new DataAnglePattern(extent, distance);
// }
//
// @Command(
// name = "#saturate",
// desc = "Saturate the existing block with a color"
//)
// public Pattern saturate(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) {
// Color color = ColorUtil.parseColor(colorStr);
// return new SaturatePattern(extent, color.getRGB(), session);
// }
//
// @Command(
// name = "#averagecolor",
// desc = "Average between the existing block and a color"
//)
// public Pattern averagecolor(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) {
// Color color = ColorUtil.parseColor(colorStr);
// return new AverageColorPattern(extent, color.getRGB(), session);
// }
//
// @Command(
// name = "#desaturate",
// desc = "Desaturated color of the existing block"
//)
// public Pattern desaturate(Extent extent, LocalSession session, @Arg(desc = "double", def = "100") double percent) {
// return new DesaturatePattern(extent, percent / 100d, session);
// }
//
// @Command(
// name = "#lighten",
// desc = "Lighten the existing block"
//)
// public Pattern lighten(Extent extent, TextureUtil util) {
// return new ShadePattern(extent, false, util);
// }
//
// @Command(
// name = "#darken",
// desc = "Darken the existing block"
//)
// public Pattern darken(Extent extent, TextureUtil util) {
// return new ShadePattern(extent, true, util);
// }
//
// @Command(
// name = "#fullcopy",
// desc = "Places your full clipboard at each block"
//)
// public Pattern fullcopy(Player player, Extent extent, LocalSession session, @Arg(desc = "String", def = "#copy") String location, @Arg(desc = "boolean", def = "false") boolean rotate, @Arg(desc = "boolean", def = "false") boolean flip) throws EmptyClipboardException, InputParseException, IOException {
// List<ClipboardHolder> clipboards;
// switch (location.toLowerCase()) {
// case "#copy":
// case "#clipboard":
// ClipboardHolder clipboard = session.getExistingClipboard();
// if (clipboard == null) {
// throw new InputParseException("To use #fullcopy, please first copy something to your clipboard");
// }
// if (!rotate && !flip) {
// return new FullClipboardPattern(extent, clipboard.getClipboard());
// }
// clipboards = Collections.singletonList(clipboard);
// break;
// default:
// MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, location, null, true);
// clipboards = multi != null ? multi.getHolders() : null;
// break;
// }
// if (clipboards == null) {
// throw new InputParseException("#fullcopy:<source>");
// }
// return new RandomFullClipboardPattern(extent, clipboards, rotate, flip);
// }
//
// @Command(
// name = "#buffer",
// desc = "Only place a block once while a pattern is in use",
// descFooter = "Only place a block once while a pattern is in use\n" +
// "Use with a brush when you don't want to apply to the same spot twice"
//)
// public Pattern buffer(Actor actor, @Arg(desc = "Pattern")Pattern pattern) {
// return new BufferedPattern(actor, pattern);
// }
//
// @Command(
// name = "#buffer2d",
// desc = "Only place a block once in a column while a pattern is in use"
//)
// public Pattern buffer2d(Actor actor, @Arg(desc = "Pattern")Pattern pattern) {
// return new BufferedPattern2D(actor, pattern);
// }
//
// @Command(
// name = "#iddatamask",
// desc = "Use the pattern's id and the existing blocks data with the provided mask",
// descFooter = "Use the pattern's id and the existing blocks data with the provided mask\n" +
// " - Use to replace slabs or where the data values needs to be shifted instead of set"
//)
// public Pattern iddatamask(Extent extent, @Range(from = 0, to = 15) @Arg(desc = "bit mask") int bitmask, @Arg(desc = "Pattern")Pattern pattern) {
//
// return new IdDataMaskPattern(extent, pattern, bitmask);
// }
//
// @Command(
// name = "#id",
// desc = "Only change the block id"
//)
// public Pattern id(Extent extent, @Arg(desc = "Pattern")Pattern pattern) {
//
// return new IdPattern(extent, pattern);
// }
//
// @Command(
// name = "#data",
// desc = "Only change the block data"
//)
// public Pattern data(Extent extent, @Arg(desc = "Pattern")Pattern pattern) {
//
// return new DataPattern(extent, pattern);
// }
//
// @Command(
// name = "#biome",
// aliases = {"$"},
// desc = "Set the biome"
//)
// public Pattern biome(Extent extent, @Arg(desc = "Biome type") BiomeType biome) {
//
// return new BiomePattern(extent, biome);
// }
//
// @Command(
// name = "#relative",
// aliases = {"#~", "#r", "#rel"},
// desc = "Offset the pattern to where you click"
//)
// public Pattern relative(@Arg(desc = "Pattern")Pattern pattern) {
//
// return new RelativePattern(pattern);
// }
//
// @Command(
// name = "#!x",
// aliases = {"#nx", "#nox"},
// desc = "The pattern will not be provided the x axis info",
// descFooter = "The pattern will not be provided the z axis info.\n" +
// "Example: #!x[#!z[#~[#l3d[pattern]]]]"
//)
// public Pattern nox(@Arg(desc = "Pattern")Pattern pattern) {
//
// return new NoXPattern(pattern);
// }
//
// @Command(
// name = "#!y",
// aliases = {"#ny", "#noy"},
// desc = "The pattern will not be provided the y axis info"
//)
// public Pattern noy(@Arg(desc = "Pattern")Pattern pattern) {
//
// return new NoYPattern(pattern);
// }
//
// @Command(
// name = "#!z",
// aliases = {"#nz", "#noz"},
// desc = "The pattern will not be provided the z axis info"
//)
// public Pattern noz(@Arg(desc = "Pattern")Pattern pattern) {
//
// return new NoZPattern(pattern);
// }
//
// @Command(
// name = "#mask",
// desc = "Apply a pattern depending on a mask"
//)
// public Pattern mask(@Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern")Pattern pass, @Arg(desc = "Pattern")Pattern fail) {
// return new MaskedPattern(mask, pass, fail);
// }
//
// @Command(
// name = "#offset",
// desc = "Offset a pattern"
//)
// public Pattern offset(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) {
//
// return new OffsetPattern(pattern, (int) x, (int) y, (int) z);
// }
//
// @Command(
// name = "#surfacespread",
// desc = "Applies to only blocks on a surface. Selects a block from provided pattern with a given randomized offset `[0, <distance>)`. e.g., Use `#existing` to randomly offset blocks in the world, or `#copy` to offset blocks in your clipboard"
//)
// public Pattern surfacespread(@Arg(desc = "spread distance (blocks)") double distance, @Arg(desc = "Pattern")Pattern pattern) {
//
// return new SurfaceRandomOffsetPattern(pattern, (int) distance);
// }
//
// @Command(
// name = "#solidspread",
// desc = "Randomly spread solid blocks"
//)
// public Pattern solidspread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) {
//
// return new SolidRandomOffsetPattern(pattern, (int) x, (int) y, (int) z);
// }
//
// @Command(
// name = "#spread",
// aliases = {"#randomoffset"},
// desc = "Randomly spread blocks"
//)
// public Pattern spread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) {
//
// return new RandomOffsetPattern(pattern, (int) x, (int) y, (int) z);
// }
//
// @Command(
// name = "#linear",
// aliases = {"#l"},
// desc = "Sequentially set blocks from a list of patterns"
//)
// public Pattern linear(@Arg(desc = "Pattern") Pattern other) {
//
// if (other instanceof RandomPattern) {
// Set<Pattern> patterns = ((RandomPattern) other).getPatterns();
// return new LinearBlockPattern(patterns.toArray(new Pattern[patterns.size()]));
// }
// return other;
// }
//
// @Command(
// name = "#linear3d",
// aliases = {"#l3d"},
// desc = "Use the x,y,z coordinate to pick a block from the list"
//)
// public Pattern linear3d(@Arg(desc = "Pattern") Pattern other) {
//
// if (other instanceof RandomPattern) {
// Set<Pattern> patterns = ((RandomPattern) other).getPatterns();
// return new Linear3DBlockPattern(patterns.toArray(new Pattern[patterns.size()]));
// }
// return other;
// }
//
// @Command(
// name = "#linear2d",
// aliases = {"#l2d"},
// desc = "Use the x,z coordinate to pick a block from the list"
//)
// public Pattern linear2d(@Arg(desc = "Pattern") Pattern other) {
//
// if (other instanceof RandomPattern) {
// Set<Pattern> patterns = ((RandomPattern) other).getPatterns();
// return new Linear2DBlockPattern(patterns.toArray(new Pattern[patterns.size()]));
// }
// return other;
// }
//
// @Command(
// name = "=",
// aliases = {"#=", "#expression"},
// desc = "Expression pattern: http://wiki.sk89q.com/wiki/WorldEdit/Expression_syntax"
//)
// public Pattern expression(Extent extent, @Arg(desc = "Expression") String input) throws ExpressionException {
//
// Expression exp = Expression.compile(input, "x", "y", "z");
// WorldEditExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO);
// exp.setEnvironment(env);
// return new ExpressionPattern(exp);
// }
//}

View File

@ -84,7 +84,6 @@ public class ToolUtilCommands {
if (maskOpt == null) {
player.printInfo(TranslatableComponent.of("worldedit.tool.mask.disabled"));
tool.setMask(null);
return;
} else {
BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext();
String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get()))
@ -150,18 +149,7 @@ public class ToolUtilCommands {
session.getBrushTool(player, false).setSize(size);
player.printInfo(TranslatableComponent.of("worldedit.tool.size.set"));
}
//todo none should be moved to the same class where it is in upstream
@Command(
name = "none",
aliases = {"/none"},
desc = "Unbind a bound tool from your current item"
)
public void none(Player player, LocalSession session) throws WorldEditException {
session.setTool(player, null);
player.print(TranslatableComponent.of("fawe.worldedit.tool.tool.none"));
}
@Command(
name = "tracemask",
aliases = {"tarmask", "tm", "targetmask"},
@ -368,31 +356,32 @@ public class ToolUtilCommands {
player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.source.mask"));
}
@Command(
name = "transform",
desc = "Set the brush transform"
)
@CommandPermissions({"worldedit.brush.options.transform", "worldedit.transform.brush"})
public void transform(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "The transform", def = "") ResettableExtent transform,
@Switch(name = 'h', desc = "TODO")
boolean offHand,
Arguments arguments) throws WorldEditException {
BrushTool tool = session.getBrushTool(player, false);
if (tool == null) {
player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none"));
return;
}
if (transform == null) {
player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform.disabled"));
tool.setTransform(null);
return;
}
BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext();
String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get())).getSubstring();
settings.addSetting(BrushSettings.SettingType.TRANSFORM, lastArg);
settings.setTransform(transform);
tool.update();
player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform"));
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// @Command(
// name = "transform",
// desc = "Set the brush transform"
// )
// @CommandPermissions({"worldedit.brush.options.transform", "worldedit.transform.brush"})
// public void transform(Player player, LocalSession session, EditSession editSession,
// @Arg(desc = "The transform", def = "") ResettableExtent transform,
// @Switch(name = 'h', desc = "TODO")
// boolean offHand,
// Arguments arguments) throws WorldEditException {
// BrushTool tool = session.getBrushTool(player, false);
// if (tool == null) {
// player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none"));
// return;
// }
// if (transform == null) {
// player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform.disabled"));
// tool.setTransform(null);
// return;
// }
// BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext();
// String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get())).getSubstring();
// settings.addSetting(BrushSettings.SettingType.TRANSFORM, lastArg);
// settings.setTransform(transform);
// tool.update();
// player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform"));
// }
}

View File

@ -1,104 +1,105 @@
package com.sk89q.worldedit.command;
import com.boydti.fawe.object.extent.Linear3DTransform;
import com.boydti.fawe.object.extent.LinearTransform;
import com.boydti.fawe.object.extent.OffsetExtent;
import com.boydti.fawe.object.extent.PatternTransform;
import com.boydti.fawe.object.extent.RandomOffsetTransform;
import com.boydti.fawe.object.extent.RandomTransform;
import com.boydti.fawe.object.extent.ResettableExtent;
import com.boydti.fawe.object.extent.ScaleTransform;
import com.boydti.fawe.object.extent.TransformExtent;
import com.boydti.fawe.util.ExtentTraverser;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.transform.BlockTransformExtent;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.transform.AffineTransform;
import java.util.Set;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class TransformCommands {
@Command(
name = "#linear",
aliases = {"#l"},
desc = "Sequentially pick from a list of transform"
)
public ResettableExtent linear(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
if (other instanceof RandomTransform) {
Set<ResettableExtent> extents = ((RandomTransform) other).getExtents();
return new LinearTransform(extents.toArray(new ResettableExtent[0]));
}
return other;
}
@Command(
name = "#linear3d",
aliases = {"#l3d"},
desc = "Use the x,y,z coordinate to pick a transform from the list"
)
public ResettableExtent linear3d(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
if (other instanceof RandomTransform) {
Set<ResettableExtent> extents = ((RandomTransform) other).getExtents();
return new Linear3DTransform(extents.toArray(new ResettableExtent[0]));
}
return other;
}
@Command(
name = "#pattern",
desc = "Always use a specific pattern"
)
public ResettableExtent pattern(Actor actor, LocalSession session, @Arg(desc = "Pattern") Pattern pattern, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
return new PatternTransform(other, pattern);
}
@Command(
name = "#offset",
desc = "Offset transform"
)
public ResettableExtent offset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
return new OffsetExtent(other, (int) x, (int) y, (int) z);
}
@Command(
name = "#spread",
aliases = {"#randomoffset"},
desc = "Random offset transform"
)
public ResettableExtent randomOffset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
return new RandomOffsetTransform(other, (int) x, (int) y, (int) z);
}
@Command(
name = "#scale",
desc = "All changes will be scaled"
)
public ResettableExtent scale(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
return new ScaleTransform(other, x, y, z);
}
@Command(
name = "#rotate",
desc = "All changes will be rotate around the initial position"
)
public ResettableExtent rotate(Player player, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
ExtentTraverser<TransformExtent> traverser = new ExtentTraverser<>(other).find(TransformExtent.class);
BlockTransformExtent affine = traverser != null ? traverser.get() : null;
if (affine == null) {
other = affine = new TransformExtent(other);
}
AffineTransform transform = (AffineTransform) affine.getTransform();
transform = transform.rotateX(x);
transform = transform.rotateY(y);
transform = transform.rotateZ(z);
affine.setTransform(transform);
return other;
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
//package com.sk89q.worldedit.command;
//
//import com.boydti.fawe.object.extent.Linear3DTransform;
//import com.boydti.fawe.object.extent.LinearTransform;
//import com.boydti.fawe.object.extent.OffsetExtent;
//import com.boydti.fawe.object.extent.PatternTransform;
//import com.boydti.fawe.object.extent.RandomOffsetTransform;
//import com.boydti.fawe.object.extent.RandomTransform;
//import com.boydti.fawe.object.extent.ResettableExtent;
//import com.boydti.fawe.object.extent.ScaleTransform;
//import com.boydti.fawe.object.extent.TransformExtent;
//import com.boydti.fawe.util.ExtentTraverser;
//import com.sk89q.worldedit.LocalSession;
//import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
//import com.sk89q.worldedit.entity.Player;
//import com.sk89q.worldedit.extension.platform.Actor;
//import com.sk89q.worldedit.extent.transform.BlockTransformExtent;
//import com.sk89q.worldedit.function.pattern.Pattern;
//import com.sk89q.worldedit.math.transform.AffineTransform;
//import java.util.Set;
//import org.enginehub.piston.annotation.Command;
//import org.enginehub.piston.annotation.CommandContainer;
//import org.enginehub.piston.annotation.param.Arg;
//
//@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class)
//public class TransformCommands {
//
// @Command(
// name = "#linear",
// aliases = {"#l"},
// desc = "Sequentially pick from a list of transform"
// )
// public ResettableExtent linear(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
// if (other instanceof RandomTransform) {
// Set<ResettableExtent> extents = ((RandomTransform) other).getExtents();
// return new LinearTransform(extents.toArray(new ResettableExtent[0]));
// }
// return other;
// }
//
// @Command(
// name = "#linear3d",
// aliases = {"#l3d"},
// desc = "Use the x,y,z coordinate to pick a transform from the list"
// )
// public ResettableExtent linear3d(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
// if (other instanceof RandomTransform) {
// Set<ResettableExtent> extents = ((RandomTransform) other).getExtents();
// return new Linear3DTransform(extents.toArray(new ResettableExtent[0]));
// }
// return other;
// }
//
// @Command(
// name = "#pattern",
// desc = "Always use a specific pattern"
// )
// public ResettableExtent pattern(Actor actor, LocalSession session, @Arg(desc = "Pattern") Pattern pattern, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
// return new PatternTransform(other, pattern);
// }
//
// @Command(
// name = "#offset",
// desc = "Offset transform"
// )
// public ResettableExtent offset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
// return new OffsetExtent(other, (int) x, (int) y, (int) z);
// }
//
// @Command(
// name = "#spread",
// aliases = {"#randomoffset"},
// desc = "Random offset transform"
//)
// public ResettableExtent randomOffset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
// return new RandomOffsetTransform(other, (int) x, (int) y, (int) z);
// }
//
// @Command(
// name = "#scale",
// desc = "All changes will be scaled"
// )
// public ResettableExtent scale(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
// return new ScaleTransform(other, x, y, z);
// }
//
// @Command(
// name = "#rotate",
// desc = "All changes will be rotate around the initial position"
// )
// public ResettableExtent rotate(Player player, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) {
// ExtentTraverser<TransformExtent> traverser = new ExtentTraverser<>(other).find(TransformExtent.class);
// BlockTransformExtent affine = traverser != null ? traverser.get() : null;
// if (affine == null) {
// other = affine = new TransformExtent(other);
// }
// AffineTransform transform = (AffineTransform) affine.getTransform();
// transform = transform.rotateX(x);
// transform = transform.rotateY(y);
// transform = transform.rotateZ(z);
// affine.setTransform(transform);
// return other;
// }
//}

View File

@ -104,7 +104,6 @@ public final class RegistryConverter<V extends Keyed> implements ArgumentConvert
: SuccessfulConversion.fromSingle(result);
}
@Override
public List<String> getSuggestions(String input) {
return SuggestionHelper.getRegistrySuggestions(registry, input).collect(Collectors.toList());
}

View File

@ -125,38 +125,39 @@ public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool
public BrushTool() {
}
public static BrushTool fromString(Player player, LocalSession session, String json) throws CommandException, InputParseException {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>() {
}.getType();
Map<String, Object> root = gson.fromJson(json, type);
if (root == null) {
getLogger(BrushTool.class).debug("Failed to load " + json);
return new BrushTool();
}
Map<String, Object> primary = (Map<String, Object>) root.get("primary");
Map<String, Object> secondary = (Map<String, Object>) root.getOrDefault("secondary", primary);
VisualMode visual = VisualMode.valueOf((String) root.getOrDefault("visual", "NONE"));
TargetMode target = TargetMode.valueOf((String) root.getOrDefault("target", "TARGET_BLOCK_RANGE"));
int range = ((Number) root.getOrDefault("range", -1)).intValue();
int offset = ((Number) root.getOrDefault("offset", 0)).intValue();
BrushTool tool = new BrushTool();
tool.visualMode = visual;
tool.targetMode = target;
tool.range = range;
tool.targetOffset = offset;
BrushSettings primarySettings = BrushSettings.get(tool, player, session, primary);
tool.setPrimary(primarySettings);
if (primary != secondary) {
BrushSettings secondarySettings = BrushSettings.get(tool, player, session, secondary);
tool.setSecondary(secondarySettings);
}
return tool;
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// public static BrushTool fromString(Player player, LocalSession session, String json) throws CommandException, InputParseException {
// Gson gson = new Gson();
// Type type = new TypeToken<Map<String, Object>>() {
// }.getType();
// Map<String, Object> root = gson.fromJson(json, type);
// if (root == null) {
// getLogger(BrushTool.class).debug("Failed to load " + json);
// return new BrushTool();
// }
// Map<String, Object> primary = (Map<String, Object>) root.get("primary");
// Map<String, Object> secondary = (Map<String, Object>) root.getOrDefault("secondary", primary);
//
// VisualMode visual = VisualMode.valueOf((String) root.getOrDefault("visual", "NONE"));
// TargetMode target = TargetMode.valueOf((String) root.getOrDefault("target", "TARGET_BLOCK_RANGE"));
// int range = ((Number) root.getOrDefault("range", -1)).intValue();
// int offset = ((Number) root.getOrDefault("offset", 0)).intValue();
//
// BrushTool tool = new BrushTool();
// tool.visualMode = visual;
// tool.targetMode = target;
// tool.range = range;
// tool.targetOffset = offset;
//
// BrushSettings primarySettings = BrushSettings.get(tool, player, session, primary);
// tool.setPrimary(primarySettings);
// if (primary != secondary) {
// BrushSettings secondarySettings = BrushSettings.get(tool, player, session, secondary);
// tool.setSecondary(secondarySettings);
// }
//
// return tool;
// }
public void setHolder(BaseItem holder) {
this.holder = holder;

View File

@ -103,7 +103,7 @@ public final class AsyncCommandBuilder<T> {
public AsyncCommandBuilder<T> onSuccess(@Nullable String message, @Nullable Consumer<T> consumer) {
checkArgument(message != null || consumer != null, "Can't have null message AND consumer");
this.successMessage = message == null ? null : TextComponent.of(message, TextColor.GRAY);
this.successMessage = message == null ? null : TextComponent.of(message, TextColor.LIGHT_PURPLE);
this.consumer = consumer;
return this;
}

View File

@ -19,7 +19,6 @@
package com.sk89q.worldedit.command.util;
import com.boydti.fawe.util.StringMan;
import com.google.common.collect.ImmutableSet;
import org.enginehub.piston.Command;
import org.enginehub.piston.gen.CommandConditionGenerator;

View File

@ -1,83 +0,0 @@
package com.sk89q.worldedit.command.util;
import com.google.common.collect.ImmutableSet;
import org.enginehub.piston.Command;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.CommandParseResult;
import org.enginehub.piston.converter.ArgumentConverter;
import org.enginehub.piston.inject.InjectedValueAccess;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.suggestion.Suggestion;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class DelegateCommandManager implements CommandManager {
@Override
public Command.Builder newCommand(String s) {
return parent.newCommand(s);
}
@Override
public void register(Command command) {
parent.register(command);
}
@Override
public void register(String name, Consumer<Command.Builder> registrationProcess) {
parent.register(name, registrationProcess);
}
@Override
public void registerManager(CommandManager manager) {
parent.registerManager(manager);
}
@Override
public Stream<Command> getAllCommands() {
return parent.getAllCommands();
}
@Override
public boolean containsCommand(String name) {
return parent.containsCommand(name);
}
@Override
public Optional<Command> getCommand(String s) {
return parent.getCommand(s);
}
@Override
public ImmutableSet<Suggestion> getSuggestions(InjectedValueAccess injectedValueAccess, List<String> list) {
return parent.getSuggestions(injectedValueAccess, list);
}
@Override
public CommandParseResult parse(InjectedValueAccess injectedValueAccess, List<String> list) {
return parent.parse(injectedValueAccess, list);
}
@Override
public Object execute(InjectedValueAccess context, List<String> args) {
return parent.execute(context, args);
}
@Override
public <T> void registerConverter(Key<T> key, ArgumentConverter<T> argumentConverter) {
parent.registerConverter(key, argumentConverter);
}
@Override
public <T> Optional<ArgumentConverter<T>> getConverter(Key<T> key) {
return parent.getConverter(key);
}
private final CommandManager parent;
public DelegateCommandManager(CommandManager parent) {
this.parent = parent;
}
}

View File

@ -24,9 +24,9 @@ import com.sk89q.worldedit.entity.metadata.EntityProperties;
import com.sk89q.worldedit.function.EntityFunction;
import javax.annotation.Nullable;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.regex.Pattern;
/**
* The implementation of /remove.

View File

@ -21,4 +21,4 @@ package com.sk89q.worldedit.command.util;
public enum HookMode {
ACTIVE, INACTIVE
}
}

View File

@ -1,24 +0,0 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.command.util;
public enum HookMode {
ACTIVE, INACTIVE
}

View File

@ -19,7 +19,6 @@
package com.sk89q.worldedit.command.util;
import com.boydti.fawe.util.StringMan;
import com.sk89q.worldedit.extension.platform.Actor;
import org.enginehub.piston.Command;
import org.enginehub.piston.inject.InjectedValueAccess;

View File

@ -32,14 +32,15 @@ import com.sk89q.worldedit.util.formatting.component.CommandUsageBox;
import com.sk89q.worldedit.util.formatting.component.InvalidComponentException;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import org.enginehub.piston.Command;
import org.enginehub.piston.CommandManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.enginehub.piston.Command;
import org.enginehub.piston.CommandManager;
/**
* Implementation of the //help command.

View File

@ -19,9 +19,6 @@
package com.sk89q.worldedit.command.util;
import static org.enginehub.piston.converter.SuggestionHelper.byPrefix;
import static org.enginehub.piston.converter.SuggestionHelper.limitByPrefix;
import com.sk89q.worldedit.registry.Keyed;
import com.sk89q.worldedit.registry.NamespacedRegistry;
import com.sk89q.worldedit.registry.Registry;
@ -40,6 +37,9 @@ import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.enginehub.piston.converter.SuggestionHelper.byPrefix;
import static org.enginehub.piston.converter.SuggestionHelper.limitByPrefix;
/**
* Internal class for generating common command suggestions.
*/

View File

@ -1,135 +1,136 @@
package com.sk89q.worldedit.extension.factory;
import com.boydti.fawe.command.FaweParser;
import com.boydti.fawe.command.SuggestInputParseException;
import com.boydti.fawe.object.extent.MultiTransform;
import com.boydti.fawe.object.extent.RandomTransform;
import com.boydti.fawe.object.extent.ResettableExtent;
import com.boydti.fawe.object.random.TrueRandom;
import com.boydti.fawe.util.StringMan;
import com.google.common.collect.Iterables;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.WorldEdit;
//import com.sk89q.worldedit.command.TransformCommands;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.internal.expression.Expression;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DefaultTransformParser extends FaweParser<ResettableExtent> {
public DefaultTransformParser(WorldEdit worldEdit) {
super(worldEdit, "transforms");
}
@Override
public ResettableExtent parseFromInput(String input, ParserContext context) throws InputParseException {
if (input.isEmpty()) return null;
List<Double> unionChances = new ArrayList<>();
List<Double> intersectionChances = new ArrayList<>();
List<ResettableExtent> intersection = new ArrayList<>();
List<ResettableExtent> union = new ArrayList<>();
final CommandLocals locals = new CommandLocals();
Actor actor = context != null ? context.getActor() : null;
if (actor != null) {
locals.put(Actor.class, actor);
}
try {
List<Map.Entry<ParseEntry, List<String>>> parsed = parse(input);
for (Map.Entry<ParseEntry, List<String>> entry : parsed) {
ParseEntry pe = entry.getKey();
String command = pe.input;
ResettableExtent transform = null;
double chance = 1;
if (command.isEmpty()) {
transform = parseFromInput(StringMan.join(entry.getValue(), ','), context);
} else {
List<String> args = entry.getValue();
String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
try {
transform = parse(command + cmdArgs, context);
} catch (SuggestInputParseException rethrow) {
throw rethrow;
} catch (Throwable e) {
throw new NoMatchException("See: //transforms");
}
if (transform == null) {
// Legacy syntax
int percentIndex = command.indexOf('%');
if (percentIndex != -1) { // Legacy percent pattern
chance = Expression.compile(command.substring(0, percentIndex)).evaluate();
command = command.substring(percentIndex + 1);
if (!entry.getValue().isEmpty()) {
if (!command.isEmpty()) command += " ";
command += StringMan.join(entry.getValue(), " ");
}
transform = parseFromInput(command, context);
} else {
throw new NoMatchException("See: //transforms");
}
}
if (pe.and) { // &
intersectionChances.add(chance);
intersection.add(transform);
} else {
if (!intersection.isEmpty()) {
if (intersection.size() == 1) {
throw new InputParseException("Error, floating &");
}
MultiTransform multi = new MultiTransform();
double total = 0;
for (int i = 0; i < intersection.size(); i++) {
Double value = intersectionChances.get(i);
total += value;
multi.add(intersection.get(i), value);
}
union.add(multi);
unionChances.add(total);
intersection.clear();
intersectionChances.clear();
}
unionChances.add(chance);
union.add(transform);
}
}
}
} catch (Throwable e) {
throw new InputParseException(e.getMessage(), e);
}
if (!intersection.isEmpty()) {
if (intersection.size() == 1) {
throw new InputParseException("Error, floating &");
}
MultiTransform multi = new MultiTransform();
double total = 0;
for (int i = 0; i < intersection.size(); i++) {
Double value = intersectionChances.get(i);
total += value;
multi.add(intersection.get(i), value);
}
union.add(multi);
unionChances.add(total);
intersection.clear();
intersectionChances.clear();
}
if (union.isEmpty()) {
throw new NoMatchException("See: //transforms");
} else if (union.size() == 1) {
return union.get(0);
} else {
RandomTransform random = new RandomTransform(new TrueRandom());
for (int i = 0; i < union.size(); i++) {
random.add(union.get(i), unionChances.get(i));
}
return random;
}
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
//package com.sk89q.worldedit.extension.factory;
//
//import com.boydti.fawe.command.FaweParser;
//import com.boydti.fawe.command.SuggestInputParseException;
//import com.boydti.fawe.object.extent.MultiTransform;
//import com.boydti.fawe.object.extent.RandomTransform;
//import com.boydti.fawe.object.extent.ResettableExtent;
//import com.boydti.fawe.object.random.TrueRandom;
//import com.boydti.fawe.util.StringMan;
//import com.google.common.collect.Iterables;
//import com.sk89q.minecraft.util.commands.CommandLocals;
//import com.sk89q.worldedit.WorldEdit;
////import com.sk89q.worldedit.command.TransformCommands;
//import com.sk89q.worldedit.extension.input.InputParseException;
//import com.sk89q.worldedit.extension.input.NoMatchException;
//import com.sk89q.worldedit.extension.input.ParserContext;
//import com.sk89q.worldedit.extension.platform.Actor;
//import com.sk89q.worldedit.internal.expression.Expression;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
//public class DefaultTransformParser extends FaweParser<ResettableExtent> {
//
// public DefaultTransformParser(WorldEdit worldEdit) {
// super(worldEdit, "transforms");
// }
//
// @Override
// public ResettableExtent parseFromInput(String input, ParserContext context) throws InputParseException {
// if (input.isEmpty()) return null;
//
// List<Double> unionChances = new ArrayList<>();
// List<Double> intersectionChances = new ArrayList<>();
//
// List<ResettableExtent> intersection = new ArrayList<>();
// List<ResettableExtent> union = new ArrayList<>();
// final CommandLocals locals = new CommandLocals();
// Actor actor = context != null ? context.getActor() : null;
// if (actor != null) {
// locals.put(Actor.class, actor);
// }
// try {
// List<Map.Entry<ParseEntry, List<String>>> parsed = parse(input);
// for (Map.Entry<ParseEntry, List<String>> entry : parsed) {
// ParseEntry pe = entry.getKey();
// String command = pe.input;
// ResettableExtent transform;
// double chance = 1;
// if (command.isEmpty()) {
// transform = parseFromInput(StringMan.join(entry.getValue(), ','), context);
// } else {
// List<String> args = entry.getValue();
// String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
// try {
// transform = parse(command + cmdArgs, context);
// } catch (SuggestInputParseException rethrow) {
// throw rethrow;
// } catch (Throwable e) {
// throw new NoMatchException("See: //transforms");
// }
// if (transform == null) {
// // Legacy syntax
// int percentIndex = command.indexOf('%');
// if (percentIndex != -1) { // Legacy percent pattern
// chance = Expression.compile(command.substring(0, percentIndex)).evaluate();
// command = command.substring(percentIndex + 1);
// if (!entry.getValue().isEmpty()) {
// if (!command.isEmpty()) command += " ";
// command += StringMan.join(entry.getValue(), " ");
// }
// transform = parseFromInput(command, context);
// } else {
// throw new NoMatchException("See: //transforms");
// }
// }
// if (pe.and) { // &
// intersectionChances.add(chance);
// intersection.add(transform);
// } else {
// if (!intersection.isEmpty()) {
// if (intersection.size() == 1) {
// throw new InputParseException("Error, floating &");
// }
// MultiTransform multi = new MultiTransform();
// double total = 0;
// for (int i = 0; i < intersection.size(); i++) {
// Double value = intersectionChances.get(i);
// total += value;
// multi.add(intersection.get(i), value);
// }
// union.add(multi);
// unionChances.add(total);
// intersection.clear();
// intersectionChances.clear();
// }
// unionChances.add(chance);
// union.add(transform);
// }
// }
// }
// } catch (Throwable e) {
// throw new InputParseException(e.getMessage(), e);
// }
// if (!intersection.isEmpty()) {
// if (intersection.size() == 1) {
// throw new InputParseException("Error, floating &");
// }
// MultiTransform multi = new MultiTransform();
// double total = 0;
// for (int i = 0; i < intersection.size(); i++) {
// Double value = intersectionChances.get(i);
// total += value;
// multi.add(intersection.get(i), value);
// }
// union.add(multi);
// unionChances.add(total);
// intersection.clear();
// intersectionChances.clear();
// }
// if (union.isEmpty()) {
// throw new NoMatchException("See: //transforms");
// } else if (union.size() == 1) {
// return union.get(0);
// } else {
// RandomTransform random = new RandomTransform(new TrueRandom());
// for (int i = 0; i < union.size(); i++) {
// random.add(union.get(i), unionChances.get(i));
// }
// return random;
// }
// }
//
//
//}

View File

@ -20,8 +20,18 @@
package com.sk89q.worldedit.extension.factory;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.factory.parser.mask.BiomeMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.BlockCategoryMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.BlockStateMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.BlocksMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.ExistingMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.ExpressionMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.LazyRegionMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.NegateMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.NoiseMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.OffsetMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.RegionMaskParser;
import com.sk89q.worldedit.extension.factory.parser.mask.SolidMaskParser;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException;
import com.sk89q.worldedit.extension.input.ParserContext;
@ -49,8 +59,6 @@ public final class MaskFactory extends AbstractFactory<Mask> {
* @param worldEdit the WorldEdit instance
*/
public MaskFactory(WorldEdit worldEdit) {
super(worldEdit, new DefaultMaskParser(worldEdit));
/*
super(worldEdit, new BlocksMaskParser(worldEdit));
register(new ExistingMaskParser(worldEdit));
@ -62,11 +70,8 @@ public final class MaskFactory extends AbstractFactory<Mask> {
register(new BlockStateMaskParser(worldEdit));
register(new NegateMaskParser(worldEdit));
register(new ExpressionMaskParser(worldEdit));
*/
register(new BlockCategoryMaskParser(worldEdit));
/*
register(new BiomeMaskParser(worldEdit));
*/
}

View File

@ -21,7 +21,11 @@ package com.sk89q.worldedit.extension.factory;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.factory.parser.pattern.BlockCategoryPatternParser;
import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser;
import com.sk89q.worldedit.extension.factory.parser.pattern.ClipboardPatternParser;
import com.sk89q.worldedit.extension.factory.parser.pattern.RandomPatternParser;
import com.sk89q.worldedit.extension.factory.parser.pattern.RandomStatePatternParser;
import com.sk89q.worldedit.extension.factory.parser.pattern.SingleBlockPatternParser;
import com.sk89q.worldedit.extension.factory.parser.pattern.TypeOrStateApplyingPatternParser;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.internal.registry.AbstractFactory;
@ -40,8 +44,6 @@ public final class PatternFactory extends AbstractFactory<Pattern> {
* @param worldEdit the WorldEdit instance
*/
public PatternFactory(WorldEdit worldEdit) {
super(worldEdit, new DefaultPatternParser(worldEdit));
/*
super(worldEdit, new SingleBlockPatternParser(worldEdit));
// split and parse each sub-pattern
@ -51,7 +53,6 @@ public final class PatternFactory extends AbstractFactory<Pattern> {
register(new ClipboardPatternParser(worldEdit));
register(new TypeOrStateApplyingPatternParser(worldEdit));
register(new RandomStatePatternParser(worldEdit));
*/
register(new BlockCategoryPatternParser(worldEdit));
}

View File

@ -43,6 +43,7 @@ import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.extent.inventory.SlottableBlockBag;
import com.sk89q.worldedit.internal.registry.InputParser;
@ -289,8 +290,17 @@ public class DefaultBlockParser extends InputParser<BaseBlock> {
if (typeString.isEmpty()) {
throw new InputParseException("Invalid format");
}
// PosX
if (typeString.matches("pos[0-9]+")) {
if ("hand".equalsIgnoreCase(typeString)) {
// Get the block type from the item in the user's hand.
final BaseBlock blockInHand = getBlockInHand(context.requireActor(), HandSide.MAIN_HAND);
state = blockInHand.toBlockState();
nbt = blockInHand.getNbtData();
} else if ("offhand".equalsIgnoreCase(typeString)) {
// Get the block type from the item in the user's off hand.
final BaseBlock blockInHand = getBlockInHand(context.requireActor(), HandSide.OFF_HAND);
state = blockInHand.toBlockState();
nbt = blockInHand.getNbtData();
} else if (typeString.matches("pos[0-9]+")) {
int index = Integer.parseInt(typeString.replaceAll("[a-z]+", ""));
// Get the block type from the "primary position"
final World world = context.requireWorld();
@ -301,45 +311,34 @@ public class DefaultBlockParser extends InputParser<BaseBlock> {
throw new InputParseException("Your selection is not complete.");
}
state = world.getBlock(primaryPosition);
} else if (typeString.matches("slot[0-9]+")) {
int slot = Integer.parseInt(typeString.substring(4)) - 1;
Actor actor = context.requireActor();
if (!(actor instanceof Player)) {
throw new InputParseException("The user is not a player!");
}
Player player = (Player) actor;
BlockBag bag = player.getInventoryBlockBag();
if (bag == null || !(bag instanceof SlottableBlockBag)) {
throw new InputParseException("Unsupported!");
}
SlottableBlockBag slottable = (SlottableBlockBag) bag;
BaseItem item = slottable.getItem(slot);
if (!item.getType().hasBlockType()) {
throw new InputParseException("You're not holding a block!");
}
state = item.getType().getBlockType().getDefaultState();
nbt = item.getNbtData();
} else {
if ("hand".equalsIgnoreCase(typeString)) {
// Get the block type from the item in the user's hand.
BaseBlock block = getBlockInHand(context.requireActor(), HandSide.MAIN_HAND);
state = block.toBlockState();
nbt = block.getNbtData();
} else if ("offhand".equalsIgnoreCase(typeString)) {
// Get the block type from the item in the user's off hand.
BaseBlock block = getBlockInHand(context.requireActor(), HandSide.OFF_HAND);
state = block.toBlockState();
nbt = block.getNbtData();
} else if (typeString.matches("slot[0-9]+")) {
int slot = Integer.parseInt(typeString.substring(4)) - 1;
Actor actor = context.requireActor();
if (!(actor instanceof Player)) {
throw new InputParseException("The user is not a player!");
}
Player player = (Player) actor;
BlockBag bag = player.getInventoryBlockBag();
if (bag == null || !(bag instanceof SlottableBlockBag)) {
throw new InputParseException("Unsupported!");
}
SlottableBlockBag slottable = (SlottableBlockBag) bag;
BaseItem item = slottable.getItem(slot);
BlockType type = BlockTypes.parse(typeString.toLowerCase(Locale.ROOT));
if (!item.getType().hasBlockType()) {
throw new InputParseException("You're not holding a block!");
}
state = item.getType().getBlockType().getDefaultState();
nbt = item.getNbtData();
} else {
BlockType type = BlockTypes.parse(typeString.toLowerCase(Locale.ROOT));
if (type != null) {
state = type.getDefaultState();
}
if (state == null) {
throw new NoMatchException("Does not match a valid block type: '" + input + "'");
}
if (type != null) {
state = type.getDefaultState();
}
if (state == null) {
throw new NoMatchException(
"Does not match a valid block type: '" + input + "'");
}
}
if (nbt == null) nbt = state.getNbtData();
@ -351,15 +350,15 @@ public class DefaultBlockParser extends InputParser<BaseBlock> {
if (stateString == null || stateString.isEmpty()) {
state = new FuzzyBlockState(state);
} else {
BlockType type = state.getBlockType();
BlockType blockType = state.getBlockType();
FuzzyBlockState.Builder fuzzyBuilder = FuzzyBlockState.builder();
fuzzyBuilder.type(type);
fuzzyBuilder.type(blockType);
String[] entries = stateString.split(",");
for (String entry : entries) {
String[] split = entry.split("=");
String key = split[0];
String val = split[1];
Property<Object> prop = type.getProperty(key);
Property<Object> prop = blockType.getProperty(key);
fuzzyBuilder.withProperty(prop, prop.getValueFor(val));
}
state = fuzzyBuilder.build();
@ -398,9 +397,17 @@ public class DefaultBlockParser extends InputParser<BaseBlock> {
// Allow setting mob spawn type
if (blockAndExtraData.length > 1) {
String mobName = blockAndExtraData[1];
EntityType mobType = EntityTypes.parse(mobName);
EntityType ent = EntityTypes.get(mobName.toLowerCase(Locale.ROOT));
if (ent == null) {
throw new NoMatchException("Unknown entity type '" + mobName + "'");
}
mobName = ent.getId();
if (!worldEdit.getPlatformManager().queryCapability(Capability.USER_COMMANDS).isValidMobType(mobName)) {
throw new NoMatchException("Unknown mob type '" + mobName + "'");
}
return validate(context, new MobSpawnerBlock(state, mobName));
} else {
//noinspection ConstantConditions
return validate(context, new MobSpawnerBlock(state, EntityTypes.PIG.getId()));
}
} else if (blockType == BlockTypes.PLAYER_HEAD || blockType == BlockTypes.PLAYER_WALL_HEAD) {

View File

@ -29,8 +29,6 @@ import com.sk89q.worldedit.internal.registry.InputParser;
import java.util.stream.Stream;
import java.util.stream.Stream;
public class BlockStateMaskParser extends InputParser<Mask> {
public BlockStateMaskParser(WorldEdit worldEdit) {

View File

@ -1,206 +1,207 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.extension.factory.parser.mask;
import com.boydti.fawe.command.FaweParser;
import com.boydti.fawe.command.SuggestInputParseException;
import com.boydti.fawe.config.Caption;
import com.boydti.fawe.util.StringMan;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.mask.BlockMaskBuilder;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.MaskIntersection;
import com.sk89q.worldedit.function.mask.MaskUnion;
import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DefaultMaskParser extends FaweParser<Mask> {
public DefaultMaskParser(WorldEdit worldEdit) {
super(worldEdit, "masks");
}
@Override
public Mask parseFromInput(String input, ParserContext context) throws InputParseException {
if (input.isEmpty()) {
throw new SuggestInputParseException("No input provided", "", () -> Stream.concat(Stream.of("#", ",", "&"), BlockTypes.getNameSpaces().stream().map(n -> n + ":")).collect(Collectors.toList()));
}
Extent extent = Request.request().getExtent();
if (extent == null) extent = context.getExtent();
List<List<Mask>> masks = new ArrayList<>();
masks.add(new ArrayList<>());
final CommandLocals locals = new CommandLocals();
Actor actor = context != null ? context.getActor() : null;
if (actor != null) {
locals.put(Actor.class, actor);
}
try {
List<Map.Entry<ParseEntry, List<String>>> parsed = parse(input);
for (Map.Entry<ParseEntry, List<String>> entry : parsed) {
ParseEntry pe = entry.getKey();
final String command = pe.input;
String full = pe.full;
Mask mask = null;
if (command.isEmpty()) {
mask = parseFromInput(StringMan.join(entry.getValue(), ','), context);
} else {
List<String> args = entry.getValue();
String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
try {
mask = parse(command + cmdArgs, context);
} catch (SuggestInputParseException rethrow) {
throw rethrow;
} catch (Throwable e) {
// TODO NOT IMPLEMENTED
// throw SuggestInputParseException.of(e, full, () -> {
// try {
// List<String> suggestions = dispatcher.get(command).getCallable().getSuggestions(cmdArgs, locals);
// if (suggestions.size() <= 2) {
// for (int i = 0; i < suggestions.size(); i++) {
// String suggestion = suggestions.get(i);
// if (suggestion.indexOf(' ') != 0) {
// String[] split = suggestion.split(" ");
// suggestion = "[" + StringMan.join(split, "][") + "]";
// suggestions.set(i, suggestion);
// }
// TODO: Ping @MattBDev to reimplement 2020-02-04
///*
// * WorldEdit, a Minecraft world manipulation toolkit
// * Copyright (C) sk89q <http://www.sk89q.com>
// * Copyright (C) WorldEdit team and contributors
// *
// * This program is free software: you can redistribute it and/or modify it
// * under the terms of the GNU Lesser General Public License as published by the
// * Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful, but WITHOUT
// * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
// * for more details.
// *
// * You should have received a copy of the GNU Lesser General Public License
// * along with this program. If not, see <http://www.gnu.org/licenses/>.
// */
//
//package com.sk89q.worldedit.extension.factory.parser.mask;
//
//import com.boydti.fawe.command.FaweParser;
//import com.boydti.fawe.command.SuggestInputParseException;
//import com.boydti.fawe.config.Caption;
//import com.boydti.fawe.util.StringMan;
//import com.sk89q.minecraft.util.commands.CommandLocals;
//import com.sk89q.worldedit.WorldEdit;
//import com.sk89q.worldedit.extension.input.InputParseException;
//import com.sk89q.worldedit.extension.input.ParserContext;
//import com.sk89q.worldedit.extension.platform.Actor;
//import com.sk89q.worldedit.extent.Extent;
//import com.sk89q.worldedit.function.mask.BlockMaskBuilder;
//import com.sk89q.worldedit.function.mask.Mask;
//import com.sk89q.worldedit.function.mask.MaskIntersection;
//import com.sk89q.worldedit.function.mask.MaskUnion;
//import com.sk89q.worldedit.session.request.Request;
//import com.sk89q.worldedit.world.block.BaseBlock;
//import com.sk89q.worldedit.world.block.BlockStateHolder;
//import com.sk89q.worldedit.world.block.BlockTypes;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//import java.util.stream.Stream;
//
//public class DefaultMaskParser extends FaweParser<Mask> {
// public DefaultMaskParser(WorldEdit worldEdit) {
// super(worldEdit, "masks");
// }
//
// @Override
// public Mask parseFromInput(String input, ParserContext context) throws InputParseException {
// if (input.isEmpty()) {
// throw new SuggestInputParseException("No input provided", "", () -> Stream.concat(Stream.of("#", ",", "&"), BlockTypes.getNameSpaces().stream().map(n -> n + ":")).collect(Collectors.toList()));
// }
// Extent extent = Request.request().getExtent();
// if (extent == null) extent = context.getExtent();
// List<List<Mask>> masks = new ArrayList<>();
// masks.add(new ArrayList<>());
//
// final CommandLocals locals = new CommandLocals();
// Actor actor = context != null ? context.getActor() : null;
// if (actor != null) {
// locals.put(Actor.class, actor);
// }
// try {
// List<Map.Entry<ParseEntry, List<String>>> parsed = parse(input);
// for (Map.Entry<ParseEntry, List<String>> entry : parsed) {
// ParseEntry pe = entry.getKey();
// final String command = pe.input;
// String full = pe.full;
// Mask mask = null;
// if (command.isEmpty()) {
// mask = parseFromInput(StringMan.join(entry.getValue(), ','), context);
// } else {
// List<String> args = entry.getValue();
// String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
// try {
// mask = parse(command + cmdArgs, context);
// } catch (SuggestInputParseException rethrow) {
// throw rethrow;
// } catch (Throwable e) {
// // TODO NOT IMPLEMENTED
//// throw SuggestInputParseException.of(e, full, () -> {
//// try {
//// List<String> suggestions = dispatcher.get(command).getCallable().getSuggestions(cmdArgs, locals);
//// if (suggestions.size() <= 2) {
//// for (int i = 0; i < suggestions.size(); i++) {
//// String suggestion = suggestions.get(i);
//// if (suggestion.indexOf(' ') != 0) {
//// String[] split = suggestion.split(" ");
//// suggestion = "[" + StringMan.join(split, "][") + "]";
//// suggestions.set(i, suggestion);
//// }
//// }
//// }
//// return suggestions;
//// } catch (CommandException e1) {
//// throw new InputParseException(e1.getMessage());
//// } catch (Throwable e2) {
//// e2.printStackTrace();
//// throw new InputParseException(e2.getMessage());
//// }
//// });
// }
// if (mask == null) {
// // Legacy patterns
// char char0 = command.charAt(0);
// boolean charMask = input.length() > 1 && input.charAt(1) != '[';
// if (charMask && input.charAt(0) == '=') {
// return parseFromInput(char0 + "[" + input.substring(1) + "]", context);
// }
// if (char0 == '#' || char0 == '?') {
// // TODO NOT IMPLEMENTED
//// throw new SuggestInputParseException(new NoMatchException("Unknown mask: " + full + ", See: //masks"), full,
//// () -> {
//// if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases());
//// return dispatcher.getAliases().stream().filter(
//// s -> s.startsWith(command.toLowerCase())
//// ).collect(Collectors.toList());
//// }
//// );
// }
// // Legacy syntax
// if (charMask) {
// switch (char0) {
// case '\\': //
// case '/': //
// case '{': //
// case '$': //
// case '%': {
// String value = command.substring(1) + ((entry.getValue().isEmpty()) ? "" : "[" + StringMan.join(entry.getValue(), "][") + "]");
// if (value.contains(":")) {
// if (value.charAt(0) == ':') value.replaceFirst(":", "");
// value = value.replaceAll(":", "][");
// }
// mask = parseFromInput("#" + char0 + "[" + value + "]", context);
// break;
// }
// return suggestions;
// } catch (CommandException e1) {
// throw new InputParseException(e1.getMessage());
// } catch (Throwable e2) {
// e2.printStackTrace();
// throw new InputParseException(e2.getMessage());
// }
// });
}
if (mask == null) {
// Legacy patterns
char char0 = command.charAt(0);
boolean charMask = input.length() > 1 && input.charAt(1) != '[';
if (charMask && input.charAt(0) == '=') {
return parseFromInput(char0 + "[" + input.substring(1) + "]", context);
}
if (char0 == '#' || char0 == '?') {
// TODO NOT IMPLEMENTED
// throw new SuggestInputParseException(new NoMatchException("Unknown mask: " + full + ", See: //masks"), full,
// () -> {
// if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases());
// return dispatcher.getAliases().stream().filter(
// s -> s.startsWith(command.toLowerCase())
// ).collect(Collectors.toList());
// case '|':
// case '~':
// case '<':
// case '>':
// case '!':
// input = input.substring(input.indexOf(char0) + 1);
// mask = parseFromInput(char0 + "[" + input + "]", context);
// if (actor != null) {
// actor.print(Caption.of("fawe.worldedit.help.command.clarifying.bracket" , char0 + "[" + input + "]"));
// }
// );
}
// Legacy syntax
if (charMask) {
switch (char0) {
case '\\': //
case '/': //
case '{': //
case '$': //
case '%': {
String value = command.substring(1) + ((entry.getValue().isEmpty()) ? "" : "[" + StringMan.join(entry.getValue(), "][") + "]");
if (value.contains(":")) {
if (value.charAt(0) == ':') value.replaceFirst(":", "");
value = value.replaceAll(":", "][");
}
mask = parseFromInput("#" + char0 + "[" + value + "]", context);
break;
}
case '|':
case '~':
case '<':
case '>':
case '!':
input = input.substring(input.indexOf(char0) + 1);
mask = parseFromInput(char0 + "[" + input + "]", context);
if (actor != null) {
actor.print(Caption.of("fawe.worldedit.help.command.clarifying.bracket" , char0 + "[" + input + "]"));
}
return mask;
}
}
}
if (mask == null) {
if (command.startsWith("[")) {
int end = command.lastIndexOf(']');
mask = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context);
} else {
List<String> entries = entry.getValue();
BlockMaskBuilder builder = new BlockMaskBuilder();
// if (StringMan.containsAny(full, "\\^$.|?+(){}<>~$!%^&*+-/"))
{
try {
builder.addRegex(full);
} catch (InputParseException ignore) {}
}
if (mask == null) {
context.setPreferringWildcard(false);
context.setRestricted(false);
BaseBlock block = worldEdit.getBlockFactory().parseFromInput(full, context);
builder.add(block);
mask = builder.build(extent);
}
}
}
}
if (pe.and) {
masks.add(new ArrayList<>());
}
masks.get(masks.size() - 1).add(mask);
}
} catch (InputParseException rethrow) {
throw rethrow;
} catch (Throwable e) {
e.printStackTrace();
throw new InputParseException(e.getMessage(), e);
}
List<Mask> maskUnions = new ArrayList<>();
for (List<Mask> maskList : masks) {
if (maskList.size() == 1) {
maskUnions.add(maskList.get(0));
} else if (maskList.size() != 0) {
maskUnions.add(new MaskUnion(maskList));
}
}
if (maskUnions.size() == 1) {
return maskUnions.get(0);
} else if (maskUnions.size() != 0) {
return new MaskIntersection(maskUnions);
} else {
return null;
}
}
}
// return mask;
// }
// }
// }
// if (mask == null) {
// if (command.startsWith("[")) {
// int end = command.lastIndexOf(']');
// mask = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context);
// } else {
// List<String> entries = entry.getValue();
// BlockMaskBuilder builder = new BlockMaskBuilder();
//// if (StringMan.containsAny(full, "\\^$.|?+(){}<>~$!%^&*+-/"))
// {
// try {
// builder.addRegex(full);
// } catch (InputParseException ignore) {}
// }
// if (mask == null) {
// context.setPreferringWildcard(false);
// context.setRestricted(false);
// BaseBlock block = worldEdit.getBlockFactory().parseFromInput(full, context);
// builder.add(block);
// mask = builder.build(extent);
// }
// }
// }
// }
// if (pe.and) {
// masks.add(new ArrayList<>());
// }
// masks.get(masks.size() - 1).add(mask);
// }
// } catch (InputParseException rethrow) {
// throw rethrow;
// } catch (Throwable e) {
// e.printStackTrace();
// throw new InputParseException(e.getMessage(), e);
// }
// List<Mask> maskUnions = new ArrayList<>();
// for (List<Mask> maskList : masks) {
// if (maskList.size() == 1) {
// maskUnions.add(maskList.get(0));
// } else if (maskList.size() != 0) {
// maskUnions.add(new MaskUnion(maskList));
// }
// }
// if (maskUnions.size() == 1) {
// return maskUnions.get(0);
// } else if (maskUnions.size() != 0) {
// return new MaskIntersection(maskUnions);
// } else {
// return null;
// }
//
// }
//}

View File

@ -1,184 +1,185 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.extension.factory.parser.pattern;
import com.boydti.fawe.command.FaweParser;
import com.boydti.fawe.command.SuggestInputParseException;
import com.boydti.fawe.object.random.TrueRandom;
import com.boydti.fawe.util.StringMan;
import com.google.common.collect.Iterables;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.RandomPattern;
import com.sk89q.worldedit.internal.expression.Expression;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DefaultPatternParser extends FaweParser<Pattern> {
public DefaultPatternParser(WorldEdit worldEdit) {
super(worldEdit, "patterns");
}
@Override
public Pattern parseFromInput(String input, ParserContext context) throws InputParseException {
if (input.isEmpty()) {
throw new SuggestInputParseException("No input provided", "", () -> Stream.concat(Stream.of("#", ",", "&"), BlockTypes.getNameSpaces().stream().map(n -> n + ":")).collect(Collectors.toList()));
}
List<Double> chances = new ArrayList<>();
List<Pattern> patterns = new ArrayList<>();
final CommandLocals locals = new CommandLocals();
Actor actor = context != null ? context.getActor() : null;
if (actor != null) {
locals.put(Actor.class, actor);
}
try {
for (Map.Entry<ParseEntry, List<String>> entry : parse(input)) {
ParseEntry pe = entry.getKey();
final String command = pe.input;
String full = pe.full;
Pattern pattern = null;
double chance = 1;
if (command.isEmpty()) {
pattern = parseFromInput(StringMan.join(entry.getValue(), ','), context);
} else {
List<String> args = entry.getValue();
String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
try {
pattern = parse(command + cmdArgs, context);
} catch (SuggestInputParseException rethrow) {
throw rethrow;
} catch (Throwable e) {
// TODO NOT IMPLEMENTED
// throw SuggestInputParseException.of(e, full, () -> {
// try {
// List<String> suggestions = dispatcher.get(command).getCallable().getSuggestions(cmdArgs, locals);
// if (suggestions.size() <= 2) {
// for (int i = 0; i < suggestions.size(); i++) {
// String suggestion = suggestions.get(i);
// if (suggestion.indexOf(' ') != 0) {
// String[] split = suggestion.split(" ");
// suggestion = "[" + StringMan.join(split, "][") + "]";
// suggestions.set(i, suggestion);
// }
// TODO: Ping @MattBDev to reimplement (or remove because this class is stupid) 2020-02-04
///*
// * WorldEdit, a Minecraft world manipulation toolkit
// * Copyright (C) sk89q <http://www.sk89q.com>
// * Copyright (C) WorldEdit team and contributors
// *
// * This program is free software: you can redistribute it and/or modify it
// * under the terms of the GNU Lesser General Public License as published by the
// * Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful, but WITHOUT
// * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
// * for more details.
// *
// * You should have received a copy of the GNU Lesser General Public License
// * along with this program. If not, see <http://www.gnu.org/licenses/>.
// */
//
//package com.sk89q.worldedit.extension.factory.parser.pattern;
//
//import com.boydti.fawe.command.FaweParser;
//import com.boydti.fawe.command.SuggestInputParseException;
//import com.boydti.fawe.object.random.TrueRandom;
//import com.boydti.fawe.util.StringMan;
//import com.google.common.collect.Iterables;
//import com.sk89q.minecraft.util.commands.CommandLocals;
//import com.sk89q.worldedit.WorldEdit;
//import com.sk89q.worldedit.extension.input.InputParseException;
//import com.sk89q.worldedit.extension.input.NoMatchException;
//import com.sk89q.worldedit.extension.input.ParserContext;
//import com.sk89q.worldedit.extension.platform.Actor;
//import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
//import com.sk89q.worldedit.function.pattern.Pattern;
//import com.sk89q.worldedit.function.pattern.RandomPattern;
//import com.sk89q.worldedit.internal.expression.Expression;
//import com.sk89q.worldedit.world.block.BlockTypes;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//import java.util.stream.Stream;
//
//public class DefaultPatternParser extends FaweParser<Pattern> {
//
// public DefaultPatternParser(WorldEdit worldEdit) {
// super(worldEdit, "patterns");
// }
//
// @Override
// public Pattern parseFromInput(String input, ParserContext context) throws InputParseException {
// if (input.isEmpty()) {
// throw new SuggestInputParseException("No input provided", "", () -> Stream.concat(Stream.of("#", ",", "&"), BlockTypes.getNameSpaces().stream().map(n -> n + ":")).collect(Collectors.toList()));
// }
// List<Double> chances = new ArrayList<>();
// List<Pattern> patterns = new ArrayList<>();
// final CommandLocals locals = new CommandLocals();
// Actor actor = context != null ? context.getActor() : null;
// if (actor != null) {
// locals.put(Actor.class, actor);
// }
// try {
// for (Map.Entry<ParseEntry, List<String>> entry : parse(input)) {
// ParseEntry pe = entry.getKey();
// final String command = pe.input;
// String full = pe.full;
// Pattern pattern = null;
// double chance = 1;
// if (command.isEmpty()) {
// pattern = parseFromInput(StringMan.join(entry.getValue(), ','), context);
// } else {
// List<String> args = entry.getValue();
// String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
// try {
// pattern = parse(command + cmdArgs, context);
// } catch (SuggestInputParseException rethrow) {
// throw rethrow;
// } catch (Throwable e) {
// // TODO NOT IMPLEMENTED
//// throw SuggestInputParseException.of(e, full, () -> {
//// try {
//// List<String> suggestions = dispatcher.get(command).getCallable().getSuggestions(cmdArgs, locals);
//// if (suggestions.size() <= 2) {
//// for (int i = 0; i < suggestions.size(); i++) {
//// String suggestion = suggestions.get(i);
//// if (suggestion.indexOf(' ') != 0) {
//// String[] split = suggestion.split(" ");
//// suggestion = "[" + StringMan.join(split, "][") + "]";
//// suggestions.set(i, suggestion);
//// }
//// }
//// }
//// return suggestions;
//// } catch (CommandException e1) {
//// throw new InputParseException(e1.getMessage());
//// } catch (Throwable e2) {
//// e2.printStackTrace();
//// throw new InputParseException(e2.getMessage());
//// }
//// });
// }
// if (pattern == null) {
// // Legacy patterns
// char char0 = command.charAt(0);
// boolean charMask = input.length() > 1 && input.charAt(1) != '[';
// if (charMask && input.charAt(0) == '=') {
// return parseFromInput(char0 + "[" + input.substring(1) + "]", context);
// }
// if (char0 == '#') {
// // TODO NOT IMPLEMENTED
//// throw new SuggestInputParseException(new NoMatchException("Unknown pattern: " + full + ", See: //patterns"), full,
//// () -> {
//// if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases());
//// return dispatcher.getAliases().stream().filter(
//// s -> s.startsWith(command.toLowerCase(Locale.ROOT))
//// ).collect(Collectors.toList());
//// }
//// );
// }
//
//
// if (charMask) {
// if (char0 == '$') {
// String value = command.substring(1) + ((entry.getValue().isEmpty()) ? ""
// : "[" + StringMan.join(entry.getValue(), "][") + "]");
// if (value.contains(":")) {
// if (value.charAt(0) == ':') {
// value.replaceFirst(":", "");
// }
// value = value.replaceAll(":", "][");
// }
// pattern = parseFromInput(char0 + "[" + value + "]", context);
// }
// }
// if (pattern == null) {
// if (command.startsWith("[")) {
// int end = command.lastIndexOf(']');
// pattern = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context);
// } else {
// int percentIndex = command.indexOf('%');
// if (percentIndex != -1) { // Legacy percent pattern
// chance = Expression.compile(command.substring(0, percentIndex)).evaluate();
// String value = command.substring(percentIndex + 1);
// if (!entry.getValue().isEmpty()) {
// if (!value.isEmpty()) value += " ";
// value += StringMan.join(entry.getValue(), " ");
// }
// pattern = parseFromInput(value, context);
// } else { // legacy block pattern
// try {
// pattern = worldEdit.getBlockFactory().parseFromInput(pe.full, context);
// } catch (NoMatchException e) {
// throw new NoMatchException(e.getMessage() + " See: //patterns");
// }
// }
// return suggestions;
// } catch (CommandException e1) {
// throw new InputParseException(e1.getMessage());
// } catch (Throwable e2) {
// e2.printStackTrace();
// throw new InputParseException(e2.getMessage());
// }
// });
}
if (pattern == null) {
// Legacy patterns
char char0 = command.charAt(0);
boolean charMask = input.length() > 1 && input.charAt(1) != '[';
if (charMask && input.charAt(0) == '=') {
return parseFromInput(char0 + "[" + input.substring(1) + "]", context);
}
if (char0 == '#') {
// TODO NOT IMPLEMENTED
// throw new SuggestInputParseException(new NoMatchException("Unknown pattern: " + full + ", See: //patterns"), full,
// () -> {
// if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases());
// return dispatcher.getAliases().stream().filter(
// s -> s.startsWith(command.toLowerCase(Locale.ROOT))
// ).collect(Collectors.toList());
// }
// );
}
if (charMask) {
if (char0 == '$') {
String value = command.substring(1) + ((entry.getValue().isEmpty()) ? ""
: "[" + StringMan.join(entry.getValue(), "][") + "]");
if (value.contains(":")) {
if (value.charAt(0) == ':') {
value.replaceFirst(":", "");
}
value = value.replaceAll(":", "][");
}
pattern = parseFromInput(char0 + "[" + value + "]", context);
}
}
if (pattern == null) {
if (command.startsWith("[")) {
int end = command.lastIndexOf(']');
pattern = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context);
} else {
int percentIndex = command.indexOf('%');
if (percentIndex != -1) { // Legacy percent pattern
chance = Expression.compile(command.substring(0, percentIndex)).evaluate();
String value = command.substring(percentIndex + 1);
if (!entry.getValue().isEmpty()) {
if (!value.isEmpty()) value += " ";
value += StringMan.join(entry.getValue(), " ");
}
pattern = parseFromInput(value, context);
} else { // legacy block pattern
try {
pattern = worldEdit.getBlockFactory().parseFromInput(pe.full, context);
} catch (NoMatchException e) {
throw new NoMatchException(e.getMessage() + " See: //patterns");
}
}
}
}
}
}
if (pattern != null) {
patterns.add(pattern);
chances.add(chance);
}
}
} catch (InputParseException rethrow) {
throw rethrow;
} catch (Throwable e) {
e.printStackTrace();
throw new InputParseException(e.getMessage(), e);
}
if (patterns.isEmpty()) {
return null;
}
if (patterns.size() == 1) {
return patterns.get(0);
}
RandomPattern random = new RandomPattern(new TrueRandom());
for (int i = 0; i < patterns.size(); i++) {
random.add(patterns.get(i), chances.get(i));
}
return random;
}
}
// }
// }
// }
// if (pattern != null) {
// patterns.add(pattern);
// chances.add(chance);
// }
// }
// } catch (InputParseException rethrow) {
// throw rethrow;
// } catch (Throwable e) {
// e.printStackTrace();
// throw new InputParseException(e.getMessage(), e);
// }
// if (patterns.isEmpty()) {
// return null;
// }
// if (patterns.size() == 1) {
// return patterns.get(0);
// }
// RandomPattern random = new RandomPattern(new TrueRandom());
// for (int i = 0; i < patterns.size(); i++) {
// random.add(patterns.get(i), chances.get(i));
// }
// return random;
// }
//}

View File

@ -24,12 +24,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.command.AnvilCommands;
import com.boydti.fawe.command.AnvilCommandsRegistration;
import com.boydti.fawe.command.CFICommands;
import com.boydti.fawe.command.CFICommandsRegistration;
import com.boydti.fawe.config.Caption;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator;
import com.boydti.fawe.object.changeset.CFIChangeSet;
import com.boydti.fawe.object.exception.FaweException;
import com.boydti.fawe.object.task.ThrowableSupplier;
import com.boydti.fawe.util.StringMan;
@ -62,13 +58,9 @@ import com.sk89q.worldedit.command.HistoryCommands;
import com.sk89q.worldedit.command.HistoryCommandsRegistration;
import com.sk89q.worldedit.command.HistorySubCommands;
import com.sk89q.worldedit.command.HistorySubCommandsRegistration;
import com.sk89q.worldedit.command.MaskCommands;
import com.sk89q.worldedit.command.MaskCommandsRegistration;
import com.sk89q.worldedit.command.NavigationCommands;
import com.sk89q.worldedit.command.NavigationCommandsRegistration;
import com.sk89q.worldedit.command.PaintBrushCommands;
import com.sk89q.worldedit.command.PatternCommands;
import com.sk89q.worldedit.command.PatternCommandsRegistration;
import com.sk89q.worldedit.command.RegionCommands;
import com.sk89q.worldedit.command.RegionCommandsRegistration;
import com.sk89q.worldedit.command.SchematicCommands;
@ -87,8 +79,6 @@ import com.sk89q.worldedit.command.ToolCommands;
import com.sk89q.worldedit.command.ToolCommandsRegistration;
import com.sk89q.worldedit.command.ToolUtilCommands;
import com.sk89q.worldedit.command.ToolUtilCommandsRegistration;
import com.sk89q.worldedit.command.TransformCommands;
import com.sk89q.worldedit.command.TransformCommandsRegistration;
import com.sk89q.worldedit.command.UtilityCommands;
import com.sk89q.worldedit.command.UtilityCommandsRegistration;
import com.sk89q.worldedit.command.WorldEditCommands;
@ -304,9 +294,10 @@ public final class PlatformCommandManager {
});
});
*/
globalInjectedValues.injectValue(Key.of(CFICommands.CFISettings.class),
context -> context.injectedValue(Key.of(Actor.class))
.orElseThrow(() -> new IllegalStateException("No CFI Settings")).getMeta("CFISettings"));
// TODO: Ping @MattBDev to reimplement 2020-02-04
// globalInjectedValues.injectValue(Key.of(CFICommands.CFISettings.class),
// context -> context.injectedValue(Key.of(Actor.class))
// .orElseThrow(() -> new IllegalStateException("No CFI Settings")).getMeta("CFISettings"));
globalInjectedValues.injectValue(Key.of(World.class),
context -> {
LocalSession localSession = context.injectedValue(Key.of(LocalSession.class))
@ -321,7 +312,6 @@ public final class PlatformCommandManager {
} else {
throw new MissingWorldException();
}
} catch (MissingWorldException e) {
exceptionConverter.convert(e);
throw new AssertionError("Should have thrown a new exception.", e);
@ -332,13 +322,13 @@ public final class PlatformCommandManager {
}
private <CI> void registerSubCommands(String name, List<String> aliases, String desc,
CommandRegistration<CI> registration, CI instance) {
CommandRegistration<CI> registration, CI instance) {
registerSubCommands(name, aliases, desc, registration, instance, m -> {});
}
private <CI> void registerSubCommands(String name, List<String> aliases, String desc,
CommandRegistration<CI> registration, CI instance,
Consumer<CommandManager> additionalConfig) {
CommandRegistration<CI> registration, CI instance,
Consumer<CommandManager> additionalConfig) {
commandManager.register(name, cmd -> {
cmd.aliases(aliases);
cmd.description(TextComponent.of(desc));
@ -396,27 +386,28 @@ public final class PlatformCommandManager {
public void registerAllCommands() {
if (Settings.IMP.ENABLED_COMPONENTS.COMMANDS) {
registerSubCommands(
"patterns",
ImmutableList.of(),
"Patterns determine what blocks are placed",
PatternCommandsRegistration.builder(),
new PatternCommands()
);
registerSubCommands(
"masks",
ImmutableList.of(),
"Masks determine which blocks are placed",
MaskCommandsRegistration.builder(),
new MaskCommands(worldEdit)
);
registerSubCommands(
"transforms",
ImmutableList.of(),
"Transforms modify how a block is placed",
TransformCommandsRegistration.builder(),
new TransformCommands()
);
// TODO: Ping @MattBDev to reimplement (or remove) 2020-02-04
// registerSubCommands(
// "patterns",
// ImmutableList.of(),
// "Patterns determine what blocks are placed",
// PatternCommandsRegistration.builder(),
// new PatternCommands()
// );
// registerSubCommands(
// "masks",
// ImmutableList.of(),
// "Masks determine which blocks are placed",
// MaskCommandsRegistration.builder(),
// new MaskCommands(worldEdit)
// );
// registerSubCommands(
// "transforms",
// ImmutableList.of(),
// "Transforms modify how a block is placed",
// TransformCommandsRegistration.builder(),
// new TransformCommands()
// );
registerSubCommands(
"schematic",
ImmutableList.of("schem", "/schematic", "/schem"),
@ -460,13 +451,14 @@ public final class PlatformCommandManager {
WorldEditCommandsRegistration.builder(),
new WorldEditCommands(worldEdit)
);
registerSubCommands(
"cfi",
ImmutableList.of("/cfi"),
"CFI commands",
CFICommandsRegistration.builder(),
new CFICommands(worldEdit)
);
// TODO: Ping @MattBDev to reimplement 2020-02-04
// registerSubCommands(
// "cfi",
// ImmutableList.of("/cfi"),
// "CFI commands",
// CFICommandsRegistration.builder(),
// new CFICommands(worldEdit)
// );
registerSubCommands(
"/anvil",
ImmutableList.of(),
@ -608,16 +600,6 @@ public final class PlatformCommandManager {
return CommandArgParser.forArgString(input).parseArgs();
}
public <T> T parseCommand(String args, Actor actor) {
InjectedValueAccess context;
if (actor == null) {
context = globalInjectedValues;
} else {
context = initializeInjectedValues(args::toString, actor, null);
}
return parseCommand(args, context);
}
public <T> T parseConverter(String args, InjectedValueAccess access, Class<T> clazz) {
ArgumentConverter<T> converter = commandManager.getConverter(Key.of(clazz)).orElse(null);
if (converter != null) {
@ -630,14 +612,6 @@ public final class PlatformCommandManager {
return null;
}
public <T> T parseCommand(String args, InjectedValueAccess access) {
if (args.isEmpty()) return null;
String[] split = parseArgs(args)
.map(Substring::getSubstring)
.toArray(String[]::new);
return (T) commandManager.execute(access, ImmutableList.copyOf(split));
}
@Subscribe
public void handleCommand(CommandEvent event) {
Request.reset();
@ -771,19 +745,20 @@ public final class PlatformCommandManager {
worldEdit.flushBlockBag(actor, editSession);
}
CFICommands.CFISettings cfi = actor.getMeta("CFISettings");
if (cfi != null) {
HeightMapMCAGenerator gen = cfi.getGenerator();
if (gen != null && gen.isModified()) {
try {
gen.update();
CFIChangeSet set = new CFIChangeSet(gen, actor.getUniqueId());
session.remember(actor, gen, set, actor.getLimit());
} catch (IOException e) {
e.printStackTrace();
}
}
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
// CFICommands.CFISettings cfi = actor.getMeta("CFISettings");
// if (cfi != null) {
// HeightMapMCAGenerator gen = cfi.getGenerator();
// if (gen != null && gen.isModified()) {
// try {
// gen.update();
// CFIChangeSet set = new CFIChangeSet(gen, actor.getUniqueId());
// session.remember(actor, gen, set, actor.getLimit());
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
Request.reset();
}

View File

@ -1,15 +1,7 @@
package com.sk89q.worldedit.extension.platform.binding;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.object.extent.NullExtent;
import com.boydti.fawe.object.extent.ResettableExtent;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extension.factory.DefaultTransformParser;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.expression.EvaluationException;
import com.sk89q.worldedit.internal.expression.Expression;
import com.sk89q.worldedit.internal.expression.ExpressionException;
@ -17,7 +9,6 @@ import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector2;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.world.World;
import java.util.Locale;
import javax.annotation.Nullable;
@ -44,29 +35,31 @@ public class PrimitiveBindings extends Bindings {
}
}
/**
* Gets an {@link Extent} from a {@link Binding}.
*
* @param argument the context
* @return an extent
* @throws InputParseException on other error
*/
@Binding
public ResettableExtent getResettableExtent(Actor actor, String argument) throws InputParseException {
if (argument.equalsIgnoreCase("#null")) {
return new NullExtent();
}
DefaultTransformParser parser = Fawe.get().getTransformParser();
ParserContext parserContext = new ParserContext();
if (actor instanceof Entity) {
Extent extent = ((Entity) actor).getExtent();
if (extent instanceof World) {
parserContext.setWorld((World) extent);
}
}
parserContext.setSession(WorldEdit.getInstance().getSessionManager().get(actor));
return parser.parseFromInput(argument, parserContext);
}
// TODO: Ping @MattBDev to reimplement 2020-02-04
//
// /**
// * Gets an {@link Extent} from a {@link Binding}.
// *
// * @param argument the context
// * @return an extent
// * @throws InputParseException on other error
// */
// @Binding
// public ResettableExtent getResettableExtent(Actor actor, String argument) throws InputParseException {
// if (argument.equalsIgnoreCase("#null")) {
// return new NullExtent();
// }
// DefaultTransformParser parser = Fawe.get().getTransformParser();
// ParserContext parserContext = new ParserContext();
// if (actor instanceof Entity) {
// Extent extent = ((Entity) actor).getExtent();
// if (extent instanceof World) {
// parserContext.setWorld((World) extent);
// }
// }
// parserContext.setSession(WorldEdit.getInstance().getSessionManager().get(actor));
// return parser.parseFromInput(argument, parserContext);
// }
/**
* Gets a type from a {@link Binding}.

View File

@ -1,6 +1,5 @@
package com.sk89q.worldedit.extension.platform.binding;
import com.boydti.fawe.command.CFICommands;
import com.boydti.fawe.config.Caption;
import com.boydti.fawe.database.DBHandler;
import com.boydti.fawe.database.RollbackDatabase;

View File

@ -19,7 +19,6 @@
package com.sk89q.worldedit.internal.command;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
@ -40,6 +39,8 @@ import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Logs called commands to a logger.
*/

View File

@ -31,7 +31,6 @@ public class CommandRegistrationHandler {
private static final CommandPermissionsConditionGenerator PERM_GEN = new CommandPermissionsConditionGenerator();
private final List<CommandCallListener> callListeners;
public CommandRegistrationHandler(List<CommandCallListener> callListeners) {

View File

@ -54,13 +54,13 @@ public class CommandUtil {
private static Component makeDeprecatedFooter(String reason, Component newCommand) {
return TextComponent.builder()
.append(DEPRECATION_MARKER)
.append(" " + reason + ".")
.append(TextComponent.newline())
.append(TextComponent.of("Use ", TextColor.GOLD, TextDecoration.ITALIC))
.append(newCommand)
.append(TextComponent.of(" instead.", TextColor.GOLD, TextDecoration.ITALIC))
.build();
.append(DEPRECATION_MARKER)
.append(" " + reason + ".")
.append(TextComponent.newline())
.append(TextComponent.of("Use ", TextColor.GOLD, TextDecoration.ITALIC))
.append(newCommand)
.append(TextComponent.of(" instead.", TextColor.GOLD, TextDecoration.ITALIC))
.build();
}
public interface NewCommandGenerator {
@ -72,45 +72,45 @@ public class CommandUtil {
public static Command deprecate(Command command, String reason,
NewCommandGenerator newCommandGenerator) {
Component deprecatedWarning = makeDeprecatedFooter(
reason,
newCommandSuggestion(newCommandGenerator,
NoInputCommandParameters.builder().build(),
command)
reason,
newCommandSuggestion(newCommandGenerator,
NoInputCommandParameters.builder().build(),
command)
);
return command.toBuilder()
.action(parameters ->
deprecatedCommandWarning(parameters, command, reason, newCommandGenerator))
.footer(command.getFooter()
.map(existingFooter -> existingFooter
.append(TextComponent.newline()).append(deprecatedWarning))
.orElse(deprecatedWarning))
.build();
.action(parameters ->
deprecatedCommandWarning(parameters, command, reason, newCommandGenerator))
.footer(command.getFooter()
.map(existingFooter -> existingFooter
.append(TextComponent.newline()).append(deprecatedWarning))
.orElse(deprecatedWarning))
.build();
}
public static Optional<Component> footerWithoutDeprecation(Command command) {
return command.getFooter()
.filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER)))
.map(footer -> Optional.of(
replaceDeprecation(footer)
))
.orElseGet(command::getFooter);
.filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER)))
.map(footer -> Optional.of(
replaceDeprecation(footer)
))
.orElseGet(command::getFooter);
}
public static Optional<Component> deprecationWarning(Command command) {
return command.getFooter()
.map(CommandUtil::extractDeprecation)
.orElseGet(command::getFooter);
.map(CommandUtil::extractDeprecation)
.orElseGet(command::getFooter);
}
public static boolean isDeprecated(Command command) {
return command.getFooter()
.filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER)))
.isPresent();
.filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER)))
.isPresent();
}
private static boolean anyComponent(Component component, Predicate<Component> test) {
return test.test(component) || component.children().stream()
.anyMatch(x -> anyComponent(x, test));
.anyMatch(x -> anyComponent(x, test));
}
private static Component replaceDeprecation(Component component) {
@ -118,9 +118,9 @@ public class CommandUtil {
return TextComponent.empty();
}
return component.children(
component.children().stream()
.map(CommandUtil::replaceDeprecation)
.collect(toList())
component.children().stream()
.map(CommandUtil::replaceDeprecation)
.collect(toList())
);
}
@ -129,26 +129,26 @@ public class CommandUtil {
return Optional.of(component);
}
return component.children().stream()
.map(CommandUtil::extractDeprecation)
.filter(Optional::isPresent)
.map(Optional::get)
.findAny();
.map(CommandUtil::extractDeprecation)
.filter(Optional::isPresent)
.map(Optional::get)
.findAny();
}
private static Object deprecatedCommandWarning(
CommandParameters parameters,
Command command,
String reason,
NewCommandGenerator generator
private static int deprecatedCommandWarning(
CommandParameters parameters,
Command command,
String reason,
NewCommandGenerator generator
) throws Exception {
parameters.injectedValue(Key.of(Actor.class))
.ifPresent(actor -> {
Component suggestion = newCommandSuggestion(generator, parameters, command);
actor.print(TextComponent.of(reason + ". Please use ", TextColor.GOLD)
.append(suggestion)
.append(TextComponent.of(" instead."))
);
});
.ifPresent(actor -> {
Component suggestion = newCommandSuggestion(generator, parameters, command);
actor.print(TextComponent.of(reason + ". Please use ", TextColor.GOLD)
.append(suggestion)
.append(TextComponent.of(" instead."))
);
});
return command.getAction().run(parameters);
}
@ -157,15 +157,15 @@ public class CommandUtil {
Command command) {
String suggestedCommand = generator.newCommand(command, parameters);
return TextComponent.of(suggestedCommand)
.decoration(TextDecoration.UNDERLINED, true)
.clickEvent(ClickEvent.suggestCommand(suggestedCommand));
.decoration(TextDecoration.UNDERLINED, true)
.clickEvent(ClickEvent.suggestCommand(suggestedCommand));
}
public static Map<String, Command> getSubCommands(Command currentCommand) {
return currentCommand.getParts().stream()
.filter(p -> p instanceof SubCommandPart)
.flatMap(p -> ((SubCommandPart) p).getCommands().stream())
.collect(Collectors.toMap(Command::getName, Function.identity()));
.filter(p -> p instanceof SubCommandPart)
.flatMap(p -> ((SubCommandPart) p).getCommands().stream())
.collect(Collectors.toMap(Command::getName, Function.identity()));
}
private static String clean(String input) {
@ -173,7 +173,7 @@ public class CommandUtil {
}
private static final Comparator<Command> BY_CLEAN_NAME =
Comparator.comparing(c -> clean(c.getName()));
Comparator.comparing(c -> clean(c.getName()));
public static Comparator<Command> byCleanName() {
return BY_CLEAN_NAME;
@ -184,15 +184,15 @@ public class CommandUtil {
*/
public static List<String> fixSuggestions(String arguments, List<Substring> suggestions) {
Substring lastArg = Iterables.getLast(
CommandArgParser.spaceSplit(arguments)
CommandArgParser.spaceSplit(arguments)
);
return suggestions.stream()
// Re-map suggestions to only operate on the last non-quoted word
.map(suggestion -> onlyOnLastQuotedWord(lastArg, suggestion))
.map(suggestion -> suggestLast(lastArg, suggestion))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
// Re-map suggestions to only operate on the last non-quoted word
.map(suggestion -> onlyOnLastQuotedWord(lastArg, suggestion))
.map(suggestion -> suggestLast(lastArg, suggestion))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
}
private static Substring onlyOnLastQuotedWord(Substring lastArg, Substring suggestion) {
@ -228,7 +228,7 @@ public class CommandUtil {
return Optional.empty();
}
checkState(end <= builder.length(),
"Suggestion ends too late, last=%s, suggestion=", last, suggestion);
"Suggestion ends too late, last=%s, suggestion=", last, suggestion);
builder.replace(start, end, suggestion.getSubstring());
return Optional.of(builder.toString());
}
@ -259,10 +259,10 @@ public class CommandUtil {
public static <T> T requireIV(Key<T> type, String name, InjectedValueAccess injectedValueAccess) {
return injectedValueAccess.injectedValue(type).orElseThrow(() ->
new IllegalStateException("No injected value for " + name + " (type " + type + ")")
new IllegalStateException("No injected value for " + name + " (type " + type + ")")
);
}
private CommandUtil() {
}
}
}

View File

@ -22,6 +22,7 @@ package com.sk89q.worldedit.internal.command;
import com.sk89q.worldedit.command.util.annotation.Confirm;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import java.util.Optional;
import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.exception.StopExecutionException;
import org.enginehub.piston.gen.CommandCallListener;
@ -39,7 +40,12 @@ public class ConfirmHandler implements CommandCallListener {
if (confirmAnnotation == null) {
return;
}
Actor actor = parameters.injectedValue(Key.of(Actor.class)).get();
Optional<Actor> actorOpt = parameters.injectedValue(Key.of(Actor.class));
if (!actorOpt.isPresent()) {
return;
}
Actor actor = actorOpt.get();
if (!confirmAnnotation.value().passes(actor, parameters, 1)) {
throw new StopExecutionException(TextComponent.empty());
}

View File

@ -40,11 +40,12 @@ import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException;
import com.sk89q.worldedit.util.io.file.FilenameResolutionException;
import com.sk89q.worldedit.util.io.file.InvalidFilenameException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.enginehub.piston.exception.CommandException;
import org.enginehub.piston.exception.UsageException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
/**

View File

@ -1,9 +1,6 @@
applyLibrariesConfiguration()
dependencies {
"shade"("FAWE-Piston:core/build/libs/core-${Versions.PISTON}:lastSuccessfulBuild@jar")
"shade"("FAWE-Piston:core-ap/annotations/build/libs/annotations-${Versions.PISTON}:lastSuccessfulBuild@jar")
"shade"("FAWE-Piston:core-ap/processor/build/libs/processor-${Versions.PISTON}:lastSuccessfulBuild@jar")
"shade"("org.enginehub.piston.core-ap:annotations:${Versions.PISTON}")
"shade"("org.enginehub.piston.core-ap:processor:${Versions.PISTON}")
}

View File

@ -8,10 +8,10 @@ dependencies {
"shade"("com.sk89q:jchronic:0.2.4a") {
exclude(group = "junit", module = "junit")
}
"shade"("com.thoughtworks.paranamer:paranamer:2.6")
"shade"("com.github.luben:zstd-jni:1.4.3-1")
"shade"("com.sk89q.lib:jlibnoise:1.0.0")
"shade"("FAWE-Piston:core/build/libs/core-${Versions.PISTON}:lastSuccessfulBuild@jar")
"shade"("FAWE-Piston:core-ap/runtime/build/libs/runtime-${Versions.PISTON}:lastSuccessfulBuild@jar")
"shade"("FAWE-Piston:default-impl/build/libs/default-impl-${Versions.PISTON}:lastSuccessfulBuild@jar")
"shade"("org.enginehub.piston:core:${Versions.PISTON}")
"shade"("org.enginehub.piston.core-ap:runtime:${Versions.PISTON}")
"shade"("org.enginehub.piston:default-impl:${Versions.PISTON}")
}