Search in sources :

Example 1 with ChunkPos

use of net.minecraft.world.level.ChunkPos in project MinecraftForge by MinecraftForge.

the class ForgeChunkManager method forceChunk.

/**
 * Forces a chunk to be loaded for the given mod with the given "owner".
 *
 * @param add {@code true} to force the chunk, {@code false} to unforce the chunk.
 *
 * @implNote Based on {@link ServerLevel#setChunkForced(int, int, boolean)}
 */
private static <T extends Comparable<? super T>> boolean forceChunk(ServerLevel world, String modId, T owner, int chunkX, int chunkZ, boolean add, boolean ticking, TicketType<TicketOwner<T>> type, Function<ForcedChunksSavedData, TicketTracker<T>> ticketGetter) {
    if (!ModList.get().isLoaded(modId)) {
        LOGGER.warn("A mod attempted to force a chunk for an unloaded mod of id: {}", modId);
        return false;
    }
    ForcedChunksSavedData saveData = world.getDataStorage().computeIfAbsent(ForcedChunksSavedData::load, ForcedChunksSavedData::new, "chunks");
    ChunkPos pos = new ChunkPos(chunkX, chunkZ);
    long chunk = pos.toLong();
    TicketTracker<T> tickets = ticketGetter.apply(saveData);
    TicketOwner<T> ticketOwner = new TicketOwner<>(modId, owner);
    boolean success;
    if (add) {
        success = tickets.add(ticketOwner, chunk, ticking);
        if (success)
            world.getChunk(chunkX, chunkZ);
    } else {
        success = tickets.remove(ticketOwner, chunk, ticking);
    }
    if (success) {
        saveData.setDirty(true);
        forceChunk(world, pos, type, ticketOwner, add, ticking);
    }
    return success;
}
Also used : ForcedChunksSavedData(net.minecraft.world.level.ForcedChunksSavedData) ChunkPos(net.minecraft.world.level.ChunkPos)

Example 2 with ChunkPos

use of net.minecraft.world.level.ChunkPos in project MinecraftForge by MinecraftForge.

the class ModelDataManager method requestModelDataRefresh.

public static void requestModelDataRefresh(BlockEntity te) {
    Preconditions.checkNotNull(te, "Tile entity must not be null");
    Level world = te.getLevel();
    cleanCaches(world);
    needModelDataRefresh.computeIfAbsent(new ChunkPos(te.getBlockPos()), $ -> Collections.synchronizedSet(new HashSet<>())).add(te.getBlockPos());
}
Also used : ChunkEvent(net.minecraftforge.event.world.ChunkEvent) IModelData(net.minecraftforge.client.model.data.IModelData) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) EventBusSubscriber(net.minecraftforge.fml.common.Mod.EventBusSubscriber) Set(java.util.Set) BlockEntity(net.minecraft.world.level.block.entity.BlockEntity) Dist(net.minecraftforge.api.distmarker.Dist) HashSet(java.util.HashSet) ChunkPos(net.minecraft.world.level.ChunkPos) Minecraft(net.minecraft.client.Minecraft) BlockPos(net.minecraft.core.BlockPos) Map(java.util.Map) Preconditions(com.google.common.base.Preconditions) SubscribeEvent(net.minecraftforge.eventbus.api.SubscribeEvent) WeakReference(java.lang.ref.WeakReference) Level(net.minecraft.world.level.Level) Collections(java.util.Collections) Bus(net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus) Nullable(javax.annotation.Nullable) Level(net.minecraft.world.level.Level) ChunkPos(net.minecraft.world.level.ChunkPos)

Example 3 with ChunkPos

use of net.minecraft.world.level.ChunkPos in project SpongeCommon by SpongePowered.

the class VolumeStreamUtils method getElementByPosition.

