Search in sources :

Example 6 with ServerWorld

use of org.spongepowered.api.world.server.ServerWorld in project SpongeCommon by SpongePowered.

the class MapTest method setMapNether.

private CommandResult setMapNether(final CommandContext ctx) throws CommandException {
    final Audience audience = ctx.cause().audience();
    final Player player = this.requirePlayer(ctx);
    final ItemStack map = player.itemInHand(HandTypes.MAIN_HAND);
    if (map.type() != ItemTypes.FILLED_MAP.get()) {
        throw new CommandException(Component.text("You must hold a map in your hand"));
    }
    final ResourceKey netherKey = ResourceKey.minecraft("the_nether");
    final Optional<ServerWorld> nether = Sponge.server().worldManager().world(netherKey);
    if (!nether.isPresent()) {
        final CompletableFuture<ServerWorld> loadedNether = Sponge.server().worldManager().loadWorld(netherKey);
        loadedNether.whenComplete((v, e) -> {
            if (e != null) {
                audience.sendMessage(Component.text("Failed to load nether world!", NamedTextColor.GREEN));
                logger.error("Error loading nether world!", e);
            } else {
                audience.sendMessage(Component.text("Loaded nether world (dim-1)", NamedTextColor.GREEN));
            }
        });
        throw new CommandException(Component.text("No nether loaded, trying to load now, please wait"));
    }
    map.require(Keys.MAP_INFO).offer(Keys.MAP_WORLD, nether.get().key());
    return CommandResult.success();
}
Also used : ServerWorld(org.spongepowered.api.world.server.ServerWorld) Player(org.spongepowered.api.entity.living.player.Player) Audience(net.kyori.adventure.audience.Audience) CommandException(org.spongepowered.api.command.exception.CommandException) ItemStack(org.spongepowered.api.item.inventory.ItemStack) ResourceKey(org.spongepowered.api.ResourceKey)

Example 7 with ServerWorld

use of org.spongepowered.api.world.server.ServerWorld in project SpongeCommon by SpongePowered.

the class AbstractSpongeRayTrace method execute.

