Search in sources :

Example 51 with WorldProperties

use of org.spongepowered.api.world.storage.WorldProperties in project Skree by Skelril.

the class WeatherCommand method execute.

@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    // World resolution
    Optional<WorldProperties> optWorldProps = args.getOne("world");
    Optional<World> optWorld;
    if (!optWorldProps.isPresent()) {
        if (!(src instanceof Player)) {
            src.sendMessage(Text.of(TextColors.RED, "You are not a player and need to specify a world!"));
            return CommandResult.empty();
        }
        optWorld = Optional.of(((Player) src).getWorld());
    } else {
        optWorld = Sponge.getServer().getWorld(optWorldProps.get().getUniqueId());
    }
    // Handled by command spec, so always provided
    Weather weather = args.<Weather>getOne("type").get();
    Optional<Integer> duration = args.getOne("duration");
    if (!duration.isPresent()) {
        // Between 5 and 15 minutes
        duration = Optional.of(Probability.getRangedRandom(5 * 60, 15 * 60));
    }
    if (duration.get() < 1) {
        src.sendMessage(Text.of(TextColors.RED, "Weather duration must be at least 1 second!"));
        return CommandResult.empty();
    }
    World world = optWorld.get();
    if (!world.isLoaded()) {
        src.sendMessage(Text.of(TextColors.RED, "The specified world was not loaded!"));
        return CommandResult.empty();
    }
    world.setWeather(weather, duration.get() * 20);
    src.sendMessage(Text.of(TextColors.YELLOW, "Changed weather state in " + world.getName() + " to: " + weather.getName() + '.'));
    return CommandResult.success();
}
Also used : Weather(org.spongepowered.api.world.weather.Weather) Player(org.spongepowered.api.entity.living.player.Player) World(org.spongepowered.api.world.World) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 52 with WorldProperties

use of org.spongepowered.api.world.storage.WorldProperties in project SpongeCommon by SpongePowered.

the class MixinMinecraftServer method saveAllWorlds.

/**
 * @author blood - June 2nd, 2016
 *
 * @reason To allow per-world auto-save tick intervals or disable auto-saving entirely
 *
 * @param dontLog Whether to log during saving
 */
@Overwrite
public void saveAllWorlds(boolean dontLog) {
    if (!this.enableSaving) {
        return;
    }
    for (WorldServer worldserver : this.worlds) {
        if (worldserver != null && !worldserver.disableLevelSaving) {
            // Sponge start - check auto save interval in world config
            if (this.isDedicatedServer() && this.isServerRunning()) {
                final IMixinWorldServer spongeWorld = (IMixinWorldServer) worldserver;
                final int autoSaveInterval = spongeWorld.getActiveConfig().getConfig().getWorld().getAutoSaveInterval();
                final boolean logAutoSave = spongeWorld.getActiveConfig().getConfig().getLogging().worldAutoSaveLogging();
                if (autoSaveInterval <= 0 || ((WorldProperties) worldserver.getWorldInfo()).getSerializationBehavior() != SerializationBehaviors.AUTOMATIC) {
                    if (logAutoSave) {
                        LOGGER.warn("Auto-saving has been disabled for level \'" + worldserver.getWorldInfo().getWorldName() + "\'/" + worldserver.provider.getDimensionType().getName() + ". " + "No chunk data will be auto-saved - to re-enable auto-saving set 'auto-save-interval' to a value greater than" + " zero in the corresponding world config.");
                    }
                    continue;
                }
                if (this.tickCounter % autoSaveInterval != 0) {
                    continue;
                }
                if (logAutoSave) {
                    LOGGER.info("Auto-saving chunks for level \'" + worldserver.getWorldInfo().getWorldName() + "\'/" + worldserver.provider.getDimensionType().getName());
                }
            } else if (!dontLog) {
                LOGGER.info("Saving chunks for level \'" + worldserver.getWorldInfo().getWorldName() + "\'/" + worldserver.provider.getDimensionType().getName());
            }
            // Sponge end
            try {
                WorldManager.saveWorld(worldserver, false);
            } catch (MinecraftException ex) {
                ex.printStackTrace();
            }
        }
    }
}
Also used : MinecraftException(net.minecraft.world.MinecraftException) WorldServer(net.minecraft.world.WorldServer) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Example 53 with WorldProperties

use of org.spongepowered.api.world.storage.WorldProperties in project SpongeCommon by SpongePowered.

the class SpongeCommonEventFactory method callChangeBlockEventModifyLiquidBreak.

