Search in sources :

Example 11 with BlockVector2

use of com.sk89q.worldedit.math.BlockVector2 in project FastAsyncWorldEdit by IntellectualSites.

the class ForgeWorld method regenerate.

@Override
public boolean regenerate(Region region, EditSession editSession) {
    // Don't even try to regen if it's going to fail.
    AbstractChunkProvider provider = getWorld().getChunkProvider();
    if (!(provider instanceof ServerChunkProvider)) {
        return false;
    }
    File saveFolder = Files.createTempDir();
    // register this just in case something goes wrong
    // normally it should be deleted at the end of this method
    saveFolder.deleteOnExit();
    try {
        ServerWorld originalWorld = (ServerWorld) getWorld();
        MinecraftServer server = originalWorld.getServer();
        SaveHandler saveHandler = new SaveHandler(saveFolder, originalWorld.getSaveHandler().getWorldDirectory().getName(), server, server.getDataFixer());
        try (World freshWorld = new ServerWorld(server, server.getBackgroundExecutor(), saveHandler, originalWorld.getWorldInfo(), originalWorld.dimension.getType(), originalWorld.getProfiler(), new NoOpChunkStatusListener())) {
            // Pre-gen all the chunks
            // We need to also pull one more chunk in every direction
            CuboidRegion expandedPreGen = new CuboidRegion(region.getMinimumPoint().subtract(16, 0, 16), region.getMaximumPoint().add(16, 0, 16));
            for (BlockVector2 chunk : expandedPreGen.getChunks()) {
                freshWorld.getChunk(chunk.getBlockX(), chunk.getBlockZ());
            }
            ForgeWorld from = new ForgeWorld(freshWorld);
            for (BlockVector3 vec : region) {
                editSession.setBlock(vec, from.getFullBlock(vec));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } catch (MaxChangedBlocksException e) {
        throw new RuntimeException(e);
    } finally {
        saveFolder.delete();
    }
    return true;
}
Also used : AbstractChunkProvider(net.minecraft.world.chunk.AbstractChunkProvider) CuboidRegion(com.sk89q.worldedit.regions.CuboidRegion) IOException(java.io.IOException) World(net.minecraft.world.World) ServerWorld(net.minecraft.world.server.ServerWorld) AbstractWorld(com.sk89q.worldedit.world.AbstractWorld) BlockVector3(com.sk89q.worldedit.math.BlockVector3) BlockVector2(com.sk89q.worldedit.math.BlockVector2) MinecraftServer(net.minecraft.server.MinecraftServer) MaxChangedBlocksException(com.sk89q.worldedit.MaxChangedBlocksException) ServerWorld(net.minecraft.world.server.ServerWorld) SaveHandler(net.minecraft.world.storage.SaveHandler) File(java.io.File) ServerChunkProvider(net.minecraft.world.server.ServerChunkProvider)

Example 12 with BlockVector2

use of com.sk89q.worldedit.math.BlockVector2 in project FastAsyncWorldEdit by IntellectualSites.

the class PaperweightAdapter method submitChunkLoadTasks.

@SuppressWarnings("unchecked")
private List<CompletableFuture<ChunkAccess>> submitChunkLoadTasks(Region region, ServerLevel serverWorld) {
    ServerChunkCache chunkManager = serverWorld.getChunkSource();
    List<CompletableFuture<ChunkAccess>> chunkLoadings = new ArrayList<>();
    // Pre-gen all the chunks
    for (BlockVector2 chunk : region.getChunks()) {
        try {
            chunkLoadings.add(((CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>) getChunkFutureMainThreadMethod.invoke(chunkManager, chunk.getX(), chunk.getZ(), ChunkStatus.FEATURES, true)).thenApply(either -> either.left().orElse(null)));
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new IllegalStateException("Couldn't load chunk for regen.", e);
        }
    }
    return chunkLoadings;
}
Also used : Property(com.sk89q.worldedit.registry.state.Property) LoadingCache(com.google.common.cache.LoadingCache) DirectionalProperty(com.sk89q.worldedit.registry.state.DirectionalProperty) StringRepresentable(net.minecraft.util.StringRepresentable) Item(net.minecraft.world.item.Item) CraftItemStack(org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemStack) BaseItemStack(com.sk89q.worldedit.blocks.BaseItemStack) BiomeTypes(com.sk89q.worldedit.world.biome.BiomeTypes) Constants(com.sk89q.worldedit.internal.Constants) Component(com.sk89q.worldedit.util.formatting.text.Component) MinecraftServer(net.minecraft.server.MinecraftServer) Location(org.bukkit.Location) SideEffect(com.sk89q.worldedit.util.SideEffect) LongArrayBinaryTag(com.sk89q.worldedit.util.nbt.LongArrayBinaryTag) Map(java.util.Map) Path(java.nio.file.Path) BlockStateHolder(com.sk89q.worldedit.world.block.BlockStateHolder) BlockStateIdAccess(com.sk89q.worldedit.internal.block.BlockStateIdAccess) BlockData(org.bukkit.block.data.BlockData) LongBinaryTag(com.sk89q.worldedit.util.nbt.LongBinaryTag) Set(java.util.Set) InteractionResult(net.minecraft.world.InteractionResult) BlockEntity(net.minecraft.world.level.block.entity.BlockEntity) InvocationTargetException(java.lang.reflect.InvocationTargetException) BinaryTag(com.sk89q.worldedit.util.nbt.BinaryTag) WorldEditPlugin(com.sk89q.worldedit.bukkit.WorldEditPlugin) CraftBlockData(org.bukkit.craftbukkit.v1_18_R1.block.data.CraftBlockData) StringBinaryTag(com.sk89q.worldedit.util.nbt.StringBinaryTag) BaseBlock(com.sk89q.worldedit.world.block.BaseBlock) ItemStack(net.minecraft.world.item.ItemStack) Extent(com.sk89q.worldedit.extent.Extent) BiomeType(com.sk89q.worldedit.world.biome.BiomeType) IntBinaryTag(com.sk89q.worldedit.util.nbt.IntBinaryTag) LevelChunk(net.minecraft.world.level.chunk.LevelChunk) ChunkHolder(net.minecraft.server.level.ChunkHolder) EntityType(net.minecraft.world.entity.EntityType) WorldGenSettings(net.minecraft.world.level.levelgen.WorldGenSettings) CraftServer(org.bukkit.craftbukkit.v1_18_R1.CraftServer) IntArrayBinaryTag(com.sk89q.worldedit.util.nbt.IntArrayBinaryTag) LazyReference(com.sk89q.worldedit.util.concurrency.LazyReference) SpigotConfig(org.spigotmc.SpigotConfig) Biome(net.minecraft.world.level.biome.Biome) TranslatableComponent(com.sk89q.worldedit.util.formatting.text.TranslatableComponent) ArrayList(java.util.ArrayList) OptionalLong(java.util.OptionalLong) WorldEditException(com.sk89q.worldedit.WorldEditException) CraftMagicNumbers(org.bukkit.craftbukkit.v1_18_R1.util.CraftMagicNumbers) RegenOptions(com.sk89q.worldedit.world.RegenOptions) ShortBinaryTag(com.sk89q.worldedit.util.nbt.ShortBinaryTag) UseOnContext(net.minecraft.world.item.context.UseOnContext) Nullable(javax.annotation.Nullable) WorldNativeAccess(com.sk89q.worldedit.internal.wna.WorldNativeAccess) DataFixer(com.sk89q.worldedit.world.DataFixer) Files(java.nio.file.Files) Lifecycle(com.mojang.serialization.Lifecycle) Field(java.lang.reflect.Field) ChunkPos(net.minecraft.world.level.ChunkPos) ExecutionException(java.util.concurrent.ExecutionException) Futures(com.google.common.util.concurrent.Futures) ForkJoinPool(java.util.concurrent.ForkJoinPool) ByteArrayBinaryTag(com.sk89q.worldedit.util.nbt.ByteArrayBinaryTag) LevelStem(net.minecraft.world.level.dimension.LevelStem) BlockState(com.sk89q.worldedit.world.block.BlockState) InteractionHand(net.minecraft.world.InteractionHand) ChunkStatus(net.minecraft.world.level.chunk.ChunkStatus) ListBinaryTag(com.sk89q.worldedit.util.nbt.ListBinaryTag) Watchdog(com.sk89q.worldedit.extension.platform.Watchdog) ResourceLocation(net.minecraft.resources.ResourceLocation) Either(com.mojang.datafixers.util.Either) BlockVector2(com.sk89q.worldedit.math.BlockVector2) BlockTypes(com.sk89q.worldedit.world.block.BlockTypes) BlockVector3(com.sk89q.worldedit.math.BlockVector3) ClientboundEntityEventPacket(net.minecraft.network.protocol.game.ClientboundEntityEventPacket) Player(org.bukkit.entity.Player) ChunkGenerator(org.bukkit.generator.ChunkGenerator) Registry(net.minecraft.core.Registry) CraftPlayer(org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer) BooleanProperty(com.sk89q.worldedit.registry.state.BooleanProperty) Locale(java.util.Locale) Refraction(com.sk89q.worldedit.bukkit.adapter.Refraction) DedicatedServer(net.minecraft.server.dedicated.DedicatedServer) CompoundBinaryTag(com.sk89q.worldedit.util.nbt.CompoundBinaryTag) Method(java.lang.reflect.Method) Bukkit(org.bukkit.Bukkit) StateDefinition(net.minecraft.world.level.block.state.StateDefinition) SafeFiles(com.sk89q.worldedit.util.io.file.SafeFiles) BlockType(com.sk89q.worldedit.world.block.BlockType) ChunkProgressListener(net.minecraft.server.level.progress.ChunkProgressListener) PrimaryLevelData(net.minecraft.world.level.storage.PrimaryLevelData) BaseItem(com.sk89q.worldedit.blocks.BaseItem) BlockHitResult(net.minecraft.world.phys.BlockHitResult) ClientboundBlockEntityDataPacket(net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket) BlockableEventLoop(net.minecraft.util.thread.BlockableEventLoop) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) BukkitImplAdapter(com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter) Blocks(net.minecraft.world.level.block.Blocks) ChunkAccess(net.minecraft.world.level.chunk.ChunkAccess) Preconditions.checkState(com.google.common.base.Preconditions.checkState) CacheLoader(com.google.common.cache.CacheLoader) Objects(java.util.Objects) Util(net.minecraft.Util) List(java.util.List) EnumProperty(com.sk89q.worldedit.registry.state.EnumProperty) BlockPos(net.minecraft.core.BlockPos) BukkitAdapter(com.sk89q.worldedit.bukkit.BukkitAdapter) CacheBuilder(com.google.common.cache.CacheBuilder) ServerChunkCache(net.minecraft.server.level.ServerChunkCache) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ServerLevel(net.minecraft.server.level.ServerLevel) OptionalInt(java.util.OptionalInt) Level(java.util.logging.Level) EndBinaryTag(com.sk89q.worldedit.util.nbt.EndBinaryTag) Environment(org.bukkit.World.Environment) ImmutableList(com.google.common.collect.ImmutableList) DoubleBinaryTag(com.sk89q.worldedit.util.nbt.DoubleBinaryTag) FloatBinaryTag(com.sk89q.worldedit.util.nbt.FloatBinaryTag) ByteBinaryTag(com.sk89q.worldedit.util.nbt.ByteBinaryTag) Direction(com.sk89q.worldedit.util.Direction) SpawnReason(org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason) WeakReference(java.lang.ref.WeakReference) BaseEntity(com.sk89q.worldedit.entity.BaseEntity) LevelStorageSource(net.minecraft.world.level.storage.LevelStorageSource) CraftWorld(org.bukkit.craftbukkit.v1_18_R1.CraftWorld) Region(com.sk89q.worldedit.regions.Region) PaperweightFaweAdapter(com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.PaperweightFaweAdapter) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Maps(com.google.common.collect.Maps) ResourceKey(net.minecraft.resources.ResourceKey) StructureBlockEntity(net.minecraft.world.level.block.entity.StructureBlockEntity) LevelSettings(net.minecraft.world.level.LevelSettings) Entity(net.minecraft.world.entity.Entity) CraftEntity(org.bukkit.craftbukkit.v1_18_R1.entity.CraftEntity) Vec3(net.minecraft.world.phys.Vec3) IntegerProperty(com.sk89q.worldedit.registry.state.IntegerProperty) DirectionProperty(net.minecraft.world.level.block.state.properties.DirectionProperty) WatchdogThread(org.spigotmc.WatchdogThread) Block(net.minecraft.world.level.block.Block) ItemType(com.sk89q.worldedit.world.item.ItemType) Clearable(net.minecraft.world.Clearable) CompletableFuture(java.util.concurrent.CompletableFuture) ChunkHolder(net.minecraft.server.level.ChunkHolder) ArrayList(java.util.ArrayList) Either(com.mojang.datafixers.util.Either) ServerChunkCache(net.minecraft.server.level.ServerChunkCache) BlockVector2(com.sk89q.worldedit.math.BlockVector2) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 13 with BlockVector2

use of com.sk89q.worldedit.math.BlockVector2 in project FastAsyncWorldEdit by IntellectualSites.

the class ChunkDeleter method groupChunks.

private Map<Path, Stream<BlockVector2>> groupChunks(ChunkDeletionInfo.ChunkBatch chunkBatch) {
    Path worldPath = Paths.get(chunkBatch.worldPath);
    if (chunkBatch.chunks != null) {
        return chunkBatch.chunks.stream().collect(Collectors.groupingBy(RegionFilePos::new)).entrySet().stream().collect(Collectors.toMap(e -> worldPath.resolve("region").resolve(e.getKey().getFileName()), e -> e.getValue().stream().sorted(chunkSorter)));
    } else {
        final BlockVector2 minChunk = chunkBatch.minChunk;
        final BlockVector2 maxChunk = chunkBatch.maxChunk;
        final RegionFilePos minRegion = new RegionFilePos(minChunk);
        final RegionFilePos maxRegion = new RegionFilePos(maxChunk);
        Map<Path, Stream<BlockVector2>> groupedChunks = new HashMap<>();
        for (int regX = minRegion.getX(); regX <= maxRegion.getX(); regX++) {
            for (int regZ = minRegion.getZ(); regZ <= maxRegion.getZ(); regZ++) {
                final Path regionPath = worldPath.resolve("region").resolve(new RegionFilePos(regX, regZ).getFileName());
                if (!Files.exists(regionPath)) {
                    continue;
                }
                int startX = regX << 5;
                int endX = (regX << 5) + 31;
                int startZ = regZ << 5;
                int endZ = (regZ << 5) + 31;
                int minX = Math.max(Math.min(startX, endX), minChunk.getBlockX());
                int minZ = Math.max(Math.min(startZ, endZ), minChunk.getBlockZ());
                int maxX = Math.min(Math.max(startX, endX), maxChunk.getBlockX());
                int maxZ = Math.min(Math.max(startZ, endZ), maxChunk.getBlockZ());
                Stream<BlockVector2> stream = Stream.iterate(BlockVector2.at(minX, minZ), bv2 -> {
                    int nextX = bv2.getBlockX();
                    int nextZ = bv2.getBlockZ();
                    if (++nextX > maxX) {
                        nextX = minX;
                        if (++nextZ > maxZ) {
                            return null;
                        }
                    }
                    return BlockVector2.at(nextX, nextZ);
                });
                groupedChunks.put(regionPath, stream);
            }
        }
        return groupedChunks;
    }
}
Also used : Path(java.nio.file.Path) TypeToken(com.google.gson.reflect.TypeToken) BlockVector2(com.sk89q.worldedit.math.BlockVector2) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) StandardCopyOption(java.nio.file.StandardCopyOption) HashSet(java.util.HashSet) BiPredicate(java.util.function.BiPredicate) Gson(com.google.gson.Gson) Map(java.util.Map) JsonWriter(com.google.gson.stream.JsonWriter) Path(java.nio.file.Path) LogManagerCompat(com.sk89q.worldedit.internal.util.LogManagerCompat) Iterator(java.util.Iterator) JsonSyntaxException(com.google.gson.JsonSyntaxException) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) JsonIOException(com.google.gson.JsonIOException) Comparator(java.util.Comparator) HashMap(java.util.HashMap) Stream(java.util.stream.Stream) BlockVector2(com.sk89q.worldedit.math.BlockVector2)

