Search in sources :

Example 1 with CompoundTag

use of org.jnbt.CompoundTag in project WorldPainter by Captain-Chaos.

the class RespawnPlayer method respawnPlayer.

public static void respawnPlayer(File levelDatFile) throws IOException {
    CompoundTag outerTag;
    try (NBTInputStream in = new NBTInputStream(new GZIPInputStream(new FileInputStream(levelDatFile)))) {
        outerTag = (CompoundTag) in.readTag();
    }
    CompoundTag dataTag = (CompoundTag) outerTag.getTag(TAG_DATA);
    int spawnX = ((IntTag) dataTag.getTag(TAG_SPAWN_X)).getValue();
    int spawnY = ((IntTag) dataTag.getTag(TAG_SPAWN_Y)).getValue();
    int spawnZ = ((IntTag) dataTag.getTag(TAG_SPAWN_Z)).getValue();
    CompoundTag playerTag = (CompoundTag) dataTag.getTag(TAG_PLAYER);
    playerTag.setTag(TAG_DEATH_TIME, new ShortTag(TAG_DEATH_TIME, (short) 0));
    playerTag.setTag(TAG_HEALTH, new ShortTag(TAG_HEALTH, (short) 20));
    List<Tag> motionList = new ArrayList<>(3);
    motionList.add(new DoubleTag(null, 0));
    motionList.add(new DoubleTag(null, 0));
    motionList.add(new DoubleTag(null, 0));
    playerTag.setTag(TAG_MOTION, new ListTag(TAG_MOTION, DoubleTag.class, motionList));
    List<Tag> posList = new ArrayList<>(3);
    posList.add(new DoubleTag(null, spawnX + 0.5));
    posList.add(new DoubleTag(null, spawnY + 3));
    posList.add(new DoubleTag(null, spawnZ + 0.5));
    playerTag.setTag(TAG_POS, new ListTag(TAG_POS, DoubleTag.class, posList));
    try (NBTOutputStream out = new NBTOutputStream(new GZIPOutputStream(new FileOutputStream(levelDatFile)))) {
        out.writeTag(outerTag);
    }
}
Also used : ArrayList(java.util.ArrayList) DoubleTag(org.jnbt.DoubleTag) ListTag(org.jnbt.ListTag) NBTOutputStream(org.jnbt.NBTOutputStream) FileInputStream(java.io.FileInputStream) ShortTag(org.jnbt.ShortTag) GZIPInputStream(java.util.zip.GZIPInputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) FileOutputStream(java.io.FileOutputStream) NBTInputStream(org.jnbt.NBTInputStream) IntTag(org.jnbt.IntTag) DoubleTag(org.jnbt.DoubleTag) ShortTag(org.jnbt.ShortTag) CompoundTag(org.jnbt.CompoundTag) Tag(org.jnbt.Tag) ListTag(org.jnbt.ListTag) CompoundTag(org.jnbt.CompoundTag) IntTag(org.jnbt.IntTag)

Example 2 with CompoundTag

use of org.jnbt.CompoundTag in project WorldPainter by Captain-Chaos.

the class DumpChunk method main.