public static ChangeBlockEvent.Break callChangeBlockEventModifyLiquidBreak(net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, int flags) {
    final PhaseTracker phaseTracker = PhaseTracker.getInstance();
    final PhaseData data = phaseTracker.getCurrentPhaseData();
    BlockState fromState = BlockUtil.fromNative(worldIn.getBlockState(pos));
    BlockState toState = BlockUtil.fromNative(state);
    User owner = data.context.getOwner().orElse(null);
    User notifier = data.context.getNotifier().orElse(null);
    Object source = data.context.getSource(LocatableBlock.class).orElse(null);
    if (source == null) {
        // Fallback
        source = worldIn;
    }
    try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        Sponge.getCauseStackManager().pushCause(source);
        Sponge.getCauseStackManager().addContext(EventContextKeys.LIQUID_BREAK, (World) worldIn);
        if (owner != null) {
            Sponge.getCauseStackManager().addContext(EventContextKeys.OWNER, owner);
        }
        if (notifier != null) {
            Sponge.getCauseStackManager().addContext(EventContextKeys.NOTIFIER, notifier);
        }
        WorldProperties world = ((World) worldIn).getProperties();
        Vector3i position = new Vector3i(pos.getX(), pos.getY(), pos.getZ());
        Transaction<BlockSnapshot> transaction = new Transaction<>(BlockSnapshot.builder().blockState(fromState).world(world).position(position).build(), BlockSnapshot.builder().blockState(toState).world(world).position(position).build());
        ChangeBlockEvent.Break event = SpongeEventFactory.createChangeBlockEventBreak(Sponge.getCauseStackManager().getCurrentCause(), Collections.singletonList(transaction));
        SpongeImpl.postEvent(event);
        return event;
    }
}
Also used : PhaseData(org.spongepowered.common.event.tracking.PhaseData) User(org.spongepowered.api.entity.living.player.User) StackFrame(org.spongepowered.api.event.CauseStackManager.StackFrame) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) World(org.spongepowered.api.world.World) ChangeBlockEvent(org.spongepowered.api.event.block.ChangeBlockEvent) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) BlockState(org.spongepowered.api.block.BlockState) IBlockState(net.minecraft.block.state.IBlockState) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction) Transaction(org.spongepowered.api.data.Transaction) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Vector3i(com.flowpowered.math.vector.Vector3i) IInteractionObject(net.minecraft.world.IInteractionObject) LocatableBlock(org.spongepowered.api.world.LocatableBlock) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 54 with WorldProperties

use of org.spongepowered.api.world.storage.WorldProperties in project SpongeCommon by SpongePowered.

the class EntityUtil method handleDisplaceEntityPortalEvent.

