<commit_before>/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered <https://www.spongepowered.org>
 * Copyright (c) contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.spongepowered.common.world.volume;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.Mth;
import net.minecraft.util.Tuple;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkBiomeContainer;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.ImposterProtoChunk;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.ProtoChunk;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.block.entity.BlockEntity;
import org.spongepowered.api.block.entity.BlockEntityArchetype;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityArchetype;
import org.spongepowered.api.world.volume.Volume;
import org.spongepowered.api.world.volume.game.Region;
import org.spongepowered.api.world.volume.stream.StreamOptions;
import org.spongepowered.api.world.volume.stream.VolumeElement;
import org.spongepowered.api.world.volume.stream.VolumeStream;
import org.spongepowered.common.accessor.world.level.block.entity.BlockEntityAccessor;
import org.spongepowered.common.accessor.world.level.chunk.ChunkBiomeContainerAccessor;
import org.spongepowered.common.util.VecHelper;
import org.spongepowered.common.world.volume.buffer.biome.ObjectArrayMutableBiomeBuffer;
import org.spongepowered.common.world.volume.buffer.block.ArrayMutableBlockBuffer;
import org.spongepowered.common.world.volume.buffer.blockentity.ObjectArrayMutableBlockEntityBuffer;
import org.spongepowered.common.world.volume.buffer.entity.ObjectArrayMutableEntityBuffer;
import org.spongepowered.math.vector.Vector3d;
import org.spongepowered.math.vector.Vector3i;

