001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.util;
020
021import com.plotsquared.core.PlotSquared;
022import com.plotsquared.core.configuration.caption.Caption;
023import com.plotsquared.core.location.Location;
024import com.plotsquared.core.player.PlotPlayer;
025import com.plotsquared.core.plot.Plot;
026import com.plotsquared.core.util.task.RunnableVal;
027import com.sk89q.jnbt.CompoundTag;
028import com.sk89q.jnbt.IntTag;
029import com.sk89q.jnbt.NBTInputStream;
030import com.sk89q.jnbt.NBTOutputStream;
031import com.sk89q.jnbt.Tag;
032import com.sk89q.worldedit.math.BlockVector2;
033import com.sk89q.worldedit.regions.CuboidRegion;
034import com.sk89q.worldedit.world.World;
035import com.sk89q.worldedit.world.biome.BiomeType;
036import com.sk89q.worldedit.world.block.BlockState;
037import com.sk89q.worldedit.world.block.BlockType;
038import com.sk89q.worldedit.world.entity.EntityType;
039import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
040import org.checkerframework.checker.index.qual.NonNegative;
041import org.checkerframework.checker.nullness.qual.NonNull;
042import org.checkerframework.checker.nullness.qual.Nullable;
043
044import java.io.ByteArrayOutputStream;
045import java.io.File;
046import java.io.FileInputStream;
047import java.io.IOException;
048import java.io.OutputStream;
049import java.net.URL;
050import java.util.Collection;
051import java.util.HashMap;
052import java.util.HashSet;
053import java.util.Map;
054import java.util.Set;
055import java.util.UUID;
056import java.util.function.Consumer;
057import java.util.function.IntConsumer;
058import java.util.zip.GZIPInputStream;
059import java.util.zip.GZIPOutputStream;
060import java.util.zip.ZipEntry;
061import java.util.zip.ZipOutputStream;
062
063public abstract class WorldUtil {
064
065    /**
066     * {@return whether the given location is valid in the world}
067     * @param location the location to check
068     * @since 7.3.6
069     */
070    public static boolean isValidLocation(Location location) {
071        return Math.abs(location.getX()) < 30000000 && Math.abs(location.getZ()) < 30000000;
072    }
073
074    /**
075     * Set the biome in a region
076     *
077     * @param world  World name
078     * @param region Region
079     * @param biome  Biome
080     * @since 6.6.0
081     */
082    public static void setBiome(String world, final CuboidRegion region, BiomeType biome) {
083        PlotSquared.platform().worldUtil().setBiomes(world, region, biome);
084    }
085
086    /**
087     * Check if a given world name corresponds to a real world
088     *
089     * @param worldName World name
090     * @return {@code true} if there exists a world with the given world name,
091     *         {@code false} if not
092     */
093    public abstract boolean isWorld(@NonNull String worldName);
094
095    /**
096     * @param location Sign location
097     * @return Sign content (or an empty string array if the block is not a sign)
098     * @deprecated May result in synchronous chunk loading
099     */
100    @Deprecated
101    public @NonNull
102    abstract String[] getSignSynchronous(@NonNull Location location);
103
104    /**
105     * Get the world spawn location
106     *
107     * @param world World name
108     * @return World spawn location
109     */
110    public @NonNull
111    abstract Location getSpawn(@NonNull String world);
112
113    /**
114     * Set the world spawn location
115     *
116     * @param location New spawn
117     */
118    public abstract void setSpawn(@NonNull Location location);
119
120    /**
121     * Save a world
122     *
123     * @param world World name
124     */
125    public abstract void saveWorld(@NonNull String world);
126
127    /**
128     * Get a string comparison with the closets block state matching a given string
129     *
130     * @param name Block name
131     * @return Comparison result containing the closets matching block
132     */
133    public @NonNull
134    abstract StringComparison<BlockState>.ComparisonResult getClosestBlock(@NonNull String name);
135
136    /**
137     * Set the block at the specified location to a sign, with given text
138     *
139     * @param location     Block location
140     * @param lines        Sign text
141     * @param replacements Text replacements
142     */
143    public abstract void setSign(
144            @NonNull Location location,
145            @NonNull Caption[] lines,
146            @NonNull TagResolver... replacements
147    );
148
149    /**
150     * Get the biome in a given chunk, asynchronously
151     *
152     * @param world  World
153     * @param x      Chunk X coordinate
154     * @param z      Chunk Z coordinate
155     * @param result Result consumer
156     */
157    public abstract void getBiome(@NonNull String world, int x, int z, @NonNull Consumer<BiomeType> result);
158
159    /**
160     * Get the biome in a given chunk, asynchronously
161     *
162     * @param world World
163     * @param x     Chunk X coordinate
164     * @param z     Chunk Z coordinate
165     * @return Biome
166     * @deprecated Use {@link #getBiome(String, int, int, Consumer)}
167     */
168    @Deprecated
169    public @NonNull
170    abstract BiomeType getBiomeSynchronous(@NonNull String world, int x, int z);
171
172    /**
173     * Get the block at a given location (asynchronously)
174     *
175     * @param location Block location
176     * @param result   Result consumer
177     */
178    public abstract void getBlock(@NonNull Location location, @NonNull Consumer<BlockState> result);
179
180    /**
181     * Get the block at a given location (synchronously)
182     *
183     * @param location Block location
184     * @return Result
185     * @deprecated Use {@link #getBlock(Location, Consumer)}
186     */
187    @Deprecated
188    public @NonNull
189    abstract BlockState getBlockSynchronous(@NonNull Location location);
190
191    /**
192     * Get the Y coordinate of the highest non-air block in the world, asynchronously
193     *
194     * @param world  World name
195     * @param x      X coordinate
196     * @param z      Z coordinate
197     * @param result Result consumer
198     */
199    public abstract void getHighestBlock(@NonNull String world, int x, int z, @NonNull IntConsumer result);
200
201    /**
202     * Get the Y coordinate of the highest non-air block in the world, synchronously
203     *
204     * @param world World name
205     * @param x     X coordinate
206     * @param z     Z coordinate
207     * @return Result
208     * @deprecated Use {@link #getHighestBlock(String, int, int, IntConsumer)}
209     */
210    @Deprecated
211    @NonNegative
212    public abstract int getHighestBlockSynchronous(@NonNull String world, int x, int z);
213
214    /**
215     * Set the biome in a region
216     *
217     * @param worldName World name
218     * @param region    Region
219     * @param biome     New biome
220     */
221    public void setBiomes(@NonNull String worldName, @NonNull CuboidRegion region, @NonNull BiomeType biome) {
222        final World world = getWeWorld(worldName);
223        region.forEach(bv -> world.setBiome(bv, biome));
224    }
225
226    /**
227     * Get the WorldEdit {@link com.sk89q.worldedit.world.World} corresponding to a world name
228     *
229     * @param world World name
230     * @return World object
231     */
232    public abstract com.sk89q.worldedit.world.@NonNull World getWeWorld(@NonNull String world);
233
234    /**
235     * Refresh (resend) chunk to player. Usually after setting the biome
236     *
237     * @param x     Chunk x location
238     * @param z     Chunk z location
239     * @param world World of the chunk
240     */
241    public abstract void refreshChunk(int x, int z, String world);
242
243    /**
244     * The legacy web interface is deprecated for removal in favor of Arkitektonika.
245     */
246    @Deprecated(forRemoval = true, since = "6.11.0")
247    public void upload(
248            final @NonNull Plot plot,
249            final @Nullable UUID uuid,
250            final @Nullable String file,
251            final @NonNull RunnableVal<URL> whenDone
252    ) {
253        plot.getHome(home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal<>() {
254            @Override
255            public void run(OutputStream output) {
256                try (final ZipOutputStream zos = new ZipOutputStream(output)) {
257                    File dat = getDat(plot.getWorldName());
258                    Location spawn = getSpawn(plot.getWorldName());
259                    if (dat != null) {
260                        ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName());
261                        zos.putNextEntry(ze);
262                        try (NBTInputStream nis = new NBTInputStream(new GZIPInputStream(new FileInputStream(dat)))) {
263                            Map<String, Tag> tag = ((CompoundTag) nis.readNamedTag().getTag()).getValue();
264                            Map<String, Tag> newMap = new HashMap<>();
265                            for (Map.Entry<String, Tag> entry : tag.entrySet()) {
266                                if (!entry.getKey().equals("Data")) {
267                                    newMap.put(entry.getKey(), entry.getValue());
268                                    continue;
269                                }
270                                Map<String, Tag> data = new HashMap<>(((CompoundTag) entry.getValue()).getValue());
271                                data.put("SpawnX", new IntTag(home.getX()));
272                                data.put("SpawnY", new IntTag(home.getY()));
273                                data.put("SpawnZ", new IntTag(home.getZ()));
274                                newMap.put("Data", new CompoundTag(data));
275                            }
276                            try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
277                                try (NBTOutputStream out = new NBTOutputStream(new GZIPOutputStream(baos, true))) {
278                                    //TODO Find what this should be called
279                                    out.writeNamedTag("Schematic????", new CompoundTag(newMap));
280                                }
281                                zos.write(baos.toByteArray());
282                            }
283                        }
284                    }
285                    setSpawn(spawn);
286                    byte[] buffer = new byte[1024];
287                    Set<BlockVector2> added = new HashSet<>();
288                    for (Plot current : plot.getConnectedPlots()) {
289                        Location bot = current.getBottomAbs();
290                        Location top = current.getTopAbs();
291                        int brx = bot.getX() >> 9;
292                        int brz = bot.getZ() >> 9;
293                        int trx = top.getX() >> 9;
294                        int trz = top.getZ() >> 9;
295                        Set<BlockVector2> files = getChunkChunks(bot.getWorldName());
296                        for (BlockVector2 mca : files) {
297                            if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz && !added.contains(
298                                    mca)) {
299                                final File file = getMcr(plot.getWorldName(), mca.getX(), mca.getZ());
300                                if (file != null) {
301                                    //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca";
302                                    String name = file.getName();
303                                    final ZipEntry ze = new ZipEntry("world" + File.separator + "region" + File.separator + name);
304                                    zos.putNextEntry(ze);
305                                    added.add(mca);
306                                    try (FileInputStream in = new FileInputStream(file)) {
307                                        int len;
308                                        while ((len = in.read(buffer)) > 0) {
309                                            zos.write(buffer, 0, len);
310                                        }
311                                    }
312                                    zos.closeEntry();
313                                }
314                            }
315                        }
316                    }
317                    zos.closeEntry();
318                    zos.flush();
319                    zos.finish();
320                } catch (IOException e) {
321                    e.printStackTrace();
322                }
323            }
324        }, whenDone));
325    }
326
327    final @Nullable File getDat(final @NonNull String world) {
328        File file = new File(PlotSquared.platform().worldContainer() + File.separator + world + File.separator + "level.dat");
329        if (file.exists()) {
330            return file;
331        }
332        return null;
333    }
334
335    @Nullable
336    private File getMcr(final @NonNull String world, final int x, final int z) {
337        final File file =
338                new File(
339                        PlotSquared.platform().worldContainer(),
340                        world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca"
341                );
342        if (file.exists()) {
343            return file;
344        }
345        return null;
346    }
347
348
349    public Set<BlockVector2> getChunkChunks(String world) {
350        File folder = new File(PlotSquared.platform().worldContainer(), world + File.separator + "region");
351        File[] regionFiles = folder.listFiles();
352        if (regionFiles == null) {
353            throw new RuntimeException("Could not find worlds folder: " + folder + " ? (no read access?)");
354        }
355        HashSet<BlockVector2> chunks = new HashSet<>();
356        for (File file : regionFiles) {
357            String name = file.getName();
358            if (name.endsWith("mca")) {
359                String[] split = name.split("\\.");
360                try {
361                    int x = Integer.parseInt(split[1]);
362                    int z = Integer.parseInt(split[2]);
363                    BlockVector2 loc = BlockVector2.at(x, z);
364                    chunks.add(loc);
365                } catch (NumberFormatException ignored) {
366                }
367            }
368        }
369        return chunks;
370    }
371
372    /**
373     * Check if two blocks are the same type)
374     *
375     * @param block1 First block
376     * @param block2 Second block
377     * @return {@code true} if the blocks have the same type, {@code false} if not
378     */
379    public abstract boolean isBlockSame(@NonNull BlockState block1, @NonNull BlockState block2);
380
381    /**
382     * Get the player health
383     *
384     * @param player Player
385     * @return Non-negative health
386     */
387    @NonNegative
388    public abstract double getHealth(@NonNull PlotPlayer<?> player);
389
390    /**
391     * Set the player health
392     *
393     * @param player Player health
394     * @param health Non-negative health
395     */
396    public abstract void setHealth(@NonNull PlotPlayer<?> player, @NonNegative double health);
397
398    /**
399     * Get the player food level
400     *
401     * @param player Player
402     * @return Non-negative food level
403     */
404    @NonNegative
405    public abstract int getFoodLevel(@NonNull PlotPlayer<?> player);
406
407    /**
408     * Set the player food level
409     *
410     * @param player    Player food level
411     * @param foodLevel Non-negative food level
412     */
413    public abstract void setFoodLevel(@NonNull PlotPlayer<?> player, @NonNegative int foodLevel);
414
415    /**
416     * Get all entity types belonging to an entity category
417     *
418     * @param category Entity category
419     * @return Set containing all entities belonging to the given category
420     */
421    public @NonNull
422    abstract Set<EntityType> getTypesInCategory(@NonNull String category);
423
424    /**
425     * Get all recognized tile entity types
426     *
427     * @return Collection containing all known tile entity types
428     */
429    public @NonNull
430    abstract Collection<BlockType> getTileEntityTypes();
431
432    /**
433     * Get the tile entity count in a chunk
434     *
435     * @param world World
436     * @param chunk Chunk coordinates
437     * @return Tile entity count
438     */
439    @NonNegative
440    public abstract int getTileEntityCount(@NonNull String world, @NonNull BlockVector2 chunk);
441
442}