Search in sources :

Example 31 with ServerLevel

use of net.minecraft.server.level.ServerLevel in project SpongeCommon by SpongePowered.

the class PrimaryLevelDataMixin method bridge$world.

@Override
@Nullable
public ServerLevel bridge$world() {
    if (!Sponge.isServerAvailable()) {
        return null;
    }
    final ServerLevel world = SpongeCommon.server().getLevel(SpongeWorldManager.createRegistryKey(this.impl$key));
    if (world == null) {
        return null;
    }
    final ServerLevelData levelData = (ServerLevelData) world.getLevelData();
    if (levelData != this) {
        return null;
    }
    return world;
}
Also used : ServerLevel(net.minecraft.server.level.ServerLevel) ServerLevelData(net.minecraft.world.level.storage.ServerLevelData) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 32 with ServerLevel

use of net.minecraft.server.level.ServerLevel in project SpongeCommon by SpongePowered.

the class SpongeBlockSnapshot method restore.

@Override
public boolean restore(final boolean force, final BlockChangeFlag flag) {
    // TODO - rewrite with the PhaseTracker being the hook or use SpongeImplHooks to do the restore.
    final Optional<ServerLevel> optionalWorld = Optional.ofNullable(this.world.get());
    if (!optionalWorld.isPresent()) {
        return false;
    }
    final ServerLevel world = optionalWorld.get();
    // this way we guarantee an exit.
    try (final PhaseContext<?> context = BlockPhase.State.RESTORING_BLOCKS.createPhaseContext(PhaseTracker.SERVER)) {
        context.buildAndSwitch();
        final BlockPos pos = VecHelper.toBlockPos(this.pos);
        if (!net.minecraft.world.level.Level.isInWorldBounds(pos)) {
            // Invalid position. Inline this check
            return false;
        }
        final net.minecraft.world.level.block.state.BlockState current = world.getBlockState(pos);
        final net.minecraft.world.level.block.state.BlockState replaced = (net.minecraft.world.level.block.state.BlockState) this.blockState;
        if (!force && (current.getBlock() != replaced.getBlock() || current != replaced)) {
            return false;
        }
        // being created during block change removals
        if (!current.is(((net.minecraft.world.level.block.state.BlockState) this.blockState).getBlock())) {
            world.removeBlockEntity(pos);
        }
        world.setBlock(pos, replaced, BlockChangeFlagManager.andNotifyClients(flag).getRawFlag());
        if (this.compound != null) {
            @Nullable BlockEntity te = world.getBlockEntity(pos);
            if (te != null) {
                te.load((net.minecraft.world.level.block.state.BlockState) this.blockState, this.compound);
            } else {
                // In cases like this, we need to directly just say "fuck it" and deserialize from the compound directly.
                try {
                    te = BlockEntity.loadStatic((net.minecraft.world.level.block.state.BlockState) this.blockState, this.compound);
                    if (te != null) {
                        world.getChunk(pos).setBlockEntity(pos, te);
                    }
                } catch (final Exception e) {
                    // Seriously? The mod should be broken then.
                    final PrettyPrinter printer = new PrettyPrinter(60).add("Unable to restore").centre().hr().add("A mod is not correctly deserializing a TileEntity that is being restored. ").addWrapped(60, "Note that this is not the fault of Sponge. Sponge is understanding that " + "a block is supposed to have a TileEntity, but the mod is breaking the contract" + "on how to re-create the tile entity. Please open an issue with the offending mod.").add("Here's the provided compound:");
                    printer.add();
                    try {
                        printer.addWrapped(80, "%s : %s", "This compound", this.compound);
                    } catch (final Throwable error) {
                        printer.addWrapped(80, "Unable to get the string of this compound. Printing out some of the entries to better assist");
                    }
                    printer.add().add("Desired World: " + this.worldKey).add("Position: " + this.pos).add("Desired BlockState: " + this.blockState);
                    printer.add();
                    printer.log(SpongeCommon.logger(), Level.ERROR);
                    // I mean, I guess. the block was set up, but not the tile entity.
                    return true;
                }
            }
            if (te != null) {
                te.setChanged();
            }
        }
        // Finally, mark the location as being updated.
        world.getChunkSource().blockChanged(pos);
        return true;
    }
}
Also used : ServerLevel(net.minecraft.server.level.ServerLevel) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) PrettyPrinter(org.spongepowered.common.util.PrettyPrinter) BlockState(org.spongepowered.api.block.BlockState) BlockPos(net.minecraft.core.BlockPos) Nullable(org.checkerframework.checker.nullness.qual.Nullable) BlockEntity(net.minecraft.world.level.block.entity.BlockEntity)