import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public final class VolumeStreamUtils {

    private VolumeStreamUtils() {}

    /**
     * Creates a {@link Supplier Supplier&lt;T&gt;} that weakly references the
     * provided {@code object} such that the object will not be referenced otherwise
     * within the Supplier itself, allowing it to be freely garbage collected, in the
     * circumstance the reference to the supplier is retained for an extended time.
     *
     * @param object The object being referenced
     * @param name The name of the object, for error printing
     * @param <T> The type of object requested
     * @return The supplier
     */
    public static <T> Supplier<T> createWeaklyReferencedSupplier(final T object, final String name) {
        final WeakReference<T> weakReference = new WeakReference<>(object);
        return () -> {
            final @Nullable T weaklyReferenced = weakReference.get();
            return Objects.requireNonNull(weaklyReferenced, () -> String.format("%s de-referenced!", name));
        };
    }

    @SuppressWarnings({"RedundantCast", "unchecked", "rawtypes"})
    public static <MC, T> org.spongepowered.api.registry.Registry<T> nativeToSpongeRegistry(final Registry<MC> registry) {
        return (org.spongepowered.api.registry.Registry<T>) (org.spongepowered.api.registry.Registry) registry;
    }

    public static Predicate<org.spongepowered.api.util.Tuple<Vector3d, EntityArchetype>> entityArchetypePositionFilter(final Vector3i min, final Vector3i max) {
        return VolumeStreamUtils.filterPositions(tuple -> tuple.first().toInt(), min, max);
    }

    public static Predicate<Map.Entry<Vector3i, BlockEntityArchetype>> blockEntityArchetypePositionFilter(final Vector3i min, final Vector3i max) {
        return VolumeStreamUtils.filterPositions(Map.Entry::getKey, min, max);
    }

    public static <T> Predicate<T> filterPositions(final Function<T, Vector3i> pos, final Vector3i min, final Vector3i max) {
        return (entity) -> {
            final Vector3i apply = pos.apply(entity);
            return apply.x() >= min.x() && apply.x() <= max.x()
                && apply.y() >= min.y() && apply.y() <= max.y()
                && apply.z() >= min.z() && apply.z() <= max.z();
        };
    }

    public static <R extends Region<R>> BiFunction<R, ChunkPos, @Nullable ChunkAccess> getChunkAccessorByStatus(
        final LevelReader worldReader,
        final boolean shouldGenerate
    ) {
        final Supplier<LevelReader> readerSupplier = VolumeStreamUtils.createWeaklyReferencedSupplier(worldReader, "IWorldReader");
        return (world, chunkPos) -> {
            final ChunkStatus chunkStatus = shouldGenerate
                ? ChunkStatus.FULL
                : ChunkStatus.EMPTY;
            final @Nullable ChunkAccess ichunk = readerSupplier.get().getChunk(chunkPos.x, chunkPos.z, chunkStatus, shouldGenerate);
            if (shouldGenerate) {
                Objects.requireNonNull(ichunk, "Chunk was expected to load fully and generate, but somehow got a null chunk!");
            }
            if (ichunk instanceof ImposterProtoChunk) {
                return ((ImposterProtoChunk) ichunk).getWrapped();
            }
            return (ChunkAccess) ichunk;
        };
    }

    public static Function<ChunkAccess, Stream<Map.Entry<BlockPos, Biome>>> getBiomesForChunkByPos(final LevelReader reader, final Vector3i min,
        final Vector3i max
    ) {
        return VolumeStreamUtils.getElementByPosition(VolumeStreamUtils.chunkSectionBiomeGetter().asTri(reader), min, max);
    }

    public static Function<ChunkAccess, Stream<Map.Entry<BlockPos, BlockState>>> getBlockStatesForSections(
        final Vector3i min,
        final Vector3i max
    ) {
        return VolumeStreamUtils.getElementByPosition(VolumeStreamUtils.chunkSectionBlockStateGetter(), min, max);
    }

    public static boolean setBiomeOnNativeChunk(final int x, final int y, final int z, final
        org.spongepowered.api.world.biome.Biome biome, final Supplier<@Nullable ChunkBiomeContainerAccessor> accessor,
        final Runnable finalizer
        ) {
        @Nullable final ChunkBiomeContainerAccessor chunkBiomeContainerAccessor = accessor.get();
        if (chunkBiomeContainerAccessor == null) {
            return false;
        }
        final int maskedX = x & ChunkBiomeContainer.HORIZONTAL_MASK;
        final int maskedY = Mth.clamp(y, 0, ChunkBiomeContainer.VERTICAL_MASK);
        final int maskedZ = z & ChunkBiomeContainer.HORIZONTAL_MASK;
        final int WIDTH_BITS = ChunkBiomeContainerAccessor.accessor$WIDTH_BITS();<commit_msg>convert positions to 'quad' positions in setBiome<commit_after>/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered <https://www.spongepowered.org>
 * Copyright (c) contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.spongepowered.common.world.volume;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.Mth;
import net.minecraft.util.Tuple;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkBiomeContainer;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.ImposterProtoChunk;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.ProtoChunk;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.block.entity.BlockEntity;
import org.spongepowered.api.block.entity.BlockEntityArchetype;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityArchetype;
import org.spongepowered.api.world.volume.Volume;
import org.spongepowered.api.world.volume.game.Region;
import org.spongepowered.api.world.volume.stream.StreamOptions;
import org.spongepowered.api.world.volume.stream.VolumeElement;
import org.spongepowered.api.world.volume.stream.VolumeStream;
import org.spongepowered.common.accessor.world.level.block.entity.BlockEntityAccessor;
import org.spongepowered.common.accessor.world.level.chunk.ChunkBiomeContainerAccessor;
import org.spongepowered.common.util.VecHelper;
import org.spongepowered.common.world.volume.buffer.biome.ObjectArrayMutableBiomeBuffer;
import org.spongepowered.common.world.volume.buffer.block.ArrayMutableBlockBuffer;
import org.spongepowered.common.world.volume.buffer.blockentity.ObjectArrayMutableBlockEntityBuffer;
import org.spongepowered.common.world.volume.buffer.entity.ObjectArrayMutableEntityBuffer;
import org.spongepowered.math.vector.Vector3d;
import org.spongepowered.math.vector.Vector3i;

import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public final class VolumeStreamUtils {

    private VolumeStreamUtils() {}

    /**
     * Creates a {@link Supplier Supplier&lt;T&gt;} that weakly references the
     * provided {@code object} such that the object will not be referenced otherwise
     * within the Supplier itself, allowing it to be freely garbage collected, in the
     * circumstance the reference to the supplier is retained for an extended time.
     *
     * @param object The object being referenced
     * @param name The name of the object, for error printing
     * @param <T> The type of object requested
     * @return The supplier
     */
    public static <T> Supplier<T> createWeaklyReferencedSupplier(final T object, final String name) {
        final WeakReference<T> weakReference = new WeakReference<>(object);
        return () -> {
            final @Nullable T weaklyReferenced = weakReference.get();
            return Objects.requireNonNull(weaklyReferenced, () -> String.format("%s de-referenced!", name));
        };
    }

    @SuppressWarnings({"RedundantCast", "unchecked", "rawtypes"})
    public static <MC, T> org.spongepowered.api.registry.Registry<T> nativeToSpongeRegistry(final Registry<MC> registry) {
        return (org.spongepowered.api.registry.Registry<T>) (org.spongepowered.api.registry.Registry) registry;
    }

    public static Predicate<org.spongepowered.api.util.Tuple<Vector3d, EntityArchetype>> entityArchetypePositionFilter(final Vector3i min, final Vector3i max) {
        return VolumeStreamUtils.filterPositions(tuple -> tuple.first().toInt(), min, max);
    }

    public static Predicate<Map.Entry<Vector3i, BlockEntityArchetype>> blockEntityArchetypePositionFilter(final Vector3i min, final Vector3i max) {
        return VolumeStreamUtils.filterPositions(Map.Entry::getKey, min, max);
    }

    public static <T> Predicate<T> filterPositions(final Function<T, Vector3i> pos, final Vector3i min, final Vector3i max) {
        return (entity) -> {
            final Vector3i apply = pos.apply(entity);
            return apply.x() >= min.x() && apply.x() <= max.x()
                && apply.y() >= min.y() && apply.y() <= max.y()
                && apply.z() >= min.z() && apply.z() <= max.z();
        };
    }

    public static <R extends Region<R>> BiFunction<R, ChunkPos, @Nullable ChunkAccess> getChunkAccessorByStatus(
        final LevelReader worldReader,
        final boolean shouldGenerate
    ) {
        final Supplier<LevelReader> readerSupplier = VolumeStreamUtils.createWeaklyReferencedSupplier(worldReader, "IWorldReader");
        return (world, chunkPos) -> {
            final ChunkStatus chunkStatus = shouldGenerate
                ? ChunkStatus.FULL
                : ChunkStatus.EMPTY;
            final @Nullable ChunkAccess ichunk = readerSupplier.get().getChunk(chunkPos.x, chunkPos.z, chunkStatus, shouldGenerate);
            if (shouldGenerate) {
                Objects.requireNonNull(ichunk, "Chunk was expected to load fully and generate, but somehow got a null chunk!");
            }
            if (ichunk instanceof ImposterProtoChunk) {
                return ((ImposterProtoChunk) ichunk).getWrapped();
            }
            return (ChunkAccess) ichunk;
        };
    }

    public static Function<ChunkAccess, Stream<Map.Entry<BlockPos, Biome>>> getBiomesForChunkByPos(final LevelReader reader, final Vector3i min,
        final Vector3i max
    ) {
        return VolumeStreamUtils.getElementByPosition(VolumeStreamUtils.chunkSectionBiomeGetter().asTri(reader), min, max);
    }

    public static Function<ChunkAccess, Stream<Map.Entry<BlockPos, BlockState>>> getBlockStatesForSections(
        final Vector3i min,
        final Vector3i max
    ) {
        return VolumeStreamUtils.getElementByPosition(VolumeStreamUtils.chunkSectionBlockStateGetter(), min, max);
    }

    public static boolean setBiomeOnNativeChunk(final int x, final int y, final int z,
        final org.spongepowered.api.world.biome.Biome biome, final Supplier<@Nullable ChunkBiomeContainerAccessor> accessor,
        final Runnable finalizer
    ) {
        @Nullable final ChunkBiomeContainerAccessor chunkBiomeContainerAccessor = accessor.get();
        if (chunkBiomeContainerAccessor == null) {
            return false;
        }
        final int maskedX = (x >> 2) & ChunkBiomeContainer.HORIZONTAL_MASK;
        final int maskedY = Mth.clamp((y >> 2), 0, ChunkBiomeContainer.VERTICAL_MASK);
        final int maskedZ = (z >> 2) & ChunkBiomeContainer.HORIZONTAL_MASK;
        final int WIDTH_BITS = ChunkBiomeContainerAccessor.accessor$WIDTH_BITS();
{'fraction_non_alphanumeric': 0.09492109038737447, 'fraction_numerical': 0.0021233859397417503, 'mean_word_length': 4.111762980346143, 'pattern_counts': {'":': 0, '<': 65, '<?xml version=': 0, '>': 81, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2563694', 'n_tokens_mistral': 4950, 'n_tokens_neox': 4832, 'n_words': 1264}