Search in sources :

Example 6 with CatalogType

use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.

the class MemoryDataView method set.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(DataQuery path, Object value) {
    checkNotNull(path, "path");
    checkNotNull(value, "value");
    final LanternDataManager manager = getDataManager();
    final List<String> parts = path.getParts();
    final String key = parts.get(0);
    if (parts.size() > 1) {
        final DataQuery subQuery = of(key);
        final Optional<DataView> subViewOptional = getUnsafeView(subQuery);
        final DataView subView;
        if (!subViewOptional.isPresent()) {
            createView(subQuery);
            subView = (DataView) this.map.get(key);
        } else {
            subView = subViewOptional.get();
        }
        subView.set(path.popFirst(), value);
        return this;
    }
    Optional<DataTypeSerializer> optDataTypeSerializer;
    TypeToken typeToken;
    if (value instanceof DataView) {
        checkArgument(value != this, "Cannot set a DataView to itself.");
        // always have to copy a data view to avoid overwriting existing
        // views and to set the interior path correctly.
        copyDataView(path, (DataView) value);
    } else if (value instanceof DataSerializable) {
        final DataContainer valueContainer = ((DataSerializable) value).toContainer();
        checkArgument(!(valueContainer).equals(this), "Cannot insert self-referencing DataSerializable");
        // see above for why this is copied
        copyDataView(path, valueContainer);
    } else if (value instanceof CatalogType) {
        return set(path, ((CatalogType) value).getId());
    } else if (value instanceof Integer || value instanceof Byte || value instanceof Short || value instanceof Float || value instanceof Double || value instanceof Long || value instanceof String || value instanceof Character || value instanceof Boolean) {
        this.map.put(key, value);
        return this;
    } else if (manager != null && (optDataTypeSerializer = manager.getTypeSerializer(typeToken = TypeToken.of(value.getClass()))).isPresent()) {
        final DataTypeSerializer serializer = optDataTypeSerializer.get();
        final Object serialized = serializer.serialize(typeToken, manager.getTypeSerializerContext(), value);
        if (serialized instanceof DataContainer) {
            final DataContainer container = (DataContainer) serialized;
            checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
            // see above for why this is copied
            copyDataView(path, container);
        } else {
            this.map.put(key, serialized);
        }
    } else if (value instanceof Collection) {
        setCollection(key, (Collection) value);
    } else if (value instanceof Map) {
        setMap(key, (Map) value);
    } else if (value.getClass().isArray()) {
        if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
            if (value instanceof byte[]) {
                this.map.put(key, ArrayUtils.clone((byte[]) value));
            } else if (value instanceof short[]) {
                this.map.put(key, ArrayUtils.clone((short[]) value));
            } else if (value instanceof int[]) {
                this.map.put(key, ArrayUtils.clone((int[]) value));
            } else if (value instanceof long[]) {
                this.map.put(key, ArrayUtils.clone((long[]) value));
            } else if (value instanceof float[]) {
                this.map.put(key, ArrayUtils.clone((float[]) value));
            } else if (value instanceof double[]) {
                this.map.put(key, ArrayUtils.clone((double[]) value));
            } else if (value instanceof boolean[]) {
                this.map.put(key, ArrayUtils.clone((boolean[]) value));
            } else {
                this.map.put(key, ArrayUtils.clone((Object[]) value));
            }
        } else {
            this.map.put(key, value);
        }
    } else {
        this.map.put(key, value);
    }
    return this;
}
Also used : DataSerializable(org.spongepowered.api.data.DataSerializable) DataContainer(org.spongepowered.api.data.DataContainer) DataQuery(org.spongepowered.api.data.DataQuery) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) TypeToken(com.google.common.reflect.TypeToken) Collection(java.util.Collection) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 7 with CatalogType

use of org.spongepowered.api.CatalogType in project LanternServer by LanternPowered.