Example 14 with BlockVector2

use of com.sk89q.worldedit.math.BlockVector2 in project FastAsyncWorldEdit by IntellectualSites.

the class Polygons method polygonizeCylinder.

/**
 * Calculates the polygon shape of a cylinder which can then be used for e.g. intersection detection.
 *
 * @param center    the center point of the cylinder
 * @param radius    the radius of the cylinder
 * @param maxPoints max points to be used for the calculation
 * @return a list of {@link BlockVector2} which resemble the shape as a polygon
 */
public static List<BlockVector2> polygonizeCylinder(BlockVector2 center, Vector2 radius, int maxPoints) {
    int nPoints = (int) Math.ceil(Math.PI * radius.length());
    // These strange semantics for maxPoints are copied from the selectSecondary method.
    if (maxPoints >= 0 && nPoints >= maxPoints) {
        nPoints = maxPoints - 1;
    }
    final List<BlockVector2> points = new ArrayList<>(nPoints);
    for (int i = 0; i < nPoints; ++i) {
        double angle = i * (2.0 * Math.PI) / nPoints;
        final Vector2 pos = Vector2.at(Math.cos(angle), Math.sin(angle));
        final BlockVector2 blockVector2D = pos.multiply(radius).toBlockPoint().add(center);
        points.add(blockVector2D);
    }
    return points;
}
Also used : BlockVector2(com.sk89q.worldedit.math.BlockVector2) Vector2(com.sk89q.worldedit.math.Vector2) ArrayList(java.util.ArrayList) BlockVector2(com.sk89q.worldedit.math.BlockVector2)

