Java Code Examples for org.bukkit.block.BlockState#getType()

The following examples show how to use org.bukkit.block.BlockState#getType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DoubleChestMatcher.java    From Modern-LWC with MIT License 6 votes vote down vote up
public boolean matches(ProtectionFinder finder) {
    // get the block state if it's a chest
    BlockState baseBlockState = finder.getBaseBlock();
    Chest baseBlockData = null;
    try {
        baseBlockData = (Chest) baseBlockState.getBlockData();
    } catch (ClassCastException e) {
        return false;
    }

    // get the block face for the neighboring chest if there is one
    BlockFace neighboringBlockFace = getNeighboringChestBlockFace(baseBlockData);
    if (neighboringBlockFace == null) {
        return false;
    }

    // if the neighboring block is a chest as well, we have a match
    Block neighboringBlock = baseBlockState.getBlock().getRelative(neighboringBlockFace);
    if (baseBlockState.getType() == neighboringBlock.getType()) {
        finder.addBlock(neighboringBlock);
        return true;
    }

    return false;
}
 
Example 2
Source File: EntityLimits.java    From askyblock with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prevents trees from growing outside of the protected area.
 *
 * @param e - event
 */
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onTreeGrow(final StructureGrowEvent e) {
    if (DEBUG) {
        plugin.getLogger().info(e.getEventName());
    }
    // Check world
    if (!IslandGuard.inWorld(e.getLocation())) {
        return;
    }
    // Check if this is on an island
    Island island = plugin.getGrid().getIslandAt(e.getLocation());
    if (island == null || island.isSpawn()) {
        return;
    }
    Iterator<BlockState> it = e.getBlocks().iterator();
    while (it.hasNext()) {
        BlockState b = it.next();
        if (b.getType() == Material.LOG || b.getType() == Material.LOG_2
                || b.getType() == Material.LEAVES || b.getType() == Material.LEAVES_2) {
            if (!island.onIsland(b.getLocation())) {
                it.remove();
            }
        }
    }
}
 
Example 3
Source File: NetherPortals.java    From askyblock with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Converts trees to gravel and glowstone
 * 
 * @param e - event
 */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onTreeGrow(final StructureGrowEvent e) {
    if (DEBUG)
        plugin.getLogger().info("DEBUG: " + e.getEventName());

    if (!Settings.netherTrees) {
        return;
    }
    if (!Settings.createNether || ASkyBlock.getNetherWorld() == null) {
        return;
    }
    // Check world
    if (!e.getLocation().getWorld().equals(ASkyBlock.getNetherWorld())) {
        return;
    }
    for (BlockState b : e.getBlocks()) {
        if (b.getType() == Material.LOG || b.getType() == Material.LOG_2) {
            b.setType(Material.GRAVEL);
        } else if (b.getType() == Material.LEAVES || b.getType() == Material.LEAVES_2) {
            b.setType(Material.GLOWSTONE);
        }
    }
}
 
Example 4
Source File: Game.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean blockPlace(GamePlayer player, Block block, BlockState replaced, ItemStack itemInHand) {
    if (status != GameStatus.RUNNING) {
        return false; // ?
    }
    if (player.isSpectator) {
        return false;
    }
    if (Main.isFarmBlock(block.getType())) {
        return true;
    }
    if (!GameCreator.isInArea(block.getLocation(), pos1, pos2)) {
        return false;
    }

    BedwarsPlayerBuildBlock event = new BedwarsPlayerBuildBlock(this, player.player, getPlayerTeam(player), block,
            itemInHand, replaced);
    Main.getInstance().getServer().getPluginManager().callEvent(event);

    if (event.isCancelled()) {
        return false;
    }

    if (replaced.getType() != Material.AIR) {
        if (region.isBlockAddedDuringGame(replaced.getLocation())) {
            return true;
        } else if (Main.isBreakableBlock(replaced.getType()) || region.isLiquid(replaced.getType())) {
            region.putOriginalBlock(block.getLocation(), replaced);
        } else {
            return false;
        }
    }
    region.addBuiltDuringGame(block.getLocation());

    return true;
}
 
Example 5
Source File: LWC.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Look for a double chest adjacent to a chest
 *
 * @param block
 * @return
 */