the class CommandParticle method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(new PatternMatchingCommandElement(Text.of("type")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            return Sponge.getGame().getRegistry().getAllOf(ParticleType.class).stream().filter(type -> ((LanternParticleType) type).getInternalType().isPresent()).map(CatalogType::getId).collect(Collectors.toList());
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<ParticleType> ret = Sponge.getGame().getRegistry().getType(ParticleType.class, choice);
            if (!ret.isPresent() || !((LanternParticleType) ret.get()).getInternalType().isPresent()) {
                throw new IllegalArgumentException("Invalid input " + choice + " was found");
            }
            return ret.get();
        }
    }, GenericArguments2.targetedVector3d(Text.of("position")), // The default value should be 0 for x, y and z
    GenericArguments2.vector3d(Text.of("offset"), Vector3d.ZERO), GenericArguments2.doubleNum(Text.of("speed"), 1.0), GenericArguments.optional(GenericArguments2.integer(Text.of("count"), 1)), GenericArguments.optional(new CommandElement(Text.of("mode")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            return args.next();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            Optional<String> arg = args.nextIfPresent();
            if (arg.isPresent()) {
                return Stream.of("normal", "force").filter(new StartsWithPredicate(arg.get())).collect(Collectors.toList());
            }
            return Collections.emptyList();
        }
    }), GenericArguments.optional(GenericArguments.player(Text.of("player"))), GenericArguments.optional(new CommandElement(Text.of("params")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            List<Integer> params = new ArrayList<>();
            while (args.hasNext()) {
                String arg = args.next();
                try {
                    params.add(Integer.parseInt(arg));
                } catch (NumberFormatException e) {
                    throw args.createError(t("Expected an integer, but input '%s' was not", arg));
                }
            }
            return params.stream().mapToInt(i -> i).toArray();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            return Collections.emptyList();
        }
    })).executor((src, args) -> {
        final LanternParticleType particleType = args.<LanternParticleType>getOne("type").get();
        final int particleId = particleType.getInternalType().getAsInt();
        final Vector3f position = args.<Vector3d>getOne("position").get().toFloat();
        final Vector3f offset = args.<Vector3d>getOne("offset").get().toFloat();
        final float speed = args.<Double>getOne("speed").get().floatValue();
        final int count = args.<Integer>getOne("count").orElse(1);
        final boolean longDistance = args.<String>getOne("mode").map(mode -> mode.equalsIgnoreCase("force")).orElse(false);
        final int[] params = args.<int[]>getOne("params").orElse(new int[0]);
        final LanternWorld world = CommandHelper.getWorld(src, args);
        final int dataLength;
        if (particleType == ParticleTypes.BLOCK_CRACK || particleType == ParticleTypes.BLOCK_DUST || particleType == ParticleTypes.FALLING_DUST) {
            dataLength = 1;
        } else if (particleType == ParticleTypes.ITEM_CRACK) {
            dataLength = 2;
        } else {
            dataLength = 0;
        }
        if (params.length != dataLength) {
            throw new CommandException(t("Invalid parameters (%s), length mismatch (got %s, expected %s) for the particle type %s", Arrays.toString(params), params.length, dataLength, particleType.getId()));
        }
        final MessagePlayOutSpawnParticle message = new MessagePlayOutSpawnParticle(particleId, position, offset, speed, count, params, longDistance);
        if (args.hasAny("player")) {
            args.<LanternPlayer>getOne("player").get().getConnection().send(message);
        } else {
            for (LanternPlayer player : world.getRawPlayers()) {
                player.getConnection().send(message);
            }
        }
        src.sendMessage(t("commands.particle.success", particleType.getName(), count));
        return CommandResult.success();
    });
}
Also used : Arrays(java.util.Arrays) MessagePlayOutSpawnParticle(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSpawnParticle) Vector3d(com.flowpowered.math.vector.Vector3d) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) GenericArguments(org.spongepowered.api.command.args.GenericArguments) ArrayList(java.util.ArrayList) ParticleType(org.spongepowered.api.effect.particle.ParticleType) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) ParticleTypes(org.spongepowered.api.effect.particle.ParticleTypes) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) LanternWorld(org.lanternpowered.server.world.LanternWorld) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) CommandResult(org.spongepowered.api.command.CommandResult) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) Stream(java.util.stream.Stream) Vector3f(com.flowpowered.math.vector.Vector3f) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer) Optional(java.util.Optional) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Collections(java.util.Collections) CommandContext(org.spongepowered.api.command.args.CommandContext) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) ParticleType(org.spongepowered.api.effect.particle.ParticleType) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) LanternWorld(org.lanternpowered.server.world.LanternWorld) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) ArrayList(java.util.ArrayList) List(java.util.List) CommandArgs(org.spongepowered.api.command.args.CommandArgs) Optional(java.util.Optional) MessagePlayOutSpawnParticle(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSpawnParticle) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) Vector3d(com.flowpowered.math.vector.Vector3d) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Vector3f(com.flowpowered.math.vector.Vector3f) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) CommandElement(org.spongepowered.api.command.args.CommandElement) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Nullable(javax.annotation.Nullable) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 8 with CatalogType

