Search in sources :

Example 1 with ItemType

use of org.spongepowered.api.item.ItemType in project SpongeCommon by SpongePowered.

the class SpongeParticleHelper method toCachedPacket.

private static ICachedParticleEffect toCachedPacket(SpongeParticleEffect effect) {
    SpongeParticleType type = effect.getType();
    EnumParticleTypes internal = type.getInternalType();
    // Special cases
    if (internal == null) {
        if (type == ParticleTypes.FIREWORKS) {
            final List<FireworkEffect> effects = type.getDefaultOption(ParticleOptions.FIREWORK_EFFECTS).get();
            if (effects.isEmpty()) {
                return EmptyCachedPacket.INSTANCE;
            }
            final net.minecraft.item.ItemStack itemStack = new net.minecraft.item.ItemStack(Items.FIREWORKS);
            FireworkUtils.setFireworkEffects(itemStack, effects);
            final SPacketEntityMetadata packetEntityMetadata = new SPacketEntityMetadata();
            packetEntityMetadata.entityId = CachedFireworkPacket.FIREWORK_ROCKET_ID;
            packetEntityMetadata.dataManagerEntries = new ArrayList<>();
            packetEntityMetadata.dataManagerEntries.add(new EntityDataManager.DataEntry<>(EntityFireworkRocket.FIREWORK_ITEM, itemStack));
            return new CachedFireworkPacket(packetEntityMetadata);
        }
        if (type == ParticleTypes.FERTILIZER) {
            int quantity = effect.getOptionOrDefault(ParticleOptions.QUANTITY).get();
            return new CachedEffectPacket(2005, quantity, false);
        } else if (type == ParticleTypes.SPLASH_POTION) {
            Potion potion = (Potion) effect.getOptionOrDefault(ParticleOptions.POTION_EFFECT_TYPE).get();
            for (PotionType potionType : PotionType.REGISTRY) {
                for (net.minecraft.potion.PotionEffect potionEffect : potionType.getEffects()) {
                    if (potionEffect.getPotion() == potion) {
                        return new CachedEffectPacket(2002, PotionType.REGISTRY.getIDForObject(potionType), false);
                    }
                }
            }
            return EmptyCachedPacket.INSTANCE;
        } else if (type == ParticleTypes.BREAK_BLOCK) {
            int state = getBlockState(effect, type.getDefaultOption(ParticleOptions.BLOCK_STATE));
            if (state == 0) {
                return EmptyCachedPacket.INSTANCE;
            }
            return new CachedEffectPacket(2001, state, false);
        } else if (type == ParticleTypes.MOBSPAWNER_FLAMES) {
            return new CachedEffectPacket(2004, 0, false);
        } else if (type == ParticleTypes.ENDER_TELEPORT) {
            return new CachedEffectPacket(2003, 0, false);
        } else if (type == ParticleTypes.DRAGON_BREATH_ATTACK) {
            return new CachedEffectPacket(2006, 0, false);
        } else if (type == ParticleTypes.FIRE_SMOKE) {
            final Direction direction = effect.getOptionOrDefault(ParticleOptions.DIRECTION).get();
            return new CachedEffectPacket(2000, getDirectionData(direction), false);
        }
        return EmptyCachedPacket.INSTANCE;
    }
    Vector3f offset = effect.getOption(ParticleOptions.OFFSET).map(Vector3d::toFloat).orElse(Vector3f.ZERO);
    int quantity = effect.getOption(ParticleOptions.QUANTITY).orElse(1);
    int[] extra = null;
    // The extra values, normal behavior offsetX, offsetY, offsetZ
    double f0 = 0f;
    double f1 = 0f;
    double f2 = 0f;
    // Depends on behavior
    // Note: If the count > 0 -> speed = 0f else if count = 0 -> speed = 1f
    Optional<BlockState> defaultBlockState;
    if (internal != EnumParticleTypes.ITEM_CRACK && (defaultBlockState = type.getDefaultOption(ParticleOptions.BLOCK_STATE)).isPresent()) {
        int state = getBlockState(effect, defaultBlockState);
        if (state == 0) {
            return EmptyCachedPacket.INSTANCE;
        }
        extra = new int[] { state };
    }
    Optional<ItemStackSnapshot> defaultSnapshot;
    if (extra == null && (defaultSnapshot = type.getDefaultOption(ParticleOptions.ITEM_STACK_SNAPSHOT)).isPresent()) {
        Optional<ItemStackSnapshot> optSnapshot = effect.getOption(ParticleOptions.ITEM_STACK_SNAPSHOT);
        if (optSnapshot.isPresent()) {
            ItemStackSnapshot snapshot = optSnapshot.get();
            extra = new int[] { Item.getIdFromItem((Item) snapshot.getType()), ((SpongeItemStackSnapshot) snapshot).getDamageValue() };
        } else {
            Optional<BlockState> optBlockState = effect.getOption(ParticleOptions.BLOCK_STATE);
            if (optBlockState.isPresent()) {
                BlockState blockState = optBlockState.get();
                Optional<ItemType> optItemType = blockState.getType().getItem();
                if (optItemType.isPresent()) {
                    extra = new int[] { Item.getIdFromItem((Item) optItemType.get()), ((Block) blockState.getType()).getMetaFromState((IBlockState) blockState) };
                } else {
                    return EmptyCachedPacket.INSTANCE;
                }
            } else {
                ItemStackSnapshot snapshot = defaultSnapshot.get();
                extra = new int[] { Item.getIdFromItem((Item) snapshot.getType()), ((SpongeItemStackSnapshot) snapshot).getDamageValue() };
            }
        }
    }
    if (extra == null) {
        extra = new int[0];
    }
    Optional<Double> defaultScale = type.getDefaultOption(ParticleOptions.SCALE);
    Optional<Color> defaultColor;
    Optional<NotePitch> defaultNote;
    Optional<Vector3d> defaultVelocity;
    if (defaultScale.isPresent()) {
        double scale = effect.getOption(ParticleOptions.SCALE).orElse(defaultScale.get());
        // Server formula: sizeServer = (-sizeClient * 2) + 2
        if (internal == EnumParticleTypes.EXPLOSION_LARGE || internal == EnumParticleTypes.SWEEP_ATTACK) {
            scale = (-scale * 2f) + 2f;
        }
        if (scale == 0f) {
            return new CachedParticlePacket(internal, offset, quantity, extra);
        }
        f0 = scale;
    } else if ((defaultColor = type.getDefaultOption(ParticleOptions.COLOR)).isPresent()) {
        Color color = effect.getOption(ParticleOptions.COLOR).orElse(null);
        boolean isSpell = internal == EnumParticleTypes.SPELL_MOB || internal == EnumParticleTypes.SPELL_MOB_AMBIENT;
        if (!isSpell && (color == null || color.equals(defaultColor.get()))) {
            return new CachedParticlePacket(internal, offset, quantity, extra);
        } else if (isSpell && color == null) {
            color = defaultColor.get();
        }
        f0 = color.getRed() / 255f;
        f1 = color.getGreen() / 255f;
        f2 = color.getBlue() / 255f;
        // but we already chose for the color, can't have both
        if (isSpell) {
            f0 = Math.max(f0, 0.001f);
            f2 = Math.max(f0, 0.001f);
        }
        // If the f0 value 0 is, the redstone will set it automatically to red 255
        if (f0 == 0f && internal == EnumParticleTypes.REDSTONE) {
            f0 = 0.00001f;
        }
    } else if ((defaultNote = type.getDefaultOption(ParticleOptions.NOTE)).isPresent()) {
        NotePitch notePitch = effect.getOption(ParticleOptions.NOTE).orElse(defaultNote.get());
        float note = ((SpongeNotePitch) notePitch).getByteId();
        if (note == 0f) {
            return new CachedParticlePacket(internal, offset, quantity, extra);
        }
        f0 = note / 24f;
    } else if ((defaultVelocity = type.getDefaultOption(ParticleOptions.VELOCITY)).isPresent()) {
        Vector3d velocity = effect.getOption(ParticleOptions.VELOCITY).orElse(defaultVelocity.get());
        f0 = velocity.getX();
        f1 = velocity.getY();
        f2 = velocity.getZ();
        Optional<Boolean> slowHorizontalVelocity = type.getDefaultOption(ParticleOptions.SLOW_HORIZONTAL_VELOCITY);
        if (slowHorizontalVelocity.isPresent() && effect.getOption(ParticleOptions.SLOW_HORIZONTAL_VELOCITY).orElse(slowHorizontalVelocity.get())) {
            f0 = 0f;
            f2 = 0f;
        }
        // The y value won't work for this effect, if the value isn't 0 the velocity won't work
        if (internal == EnumParticleTypes.WATER_SPLASH) {
            f1 = 0f;
        }
        if (f0 == 0f && f1 == 0f && f2 == 0f) {
            return new CachedParticlePacket(internal, offset, quantity, extra);
        }
    }
    // Is this check necessary?
    if (f0 == 0f && f1 == 0f && f2 == 0f) {
        return new CachedParticlePacket(internal, offset, quantity, extra);
    }
    return new CachedOffsetParticlePacket(internal, new Vector3f(f0, f1, f2), offset, quantity, extra);
}
Also used : ItemType(org.spongepowered.api.item.ItemType) FireworkEffect(org.spongepowered.api.item.FireworkEffect) Direction(org.spongepowered.api.util.Direction) NotePitch(org.spongepowered.api.data.type.NotePitch) SpongeNotePitch(org.spongepowered.common.data.type.SpongeNotePitch) Item(net.minecraft.item.Item) SpongeNotePitch(org.spongepowered.common.data.type.SpongeNotePitch) IBlockState(net.minecraft.block.state.IBlockState) Optional(java.util.Optional) Potion(net.minecraft.potion.Potion) Color(org.spongepowered.api.util.Color) SPacketEntityMetadata(net.minecraft.network.play.server.SPacketEntityMetadata) BlockState(org.spongepowered.api.block.BlockState) IBlockState(net.minecraft.block.state.IBlockState) Vector3d(com.flowpowered.math.vector.Vector3d) EnumParticleTypes(net.minecraft.util.EnumParticleTypes) Vector3f(com.flowpowered.math.vector.Vector3f) EntityDataManager(net.minecraft.network.datasync.EntityDataManager) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) SpongeItemStackSnapshot(org.spongepowered.common.item.inventory.SpongeItemStackSnapshot) PotionType(net.minecraft.potion.PotionType)