Example 33 with ServerLevel

use of net.minecraft.server.level.ServerLevel in project SpongeCommon by SpongePowered.

the class SpongeCommonEventFactory method fireCreateMapEvent.

public static Optional<MapInfo> fireCreateMapEvent(final Cause cause, final Set<Value<?>> values) {
    final ServerLevel defaultWorld = (ServerLevel) Sponge.server().worldManager().defaultWorld();
    final MapIdTrackerBridge mapIdTrackerBridge = (MapIdTrackerBridge) defaultWorld.getDataStorage().computeIfAbsent(MapIndex::new, Constants.Map.MAP_INDEX_DATA_NAME);
    final int id = mapIdTrackerBridge.bridge$getHighestMapId().orElse(-1) + 1;
    final String s = Constants.Map.MAP_PREFIX + id;
    final MapItemSavedData mapData = new MapItemSavedData(s);
    // Set default to prevent NPEs
    mapData.dimension = Level.OVERWORLD;
    final MapInfo mapInfo = (MapInfo) mapData;
    for (final Value<?> value : values) {
        mapInfo.offer(value);
    }
    final CreateMapEvent event = SpongeEventFactory.createCreateMapEvent(cause, mapInfo);
    SpongeCommon.post(event);
    if (event.isCancelled()) {
        return Optional.empty();
    }
    // Advance map id.
    final int mcId = defaultWorld.getFreeMapId();
    if (id != mcId) {
        // TODO: REMOVE OR replace for Integer.MAX_VALUE
        SpongeCommon.logger().warn("Map size corruption, vanilla only allows " + Integer.MAX_VALUE + "! " + "Expected next number was not equal to the true next number.");
        SpongeCommon.logger().warn("Expected: " + id + ". Got: " + mcId);
        SpongeCommon.logger().warn("Automatically cancelling map creation");
        mapIdTrackerBridge.bridge$setHighestMapId(id - 1);
        return Optional.empty();
    }
    defaultWorld.setMapData(mapData);
    ((SpongeMapStorage) Sponge.server().mapStorage()).addMapInfo(mapInfo);
    return Optional.of(mapInfo);
}
Also used : MapIdTrackerBridge(org.spongepowered.common.bridge.map.MapIdTrackerBridge) ServerLevel(net.minecraft.server.level.ServerLevel) MapItemSavedData(net.minecraft.world.level.saveddata.maps.MapItemSavedData) CreateMapEvent(org.spongepowered.api.event.action.CreateMapEvent) MapInfo(org.spongepowered.api.map.MapInfo) SpongeMapStorage(org.spongepowered.common.map.SpongeMapStorage)

Example 34 with ServerLevel

use of net.minecraft.server.level.ServerLevel in project SpongeCommon by SpongePowered.

the class SpongeCommonEventFactory method handlePistonEvent.

/**
 * This simulates the blocks a piston moves and calls the event for saner
 * debugging.
 *
 * @return if the event was cancelled
 */