public static void main(String[] args) throws IOException {
    File levelDatFile = new File(args[0]);
    int chunkX = Integer.parseInt(args[1]);
    int chunkY = Integer.parseInt(args[2]);
    Level level = Level.load(levelDatFile);
    CompoundTag tag;
    try (NBTInputStream in = new NBTInputStream(RegionFileCache.getChunkDataInputStream(levelDatFile.getParentFile(), chunkX, chunkY, level.getVersion()))) {
        tag = (CompoundTag) in.readTag();
    }
    Chunk chunk = (level.getVersion() == SUPPORTED_VERSION_1) ? new ChunkImpl(tag, level.getMaxHeight()) : new ChunkImpl2(tag, level.getMaxHeight());
    System.out.println("Biomes");
    System.out.println("X-->");
    for (int z = 0; z < 16; z++) {
        for (int x = 0; x < 16; x++) {
            System.out.printf("[%3d]", chunk.getBiome(x, z));
        }
        if (z == 0) {
            System.out.print(" Z");
        } else if (z == 1) {
            System.out.print(" |");
        } else if (z == 2) {
            System.out.print(" v");
        }
        System.out.println();
    }
    System.out.println("Blocks:");
    List<TileEntity> tileEntities = chunk.getTileEntities();
    for (int y = 0; y < level.getMaxHeight(); y++) {
        boolean blockFound = false;
        x: for (int x = 0; x < 16; x++) {
            for (int z = 0; z < 16; z++) {
                if (chunk.getBlockType(x, y, z) != 0) {
                    blockFound = true;
                    break x;
                }
            }
        }
        if (!blockFound) {
            break;
        }
        System.out.println("X-->");
        for (int z = 0; z < 16; z++) {
            for (int x = 0; x < 16; x++) {
                int blockType = chunk.getBlockType(x, y, z);
                int data = chunk.getDataValue(x, y, z);
                if (blockType > 0) {
                    if (BLOCKS[blockType].tileEntity) {
                        int count = 0;
                        for (Iterator<TileEntity> i = tileEntities.iterator(); i.hasNext(); ) {
                            TileEntity tileEntity = i.next();
                            if ((tileEntity.getX() == x) && (tileEntity.getY() == y) && (tileEntity.getZ() == z)) {
                                count++;
                                i.remove();
                            }
                        }
                        if (count == 1) {
                            if (data > 0) {
                                System.out.printf("[%3.3s:%2d]", BLOCK_TYPE_NAMES[blockType], data);
                            } else {
                                System.out.printf("[%3.3s:  ]", BLOCK_TYPE_NAMES[blockType]);
                            }
                        } else {
                            System.out.printf("!%3.3s!%2d!", BLOCK_TYPE_NAMES[blockType], count);
                        }
                    } else {
                        if (data > 0) {
                            System.out.printf("[%3.3s:%2d]", BLOCK_TYPE_NAMES[blockType], data);
                        } else {
                            System.out.printf("[%3.3s:  ]", BLOCK_TYPE_NAMES[blockType]);
                        }
                    }
                } else {
                    System.out.print("[   :  ]");
                }
            }
            if (z == 0) {
                System.out.print(" Z");
            } else if (z == 1) {
                System.out.print(" |");
            } else if (z == 2) {
                System.out.print(" v");
            } else if (z == 15) {
                System.out.print(" Y: " + y);
            }
            System.out.println();
        }
    }
    if (!tileEntities.isEmpty()) {
        System.out.println("Unmatched tile entities!");
        for (TileEntity tileEntity : tileEntities) {
            System.out.println(tileEntity.getId() + "@" + tileEntity.getX() + "," + tileEntity.getY() + "," + tileEntity.getZ());
        }
    }
}
Also used : NBTInputStream(org.jnbt.NBTInputStream) File(java.io.File) CompoundTag(org.jnbt.CompoundTag)

Example 3 with CompoundTag

use of org.jnbt.CompoundTag in project WorldPainter by Captain-Chaos.

the class JavaWorldMerger method copyAllChunks.