Example 2 with ItemType

use of org.spongepowered.api.item.ItemType in project SpongeCommon by SpongePowered.

the class SpongeItemStackBuilder method fromContainer.

@Override
public ItemStack.Builder fromContainer(DataView container) {
    checkNotNull(container);
    if (!container.contains(DataQueries.ITEM_TYPE) || !container.contains(DataQueries.ITEM_COUNT) || !container.contains(DataQueries.ITEM_DAMAGE_VALUE)) {
        return this;
    }
    reset();
    final int count = getData(container, DataQueries.ITEM_COUNT, Integer.class);
    quantity(count);
    final String itemTypeId = getData(container, DataQueries.ITEM_TYPE, String.class);
    final ItemType itemType = SpongeImpl.getRegistry().getType(ItemType.class, itemTypeId).get();
    itemType(itemType);
    this.damageValue = getData(container, DataQueries.ITEM_DAMAGE_VALUE, Integer.class);
    if (container.contains(DataQueries.UNSAFE_NBT)) {
        final NBTTagCompound compound = NbtTranslator.getInstance().translateData(container.getView(DataQueries.UNSAFE_NBT).get());
        if (compound.hasKey(NbtDataUtil.SPONGE_DATA, NbtDataUtil.TAG_COMPOUND)) {
            compound.removeTag(NbtDataUtil.SPONGE_DATA);
        }
        this.compound = compound;
    }
    if (container.contains(DataQueries.DATA_MANIPULATORS)) {
        final List<DataView> views = container.getViewList(DataQueries.DATA_MANIPULATORS).get();
        final SerializedDataTransaction transaction = DataUtil.deserializeManipulatorList(views);
        final List<DataManipulator<?, ?>> manipulators = transaction.deserializedManipulators;
        this.itemDataSet = new HashSet<>();
        manipulators.forEach(this.itemDataSet::add);
    }
    return this;
}
Also used : DataView(org.spongepowered.api.data.DataView) SerializedDataTransaction(org.spongepowered.common.data.persistence.SerializedDataTransaction) ImmutableDataManipulator(org.spongepowered.api.data.manipulator.ImmutableDataManipulator) DataManipulator(org.spongepowered.api.data.manipulator.DataManipulator) ItemType(org.spongepowered.api.item.ItemType) NBTTagCompound(net.minecraft.nbt.NBTTagCompound)