public static boolean handlePistonEvent(final TrackedWorldBridge world, final BlockPos pos, final net.minecraft.world.level.block.state.BlockState blockstate, final int eventId) {
    final boolean extending = (eventId == 0);
    final net.minecraft.core.Direction direction = blockstate.getValue(DirectionalBlock.FACING);
    final LocatableBlock locatable = new SpongeLocatableBlockBuilder().world((ServerWorld) world).state((BlockState) blockstate).position(pos.getX(), pos.getY(), pos.getZ()).build();
    // Sets toss out duplicate values (even though there shouldn't be any)
    final HashSet<ServerLocation> locations = new HashSet<>();
    locations.add(ServerLocation.of((ServerWorld) world, pos.getX(), pos.getY(), pos.getZ()));
    final PistonStructureResolver movedBlocks = new PistonStructureResolver((ServerLevel) world, pos, direction, extending);
    // calculates blocks to be moved
    movedBlocks.resolve();
    Stream.concat(movedBlocks.getToPush().stream(), movedBlocks.getToDestroy().stream()).map(block -> ServerLocation.of((ServerWorld) world, block.getX(), block.getY(), block.getZ())).collect(// SUPER
    Collectors.toCollection(() -> locations));
    // If the piston is extending and there are no blocks to destroy, add the offset location for protection purposes
    if (extending && movedBlocks.getToDestroy().isEmpty()) {
        final List<BlockPos> movedPositions = movedBlocks.getToPush();
        final BlockPos offsetPos;
        // If there are no blocks to move, add the offset of piston
        if (movedPositions.isEmpty()) {
            offsetPos = pos.relative(direction);
        } else {
            // Add the offset of last block set to move
            offsetPos = movedPositions.get(movedPositions.size() - 1).relative(direction);
        }
        locations.add(ServerLocation.of((ServerWorld) world, offsetPos.getX(), offsetPos.getY(), offsetPos.getZ()));
    }
    try (final CauseStackManager.StackFrame frame = PhaseTracker.getInstance().pushCauseFrame()) {
        if (extending) {
            frame.addContext(EventContextKeys.PISTON_EXTEND, (ServerWorld) world);
        } else {
            frame.addContext(EventContextKeys.PISTON_RETRACT, (ServerWorld) world);
        }
        return SpongeCommonEventFactory.callChangeBlockEventPre((ServerLevelBridge) world, ImmutableList.copyOf(locations), locatable).isCancelled();
    }
}
Also used : ServerLevelBridge(org.spongepowered.common.bridge.server.level.ServerLevelBridge) ChangeBlockEvent(org.spongepowered.api.event.block.ChangeBlockEvent) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) CreatorTrackedBridge(org.spongepowered.common.bridge.CreatorTrackedBridge) Living(org.spongepowered.api.entity.living.Living) JukeboxBlockEntity(net.minecraft.world.level.block.entity.JukeboxBlockEntity) ServerboundPlayerActionPacket(net.minecraft.network.protocol.game.ServerboundPlayerActionPacket) Set(java.util.Set) MapIdTrackerBridge(org.spongepowered.common.bridge.map.MapIdTrackerBridge) BlockState(org.spongepowered.api.block.BlockState) Direction(org.spongepowered.api.util.Direction) ConstructEntityEvent(org.spongepowered.api.event.entity.ConstructEntityEvent) Stream(java.util.stream.Stream) World(org.spongepowered.api.world.World) ItemStack(net.minecraft.world.item.ItemStack) Player(org.spongepowered.api.entity.living.player.Player) MoveEntityEvent(org.spongepowered.api.event.entity.MoveEntityEvent) ServerLocation(org.spongepowered.api.world.server.ServerLocation) SpongeMapStorage(org.spongepowered.common.map.SpongeMapStorage) LevelChunkBridge(org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge) EventContextKeys(org.spongepowered.api.event.EventContextKeys) ServerWorld(org.spongepowered.api.world.server.ServerWorld) DestructEntityEvent(org.spongepowered.api.event.entity.DestructEntityEvent) Agent(org.spongepowered.api.entity.living.Agent) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) EntityBridge(org.spongepowered.common.bridge.world.entity.EntityBridge) RotateEntityEvent(org.spongepowered.api.event.entity.RotateEntityEvent) PlaySoundEvent(org.spongepowered.api.event.sound.PlaySoundEvent) DetonateExplosiveEvent(org.spongepowered.api.event.entity.explosive.DetonateExplosiveEvent) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) CauseStackManager(org.spongepowered.api.event.CauseStackManager) GeneralPhase(org.spongepowered.common.event.tracking.phase.general.GeneralPhase) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) PlayerTracker(org.spongepowered.common.entity.PlayerTracker) UnknownProjectileSource(org.spongepowered.common.entity.projectile.UnknownProjectileSource) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) Entity(org.spongepowered.api.entity.Entity) Cause(org.spongepowered.api.event.Cause) Explosive(org.spongepowered.api.entity.explosive.Explosive) PistonStructureResolver(net.minecraft.world.level.block.piston.PistonStructureResolver) Audience(net.kyori.adventure.audience.Audience) VecHelper(org.spongepowered.common.util.VecHelper) InteractionHand(net.minecraft.world.InteractionHand) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) LivingEntity(net.minecraft.world.entity.LivingEntity) MapItemSavedData(net.minecraft.world.level.saveddata.maps.MapItemSavedData) MusicDisc(org.spongepowered.api.effect.sound.music.MusicDisc) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) HandType(org.spongepowered.api.data.type.HandType) DropItemEvent(org.spongepowered.api.event.item.inventory.DropItemEvent) ExplosiveBridge(org.spongepowered.common.bridge.explosives.ExplosiveBridge) CollideBlockEvent(org.spongepowered.api.event.block.CollideBlockEvent) SetAITargetEvent(org.spongepowered.api.event.entity.ai.SetAITargetEvent) TrackedWorldBridge(org.spongepowered.common.bridge.world.TrackedWorldBridge) ActiveChunkReferantBridge(org.spongepowered.common.bridge.world.level.chunk.ActiveChunkReferantBridge) CollideEntityEvent(org.spongepowered.api.event.entity.CollideEntityEvent) NotePitch(org.spongepowered.api.data.type.NotePitch) InteractEntityEvent(org.spongepowered.api.event.entity.InteractEntityEvent) LocatableBlock(org.spongepowered.api.world.LocatableBlock) SoundType(org.spongepowered.api.effect.sound.SoundType) BlockHitResult(net.minecraft.world.phys.BlockHitResult) GameRules(net.minecraft.world.level.GameRules) Sponge(org.spongepowered.api.Sponge) InstrumentType(org.spongepowered.api.data.type.InstrumentType) UUID(java.util.UUID) ProjectileSource(org.spongepowered.api.projectile.source.ProjectileSource) Collectors(java.util.stream.Collectors) Tristate(org.spongepowered.api.util.Tristate) List(java.util.List) Sound(net.kyori.adventure.sound.Sound) MapInfo(org.spongepowered.api.map.MapInfo) BlockPos(net.minecraft.core.BlockPos) SoundEvent(net.minecraft.sounds.SoundEvent) Explosion(org.spongepowered.api.world.explosion.Explosion) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) Optional(java.util.Optional) InteractItemEvent(org.spongepowered.api.event.item.inventory.InteractItemEvent) Level(net.minecraft.world.level.Level) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) NonNull(org.checkerframework.checker.nullness.qual.NonNull) Constants(org.spongepowered.common.util.Constants) ServerLevel(net.minecraft.server.level.ServerLevel) Value(org.spongepowered.api.data.value.Value) EntityDamageSource(net.minecraft.world.damagesource.EntityDamageSource) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) EntityTypes(org.spongepowered.api.entity.EntityTypes) ItemStackUtil(org.spongepowered.common.item.util.ItemStackUtil) Component(net.kyori.adventure.text.Component) DamageSource(net.minecraft.world.damagesource.DamageSource) SoundTypes(org.spongepowered.api.effect.sound.SoundTypes) PlatformEntityBridge(org.spongepowered.common.bridge.world.entity.PlatformEntityBridge) Nullable(org.checkerframework.checker.nullness.qual.Nullable) LevelBridge(org.spongepowered.common.bridge.world.level.LevelBridge) DirectionFacingProvider(org.spongepowered.common.registry.provider.DirectionFacingProvider) EntityHitResult(net.minecraft.world.phys.EntityHitResult) SpongeLocatableBlockBuilder(org.spongepowered.common.world.server.SpongeLocatableBlockBuilder) SpongeCommon(org.spongepowered.common.SpongeCommon) MapIndex(net.minecraft.world.level.saveddata.maps.MapIndex) HitResult(net.minecraft.world.phys.HitResult) MovementTypes(org.spongepowered.api.event.cause.entity.MovementTypes) Vector3d(org.spongepowered.math.vector.Vector3d) CreateMapEvent(org.spongepowered.api.event.action.CreateMapEvent) Block(net.minecraft.world.level.block.Block) SpawnTypes(org.spongepowered.api.event.cause.entity.SpawnTypes) Collections(java.util.Collections) DirectionalBlock(net.minecraft.world.level.block.DirectionalBlock) Jukebox(org.spongepowered.api.block.entity.Jukebox) SpongeLocatableBlockBuilder(org.spongepowered.common.world.server.SpongeLocatableBlockBuilder) ServerLocation(org.spongepowered.api.world.server.ServerLocation) ServerWorld(org.spongepowered.api.world.server.ServerWorld) CauseStackManager(org.spongepowered.api.event.CauseStackManager) PistonStructureResolver(net.minecraft.world.level.block.piston.PistonStructureResolver) LocatableBlock(org.spongepowered.api.world.LocatableBlock) BlockPos(net.minecraft.core.BlockPos) ServerLevelBridge(org.spongepowered.common.bridge.server.level.ServerLevelBridge) HashSet(java.util.HashSet)