private static <T> Function<ChunkAccess, Stream<Map.Entry<BlockPos, T>>> getElementByPosition(final TriFunction<ChunkAccess, LevelChunkSection, BlockPos, T> elementAccessor, final Vector3i min, final Vector3i max) {
    // Build the min and max
    final ChunkCursor minCursor = new ChunkCursor(min);
    final ChunkCursor maxCursor = new ChunkCursor(max);
    return chunk -> {
        final ChunkPos pos = chunk.getPos();
        final int xStart = pos.x == minCursor.chunkX ? minCursor.xOffset : 0;
        // 16 because IntStream.range is upper range exclusive
        final int xEnd = pos.x == maxCursor.chunkX ? maxCursor.xOffset + 1 : 16;
        final int zStart = pos.z == minCursor.chunkZ ? minCursor.zOffset : 0;
        // 16 because IntStream.range is upper range exclusive
        final int zEnd = pos.z == maxCursor.chunkZ ? maxCursor.zOffset + 1 : 16;
        final int chunkMinX = pos.x << 4;
        final int chunkMinZ = pos.z << 4;
        return Arrays.stream(chunk.getSections()).filter(Objects::nonNull).filter(chunkSection -> chunkSection.bottomBlockY() >= minCursor.ySection && chunkSection.bottomBlockY() <= maxCursor.ySection).flatMap(chunkSection -> IntStream.range(zStart, zEnd).mapToObj(z -> IntStream.range(xStart, xEnd).mapToObj(x -> {
            final int sectionY = chunkSection.bottomBlockY();
            final int yStart = sectionY == minCursor.ySection ? minCursor.yOffset : 0;
            // plus 1 because of IntStream range exclusive
            final int yEnd = sectionY == maxCursor.ySection ? maxCursor.yOffset + 1 : 16;
            return IntStream.range(yStart, yEnd).mapToObj(y -> {
                final int adjustedX = x + chunkMinX;
                final int adjustedY = y + sectionY;
                final int adjustedZ = z + chunkMinZ;
                final BlockPos blockPos = new BlockPos(adjustedX, adjustedY, adjustedZ);
                final T apply = Objects.requireNonNull(elementAccessor.apply(chunk, chunkSection, blockPos), "Element cannot be null");
                return new AbstractMap.SimpleEntry<>(blockPos, apply);
            });
        })).flatMap(Function.identity()).flatMap(Function.identity()));
    };
}
Also used : Arrays(java.util.Arrays) BiFunction(java.util.function.BiFunction) Registry(net.minecraft.core.Registry) MonotonicNonNull(org.checkerframework.checker.nullness.qual.MonotonicNonNull) ChunkBiomeContainerAccessor(org.spongepowered.common.accessor.world.level.chunk.ChunkBiomeContainerAccessor) Map(java.util.Map) ImposterProtoChunk(net.minecraft.world.level.chunk.ImposterProtoChunk) BlockEntityArchetype(org.spongepowered.api.block.entity.BlockEntityArchetype) BlockEntityAccessor(org.spongepowered.common.accessor.world.level.block.entity.BlockEntityAccessor) BuiltinRegistries(net.minecraft.data.BuiltinRegistries) ObjectArrayMutableBiomeBuffer(org.spongepowered.common.world.volume.buffer.biome.ObjectArrayMutableBiomeBuffer) Predicate(java.util.function.Predicate) Collection(java.util.Collection) StreamOptions(org.spongepowered.api.world.volume.stream.StreamOptions) Set(java.util.Set) UUID(java.util.UUID) LevelReader(net.minecraft.world.level.LevelReader) ObjectArrayMutableEntityBuffer(org.spongepowered.common.world.volume.buffer.entity.ObjectArrayMutableEntityBuffer) ChunkAccess(net.minecraft.world.level.chunk.ChunkAccess) Objects(java.util.Objects) CompoundTag(net.minecraft.nbt.CompoundTag) Stream(java.util.stream.Stream) BlockPos(net.minecraft.core.BlockPos) BlockEntityType(net.minecraft.world.level.block.entity.BlockEntityType) ChunkBiomeContainer(net.minecraft.world.level.chunk.ChunkBiomeContainer) Volume(org.spongepowered.api.world.volume.Volume) Level(net.minecraft.world.level.Level) BlockEntity(org.spongepowered.api.block.entity.BlockEntity) IntStream(java.util.stream.IntStream) LevelChunk(net.minecraft.world.level.chunk.LevelChunk) NonNull(org.checkerframework.checker.nullness.qual.NonNull) ArrayMutableBlockBuffer(org.spongepowered.common.world.volume.buffer.block.ArrayMutableBlockBuffer) ProtoChunk(net.minecraft.world.level.chunk.ProtoChunk) BlockState(net.minecraft.world.level.block.state.BlockState) VolumeElement(org.spongepowered.api.world.volume.stream.VolumeElement) Biome(net.minecraft.world.level.biome.Biome) Region(org.spongepowered.api.world.volume.game.Region) Function(java.util.function.Function) Supplier(java.util.function.Supplier) BiConsumer(java.util.function.BiConsumer) ObjectArrayMutableBlockEntityBuffer(org.spongepowered.common.world.volume.buffer.blockentity.ObjectArrayMutableBlockEntityBuffer) WeakReference(java.lang.ref.WeakReference) Nullable(org.checkerframework.checker.nullness.qual.Nullable) LinkedHashSet(java.util.LinkedHashSet) VolumeStream(org.spongepowered.api.world.volume.stream.VolumeStream) Tuple(net.minecraft.util.Tuple) Entity(org.spongepowered.api.entity.Entity) ChunkPos(net.minecraft.world.level.ChunkPos) AbstractMap(java.util.AbstractMap) Vector3d(org.spongepowered.math.vector.Vector3d) LevelChunkSection(net.minecraft.world.level.chunk.LevelChunkSection) VecHelper(org.spongepowered.common.util.VecHelper) ChunkStatus(net.minecraft.world.level.chunk.ChunkStatus) Mth(net.minecraft.util.Mth) EntityArchetype(org.spongepowered.api.entity.EntityArchetype) Vector3i(org.spongepowered.math.vector.Vector3i) AbstractMap(java.util.AbstractMap) ChunkPos(net.minecraft.world.level.ChunkPos) BlockPos(net.minecraft.core.BlockPos)