Example 3 with ItemType

use of org.spongepowered.api.item.ItemType in project SpongeCommon by SpongePowered.

the class SpongeItemStackBuilder method fromBlockState.

@Override
public ItemStack.Builder fromBlockState(BlockState blockState) {
    final IBlockState minecraftState = BlockUtil.toNative(blockState);
    final Optional<ItemType> item = blockState.getType().getItem();
    if (!item.isPresent()) {
        new PrettyPrinter(60).add("Invalid BlockState").centre().hr().add("Someone attempted to create an ItemStack from a BlockState that does not have a valid item!").add("%s : %s", "BlockState", blockState).add("%s : %s", "BlockType", blockState.getType()).add(new Exception("Stacktrace")).trace();
        return this;
    }
    itemType(item.get());
    this.damageValue = minecraftState.getBlock().damageDropped(minecraftState);
    return this;
}
Also used : PrettyPrinter(org.spongepowered.asm.util.PrettyPrinter) IBlockState(net.minecraft.block.state.IBlockState) ItemType(org.spongepowered.api.item.ItemType) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException)

Example 4 with ItemType

use of org.spongepowered.api.item.ItemType in project SpongeCommon by SpongePowered.

the class SpongeItemStackBuilder method fromBlockSnapshot.

@Override
public ItemStack.Builder fromBlockSnapshot(BlockSnapshot blockSnapshot) {
    checkNotNull(blockSnapshot, "The snapshot was null!");
    reset();
    final BlockType blockType = blockSnapshot.getState().getType();
    final Optional<ItemType> itemType = blockType.getItem();
    itemType(itemType.orElseThrow(() -> new IllegalArgumentException("ItemType not found for block type: " + blockType.getId())));
    quantity(1);
    if (blockSnapshot instanceof SpongeBlockSnapshot) {
        final Block block = (Block) blockType;
        this.damageValue = block.damageDropped((IBlockState) blockSnapshot.getState());
        final Optional<NBTTagCompound> compound = ((SpongeBlockSnapshot) blockSnapshot).getCompound();
        if (compound.isPresent()) {
            this.compound = new NBTTagCompound();
            this.compound.setTag(NbtDataUtil.BLOCK_ENTITY_TAG, compound.get());
        }
    // todo probably needs more testing, but this'll do donkey...
    } else {
        // TODO handle through the API specifically handling the rest of the data stuff
        blockSnapshot.getContainers().forEach(this::itemData);
    }
    return this;
}
Also used : SpongeBlockSnapshot(org.spongepowered.common.block.SpongeBlockSnapshot) IBlockState(net.minecraft.block.state.IBlockState) BlockType(org.spongepowered.api.block.BlockType) ItemType(org.spongepowered.api.item.ItemType) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) Block(net.minecraft.block.Block)