@Override
@NonNull
public Optional<RayTraceResult<@NonNull T>> execute() {
    this.setupEnd();
    // get the direction
    final Vector3d directionWithLength = this.end.sub(this.start);
    final double length = directionWithLength.length();
    final Vector3d direction = directionWithLength.normalize();
    if (direction.lengthSquared() == 0) {
        throw new IllegalStateException("The start and end must be two different vectors");
    }
    final ServerWorld serverWorld = Sponge.server().worldManager().world(this.world).orElseThrow(() -> new IllegalStateException("World with key " + this.world.formatted() + " is not loaded!"));
    Vector3i currentBlock = this.initialBlock(direction);
    final Vector3i steps = this.createSteps(direction);
    // The ray equation is, vec(u) + t vec(d). From a point (x, y), there is a t
    // that we need to traverse to get to a boundary. We work that out now...
    TData tData = this.createInitialTData(direction);
    Vector3d currentLocation = new Vector3d(this.start.x(), this.start.y(), this.start.z());
    final boolean requiresEntityTracking = this.requiresEntityTracking();
    boolean requireAdvancement = true;
    while (requireAdvancement) {
        final net.minecraft.world.phys.Vec3 vec3dstart = VecHelper.toVanillaVector3d(currentLocation);
        // As this iteration is for the CURRENT block location, we need to check where we are with the filter.
        if (this.continueWhileLocation != null && !this.continueWhileLocation.test(ServerLocation.of(serverWorld, currentBlock))) {
            return Optional.empty();
        }
        final Vector3d nextLocation;
        final net.minecraft.world.phys.Vec3 vec3dend;
        if (tData.getTotalTWithNextStep() > length) {
            // This is the last step, we break out of the loop after this set of checks.
            requireAdvancement = false;
            nextLocation = this.end;
            vec3dend = VecHelper.toVanillaVector3d(this.end);
        } else {
            nextLocation = currentLocation.add(direction.x() * tData.getNextStep(), direction.y() * tData.getNextStep(), direction.z() * tData.getNextStep());
            vec3dend = VecHelper.toVanillaVector3d(nextLocation);
        }
        // Get the selection result.
        final Optional<RayTraceResult<@NonNull T>> result = this.testSelectLocation(serverWorld, vec3dstart, vec3dend);
        if (result.isPresent() && !this.shouldCheckFailures()) {
            // that's blocking the view.
            return result;
        }
        // Ensure that the block can be travelled through.
        if (!this.shouldAdvanceThroughBlock(serverWorld, vec3dstart, vec3dend)) {
            return Optional.empty();
        }
        // Ensure that the entities in the block can be travelled through.
        if (requiresEntityTracking && this.continueWhileEntity != null) {
            final double resultDistance;
            if (result.isPresent()) {
                resultDistance = result.get().hitPosition().distanceSquared(currentLocation);
            } else {
                resultDistance = Double.MAX_VALUE;
            }
            final AABB targetAABB = this.getBlockAABB(currentBlock);
            for (final net.minecraft.world.entity.Entity entity : this.getFailingEntities(serverWorld, targetAABB)) {
                final Optional<net.minecraft.world.phys.Vec3> vec3d = entity.getBoundingBox().clip(vec3dstart, vec3dend);
                if (vec3d.isPresent()) {
                    final net.minecraft.world.phys.Vec3 hitPosition = vec3d.get();
                    final double sqdist = hitPosition.distanceToSqr(vec3dstart);
                    if (sqdist < resultDistance) {
                        // We have a failure, so at this point we just bail out and end the trace.
                        return Optional.empty();
                    }
                }
            }
        }
        // If we still have a result at this point, return it.
        if (result.isPresent()) {
            return result;
        }
        if (requireAdvancement) {
            currentLocation = nextLocation;
            currentBlock = this.getNextBlock(currentBlock, tData, steps);
            tData = this.advance(tData, steps, direction);
        }
    }
    return Optional.empty();
}
Also used : RayTraceResult(org.spongepowered.api.util.blockray.RayTraceResult) ServerWorld(org.spongepowered.api.world.server.ServerWorld) Vector3d(org.spongepowered.math.vector.Vector3d) NonNull(org.checkerframework.checker.nullness.qual.NonNull) Vector3i(org.spongepowered.math.vector.Vector3i) AABB(net.minecraft.world.phys.AABB) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Example 8 with ServerWorld

use of org.spongepowered.api.world.server.ServerWorld in project SpongeCommon by SpongePowered.

the class BedBlockMixin method impl$onUseBed.

@Inject(method = "use", at = @At(value = "HEAD"), cancellable = true)
private void impl$onUseBed(final BlockState param0, final Level param1, final BlockPos param2, final Player param3, final InteractionHand param4, final BlockHitResult param5, final CallbackInfoReturnable<InteractionResult> cir) {
    if (!param1.isClientSide) {
        final Cause currentCause = Sponge.server().causeStackManager().currentCause();
        final BlockPos bedLocation = param5.getBlockPos();
        final BlockSnapshot snapshot = ((ServerWorld) param1).createSnapshot(bedLocation.getX(), bedLocation.getY(), bedLocation.getZ());
        if (Sponge.eventManager().post(SpongeEventFactory.createSleepingEventPre(currentCause, snapshot, (Living) param3))) {
            cir.setReturnValue(InteractionResult.CONSUME);
        }
    }
}
Also used : ServerWorld(org.spongepowered.api.world.server.ServerWorld) Living(org.spongepowered.api.entity.living.Living) Cause(org.spongepowered.api.event.Cause) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) BlockPos(net.minecraft.core.BlockPos) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 9 with ServerWorld

use of org.spongepowered.api.world.server.ServerWorld in project SpongeCommon by SpongePowered.

the class SpongeCommonEventFactory method throwDropItemAndConstructEvent.

