3

I am trying to load and paste a .schematic file (without hooking the MCEdit API) in bukkit. Below is the function/method i use to paste the schematic. While pasting, i keep getting a NullPointerException in the pasting process. When i logged what items were getting placed, i see grass blocks, stone, but not my chests, anything in the chests, or beacons (Maybe even more blocks).

The error occurs on this line: block.setData(blockData[index], true);

I think this has to do something with the metaData, but how would i get that information from the schematic file and apply it to each of the blocks?

Question: How can i paste items with metaData like (Chest with contents, torches, beacons, etc.?

@SuppressWarnings("deprecation")
public void pasteSchematic(World world, Location loc, Schematic schematic)
{
    byte[] blocks = schematic.getBlocks();
    byte[] blockData = schematic.getData();

    short length = schematic.getLenght();
    short width = schematic.getWidth();
    short height = schematic.getHeight();

    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            for (int z = 0; z < length; ++z) {
                int index = y * width * length + z * width + x;
                Block block = new Location(world, x + loc.getX(), y + loc.getY(), z + loc.getZ()).getBlock();
                block.setTypeId(blocks[index], true);
                block.setData(blockData[index], true);
                if(block.getType() == Material.BEACON || block instanceof Beacon) {
                    // Add location up one block
                    getLogger().info("Block is a Beacon!");
                    spawnLocations.add(block.getLocation().add(new Location(block.getWorld(),0,1,0)));
                } else {
                    getLogger().info("Block is a " + block.getType().toString() + " block!");
                }
            }
        }
    }
}

And to load the schematic file:

public Schematic loadSchematic(File file) throws IOException
{
    FileInputStream stream = new FileInputStream(file);
    @SuppressWarnings("resource")
    NBTInputStream nbtStream = new NBTInputStream(stream);

    CompoundTag schematicTag = (CompoundTag) nbtStream.readTag();
    if (!schematicTag.getName().equals("Schematic")) {
        throw new IllegalArgumentException("Tag \"Schematic\" does not exist or is not first");
    }

    Map<String, Tag> schematic = schematicTag.getValue();
    if (!schematic.containsKey("Blocks")) {
        throw new IllegalArgumentException("Schematic file is missing a \"Blocks\" tag");
    }

    short width = getChildTag(schematic, "Width", ShortTag.class).getValue();
    short length = getChildTag(schematic, "Length", ShortTag.class).getValue();
    short height = getChildTag(schematic, "Height", ShortTag.class).getValue();

    String materials = getChildTag(schematic, "Materials", StringTag.class).getValue();
    if (!materials.equals("Alpha")) {
        throw new IllegalArgumentException("Schematic file is not an Alpha schematic");
    }

    byte[] blocks = getChildTag(schematic, "Blocks", ByteArrayTag.class).getValue();
    byte[] blockData = getChildTag(schematic, "Data", ByteArrayTag.class).getValue();
    return new Schematic(blocks, blockData, width, length, height);
}

/**
* Get child tag of a NBT structure.
*
* @param items The parent tag map
* @param key The name of the tag to get
* @param expected The expected type of the tag
* @return child tag casted to the expected type
* @throws DataException if the tag does not exist or the tag is not of the
* expected type
*/
private static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected) throws IllegalArgumentException
{
    if (!items.containsKey(key)) {
        throw new IllegalArgumentException("Schematic file is missing a \"" + key + "\" tag");
    }
    Tag tag = items.get(key);
    if (!expected.isInstance(tag)) {
        throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName());
    }
    return expected.cast(tag);
}

UPDATE After further testing, even if i remove the chest and the beacon (just grass and stone) the error still occurs. I am calling this event onSignChange if that helps.

Below is the error in the console:

[21:34:22 ERROR]: Could not pass event SignChangeEvent to SkyWars v1.0.0
org.bukkit.event.EventException
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
va:294) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.jav
a:62) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.j
ava:501) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.j
ava:486) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.PlayerConnection.a(PlayerConnection.java
:1586) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.PacketPlayInUpdateSign.a(SourceFile:48)
[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.PacketPlayInUpdateSign.handle(SourceFile
:9) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.NetworkManager.a(NetworkManager.java:157
) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.ServerConnection.c(SourceFile:134) [serv
er.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.MinecraftServer.v(MinecraftServer.java:6
67) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.DedicatedServer.v(DedicatedServer.java:2
60) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.MinecraftServer.u(MinecraftServer.java:5
58) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.MinecraftServer.run(MinecraftServer.java
:469) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at net.minecraft.server.v1_7_R3.ThreadServerApplication.run(SourceFile:6
28) [server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
Caused by: java.lang.NullPointerException
        at org.bukkit.craftbukkit.v1_7_R3.util.CraftMagicNumbers.getBlock(CraftM
agicNumbers.java:80) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at org.bukkit.craftbukkit.v1_7_R3.util.CraftMagicNumbers.getBlock(CraftM
agicNumbers.java:36) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at org.bukkit.craftbukkit.v1_7_R3.block.CraftBlock.getNMSBlock(CraftBloc
k.java:55) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at org.bukkit.craftbukkit.v1_7_R3.block.CraftBlock.setTypeIdAndData(Craf
tBlock.java:129) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at org.bukkit.craftbukkit.v1_7_R3.block.CraftBlock.setTypeId(CraftBlock.
java:124) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        at com.FeaRCode.SkyWars.SkyWars.pasteSchematic(SkyWars.java:132) ~[?:?]
        at com.FeaRCode.SkyWars.GameEvents.OnSignChange(GameEvents.java:33) ~[?:
?]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0
_05]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0
_05]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1
.8.0_05]
        at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_05]
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
va:292) ~[server.jar:git-Bukkit-1.7.9-R0.1-6-g4d832c3-b3090jnks]
        ... 13 more

Line 132 in skywars is this: block.setData(blockData[index], true); The line in GameEvents is when i call this Method.

Update 2 Here is some code with the API Usage