Example 5 with ItemType

use of org.spongepowered.api.item.ItemType in project SpongeCommon by SpongePowered.

the class CooldownTrackerTest method onInit.

@Listener
public void onInit(GameInitializationEvent event) {
    final CommandSpec test = CommandSpec.builder().executor((src, args) -> {
        if (!(src instanceof Player)) {
            throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
        }
        final Player player = (Player) src;
        final CooldownTracker cooldownTracker = player.getCooldownTracker();
        final ItemType itemType = player.getItemInHand(HandTypes.MAIN_HAND).orElse(ItemStack.empty()).getType();
        if (!cooldownTracker.hasCooldown(itemType)) {
            player.sendMessage(Text.of(TextColors.GRAY, "The item type in your hand is not on cooldown!"));
        } else {
            player.sendMessage(Text.of(TextColors.GRAY, "The cooldown remaining for the item type in your hand is ", TextColors.GOLD, cooldownTracker.getCooldown(itemType).orElse(0), TextColors.GRAY, " tick(s)."));
            player.sendMessage(Text.of(TextColors.GRAY, "This item type has ", TextColors.GOLD, new DecimalFormat("#.00").format(cooldownTracker.getFractionRemaining(itemType).orElse(0.0) * 100) + "%", TextColors.GRAY, " of its cooldown remaining."));
        }
        return CommandResult.success();
    }).build();
    final CommandSpec set = CommandSpec.builder().executor((src, args) -> {
        if (!(src instanceof Player)) {
            throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
        }
        final Player player = (Player) src;
        final int cooldown = args.<Integer>getOne("cooldown").orElse(10);
        player.getCooldownTracker().setCooldown(player.getItemInHand(HandTypes.MAIN_HAND).orElse(ItemStack.empty()).getType(), cooldown);
        player.sendMessage(Text.of(TextColors.GRAY, "You have given the item type in your hand a cooldown of ", TextColors.GOLD, cooldown, TextColors.GRAY, " tick(s)."));
        return CommandResult.success();
    }).arguments(GenericArguments.integer(Text.of("cooldown"))).build();
    final CommandSpec enable = CommandSpec.builder().executor(((src, args) -> {
        if (!(src instanceof Player)) {
            throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!"));
        }
        final Player player = (Player) src;
        if (!this.enabled.remove(player.getUniqueId())) {
            this.enabled.add(player.getUniqueId());
            src.sendMessage(Text.of(TextColors.GOLD, "You have enabled the cooldown listeners!"));
        } else {
            src.sendMessage(Text.of(TextColors.GOLD, "You have disabled the cooldown listeners!"));
        }
        return CommandResult.success();
    })).build();
    Sponge.getCommandManager().register(this, CommandSpec.builder().executor(((src, args) -> {
        src.sendMessage(Text.of(TextColors.GOLD, "Use cooldown set|test|enable"));
        return CommandResult.success();
    })).child(test, "test").child(set, "set").child(enable, "enable", "disable").build(), "cooldowns");
}
Also used : CommandResult(org.spongepowered.api.command.CommandResult) GameInitializationEvent(org.spongepowered.api.event.game.state.GameInitializationEvent) DecimalFormat(java.text.DecimalFormat) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) UUID(java.util.UUID) GenericArguments(org.spongepowered.api.command.args.GenericArguments) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) HashSet(java.util.HashSet) CooldownTracker(org.spongepowered.api.entity.living.player.CooldownTracker) CooldownEvent(org.spongepowered.api.event.entity.living.humanoid.player.CooldownEvent) Plugin(org.spongepowered.api.plugin.Plugin) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Text(org.spongepowered.api.text.Text) Order(org.spongepowered.api.event.Order) HandTypes(org.spongepowered.api.data.type.HandTypes) Player(org.spongepowered.api.entity.living.player.Player) Listener(org.spongepowered.api.event.Listener) ItemType(org.spongepowered.api.item.ItemType) TextColors(org.spongepowered.api.text.format.TextColors) Player(org.spongepowered.api.entity.living.player.Player) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) ItemType(org.spongepowered.api.item.ItemType) DecimalFormat(java.text.DecimalFormat) CommandException(org.spongepowered.api.command.CommandException) CooldownTracker(org.spongepowered.api.entity.living.player.CooldownTracker) Listener(org.spongepowered.api.event.Listener)

Aggregations

ItemType (org.spongepowered.api.item.ItemType)53 ItemStack (org.spongepowered.api.item.inventory.ItemStack)19 BlockState (org.spongepowered.api.block.BlockState)12 Listener (org.spongepowered.api.event.Listener)12 World (org.spongepowered.api.world.World)11 Optional (java.util.Optional)9 Text (org.spongepowered.api.text.Text)8 Region (br.net.fabiozumbi12.RedProtect.Sponge.Region)7 ArrayList (java.util.ArrayList)7 Sponge (org.spongepowered.api.Sponge)7 BlockType (org.spongepowered.api.block.BlockType)7 List (java.util.List)6 BlockSnapshot (org.spongepowered.api.block.BlockSnapshot)6 Player (org.spongepowered.api.entity.living.player.Player)6 Vector3d (com.flowpowered.math.vector.Vector3d)5 CommandResult (org.spongepowered.api.command.CommandResult)5 Collectors (java.util.stream.Collectors)4 IBlockState (net.minecraft.block.state.IBlockState)4 Inventory (org.spongepowered.api.item.inventory.Inventory)4 ItemStackSnapshot (org.spongepowered.api.item.inventory.ItemStackSnapshot)4