public Block findAdjacentDoubleChest(Block block) {
    if (!DoubleChestMatcher.PROTECTABLES_CHESTS.contains(block.getType())) {
        throw new UnsupportedOperationException(
                "findAdjacentDoubleChest() cannot be called on a: " + block.getType());
    }

    BlockState baseBlockState = block.getState();
    Chest baseBlockData = null;
    try {
        baseBlockData = (Chest) baseBlockState.getBlockData();
    } catch (ClassCastException e) {
        return null;
    }

    // get the block face for the neighboring chest if there is one
    BlockFace neighboringBlockFace = DoubleChestMatcher.getNeighboringChestBlockFace(baseBlockData);
    if (neighboringBlockFace == null) {
        return null;
    }

    // if the neighboring block is a chest as well, we have a match
    Block neighboringBlock = baseBlockState.getBlock().getRelative(neighboringBlockFace);
    if (baseBlockState.getType() == neighboringBlock.getType()) {
        return block;
    }

    return null;
}
 
Example 6
Source File: LWC.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Matches all possible blocks that can be considered a 'protection' e.g
 * clicking a chest will match double chests, clicking a door or block below a
 * door matches the whole door
 *
 * @param state
 * @return the List of possible blocks
 */
public boolean isProtectable(BlockState state) {
    Material material = state.getType();

    if (material == null) {
        return false;
    }

    return Boolean.parseBoolean(resolveProtectionConfiguration(state, "enabled"));
}
 
Example 7
Source File: LWC.java    From Modern-LWC with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
public String resolveProtectionConfiguration(BlockState state, String node) {
    Material material = state.getType();
    String cacheKey = state.getRawData() + "-" + material.toString() + "-" + node;
    if (protectionConfigurationCache.containsKey(cacheKey)) {
        return protectionConfigurationCache.get(cacheKey);
    }

    List<String> names = new ArrayList<String>();

    String materialName = normalizeMaterialName(material);

    // add the name & the block id
    names.add(materialName);
    names.add(materialName + ":" + state.getRawData());

    // add both upper and lower material name
    names.add(material.toString());
    names.add(material.toString().toLowerCase());

    // Add the wildcards last so it can be overriden
    names.add("*");

    if (materialName.contains("_")) { // Prefix wildcarding for shulker boxes & gates
        names.add("*_" + materialName.substring(materialName.indexOf("_") + 1));
    }

    String value = configuration.getString("protections." + node);

    for (String name : names) {
        String temp = configuration.getString("protections.blocks." + name + "." + node);

        if (temp != null && !temp.isEmpty()) {
            value = temp;
        }
    }

    protectionConfigurationCache.put(cacheKey, value);
    return value;
}
 
Example 8
Source File: Game.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean blockPlace(GamePlayer player, Block block, BlockState replaced, ItemStack itemInHand) {
    if (status != GameStatus.RUNNING) {
        return false; // ?
    }
    if (player.isSpectator) {
        return false;
    }
    if (Main.isFarmBlock(block.getType())) {
        return true;
    }
    if (!GameCreator.isInArea(block.getLocation(), pos1, pos2)) {
        return false;
    }

    BedwarsPlayerBuildBlock event = new BedwarsPlayerBuildBlock(this, player.player, getPlayerTeam(player), block,
            itemInHand, replaced);
    Main.getInstance().getServer().getPluginManager().callEvent(event);

    if (event.isCancelled()) {
        return false;
    }

    if (replaced.getType() != Material.AIR) {
        if (region.isBlockAddedDuringGame(replaced.getLocation())) {
            return true;
        } else if (Main.isBreakableBlock(replaced.getType()) || region.isLiquid(replaced.getType())) {
            region.putOriginalBlock(block.getLocation(), replaced);
        } else {
            return false;
        }
    }
    region.addBuiltDuringGame(block.getLocation());

    return true;
}
 
Example 9
Source File: NewBlockCompat.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("null")
@Nullable
@Override
public BlockValues getBlockValues(BlockState block) {
	// If block doesn't have useful data, data field of type is MaterialData
	if (block.getType().isBlock())
		return new NewBlockValues(block.getType(), block.getBlockData(), false);
	return null;
}
 
Example 10
Source File: BlockListener.java    From WorldGuardExtraFlagsPlugin with MIT License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onEntityBlockFormEvent(EntityBlockFormEvent event)
{
	if (SupportedFeatures.isFrostwalkerSupported())
	{
		BlockState newState = event.getNewState();
		if (newState.getType() == Material.FROSTED_ICE)
		{
			ApplicableRegionSet regions = this.plugin.getWorldGuardCommunicator().getRegionContainer().createQuery().getApplicableRegions(newState.getLocation());
			
			Entity entity = event.getEntity();
			if (entity instanceof Player)
			{
				Player player = (Player)entity;
				if (WorldGuardUtils.queryValue(player, player.getWorld(), regions.getRegions(), Flags.FROSTWALKER) == State.DENY)
				{
					event.setCancelled(true);
				}
			}
			else
			{
				if (regions.queryValue(null, Flags.FROSTWALKER) == State.DENY)
				{
					event.setCancelled(true);
				}
			}
		}
	}
}
 