Example 35 with ServerLevel

use of net.minecraft.server.level.ServerLevel in project SpongeCommon by SpongePowered.

the class SpongeWorldManager method unloadWorld.

@Override
public CompletableFuture<Boolean> unloadWorld(final ResourceKey key) {
    final net.minecraft.resources.ResourceKey<Level> registryKey = SpongeWorldManager.createRegistryKey(Objects.requireNonNull(key, "key"));
    if (Level.OVERWORLD.equals(registryKey)) {
        return CompletableFuture.completedFuture(false);
    }
    final ServerLevel world = this.worlds.get(registryKey);
    if (world == null) {
        return CompletableFuture.completedFuture(false);
    }
    return this.unloadWorld((org.spongepowered.api.world.server.ServerWorld) world);
}
Also used : ServerLevel(net.minecraft.server.level.ServerLevel) Level(net.minecraft.world.level.Level) ServerLevel(net.minecraft.server.level.ServerLevel)

Aggregations

ServerLevel (net.minecraft.server.level.ServerLevel)115 BlockPos (net.minecraft.core.BlockPos)30 Nullable (org.checkerframework.checker.nullness.qual.Nullable)21 Level (net.minecraft.world.level.Level)20 BlockEntity (net.minecraft.world.level.block.entity.BlockEntity)16 Entity (net.minecraft.world.entity.Entity)14 ServerPlayer (net.minecraft.server.level.ServerPlayer)11 ItemStack (net.minecraft.world.item.ItemStack)10 SpongeBlockSnapshot (org.spongepowered.common.block.SpongeBlockSnapshot)10 IOException (java.io.IOException)9 LevelChunk (net.minecraft.world.level.chunk.LevelChunk)9 CraftWorld (org.bukkit.craftbukkit.v1_18_R1.CraftWorld)9 ArrayList (java.util.ArrayList)8 BlockState (net.minecraft.world.level.block.state.BlockState)8 List (java.util.List)7 Optional (java.util.Optional)7 UUID (java.util.UUID)7 Vec3 (net.minecraft.world.phys.Vec3)7 CraftWorld (org.bukkit.craftbukkit.v1_17_R1.CraftWorld)7 Cause (org.spongepowered.api.event.Cause)7