private String copyAllChunks(MinecraftWorld minecraftWorld, File oldRegionDir, Dimension dimension, Point regionCoords, ProgressReceiver progressReceiver) throws IOException, ProgressReceiver.OperationCancelled {
    if (progressReceiver != null) {
        progressReceiver.setMessage("Copying chunks unchanged");
    }
    int lowestChunkX = regionCoords.x << 5;
    int highestChunkX = (regionCoords.x << 5) + 31;
    int lowestChunkY = regionCoords.y << 5;
    int highestChunkY = (regionCoords.y << 5) + 31;
    Platform platform = dimension.getWorld().getPlatform();
    int maxHeight = dimension.getMaxHeight();
    Map<Point, RegionFile> regionFiles = new HashMap<>();
    Set<Point> damagedRegions = new HashSet<>();
    StringBuilder reportBuilder = new StringBuilder();
    try {
        int chunkNo = 0;
        for (int chunkX = lowestChunkX; chunkX <= highestChunkX; chunkX++) {
            for (int chunkY = lowestChunkY; chunkY <= highestChunkY; chunkY++) {
                chunkNo++;
                if (progressReceiver != null) {
                    progressReceiver.setProgress((float) chunkNo / 1024);
                }
                int regionX = chunkX >> 5;
                int regionY = chunkY >> 5;
                Point coords = new Point(regionX, regionY);
                if (damagedRegions.contains(coords)) {
                    // reported and logged earlier
                    continue;
                }
                RegionFile regionFile = regionFiles.get(coords);
                if (regionFile == null) {
                    File file = new File(oldRegionDir, "r." + regionX + "." + regionY + (platform.equals(DefaultPlugin.JAVA_ANVIL) ? ".mca" : ".mcr"));
                    try {
                        regionFile = new RegionFile(file);
                        regionFiles.put(coords, regionFile);
                    } catch (IOException e) {
                        reportBuilder.append("I/O error while opening region file " + file + " (message: \"" + e.getMessage() + "\"); skipping region" + EOL);
                        logger.error("I/O error while opening region file " + file + "; skipping region", e);
                        damagedRegions.add(coords);
                        continue;
                    }
                }
                int chunkXInRegion = chunkX & 0x1f;
                int chunkYInRegion = chunkY & 0x1f;
                if (regionFile.containsChunk(chunkXInRegion, chunkYInRegion)) {
                    Tag tag;
                    try {
                        InputStream chunkData = regionFile.getChunkDataInputStream(chunkXInRegion, chunkYInRegion);
                        if (chunkData == null) {
                            // This should never happen, since we checked
                            // with isChunkPresent(), but in practice it
                            // does. Perhaps corrupted data?
                            reportBuilder.append("Missing chunk data for chunk " + chunkXInRegion + ", " + chunkYInRegion + " in " + regionFile + "; skipping chunk" + EOL);
                            logger.warn("Missing chunk data for chunk " + chunkXInRegion + ", " + chunkYInRegion + " in " + regionFile + "; skipping chunk");
                            continue;
                        }
                        try (NBTInputStream in = new NBTInputStream(chunkData)) {
                            tag = in.readTag();
                        }
                    } catch (IOException e) {
                        reportBuilder.append("I/O error while reading chunk " + chunkXInRegion + ", " + chunkYInRegion + " from file " + regionFile + " (message: \"" + e.getMessage() + "\"); skipping chunk" + EOL);
                        logger.error("I/O error while reading chunk " + chunkXInRegion + ", " + chunkYInRegion + " from file " + regionFile + "; skipping chunk", e);
                        continue;
                    } catch (IllegalArgumentException e) {
                        reportBuilder.append("Illegal argument exception while reading chunk " + chunkXInRegion + ", " + chunkYInRegion + " from file " + regionFile + " (message: \"" + e.getMessage() + "\"); skipping chunk" + EOL);
                        logger.error("Illegal argument exception while reading chunk " + chunkXInRegion + ", " + chunkYInRegion + " from file " + regionFile + "; skipping chunk", e);
                        continue;
                    }
                    Chunk existingChunk = platform.equals(DefaultPlugin.JAVA_MCREGION) ? new ChunkImpl((CompoundTag) tag, maxHeight) : new ChunkImpl2((CompoundTag) tag, maxHeight);
                    minecraftWorld.addChunk(existingChunk);
                }
            }
        }
    } finally {
        for (RegionFile regionFile : regionFiles.values()) {
            regionFile.close();
        }
    }
    if (progressReceiver != null) {
        progressReceiver.setProgress(1.0f);
    }
    return reportBuilder.length() != 0 ? reportBuilder.toString() : null;
}
Also used : NBTInputStream(org.jnbt.NBTInputStream) NBTInputStream(org.jnbt.NBTInputStream) CompoundTag(org.jnbt.CompoundTag) Tag(org.jnbt.Tag) CompoundTag(org.jnbt.CompoundTag)

Example 4 with CompoundTag

use of org.jnbt.CompoundTag in project WorldPainter by Captain-Chaos.

the class Bo3Object method loadTileEntity.