use of org.spongepowered.api.CatalogType in project Nucleus by NucleusPowered.

the class SetWorthCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    String id = getCatalogTypeFromHandOrArgs(src, item, args).getId();
    Type transactionType = args.<Type>getOne(type).get();
    double newCost = args.<Double>getOne(cost).get();
    if (newCost < 0) {
        newCost = -1;
    }
    // Get the item from the system.
    ItemDataNode node = itemDataService.getDataForItem(id);
    // Get the current item worth.
    double currentWorth = transactionType.getter.apply(node);
    String worth;
    String newWorth;
    if (econHelper.economyServiceExists()) {
        worth = econHelper.getCurrencySymbol(currentWorth);
        newWorth = econHelper.getCurrencySymbol(newCost);
    } else {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.noeconservice"));
        worth = String.valueOf(currentWorth);
        newWorth = String.valueOf(newCost);
    }
    String name;
    Optional<CatalogType> type = Util.getCatalogTypeForItemFromId(id);
    name = type.map(Util::getTranslatableIfPresentOnCatalogType).orElse(id);
    if (currentWorth == newCost) {
        if (currentWorth < 0) {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.alreadyunavailable", name, transactionType.getTranslation()));
        } else {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.samecost", transactionType.getTranslation(), name, worth));
        }
        return CommandResult.empty();
    }
    // Set the item worth.
    transactionType.setter.accept(node, newCost);
    itemDataService.setDataForItem(id, node);
    // Tell the user.
    if (currentWorth == -1) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.success.new", name, transactionType.getTranslation(), newWorth));
    } else if (newCost == -1) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.success.removed", name, transactionType.getTranslation(), worth));
    } else {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.setworth.success.changed", name, transactionType.getTranslation(), newWorth, worth));
    }
    return CommandResult.success();
}
Also used : CatalogType(org.spongepowered.api.CatalogType) CatalogType(org.spongepowered.api.CatalogType) Util(io.github.nucleuspowered.nucleus.Util) ItemDataNode(io.github.nucleuspowered.nucleus.configurate.datatypes.ItemDataNode)

Example 9 with CatalogType

use of org.spongepowered.api.CatalogType in project Nucleus by NucleusPowered.

the class WorthCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    CatalogType type = getCatalogTypeFromHandOrArgs(src, item, args);
    String id = type.getId();
    // Get the item from the system.
    ItemDataNode node = itemDataService.getDataForItem(id);
    // Get the current item worth.
    MessageProvider provider = plugin.getMessageProvider();
    if (!econHelper.economyServiceExists()) {
        src.sendMessage(provider.getTextMessageWithFormat("command.setworth.noeconservice"));
    }
    double buyPrice = node.getServerBuyPrice();
    double sellPrice = node.getServerSellPrice();
    StringBuilder stringBuilder = new StringBuilder();
    if (buyPrice >= 0) {
        stringBuilder.append(provider.getMessageWithFormat("command.worth.buy", econHelper.getCurrencySymbol(node.getServerBuyPrice())));
    }
    if (sellPrice >= 0) {
        if (stringBuilder.length() > 0) {
            stringBuilder.append(" - ");
        }
        stringBuilder.append(provider.getMessageWithFormat("command.worth.sell", econHelper.getCurrencySymbol(node.getServerSellPrice())));
    }
    if (stringBuilder.length() == 0) {
        src.sendMessage(provider.getTextMessageWithFormat("command.worth.nothing", Util.getTranslatableIfPresentOnCatalogType(type)));
    } else {
        src.sendMessage(provider.getTextMessageWithFormat("command.worth.something", Util.getTranslatableIfPresentOnCatalogType(type), stringBuilder.toString()));
    }
    return CommandResult.success();
}
Also used : CatalogType(org.spongepowered.api.CatalogType) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) ItemDataNode(io.github.nucleuspowered.nucleus.configurate.datatypes.ItemDataNode)

Example 10 with CatalogType

use of org.spongepowered.api.CatalogType in project SpongeCommon by SpongePowered.