Example 11
Source File: LWC.java    From Modern-LWC with MIT License 4 votes vote down vote up
public Protection findProtection(BlockState block) {
    // If the block type is AIR, then we have a problem .. but attempt to
    // load a protection anyway
    // Note: this call stems from a very old bug in Bukkit that likely does
    // not exist anymore at all
    // but is kept just incase. At one point getBlock() in Bukkit would
    // sometimes say a block
    // is an air block even though the client and server sees it differently
    // (ie a chest).
    // This was of course very problematic!
    if (block != null) {
        if (block.getType() == Material.AIR || block instanceof EntityBlock) {
            // We won't be able to match any other blocks anyway, so the least
            // we can do is attempt to load a protection
            return physicalDatabase.loadProtection(block.getWorld().getName(), block.getX(), block.getY(),
                    block.getZ());
        }

        Protection found = null;
        try {
            // Create a protection finder
            ProtectionFinder finder = new ProtectionFinder(this);

            // Search for a protection
            boolean result = finder.matchBlocks(block);

            // We're done, load the possibly loaded protection
            if (result) {
                found = finder.loadProtection();
            }

            if (found == null) {
                protectionCache.addKnownNull(protectionCache.cacheKey(block.getLocation()));
            }
        } catch (Exception e) {
        }
        return found;
    } else {
        log("Block is null");
    }
    return null;
}
 
Example 12
Source File: ProtectionFinder.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
 * Try and load a protection for a given block. If succeded, cache it locally
 *
 * @param block
 * @param noAutoCache if a match is found, don't cache it to be the protection we use
 * @return
 */
protected Result tryLoadProtection(BlockState block, boolean noAutoCache) {
    if (matchedProtection != null) {
        return Result.E_FOUND;
    }

    LWC lwc = LWC.getInstance();
    ProtectionCache cache = lwc.getProtectionCache();

    // Check the cache
    if ((matchedProtection = cache.getProtection(block)) != null) {
        searched = true;
        if (matchedProtection.getProtectionFinder() == null) {
            fullMatchBlocks();
            matchedProtection.setProtectionFinder(this);
            cache.addProtection(matchedProtection);
        }
        return Result.E_FOUND;
    }

    // Manual intervention is required
    if (block.getType() == Material.REDSTONE_WIRE || block.getType() == Material.REDSTONE_WALL_TORCH ||
            block.getType() == Material.REDSTONE_TORCH) {
        return Result.E_ABORT;
    }

    // don't bother trying to load it if it is not protectable
    if (!lwc.isProtectable(block)) {
        return Result.E_NOT_FOUND;
    }

    // Null-check
    if (block.getWorld() == null) {
        return Result.E_NOT_FOUND;
    }

    Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ());

    if (protection != null) {
        if (protection.getProtectionFinder() == null) {
            protection.setProtectionFinder(this);
            fullMatchBlocks();
            cache.addProtection(matchedProtection);
        }

        // ensure it's the right block
        if (protection.getBlockId() > 0) {
            if (protection.isBlockInWorld()) {
                if (noAutoCache) {
                    return Result.E_FOUND;
                }

                this.matchedProtection = protection;
                searched = true;
            } else {
                // Removing orrupted protection
                protection.remove();
            }
        }
    }

    return this.matchedProtection != null ? Result.E_FOUND : Result.E_NOT_FOUND;
}
 
Example 13
Source File: WoolMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static boolean isValidWool(DyeColor expectedColor, BlockState state) {
    return state.getType() == Material.WOOL && expectedColor.getWoolData() == state.getRawData();
}
 
Example 14
Source File: BlockDropsMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This is not an event handler. It is called explicitly by BlockTransformListener
 * after all event handlers have been called.
 */