@Nullable
public static MoveEntityEvent.Teleport.Portal handleDisplaceEntityPortalEvent(Entity entityIn, int targetDimensionId, @Nullable Teleporter teleporter) {
    SpongeImplHooks.registerPortalAgentType(teleporter);
    final MinecraftServer mcServer = SpongeImpl.getServer();
    final IMixinPlayerList mixinPlayerList = (IMixinPlayerList) mcServer.getPlayerList();
    final IMixinEntity mixinEntity = (IMixinEntity) entityIn;
    final Transform<World> fromTransform = mixinEntity.getTransform();
    final WorldServer fromWorld = ((WorldServer) entityIn.world);
    final IMixinWorldServer fromMixinWorld = (IMixinWorldServer) fromWorld;
    boolean sameDimension = entityIn.dimension == targetDimensionId;
    // handle the end
    if (targetDimensionId == 1 && fromWorld.provider instanceof WorldProviderEnd) {
        targetDimensionId = 0;
    }
    WorldServer toWorld = mcServer.getWorld(targetDimensionId);
    // not being loaded then short-circuit to prevent unnecessary logic from running
    if (!sameDimension && fromWorld == toWorld) {
        return null;
    }
    if (teleporter == null) {
        teleporter = toWorld.getDefaultTeleporter();
    }
    final Map<String, String> portalAgents = fromMixinWorld.getActiveConfig().getConfig().getWorld().getPortalAgents();
    String worldName = "";
    String teleporterClassName = teleporter.getClass().getName();
    // check for new destination in config
    if (teleporterClassName.equals("net.minecraft.world.Teleporter")) {
        worldName = portalAgents.get("minecraft:default_" + toWorld.provider.getDimensionType().getName().toLowerCase(Locale.ENGLISH));
        if (worldName == null && toWorld.provider instanceof WorldProviderHell) {
            worldName = portalAgents.get("minecraft:default_nether");
        }
    } else {
        // custom
        worldName = portalAgents.get("minecraft:" + teleporter.getClass().getSimpleName());
    }
    if (worldName != null && !worldName.equals("")) {
        for (WorldProperties worldProperties : Sponge.getServer().getAllWorldProperties()) {
            if (worldProperties.getWorldName().equalsIgnoreCase(worldName)) {
                Optional<World> spongeWorld = Sponge.getServer().loadWorld(worldProperties);
                if (spongeWorld.isPresent()) {
                    toWorld = (WorldServer) spongeWorld.get();
                    teleporter = toWorld.getDefaultTeleporter();
                    if (fromWorld.provider.isNether() || toWorld.provider.isNether()) {
                        ((IMixinTeleporter) teleporter).setNetherPortalType(true);
                    } else {
                        ((IMixinTeleporter) teleporter).setNetherPortalType(false);
                    }
                }
            }
        }
    }
    adjustEntityPostionForTeleport(mixinPlayerList, entityIn, fromWorld, toWorld);
    try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame();
        TeleportingContext context = EntityPhase.State.CHANGING_DIMENSION.createPhaseContext().setTargetWorld(toWorld).buildAndSwitch()) {
        Sponge.getCauseStackManager().pushCause(teleporter);
        Sponge.getCauseStackManager().pushCause(mixinEntity);
        Sponge.getCauseStackManager().addContext(EventContextKeys.TELEPORT_TYPE, TeleportTypes.PORTAL);
        if (entityIn.isEntityAlive() && !(fromWorld.provider instanceof WorldProviderEnd)) {
            fromWorld.profiler.startSection("placing");
            // Note: We must always use placeInPortal to support mods.
            if (!((IMixinTeleporter) teleporter).isVanilla() || entityIn.getLastPortalVec() != null) {
                teleporter.placeInPortal(entityIn, entityIn.rotationYaw);
            }
            fromWorld.profiler.endSection();
        }
        // Complete phases, just because we need to. The phases don't actually do anything, because the processing resides here.
        // Grab the exit location of entity after being placed into portal
        final Transform<World> portalExitTransform = mixinEntity.getTransform().setExtent((World) toWorld);
        // Use setLocationAndAngles to avoid firing MoveEntityEvent to plugins
        mixinEntity.setLocationAndAngles(fromTransform);
        final MoveEntityEvent.Teleport.Portal event = SpongeEventFactory.createMoveEntityEventTeleportPortal(Sponge.getCauseStackManager().getCurrentCause(), fromTransform, portalExitTransform, (PortalAgent) teleporter, mixinEntity, true);
        SpongeImpl.postEvent(event);
        final Vector3i chunkPosition = mixinEntity.getLocation().getChunkPosition();
        final IMixinTeleporter toMixinTeleporter = (IMixinTeleporter) teleporter;
        final List<BlockSnapshot> capturedBlocks = context.getCapturedBlocks();
        final Transform<World> toTransform = event.getToTransform();
        if (event.isCancelled()) {
            // We need to make sure to only restore the location if
            if (!portalExitTransform.getExtent().getUniqueId().equals(mixinEntity.getLocation().getExtent().getUniqueId())) {
                // update cache
                ((IMixinTeleporter) teleporter).removePortalPositionFromCache(ChunkPos.asLong(chunkPosition.getX(), chunkPosition.getZ()));
                if (!capturedBlocks.isEmpty()) {
                    for (BlockSnapshot original : Lists.reverse(capturedBlocks)) {
                        original.restore(true, BlockChangeFlags.NONE);
                    }
                    capturedBlocks.clear();
                }
                mixinEntity.setLocationAndAngles(fromTransform);
            } else {
                // Call setTransform to let plugins know mods changed the position
                // Guarantees plugins such as Nucleus can track changed locations properly
                mixinEntity.setTransform(mixinEntity.getTransform());
            }
            return event;
        }
        if (!portalExitTransform.equals(toTransform)) {
            // if plugin set to same world, just set the transform
            if (fromWorld == toTransform.getExtent()) {
                // force cancel so we know to skip remaining logic
                event.setCancelled(true);
                // update cache
                toMixinTeleporter.removePortalPositionFromCache(ChunkPos.asLong(chunkPosition.getX(), chunkPosition.getZ()));
                // Undo created portal
                if (!capturedBlocks.isEmpty()) {
                    for (BlockSnapshot original : Lists.reverse(capturedBlocks)) {
                        original.restore(true, BlockChangeFlags.NONE);
                    }
                }
                capturedBlocks.clear();
                mixinEntity.setLocationAndAngles(toTransform);
                return event;
            }
        } else {
            if (toWorld.provider instanceof WorldProviderEnd) {
                BlockPos blockpos = entityIn.world.getTopSolidOrLiquidBlock(toWorld.getSpawnPoint());
                entityIn.moveToBlockPosAndAngles(blockpos, entityIn.rotationYaw, entityIn.rotationPitch);
            }
        }
        if (!capturedBlocks.isEmpty() && !TrackingUtil.processBlockCaptures(capturedBlocks, EntityPhase.State.CHANGING_DIMENSION, context)) {
            toMixinTeleporter.removePortalPositionFromCache(ChunkPos.asLong(chunkPosition.getX(), chunkPosition.getZ()));
        }
        if (!event.getKeepsVelocity()) {
            entityIn.motionX = 0;
            entityIn.motionY = 0;
            entityIn.motionZ = 0;
        }
        return event;
    }
}
Also used : IMixinPlayerList(org.spongepowered.common.interfaces.IMixinPlayerList) WorldProviderEnd(net.minecraft.world.WorldProviderEnd) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) IMixinTeleporter(org.spongepowered.common.interfaces.world.IMixinTeleporter) IMixinEntity(org.spongepowered.common.interfaces.entity.IMixinEntity) WorldServer(net.minecraft.world.WorldServer) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) World(org.spongepowered.api.world.World) MinecraftServer(net.minecraft.server.MinecraftServer) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Vector3i(com.flowpowered.math.vector.Vector3i) WorldProviderHell(net.minecraft.world.WorldProviderHell) TeleportingContext(org.spongepowered.common.event.tracking.phase.entity.TeleportingContext) BlockPos(net.minecraft.util.math.BlockPos) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) Nullable(javax.annotation.Nullable)

