在Bukkit中从原理图设置方块数据?

3
我正试图在bukkit中加载和粘贴一个.schematic文件(未连接MCEdit API)。以下是我用于粘贴原理图的函数/方法。在粘贴过程中,我不断收到NullPointerException错误。当我记录下正在放置的物品时,我看到草块、石头,但没有我的箱子,箱子里的任何东西或信标(甚至可能还有更多方块)。
错误发生在这一行:block.setData(blockData [index],true);
我认为这与元数据有关,但如何从原理图文件中获取该信息并将其应用于每个方块?
问题:如何粘贴具有元数据的物品(带内容的箱子、火把、信标等)?
@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!");
                }
            }
        }
    }
}

加载原理图文件:

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);
}
更新 经过进一步测试,即使我移除了箱子和信标(只留下草和石头),错误仍会发生。如果有帮助,我正在调用此事件onSignChange
以下是控制台中的错误:
[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

天空战争中的第132行代码如下:block.setData(blockData[index], true); 这行代码在GameEvents中被调用。

更新2 以下是一些带有API使用的代码

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!");
                }
            }
        }
    }
}

请问SkyWars.java文件中的第132行在哪里?另外,请问GameEvents.java文件中第33行的代码是什么?能否提供完整的SkyWars类的代码呢?这将非常有帮助。 - Jojodmo
@jojodmo 当然,我现在就会做。另外,如果有一种使用WorldEdit API并循环遍历块的方法,那也可以。 - Hunter Mitchell
你有没有考虑过直接使用已经支持所有这些功能的WorldEdit API?编辑:如果是这样,那就容易多了,现在添加一个答案。 - Rogue
@Rogue 是的,但我能循环遍历原理图文件包含的每个位置吗?请看一下我的评论。谢谢。 - Hunter Mitchell
@Rogue 我即将发布一些我非常快速创建的代码。这看起来非常低效/卡顿,而且我甚至不知道它是否有效。 - Hunter Mitchell
@Rogue 经过测试,它可以工作,但在这一行中我遇到了一个问题,会导致 Null Pointer Exception:spawnLocations.add(block.getLocation().add(new Location(block.getWorld(),0,1,0))); 在记录器记录它是信标之后。难道方块还没有被放置吗?是否有一种方法可以使这个计算更加简洁? - Hunter Mitchell
2个回答

4

我可以在没有使用任何其他外部导入库的情况下完成这个操作,甚至不用像现在默认包含在Minecraft中的jnbt,只需像这样进行操作:

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;
}

当所有块都放置完毕后,您现在可以迭代由 pasteSchematic 返回的 List。以下是迭代的方法:

List<Location> locationss = pasteSchematic(mySchematicFile);
for(Location loc : locations){
 if(loc.getBlock().getType().equals(Material.BEACON)){
  //a beacon was plasted at the loc
 }
}

谢谢,你能否编辑代码,让我在放置时检查它是否是信标,而不是之后?(在For循环中使用If(...))谢谢。 - Hunter Mitchell
@EliteGamer 你可能需要使用 craftbukkit 来使用这些导入:net.minecraft.server.v1_7_R3.NBTCompressedStreamToolsnet.minecraft.server.v1_7_R3.NBTTagCompound。如果你不想使用 nms 代码,那么你可以回到使用你的 jnbt 类。 - Jojodmo
使用CraftBukkit替代Bukkit有什么缺点吗? - Hunter Mitchell
我也发现每个块的位置都是相同的。因此,每个生成位置并不是实际对象所在的位置。 - Hunter Mitchell
是的,由于某种原因,所有东西都被放在一个块中(看起来是这样),而空气是最后一个块。我确实在World Edit中保存了它并将其导入到我的项目中。 - Hunter Mitchell
显示剩余5条评论

3
只要您拥有原理图的实例和WorldEdit API中的位置,就可以轻松完成以下操作:
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;
}

从文件中加载CuboidClipboard:

File f = /* your schematic file */;
SchematicFormat format = SchematicFormat.getFormat(f);
CuboidClipboard paste = format.load(f);

好的,谢谢。但是我该如何迭代每个方块以检测其类型,比如检测它是信标/箱子之类的。这也是我没有直接使用API的原因之一。谢谢。 - Hunter Mitchell
要检查和审查每个被粘贴的块,您需要使用三维 for 循环并逐个设置每个块。另外有帮助的是在不同的线程上计算这些块的位置,并且您甚至可以根据所做的操作将块排序到不同的队列中(最好放入类似于 HashMap<Location, /*type*/> 的东西中)。 - Rogue
你可能会从另一个项目的这些代码中得到一些想法(http://pastie.org/pastes/9271504/text)。请注意,它有点混乱,需要花费一些时间来清理,但如果你在不同的线程上进行计算,然后使用`BukkitScheduler#callSyncTask`和方块更改,就可以提高一些效率。 - Rogue
好的,谢谢。另外,那段代码确实可以工作,但为什么在尝试将信标位置添加到我的生成列表时会出现空指针异常? - Hunter Mitchell
首先,您每次都在0, 1, 0处创建位置(而不是使用Location#add)。请尝试检查spawnLocationsblock是否为空。 - Rogue
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接