@SuppressWarnings("deprecation")
public void doBlockDrops(final BlockTransformEvent event) {
    if(!causesDrops(event.getCause())) {
        return;
    }

    final BlockDrops drops = event.getDrops();
    if(drops != null) {
        event.setCancelled(true);
        final BlockState oldState = event.getOldState();
        final BlockState newState = event.getNewState();
        final Block block = event.getOldState().getBlock();
        final int newTypeId = newState.getTypeId();
        final byte newData = newState.getRawData();

        block.setTypeIdAndData(newTypeId, newData, true);

        boolean explosion = false;
        MatchPlayer player = ParticipantBlockTransformEvent.getParticipant(event);

        if(event.getCause() instanceof EntityExplodeEvent) {
            EntityExplodeEvent explodeEvent = (EntityExplodeEvent) event.getCause();
            explosion = true;

            if(drops.fallChance != null &&
               oldState.getType().isBlock() &&
               oldState.getType() != Material.AIR &&
               this.getMatch().getRandom().nextFloat() < drops.fallChance) {

                FallingBlock fallingBlock = event.getOldState().spawnFallingBlock();
                fallingBlock.setDropItem(false);

                if(drops.landChance != null && this.getMatch().getRandom().nextFloat() >= drops.landChance) {
                    this.fallingBlocksThatWillNotLand.add(fallingBlock);
                }

                Vector v = fallingBlock.getLocation().subtract(explodeEvent.getLocation()).toVector();
                double distance = v.length();
                v.normalize().multiply(BASE_FALL_SPEED * drops.fallSpeed / Math.max(1d, distance));

                // A very simple deflection model. Check for a solid
                // neighbor block and "bounce" the velocity off of it.
                Block west = block.getRelative(BlockFace.WEST);
                Block east = block.getRelative(BlockFace.EAST);
                Block down = block.getRelative(BlockFace.DOWN);
                Block up = block.getRelative(BlockFace.UP);
                Block north = block.getRelative(BlockFace.NORTH);
                Block south = block.getRelative(BlockFace.SOUTH);

                if((v.getX() < 0 && west != null && Materials.isColliding(west.getType())) ||
                    v.getX() > 0 && east != null && Materials.isColliding(east.getType())) {
                    v.setX(-v.getX());
                }

                if((v.getY() < 0 && down != null && Materials.isColliding(down.getType())) ||
                    v.getY() > 0 && up != null && Materials.isColliding(up.getType())) {
                    v.setY(-v.getY());
                }

                if((v.getZ() < 0 && north != null && Materials.isColliding(north.getType())) ||
                    v.getZ() > 0 && south != null && Materials.isColliding(south.getType())) {
                    v.setZ(-v.getZ());
                }

                fallingBlock.setVelocity(v);
            }
        }

        dropObjects(drops, player, newState.getLocation(), 1d, explosion);

    }
}
 
Example 15
Source File: MapScanner.java    From VoxelGamesLibv2 with MIT License 4 votes vote down vote up
/**
 * Searches the map for "markers". Most of the time these are implemented as tile entities (skulls)
 *
 * @param map    the map to scan
 * @param center the center location
 * @param range  the range in where to scan
 */
public void searchForMarkers(@Nonnull Map map, @Nonnull Vector3D center, int range, @Nonnull UUID gameid) {
    World world = Bukkit.getWorld(map.getLoadedName(gameid));
    if (world == null) {
        throw new MapException("Could not find world " + map.getLoadedName(gameid) + "(" + map.getInfo().getDisplayName() + ")" + ". Is it loaded?");
    }

    List<Marker> markers = new ArrayList<>();
    List<ChestMarker> chestMarkers = new ArrayList<>();

    int startX = (int) center.getX();
    int startY = (int) center.getZ();

    int minX = Math.min(startX - range, startX + range);
    int minZ = Math.min(startY - range, startY + range);

    int maxX = Math.max(startX - range, startX + range);
    int maxZ = Math.max(startY - range, startY + range);

    for (int x = minX; x <= maxX; x += 16) {
        for (int z = minZ; z <= maxZ; z += 16) {
            Chunk chunk = world.getChunkAt(x >> 4, z >> 4);
            for (BlockState te : chunk.getTileEntities()) {
                if (te.getType() == Material.PLAYER_HEAD) {
                    Skull skull = (Skull) te;
                    String markerData = getMarkerData(skull);
                    if (markerData == null) continue;
                    MarkerDefinition markerDefinition = mapHandler.createMarkerDefinition(markerData);
                    markers.add(new Marker(new Vector3D(skull.getX(), skull.getY(), skull.getZ()),
                            DirectionUtil.directionToYaw(skull.getRotation()),
                            markerData, markerDefinition));
                } else if (te.getType() == Material.CHEST) {
                    Chest chest = (Chest) te;
                    String name = chest.getBlockInventory().getName();
                    ItemStack[] items = new ItemStack[chest.getBlockInventory()
                            .getStorageContents().length];
                    for (int i = 0; i < items.length; i++) {
                        ItemStack is = chest.getBlockInventory().getItem(i);
                        if (is == null) {
                            items[i] = new ItemStack(Material.AIR);
                        } else {
                            items[i] = is;
                        }
                    }
                    chestMarkers
                            .add(new ChestMarker(new Vector3D(chest.getX(), chest.getY(), chest.getZ()), name,
                                    items));
                }
            }
        }
    }

    map.setMarkers(markers);
    map.setChestMarkers(chestMarkers);
}
 