/**
 * @author gabizou - April 19th, 2018
 * Creates two events here:
 * - {@link DropItemEvent}
 * - {@link ConstructEntityEvent}
 *
 * This is to reduce the code size from normal entity drops and player drops.
 * While player drops usually require performing position and motion modifications,
 * we return the item stack if it is to be thrown (this allows the event to have a
 * say in what item is dropped).
 *
 * @param entity The entity throwing the item
 * @param posX The position x for the item stack to spawn
 * @param posY The position y for the item stack to spawn
 * @param posZ The position z for the item stack to spawn
 * @param snapshot The item snapshot of the item to drop
 * @param original The original list to be used
 * @param frame
 * @return The item if it is to be spawned, null if to be ignored
 */
@Nullable
public static ItemStack throwDropItemAndConstructEvent(final net.minecraft.world.entity.Entity entity, final double posX, final double posY, final double posZ, final ItemStackSnapshot snapshot, final List<ItemStackSnapshot> original, final CauseStackManager.StackFrame frame) {
    final ItemStack item;
    frame.pushCause(entity);
    // FIRST we want to throw the DropItemEvent.PRE
    final DropItemEvent.Pre dropEvent = SpongeEventFactory.createDropItemEventPre(frame.currentCause(), ImmutableList.of(snapshot), original);
    SpongeCommon.post(dropEvent);
    if (dropEvent.isCancelled()) {
        return null;
    }
    if (dropEvent.droppedItems().isEmpty()) {
        return null;
    }
    // SECOND throw the ConstructEntityEvent
    frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.DROPPED_ITEM);
    final ConstructEntityEvent.Pre event = SpongeEventFactory.createConstructEntityEventPre(frame.currentCause(), ServerLocation.of((ServerWorld) entity.level, posX, posY, posZ), new Vector3d(0, 0, 0), EntityTypes.ITEM.get());
    frame.removeContext(EventContextKeys.SPAWN_TYPE);
    SpongeCommon.post(event);
    if (event.isCancelled()) {
        return null;
    }
    item = event.isCancelled() ? null : ItemStackUtil.fromSnapshotToNative(dropEvent.droppedItems().get(0));
    if (item == null) {
        return null;
    }
    return item;
}
Also used : ConstructEntityEvent(org.spongepowered.api.event.entity.ConstructEntityEvent) ServerWorld(org.spongepowered.api.world.server.ServerWorld) DropItemEvent(org.spongepowered.api.event.item.inventory.DropItemEvent) Vector3d(org.spongepowered.math.vector.Vector3d) ItemStack(net.minecraft.world.item.ItemStack) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 10 with ServerWorld

use of org.spongepowered.api.world.server.ServerWorld 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)

Aggregations

ServerWorld (org.spongepowered.api.world.server.ServerWorld)43 Vector3d (org.spongepowered.math.vector.Vector3d)13 BlockPos (net.minecraft.core.BlockPos)12 Cause (org.spongepowered.api.event.Cause)12 BlockSnapshot (org.spongepowered.api.block.BlockSnapshot)11 CauseStackManager (org.spongepowered.api.event.CauseStackManager)11 ServerLocation (org.spongepowered.api.world.server.ServerLocation)11 Inject (org.spongepowered.asm.mixin.injection.Inject)10 ArrayList (java.util.ArrayList)9 NonNull (org.checkerframework.checker.nullness.qual.NonNull)9 ResourceKey (org.spongepowered.api.ResourceKey)8 List (java.util.List)7 Optional (java.util.Optional)7 ServerLevel (net.minecraft.server.level.ServerLevel)7 Entity (net.minecraft.world.entity.Entity)7 Living (org.spongepowered.api.entity.living.Living)7 SpongeCommon (org.spongepowered.common.SpongeCommon)7 Component (net.kyori.adventure.text.Component)6 LivingEntity (net.minecraft.world.entity.LivingEntity)6 ItemStack (net.minecraft.world.item.ItemStack)6