private static TileEntity loadTileEntity(File bo3File, String nbtFileName) throws IOException {
    File nbtFile = new File(bo3File.getParentFile(), nbtFileName);
    try (NBTInputStream in = new NBTInputStream(new GZIPInputStream(new FileInputStream(nbtFile)))) {
        CompoundTag tag = (CompoundTag) in.readTag();
        Map<String, Tag> map = tag.getValue();
        if ((map.size() == 1) && (map.values().iterator().next() instanceof CompoundTag)) {
            // contains the data
            return TileEntity.fromNBT((CompoundTag) tag.getValue().values().iterator().next());
        } else {
            return TileEntity.fromNBT(tag);
        }
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) NBTInputStream(org.jnbt.NBTInputStream) CompoundTag(org.jnbt.CompoundTag) Tag(org.jnbt.Tag) CompoundTag(org.jnbt.CompoundTag)

Example 5 with CompoundTag

use of org.jnbt.CompoundTag in project WorldPainter by Captain-Chaos.

the class JavaWorldMerger method mergeBiomes.

/**
 * Merge only the biomes, leave everything else the same.
 */
public void mergeBiomes(File backupDir, ProgressReceiver progressReceiver) throws IOException, ProgressReceiver.OperationCancelled {
    // Read existing level.dat file and perform sanity checks
    Level level = performSanityChecks(true);
    // Backup existing level
    File worldDir = levelDatFile.getParentFile();
    if (!worldDir.renameTo(backupDir)) {
        throw new FileInUseException("Could not move " + worldDir + " to " + backupDir);
    }
    if (!worldDir.mkdirs()) {
        throw new IOException("Could not create " + worldDir);
    }
    // Copy everything that we are not going to generate (this includes the
    // Nether and End dimensions)
    File[] files = backupDir.listFiles();
    // noinspection ConstantConditions // Cannot happen because we previously loaded level.dat from it
    for (File file : files) {
        if ((!file.getName().equalsIgnoreCase("session.lock")) && (!file.getName().equalsIgnoreCase("region"))) {
            if (file.isFile()) {
                FileUtils.copyFileToDir(file, worldDir);
            } else if (file.isDirectory()) {
                FileUtils.copyDir(file, new File(worldDir, file.getName()));
            } else {
                logger.warn("Not copying " + file + "; not a regular file or directory");
            }
        }
    }
    // Write session.lock file
    File sessionLockFile = new File(worldDir, "session.lock");
    try (DataOutputStream sessionOut = new DataOutputStream(new FileOutputStream(sessionLockFile))) {
        sessionOut.writeLong(System.currentTimeMillis());
    }
    // Process all chunks and copy just the biomes
    if (progressReceiver != null) {
        progressReceiver.setMessage("Merging biomes");
    }
    // Find all the region files of the existing level
    File oldRegionDir = new File(backupDir, "region");
    final Pattern regionFilePattern = Pattern.compile("r\\.-?\\d+\\.-?\\d+\\.mca");
    File[] oldRegionFiles = oldRegionDir.listFiles((dir, name) -> regionFilePattern.matcher(name).matches());
    // Process each region file, copying every chunk unmodified, except
    // for the biomes
    // Can only happen for corrupted maps
    @SuppressWarnings("ConstantConditions") int totalChunkCount = oldRegionFiles.length * 32 * 32, chunkCount = 0;
    File newRegionDir = new File(worldDir, "region");
    newRegionDir.mkdirs();
    Dimension dimension = world.getDimension(DIM_NORMAL);
    for (File file : oldRegionFiles) {
        try (RegionFile oldRegion = new RegionFile(file)) {
            String[] parts = file.getName().split("\\.");
            int regionX = Integer.parseInt(parts[1]);
            int regionZ = Integer.parseInt(parts[2]);
            File newRegionFile = new File(newRegionDir, "r." + regionX + "." + regionZ + ".mca");
            try (RegionFile newRegion = new RegionFile(newRegionFile)) {
                for (int x = 0; x < 32; x++) {
                    for (int z = 0; z < 32; z++) {
                        if (oldRegion.containsChunk(x, z)) {
                            ChunkImpl2 chunk;
                            try (NBTInputStream in = new NBTInputStream(oldRegion.getChunkDataInputStream(x, z))) {
                                CompoundTag tag = (CompoundTag) in.readTag();
                                chunk = new ChunkImpl2(tag, level.getMaxHeight());
                            }
                            int chunkX = chunk.getxPos(), chunkZ = chunk.getzPos();
                            for (int xx = 0; xx < 16; xx++) {
                                for (int zz = 0; zz < 16; zz++) {
                                    chunk.setBiome(xx, zz, dimension.getLayerValueAt(Biome.INSTANCE, (chunkX << 4) | xx, (chunkZ << 4) | zz));
                                }
                            }
                            try (NBTOutputStream out = new NBTOutputStream(newRegion.getChunkDataOutputStream(x, z))) {
                                out.writeTag(chunk.toNBT());
                            }
                        }
                        chunkCount++;
                        if (progressReceiver != null) {
                            progressReceiver.setProgress((float) chunkCount / totalChunkCount);
                        }
                    }
                }
            }
        }
    }
    // Rewrite session.lock file
    try (DataOutputStream sessionOut = new DataOutputStream(new FileOutputStream(sessionLockFile))) {
        sessionOut.writeLong(System.currentTimeMillis());
    }
}
Also used : FileInUseException(org.pepsoft.worldpainter.util.FileInUseException) Pattern(java.util.regex.Pattern) Dimension(org.pepsoft.worldpainter.Dimension) NBTOutputStream(org.jnbt.NBTOutputStream) NBTInputStream(org.jnbt.NBTInputStream) CompoundTag(org.jnbt.CompoundTag)

Aggregations

CompoundTag (org.jnbt.CompoundTag)12 NBTInputStream (org.jnbt.NBTInputStream)12 Tag (org.jnbt.Tag)7 File (java.io.File)5 Pattern (java.util.regex.Pattern)4 IOException (java.io.IOException)3 GZIPInputStream (java.util.zip.GZIPInputStream)3 InputStream (java.io.InputStream)2 NBTOutputStream (org.jnbt.NBTOutputStream)2 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 ArrayList (java.util.ArrayList)1 BitSet (java.util.BitSet)1 Matcher (java.util.regex.Matcher)1 GZIPOutputStream (java.util.zip.GZIPOutputStream)1 DoubleTag (org.jnbt.DoubleTag)1 IntTag (org.jnbt.IntTag)1 ListTag (org.jnbt.ListTag)1 ShortTag (org.jnbt.ShortTag)1 ChunkImpl2 (org.pepsoft.minecraft.ChunkImpl2)1