Example 16
Source File: BlockDropsMatchModule.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This is not an event handler. It is called explicitly by BlockTransformListener after all event
 * handlers have been called.
 */
@SuppressWarnings("deprecation")
public void doBlockDrops(final BlockTransformEvent event) {
  if (!causesDrops(event.getCause())) {
    return;
  }

  final BlockDrops drops = event.getDrops();
  if (drops != null) {
    event.setCancelled(true);
    final BlockState oldState = event.getOldState();
    final BlockState newState = event.getNewState();
    final Block block = event.getOldState().getBlock();
    final int newTypeId = newState.getTypeId();
    final byte newData = newState.getRawData();

    block.setTypeIdAndData(newTypeId, newData, true);

    if (event.getCause() instanceof EntityExplodeEvent) {
      EntityExplodeEvent explodeEvent = (EntityExplodeEvent) event.getCause();
      final float yield = explodeEvent.getYield();

      if (drops.fallChance != null
          && oldState.getType().isBlock()
          && oldState.getType() != Material.AIR
          && match.getRandom().nextFloat() < drops.fallChance) {

        FallingBlock fallingBlock =
            match
                .getWorld()
                .spawnFallingBlock(
                    block.getLocation(),
                    event.getOldState().getType(),
                    event.getOldState().getRawData());
        fallingBlock.setDropItem(false);

        if (drops.landChance != null && match.getRandom().nextFloat() >= drops.landChance) {
          this.fallingBlocksThatWillNotLand.add(fallingBlock);
        }

        Vector v = fallingBlock.getLocation().subtract(explodeEvent.getLocation()).toVector();
        double distance = v.length();
        v.normalize().multiply(BASE_FALL_SPEED * drops.fallSpeed / Math.max(1d, distance));

        // A very simple deflection model. Check for a solid
        // neighbor block and "bounce" the velocity off of it.
        Block west = block.getRelative(BlockFace.WEST);
        Block east = block.getRelative(BlockFace.EAST);
        Block down = block.getRelative(BlockFace.DOWN);
        Block up = block.getRelative(BlockFace.UP);
        Block north = block.getRelative(BlockFace.NORTH);
        Block south = block.getRelative(BlockFace.SOUTH);

        if ((v.getX() < 0 && west != null && west.getType().isSolid())
            || v.getX() > 0 && east != null && east.getType().isSolid()) {
          v.setX(-v.getX());
        }

        if ((v.getY() < 0 && down != null && down.getType().isSolid())
            || v.getY() > 0 && up != null && up.getType().isSolid()) {
          v.setY(-v.getY());
        }

        if ((v.getZ() < 0 && north != null && north.getType().isSolid())
            || v.getZ() > 0 && south != null && south.getType().isSolid()) {
          v.setZ(-v.getZ());
        }

        fallingBlock.setVelocity(v);
      }

      // Defer item drops so the explosion doesn't destroy them
      match
          .getExecutor(MatchScope.RUNNING)
          .execute(() -> dropItems(drops, newState.getLocation(), yield));
    } else {
      MatchPlayer player = ParticipantBlockTransformEvent.getParticipant(event);
      if (player == null
          || player.getBukkit().getGameMode()
              != GameMode.CREATIVE) { // Don't drop items in creative mode
        dropItems(drops, newState.getLocation(), 1d);
        dropExperience(drops, newState.getLocation());
      }
    }
  }
}
 
Example 17
Source File: WoolMatchModule.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static boolean isValidWool(DyeColor expectedColor, BlockState state) {
  return state.getType() == Material.WOOL && expectedColor.getWoolData() == state.getRawData();
}
 
Example 18
Source File: LWC.java    From Modern-LWC with MIT License 3 votes vote down vote up
/**
 * Find a protection linked to the block at [x, y, z]
 *
 * @param block
 * @param block2
 * @return
 */

@SuppressWarnings("deprecation")
public boolean blockEquals(BlockState block, BlockState block2) {
    return block.getType() == block2.getType() && block.getX() == block2.getX() && block.getY() == block2.getY()
            && block.getZ() == block2.getZ() && block.getRawData() == block2.getRawData();
}