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();
}
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();
}
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);
}
}
}
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;
}
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();
}
}
Aggregations