Example 55 with WorldProperties

use of org.spongepowered.api.world.storage.WorldProperties in project SpongeCommon by SpongePowered.

the class MixinWorldSettings method onConstruct.

@Inject(method = "<init>(Lnet/minecraft/world/storage/WorldInfo;)V", at = @At(value = "RETURN"))
public void onConstruct(WorldInfo info, CallbackInfo ci) {
    // Set above: info.getSeed(), info.getGameType(),  info.isMapFeaturesEnabled(), info.isHardcoreModeEnabled(), info.getTerrainType()
    final WorldProperties properties = (WorldProperties) info;
    if (((IMixinWorldInfo) properties).getWorldConfig() != null) {
        this.dimensionType = properties.getDimensionType();
        this.difficulty = properties.getDifficulty();
        this.serializationBehavior = properties.getSerializationBehavior();
        this.generatorSettings = properties.getGeneratorSettings().copy();
        this.isEnabled = properties.isEnabled();
        this.loadOnStartup = properties.loadOnStartup();
        this.keepSpawnLoaded = properties.doesKeepSpawnLoaded();
        this.generateSpawnOnLoad = properties.doesGenerateSpawnOnLoad();
        this.pvpEnabled = properties.isPVPEnabled();
        this.generateBonusChest = properties.doesGenerateBonusChest();
        WorldGeneratorModifierRegistryModule.getInstance().checkAllRegistered(properties.getGeneratorModifiers());
        this.generatorModifiers = ImmutableList.copyOf(properties.getGeneratorModifiers());
    }
}
Also used : WorldProperties(org.spongepowered.api.world.storage.WorldProperties) Inject(org.spongepowered.asm.mixin.injection.Inject)

Aggregations

WorldProperties (org.spongepowered.api.world.storage.WorldProperties)109 World (org.spongepowered.api.world.World)37 CommandException (org.spongepowered.api.command.CommandException)27 ArrayList (java.util.ArrayList)26 Player (org.spongepowered.api.entity.living.player.Player)19 Text (org.spongepowered.api.text.Text)16 Vector3d (com.flowpowered.math.vector.Vector3d)9 ReturnMessageException (io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException)9 Listener (org.spongepowered.api.event.Listener)9 WorldGeneratorModifier (org.spongepowered.api.world.gen.WorldGeneratorModifier)9 List (java.util.List)8 Optional (java.util.Optional)8 CommandResult (org.spongepowered.api.command.CommandResult)8 Vector3i (com.flowpowered.math.vector.Vector3i)7 IOException (java.io.IOException)7 Sponge (org.spongepowered.api.Sponge)7 CommandSource (org.spongepowered.api.command.CommandSource)7 IMixinWorldInfo (org.spongepowered.common.interfaces.world.IMixinWorldInfo)7 GenericArguments (org.spongepowered.api.command.args.GenericArguments)6 Location (org.spongepowered.api.world.Location)6