Example 4 with ChunkPos

use of net.minecraft.world.level.ChunkPos in project SpongeCommon by SpongePowered.

the class ServerPlayerMixin method teleportTo.

/*
    @Inject(method = "markPlayerActive()V", at = @At("HEAD"))
    private void impl$onPlayerActive(final CallbackInfo ci) {
        ((ServerPlayNetHandlerBridge) this.connection).bridge$resendLatestResourcePackRequest();
    }
*/
/**
 * @author zidane - November 21st, 2020 - Minecraft 1.15
 * @reason Ensure that the teleport hook honors our events
 */
@Overwrite
public void teleportTo(final net.minecraft.server.level.ServerLevel world, final double x, final double y, final double z, final float yaw, final float pitch) {
    final net.minecraft.server.level.ServerPlayer player = (net.minecraft.server.level.ServerPlayer) (Object) this;
    double actualX = x;
    double actualY = y;
    double actualZ = z;
    double actualYaw = yaw;
    double actualPitch = pitch;
    final boolean hasMovementContext = PhaseTracker.getCauseStackManager().currentContext().containsKey(EventContextKeys.MOVEMENT_TYPE);
    try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
        if (!hasMovementContext) {
            frame.addContext(EventContextKeys.MOVEMENT_TYPE, MovementTypes.PLUGIN);
        }
        if (world == player.level) {
            @Nullable final Vector3d destination = this.impl$fireMoveEvent(PhaseTracker.SERVER, new Vector3d(x, y, z));
            if (destination == null) {
                return;
            }
            actualX = destination.x();
            actualY = destination.y();
            actualZ = destination.z();
            if (ShouldFire.ROTATE_ENTITY_EVENT) {
                final RotateEntityEvent rotateEvent = SpongeEventFactory.createRotateEntityEvent(frame.currentCause(), (org.spongepowered.api.entity.Entity) player, new Vector3d(actualPitch, actualYaw, 0), new Vector3d(pitch, yaw, 0));
                SpongeCommon.post(rotateEvent);
                actualYaw = rotateEvent.isCancelled() ? player.yRot : rotateEvent.toRotation().y();
                actualPitch = rotateEvent.isCancelled() ? player.xRot : rotateEvent.toRotation().x();
            }
            this.shadow$setCamera(player);
            this.shadow$stopRiding();
            if (player.isSleeping()) {
                player.stopSleepInBed(true, true);
            }
            player.connection.teleport(actualX, actualY, actualZ, (float) actualYaw, (float) actualPitch);
            player.setYHeadRot((float) actualYaw);
            final ChunkPos chunkpos = new ChunkPos(new BlockPos(actualX, actualY, actualZ));
            world.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, chunkpos, 1, player.getId());
        } else {
            final ChangeEntityWorldEvent.Pre preEvent = PlatformHooks.INSTANCE.getEventHooks().callChangeEntityWorldEventPre(player, world);
            if (SpongeCommon.post(preEvent)) {
                return;
            }
            if (ShouldFire.MOVE_ENTITY_EVENT) {
                final MoveEntityEvent posEvent = SpongeEventFactory.createChangeEntityWorldEventReposition(frame.currentCause(), (org.spongepowered.api.entity.Entity) player, preEvent.originalWorld(), VecHelper.toVector3d(player.position()), new Vector3d(x, y, z), preEvent.originalDestinationWorld(), new Vector3d(x, y, z), preEvent.destinationWorld());
                if (SpongeCommon.post(posEvent)) {
                    return;
                }
                actualX = posEvent.destinationPosition().x();
                actualY = posEvent.destinationPosition().y();
                actualZ = posEvent.destinationPosition().z();
            }
            this.shadow$setPos(actualX, actualY, actualZ);
            if (ShouldFire.ROTATE_ENTITY_EVENT) {
                final RotateEntityEvent rotateEvent = SpongeEventFactory.createRotateEntityEvent(frame.currentCause(), (org.spongepowered.api.entity.Entity) player, new Vector3d(actualYaw, actualPitch, 0), new Vector3d(yaw, pitch, 0));
                if (!SpongeCommon.post(rotateEvent)) {
                    actualYaw = (float) rotateEvent.toRotation().x();
                    actualPitch = (float) rotateEvent.toRotation().y();
                }
            }
            this.yRot = (float) actualYaw;
            this.xRot = (float) actualPitch;
            EntityUtil.performPostChangePlayerWorldLogic(player, (net.minecraft.server.level.ServerLevel) preEvent.originalWorld(), (net.minecraft.server.level.ServerLevel) preEvent.originalDestinationWorld(), (net.minecraft.server.level.ServerLevel) preEvent.destinationWorld(), false);
        }
    }
}
Also used : MoveEntityEvent(org.spongepowered.api.event.entity.MoveEntityEvent) ChangeEntityWorldEvent(org.spongepowered.api.event.entity.ChangeEntityWorldEvent) RotateEntityEvent(org.spongepowered.api.event.entity.RotateEntityEvent) Vector3d(org.spongepowered.math.vector.Vector3d) CauseStackManager(org.spongepowered.api.event.CauseStackManager) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) ChunkPos(net.minecraft.world.level.ChunkPos) BlockPos(net.minecraft.core.BlockPos) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Identity(net.kyori.adventure.identity.Identity) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Example 5 with ChunkPos