the class MemoryDataView method set.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(DataQuery path, Object value) {
    checkNotNull(path, "path");
    checkNotNull(value, "value");
    checkState(this.container != null);
    @Nullable DataManager manager;
    // TODO: this call to getDataManager each set can be cleaned up
    try {
        manager = Sponge.getDataManager();
    } catch (Exception e) {
        manager = null;
    }
    List<String> parts = path.getParts();
    String key = parts.get(0);
    if (parts.size() > 1) {
        DataQuery subQuery = of(key);
        Optional<DataView> subViewOptional = this.getUnsafeView(subQuery);
        DataView subView;
        if (!subViewOptional.isPresent()) {
            this.createView(subQuery);
            subView = (DataView) this.map.get(key);
        } else {
            subView = subViewOptional.get();
        }
        subView.set(path.popFirst(), value);
        return this;
    }
    if (value instanceof DataView) {
        checkArgument(value != this, "Cannot set a DataView to itself.");
        // always have to copy a data view to avoid overwriting existing
        // views and to set the interior path correctly.
        copyDataView(path, (DataView) value);
    } else if (value instanceof DataSerializable) {
        DataContainer valueContainer = ((DataSerializable) value).toContainer();
        checkArgument(!(valueContainer).equals(this), "Cannot insert self-referencing DataSerializable");
        // see above for why this is copied
        copyDataView(path, valueContainer);
    } else if (value instanceof CatalogType) {
        return set(path, ((CatalogType) value).getId());
    } else if (manager != null && manager.getTranslator(value.getClass()).isPresent()) {
        DataTranslator serializer = manager.getTranslator(value.getClass()).get();
        final DataContainer container = serializer.translate(value);
        checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
        // see above for why this is copied
        copyDataView(path, container);
    } else if (value instanceof Collection) {
        setCollection(key, (Collection) value);
    } else if (value instanceof Map) {
        setMap(key, (Map) value);
    } else if (value.getClass().isArray()) {
        if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
            if (value instanceof byte[]) {
                this.map.put(key, ArrayUtils.clone((byte[]) value));
            } else if (value instanceof short[]) {
                this.map.put(key, ArrayUtils.clone((short[]) value));
            } else if (value instanceof int[]) {
                this.map.put(key, ArrayUtils.clone((int[]) value));
            } else if (value instanceof long[]) {
                this.map.put(key, ArrayUtils.clone((long[]) value));
            } else if (value instanceof float[]) {
                this.map.put(key, ArrayUtils.clone((float[]) value));
            } else if (value instanceof double[]) {
                this.map.put(key, ArrayUtils.clone((double[]) value));
            } else if (value instanceof boolean[]) {
                this.map.put(key, ArrayUtils.clone((boolean[]) value));
            } else {
                this.map.put(key, ArrayUtils.clone((Object[]) value));
            }
        } else {
            this.map.put(key, value);
        }
    } else {
        this.map.put(key, value);
    }
    return this;
}
Also used : DataTranslator(org.spongepowered.api.data.persistence.DataTranslator) DataManager(org.spongepowered.api.data.DataManager) DataSerializable(org.spongepowered.api.data.DataSerializable) DataView(org.spongepowered.api.data.DataView) DataContainer(org.spongepowered.api.data.DataContainer) CatalogType(org.spongepowered.api.CatalogType) Collection(java.util.Collection) DataQuery(org.spongepowered.api.data.DataQuery) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Nullable(javax.annotation.Nullable)

Aggregations

CatalogType (org.spongepowered.api.CatalogType)26 Map (java.util.Map)12 ArrayList (java.util.ArrayList)8 ItemDataNode (io.github.nucleuspowered.nucleus.configurate.datatypes.ItemDataNode)7 DataView (org.spongepowered.api.data.DataView)6 Nullable (javax.annotation.Nullable)5 CatalogRegistryModule (org.spongepowered.api.registry.CatalogRegistryModule)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 Collection (java.util.Collection)4 List (java.util.List)4 Optional (java.util.Optional)4 Sponge (org.spongepowered.api.Sponge)4 DataContainer (org.spongepowered.api.data.DataContainer)4 Text (org.spongepowered.api.text.Text)4 ImmutableList (com.google.common.collect.ImmutableList)3 IOException (java.io.IOException)3 Method (java.lang.reflect.Method)3 IdentityHashMap (java.util.IdentityHashMap)3 BlockState (org.spongepowered.api.block.BlockState)3 DataSerializable (org.spongepowered.api.data.DataSerializable)3