public void pasteSchematic(World world, Location loc)
{
    File schematic = new File(this.getDataFolder() + File.separator + fileName);
    Location topLeft;
    Location bottomRight;
    Vector v = new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
    BukkitWorld BWf = new BukkitWorld(currentWorld);
    EditSession es = new EditSession(BWf, -1);
    try {
        CuboidClipboard cc = SchematicFormat.getFormat(schematic).load(schematic);
        try {
            cc.paste(es, v, true);
            topLeft = new Location(currentWorld, loc.getBlockX() + cc.getWidth(), loc.getBlockY() + cc.getHeight(), loc.getBlockZ() + cc.getLength());
            bottomRight = new Location(currentWorld, loc.getBlockX() - cc.getWidth(), loc.getBlockY() - cc.getHeight(), loc.getBlockZ() - cc.getLength());
            calculateSpawnLocations(topLeft, bottomRight);
        } catch (MaxChangedBlocksException e) {
        e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DataException e) {
        e.printStackTrace();
    }

}

public void calculateSpawnLocations(Location loc1, Location loc2)
{
    int topBlockX = (loc1.getBlockX() < loc2.getBlockX() ? loc2.getBlockX() : loc1.getBlockX());
    int bottomBlockX = (loc1.getBlockX() > loc2.getBlockX() ? loc2.getBlockX() : loc1.getBlockX());

    int topBlockY = (loc1.getBlockY() < loc2.getBlockY() ? loc2.getBlockY() : loc1.getBlockY());
    int bottomBlockY = (loc1.getBlockY() > loc2.getBlockY() ? loc2.getBlockY() : loc1.getBlockY());

    int topBlockZ = (loc1.getBlockZ() < loc2.getBlockZ() ? loc2.getBlockZ() : loc1.getBlockZ());
    int bottomBlockZ = (loc1.getBlockZ() > loc2.getBlockZ() ? loc2.getBlockZ() : loc1.getBlockZ());

    for(int x = bottomBlockX; x <= topBlockX; x++)
    {
        for(int z = bottomBlockZ; z <= topBlockZ; z++)
        {
            for(int y = bottomBlockY; y <= topBlockY; y++)
            {
                Block block = loc1.getWorld().getBlockAt(x, y, z);
                if(block instanceof Beacon || block.getType() == Material.BEACON || block.getType().equals(Material.BEACON)) {
                    // Add location up one block
                    getLogger().info("Block is a Beacon!");
                    spawnLocations.add(block.getLocation().add(new Location(block.getWorld(),0,1,0)));
                } else {
                    getLogger().info("Block is a " + block.getType().toString() + " block!");
                }
            }
        }
    }
}
Hunter Mitchell
  • 7,063
  • 18
  • 69
  • 116
  • Where is line `132` in `SkyWars.java`? Also, what is the code on line `33` in `GameEvents.java`. Could you paste your full `SkyWars` class please? It would help a lot – Jojodmo Jun 08 '14 at 18:40
  • @jojodmo Sure, i will do that right now. Also, if there is a way to use the WorldEdit API and loop through the blocks, that would be fine. – Hunter Mitchell Jun 08 '14 at 19:01
  • Have you thought about just using the WorldEdit API, which already supports all of this? *Edit:* in that case it's much easier, adding an answer now. – Rogue Jun 08 '14 at 19:15
  • @Rogue Yes, but can i loop through each place that the schematic file contains? See my comment on you answer. Thanks. – Hunter Mitchell Jun 08 '14 at 19:28
  • @Rogue I am about to post some code that i created very fast. This looks VERY inefficient/laggy and i don't even know if it works yet. – Hunter Mitchell Jun 08 '14 at 19:31
  • @Rogue After testing it it worked, with one issue on this line i get a Null Pointer Exception: `spawnLocations.add(block.getLocation().add(new Location(block.getWorld(),0,1,0)));` after the logger logs it is a Beacon. Has the block not been placed yet? And is there a way to make this calculation a little bit more compact? – Hunter Mitchell Jun 08 '14 at 19:38

2 Answers2

4

I do this without using any other external imports, not even jnbt, which is now included in minecraft by default, by doing something like this:

public class Schematic{

 public List<Location> pasteSchematic(File f){  
  try{
   FileInputStream fis = new FileInputStream(f);
   NBTTagCompound nbt = NBTCompressedStreamTools.a(fis);

   short width = nbt.getShort("Width");
   short height = nbt.getShort("Height");
   short length = nbt.getShort("Length");

   byte[] blocks = nbt.getByteArray("Blocks");
   byte[] data = nbt.getByteArray("Data");

   fis.close();


   List<Location> locations = new ArrayList<Location>();
   //paste
   for(int x = 0; x < this.width; ++x){
    for(int y = 0; y < this.height; ++y){
     for(int z = 0; z < this.length; ++z){
      int index = y * this.width * this.length + z * this.width + x;
      final Location l = new Location(loc.getWorld(), x + loc.getX(), y + loc.getY(), z + loc.getZ());
      int b = this.blocks[index] & 0xFF;//make the block unsigned, so that blocks with an id over 127, like quartz and emerald, can be pasted
      final Block block = l.getBlock();
      block.setType(Material.getMaterial(b));
      block.setData(this.data[index]);

      Material m = Material.getMaterial(b);
      //you can check what type the block is here, like if(m.equals(Material.BEACON)) to check if it's a beacon        

      locations.add(l);
     }
    }
   }
  }
  catch(Exception e){e.printStackTrace();}
 }
 return locations;
}

now you can iterate over the List that is returned by pasteSchematic after all of the blocks are placed. Here's how you could do it:

List<Location> locationss = pasteSchematic(mySchematicFile);
for(Location loc : locations){
 if(loc.getBlock().getType().equals(Material.BEACON)){
  //a beacon was plasted at the loc
 }
}
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
  • Thanks, could you edit the code to where i check if it is a beacon at the time of the placing, not after. (If(...) inside the For loop) Thanks. – Hunter Mitchell Jun 08 '14 at 20:17
  • Also, i can not find the import in bukkit for `NBTTagCompound` how do i use it if it will not compile? – Hunter Mitchell Jun 08 '14 at 20:19
  • @EliteGamer You may have to use `craftbukkit` to use those imports: `net.minecraft.server.v1_7_R3.NBTCompressedStreamTools` and `net.minecraft.server.v1_7_R3.NBTTagCompound`. If you don't want to use `nms` code, then you could always go back to using your jnbt class – Jojodmo Jun 08 '14 at 20:21
  • Are there any drawbacks to using CraftBukkit in place of Bukkit? – Hunter Mitchell Jun 08 '14 at 20:24
  • I also have discovered the Locations are all the same for each block. So each of the spawn locations are not where the actual object is. – Hunter Mitchell Jun 10 '14 at 19:44
  • @EliteGamer What do you mean? All of the blocks are spawning in the same place so only 1 block is spawned? If that's the case, how are you saving the schematic file? Try using WorldEdit to save them – Jojodmo Jun 10 '14 at 20:33
  • Yes, for some reason everything is being placed in one block (it seems) and air is the last block. I did save it in World Edit and imported it into my project. – Hunter Mitchell Jun 10 '14 at 20:49
  • @EliteGamer Try putting a `System.out.println()` inside of the 3 for loops, have it contain the world, x, y, and z coords of the location it's being pasted at, the data value, the material ID, and the material that is being placed. That may lead you somewhere. – Jojodmo Jun 10 '14 at 22:01
  • What is `get(b)` in `block.setType(get(b));`? – Spotlight Jun 17 '16 at 00:45
  • @Spotlight I just updated the answer - it can be replaced with `Material.getMaterial(b)`; There was a `get(b)` method there because I had a HashMap of vanilla materials which would later be replaced by custom server blocks (for example, sponges >> mob repellers, emerald block >> medium locked chest, etc) – Jojodmo Jun 17 '16 at 02:15
3

As long as you have an instance of the schematic and a location with the WorldEdit API, this is very simple:

public boolean pasteSchematic(Location origin, CuboidClipboard schematic) {
    EditSession editSession = new EditSession(BukkitUtil.getLocalWorld(origin.getWorld()), -1); //-1 means no limit on blocks
    try {
        schematic.paste(editSession, new Vector(origin.getBlockX(), origin.getBlockY(), origin.getBlockZ()), true); // The 'true' boolean is whether or not to paste for air
    } catch (MaxChangedBlocksException ignored) {
        return false;
    }
    return true;
}

And loading that CuboidClipboard from a file:

File f = /* your schematic file */;
SchematicFormat format = SchematicFormat.getFormat(f);
CuboidClipboard paste = format.load(f);
Rogue
  • 11,105
  • 5
  • 45
  • 71
  • Ok, thanks, but how would i iterate through each block to detect the type of it. Like detecting it is a beacon/chest. That was one reason i did not directly go with the API. Thanks. – Hunter Mitchell Jun 08 '14 at 19:27
  • To go over and review every block being pasted you'd need to have a 3-dimension `for` loop and literally set each block. What also helps is doing the calculation for the location of those blocks on a different thread, and you can even sort the blocks into different queues based on what you do (ideally putting into something like a `HashMap` – Rogue Jun 08 '14 at 19:31
  • Ok, thanks. How exactly would i do that. As mentioned above i did add a way i *thought* might work. Is this what you were meaning? – Hunter Mitchell Jun 08 '14 at 19:33
  • You might get an idea [from some of this code on another project](http://pastie.org/pastes/9271504/text). Note it's a bit messy, and would take a while to clean up, but if you do the calculations on a different thread and then use `BukkitScheduler#callSyncTask` with the block changes you'll have some efficiency. – Rogue Jun 08 '14 at 19:46
  • Ok, thanks. Also, that code does work, but why do i get a Null Pointer Exception after it tries to add the beacon's location to my List of Spawns? – Hunter Mitchell Jun 08 '14 at 19:47
  • well firstly you're creating your location at `0, 1, 0` every time (and not using `Location#add`). Try checking to make sure that `spawnLocations` and `block` are not null – Rogue Jun 08 '14 at 19:50
  • `spawnLocations.add(block.getLocation().add(new Location(block.getWorld(),0,1,0)));` Gets the block location and adds +1 to the Y value (So the player can spawn on top, not in the block). Then adds that entire location to the list. – Hunter Mitchell Jun 08 '14 at 19:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/55287/discussion-between-rogue-and-elite-gamer). – Rogue Jun 08 '14 at 19:56