Example 15 with BlockVector2

use of com.sk89q.worldedit.math.BlockVector2 in project FastAsyncWorldEdit by IntellectualSites.

the class FolderSnapshot method getChunkTag.

@Override
public CompoundTag getChunkTag(BlockVector3 position) throws DataException, IOException {
    BlockVector2 pos = position.toBlockVector2();
    Optional<Path> regFolder = getRegionFolder();
    if (!regFolder.isPresent()) {
        Path chunkFile = getFolder().resolve(LegacyChunkStore.getFilename(pos, "/"));
        if (!Files.exists(chunkFile)) {
            throw new MissingChunkException();
        }
        return ChunkStoreHelper.readCompoundTag(() -> new GZIPInputStream(Files.newInputStream(chunkFile)));
    }
    Path regionFile = regFolder.get().resolve(McRegionChunkStore.getFilename(pos));
    if (!Files.exists(regionFile)) {
        // Try mcr as well
        regionFile = regionFile.resolveSibling(regionFile.getFileName().toString().replace(".mca", ".mcr"));
        if (!Files.exists(regionFile)) {
            throw new MissingChunkException();
        }
    }
    try (InputStream stream = Files.newInputStream(regionFile)) {
        McRegionReader regionReader = new McRegionReader(stream);
        return ChunkStoreHelper.readCompoundTag(() -> regionReader.getChunkInputStream(pos));
    }
}
Also used : Path(java.nio.file.Path) GZIPInputStream(java.util.zip.GZIPInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) McRegionReader(com.sk89q.worldedit.world.storage.McRegionReader) BlockVector2(com.sk89q.worldedit.math.BlockVector2) MissingChunkException(com.sk89q.worldedit.world.storage.MissingChunkException)

Aggregations

BlockVector2 (com.sk89q.worldedit.math.BlockVector2)55 BlockVector3 (com.sk89q.worldedit.math.BlockVector3)19 ArrayList (java.util.ArrayList)13 IOException (java.io.IOException)9 Map (java.util.Map)9 ProtectedPolygonalRegion (com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion)7 ProtectedRegion (com.sk89q.worldguard.protection.regions.ProtectedRegion)6 LinkedHashMap (java.util.LinkedHashMap)6 GlobalProtectedRegion (com.sk89q.worldguard.protection.regions.GlobalProtectedRegion)5 Path (java.nio.file.Path)5 Iterator (java.util.Iterator)5 Set (java.util.Set)5 JsonIOException (com.google.gson.JsonIOException)4 CuboidRegion (com.sk89q.worldedit.regions.CuboidRegion)4 Location (com.sk89q.worldedit.util.Location)4 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 List (java.util.List)4 CommandPermissions (com.sk89q.worldedit.command.util.CommandPermissions)3 Region (com.sk89q.worldedit.regions.Region)3