use of net.minecraft.world.level.ChunkPos in project SpongeCommon by SpongePowered.

the class ServerPlayerMixin method impl$setLocation.

@Override
protected final boolean impl$setLocation(final boolean isChangeOfWorld, final ServerLevel originalDestination, final ServerLevel destinationWorld, final Vector3d destinationPosition) {
    final net.minecraft.server.level.ServerPlayer player = ((net.minecraft.server.level.ServerPlayer) (Object) this);
    player.stopRiding();
    if (player.isSleeping()) {
        player.stopSleepInBed(true, true);
    }
    final ChunkPos chunkPos = VecHelper.toChunkPos(Sponge.server().chunkLayout().forceToChunk(destinationPosition.toInt()));
    destinationWorld.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, chunkPos, 1, player.getId());
    if (isChangeOfWorld) {
        this.shadow$absMoveTo(destinationPosition.x(), destinationPosition.y(), destinationPosition.z(), this.yRot, this.xRot);
        EntityUtil.performPostChangePlayerWorldLogic(player, this.shadow$getLevel(), destinationWorld, destinationWorld, false);
    } else {
        this.connection.teleport(destinationPosition.x(), destinationPosition.y(), destinationPosition.z(), this.yRot, this.xRot, new HashSet<>());
        this.connection.resetPosition();
    }
    return true;
}
Also used : ChunkPos(net.minecraft.world.level.ChunkPos)

Aggregations

ChunkPos (net.minecraft.world.level.ChunkPos)22 BlockPos (net.minecraft.core.BlockPos)12 Level (net.minecraft.world.level.Level)8 Vector3d (org.spongepowered.math.vector.Vector3d)6 ServerLevel (net.minecraft.server.level.ServerLevel)5 Map (java.util.Map)4 ServerChunkCache (net.minecraft.server.level.ServerChunkCache)4 LevelChunk (net.minecraft.world.level.chunk.LevelChunk)4 Collection (java.util.Collection)3 Objects (java.util.Objects)3 UUID (java.util.UUID)3 Stream (java.util.stream.Stream)3 BlockState (net.minecraft.world.level.block.state.BlockState)3 LongIterator (it.unimi.dsi.fastutil.longs.LongIterator)2 IOException (java.io.IOException)2 WeakReference (java.lang.ref.WeakReference)2 Set (java.util.Set)2 ClientboundLightUpdatePacket (net.minecraft.network.protocol.game.ClientboundLightUpdatePacket)2 ThreadedLevelLightEngine (net.minecraft.server.level.ThreadedLevelLightEngine)2 ChunkProgressListener (net.minecraft.server.level.progress.ChunkProgressListener)2