Search in sources :

Example 41 with IMixinWorldServer

use of org.spongepowered.common.interfaces.world.IMixinWorldServer 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 42 with IMixinWorldServer

use of org.spongepowered.common.interfaces.world.IMixinWorldServer 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(IMixinWorldServer world, WorldServer.ServerBlockEventList list, Object obj, BlockPos pos, Block blockIn, int eventId, int eventParam) {
    boolean extending = (eventId == 0);
    final IBlockState blockstate = ((net.minecraft.world.World) world).getBlockState(pos);
    EnumFacing direction = blockstate.getValue(BlockDirectional.FACING);
    final LocatableBlock locatable = LocatableBlock.builder().location(new Location<>((World) world, pos.getX(), pos.getY(), pos.getZ())).state((BlockState) blockstate).build();
    // Sets toss out duplicate values (even though there shouldn't be any)
    HashSet<Location<org.spongepowered.api.world.World>> locations = new HashSet<>();
    locations.add(new Location<>((World) world, pos.getX(), pos.getY(), pos.getZ()));
    BlockPistonStructureHelper movedBlocks = new BlockPistonStructureHelper((WorldServer) world, pos, direction, extending);
    // calculates blocks to be moved
    movedBlocks.canMove();
    Stream.concat(movedBlocks.getBlocksToMove().stream(), movedBlocks.getBlocksToDestroy().stream()).map(block -> new Location<>((World) 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.getBlocksToDestroy().isEmpty()) {
        final List<BlockPos> movedPositions = movedBlocks.getBlocksToMove();
        BlockPos offsetPos;
        // If there are no blocks to move, add the offset of piston
        if (movedPositions.isEmpty()) {
            offsetPos = pos.offset(direction);
        } else {
            // Add the offset of last block set to move
            offsetPos = movedPositions.get(movedPositions.size() - 1).offset(direction);
        }
        locations.add(new Location<>((World) world, offsetPos.getX(), offsetPos.getY(), offsetPos.getZ()));
    }
    try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        if (extending) {
            Sponge.getCauseStackManager().addContext(EventContextKeys.PISTON_EXTEND, world.asSpongeWorld());
        } else {
            Sponge.getCauseStackManager().addContext(EventContextKeys.PISTON_RETRACT, world.asSpongeWorld());
        }
        return SpongeCommonEventFactory.callChangeBlockEventPre(world, ImmutableList.copyOf(locations), locatable).isCancelled();
    }
}
Also used : ChangeBlockEvent(org.spongepowered.api.event.block.ChangeBlockEvent) EnumHand(net.minecraft.util.EnumHand) IMixinChunk(org.spongepowered.common.interfaces.IMixinChunk) ItemStackUtil(org.spongepowered.common.item.inventory.util.ItemStackUtil) SPacketOpenWindow(net.minecraft.network.play.server.SPacketOpenWindow) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction) Block(net.minecraft.block.Block) PhaseData(org.spongepowered.common.event.tracking.PhaseData) Map(java.util.Map) Living(org.spongepowered.api.entity.living.Living) ClickInventoryEvent(org.spongepowered.api.event.item.inventory.ClickInventoryEvent) EnumSet(java.util.EnumSet) Location(org.spongepowered.api.world.Location) StackFrame(org.spongepowered.api.event.CauseStackManager.StackFrame) EntityUtil(org.spongepowered.common.entity.EntityUtil) BlockState(org.spongepowered.api.block.BlockState) Direction(org.spongepowered.api.util.Direction) Stream(java.util.stream.Stream) World(org.spongepowered.api.world.World) HandTypes(org.spongepowered.api.data.type.HandTypes) IMixinInventory(org.spongepowered.common.interfaces.IMixinInventory) Player(org.spongepowered.api.entity.living.player.Player) Container(net.minecraft.inventory.Container) DestructEntityEvent(org.spongepowered.api.event.entity.DestructEntityEvent) Vector3d(com.flowpowered.math.vector.Vector3d) Agent(org.spongepowered.api.entity.living.Agent) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ItemStack(net.minecraft.item.ItemStack) Text(org.spongepowered.api.text.Text) IMixinContainer(org.spongepowered.common.interfaces.IMixinContainer) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) CauseStackManager(org.spongepowered.api.event.CauseStackManager) TileEntityHopper(net.minecraft.tileentity.TileEntityHopper) WorldServer(net.minecraft.world.WorldServer) Nullable(javax.annotation.Nullable) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) PacketPhaseUtil.handleCustomCursor(org.spongepowered.common.event.tracking.phase.packet.PacketPhaseUtil.handleCustomCursor) PlayerTracker(org.spongepowered.common.entity.PlayerTracker) BlockPos(net.minecraft.util.math.BlockPos) BlockUtil(org.spongepowered.common.block.BlockUtil) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) Entity(org.spongepowered.api.entity.Entity) IBlockState(net.minecraft.block.state.IBlockState) CPacketCreativeInventoryAction(net.minecraft.network.play.client.CPacketCreativeInventoryAction) QueryOperationTypes(org.spongepowered.api.item.inventory.query.QueryOperationTypes) OrderedInventory(org.spongepowered.api.item.inventory.type.OrderedInventory) EntityLivingBase(net.minecraft.entity.EntityLivingBase) Vector3i(com.flowpowered.math.vector.Vector3i) BlockDirectional(net.minecraft.block.BlockDirectional) EntityDamageSource(net.minecraft.util.EntityDamageSource) VecHelper(org.spongepowered.common.util.VecHelper) MessageEvent(org.spongepowered.api.event.message.MessageEvent) IInteractionObject(net.minecraft.world.IInteractionObject) EventContextKeys(org.spongepowered.api.event.cause.EventContextKeys) IMixinEntity(org.spongepowered.common.interfaces.entity.IMixinEntity) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) ProjectileSource(org.spongepowered.api.entity.projectile.source.ProjectileSource) EntityPlayerMP(net.minecraft.entity.player.EntityPlayerMP) TileEntity(org.spongepowered.api.block.tileentity.TileEntity) CollideBlockEvent(org.spongepowered.api.event.block.CollideBlockEvent) SetAITargetEvent(org.spongepowered.api.event.entity.ai.SetAITargetEvent) CraftItemEvent(org.spongepowered.api.event.item.inventory.CraftItemEvent) InventoryArchetypes(org.spongepowered.api.item.inventory.InventoryArchetypes) SPacketSetSlot(net.minecraft.network.play.server.SPacketSetSlot) CollideEntityEvent(org.spongepowered.api.event.entity.CollideEntityEvent) Transaction(org.spongepowered.api.data.Transaction) EntityItem(net.minecraft.entity.item.EntityItem) User(org.spongepowered.api.entity.living.player.User) InteractEntityEvent(org.spongepowered.api.event.entity.InteractEntityEvent) LocatableBlock(org.spongepowered.api.world.LocatableBlock) Sponge(org.spongepowered.api.Sponge) State(org.spongepowered.common.event.tracking.phase.block.BlockPhase.State) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Tristate(org.spongepowered.api.util.Tristate) InventoryArchetype(org.spongepowered.api.item.inventory.InventoryArchetype) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) EntityPlayer(net.minecraft.entity.player.EntityPlayer) ChangeInventoryEvent(org.spongepowered.api.event.item.inventory.ChangeInventoryEvent) CraftingInventory(org.spongepowered.api.item.inventory.crafting.CraftingInventory) CarriedInventory(org.spongepowered.api.item.inventory.type.CarriedInventory) CraftingRecipe(org.spongepowered.api.item.recipe.crafting.CraftingRecipe) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) Optional(java.util.Optional) InteractItemEvent(org.spongepowered.api.event.item.inventory.InteractItemEvent) NotifyNeighborBlockEvent(org.spongepowered.api.event.block.NotifyNeighborBlockEvent) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) EventContext(org.spongepowered.api.event.cause.EventContext) BlockPistonStructureHelper(net.minecraft.block.state.BlockPistonStructureHelper) Inventory(org.spongepowered.api.item.inventory.Inventory) SpongeImpl(org.spongepowered.common.SpongeImpl) AbstractHorse(net.minecraft.entity.passive.AbstractHorse) SpongeImplHooks(org.spongepowered.common.SpongeImplHooks) SpongeTexts(org.spongepowered.common.text.SpongeTexts) CustomInventory(org.spongepowered.common.item.inventory.custom.CustomInventory) HashMap(java.util.HashMap) Function(java.util.function.Function) HashSet(java.util.HashSet) RayTraceResult(net.minecraft.util.math.RayTraceResult) ContainerUtil(org.spongepowered.common.item.inventory.util.ContainerUtil) IMixinEntityPlayerMP(org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP) ImmutableList(com.google.common.collect.ImmutableList) IMixinInventoryPlayer(org.spongepowered.common.interfaces.entity.player.IMixinInventoryPlayer) WeakReference(java.lang.ref.WeakReference) InventoryUtil(org.spongepowered.common.item.inventory.util.InventoryUtil) DirectionFacingProvider(org.spongepowered.common.registry.provider.DirectionFacingProvider) Iterator(java.util.Iterator) EnumFacing(net.minecraft.util.EnumFacing) Item(org.spongepowered.api.entity.Item) InteractInventoryEvent(org.spongepowered.api.event.item.inventory.InteractInventoryEvent) DamageSource(net.minecraft.util.DamageSource) ContainerPlayer(net.minecraft.inventory.ContainerPlayer) IInventory(net.minecraft.inventory.IInventory) PacketPhaseUtil(org.spongepowered.common.event.tracking.phase.packet.PacketPhaseUtil) Slot(net.minecraft.inventory.Slot) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) SlotIndex(org.spongepowered.api.item.inventory.property.SlotIndex) Collections(java.util.Collections) IBlockState(net.minecraft.block.state.IBlockState) EnumFacing(net.minecraft.util.EnumFacing) World(org.spongepowered.api.world.World) BlockPistonStructureHelper(net.minecraft.block.state.BlockPistonStructureHelper) BlockState(org.spongepowered.api.block.BlockState) IBlockState(net.minecraft.block.state.IBlockState) StackFrame(org.spongepowered.api.event.CauseStackManager.StackFrame) LocatableBlock(org.spongepowered.api.world.LocatableBlock) BlockPos(net.minecraft.util.math.BlockPos) Location(org.spongepowered.api.world.Location) HashSet(java.util.HashSet)

Example 43 with IMixinWorldServer

use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.

the class MixinBlock method onDropBlockAsItemWithChanceHead.

// This method can be called directly by pistons, mods, etc. so the hook must go here
@Inject(method = "dropBlockAsItemWithChance", at = @At(value = "HEAD"), cancellable = true)
public void onDropBlockAsItemWithChanceHead(net.minecraft.world.World worldIn, BlockPos pos, IBlockState state, float chance, int fortune, CallbackInfo ci) {
    if (!((IMixinWorld) worldIn).isFake()) {
        if (PhaseTracker.getInstance().getCurrentState() == BlockPhase.State.RESTORING_BLOCKS) {
            ci.cancel();
            return;
        }
        final IMixinWorldServer mixinWorld = (IMixinWorldServer) worldIn;
        final PhaseTracker phaseTracker = PhaseTracker.getInstance();
        final IPhaseState<?> currentState = phaseTracker.getCurrentState();
        final boolean shouldEnterBlockDropPhase = !phaseTracker.getCurrentContext().isCapturingBlockItemDrops() && !currentState.alreadyCapturingItemSpawns() && !currentState.isWorldGeneration();
        if (shouldEnterBlockDropPhase) {
            // TODO: Change source to LocatableBlock
            PhaseContext<?> context = BlockPhase.State.BLOCK_DROP_ITEMS.createPhaseContext().source(mixinWorld.createSpongeBlockSnapshot(state, state, pos, BlockChangeFlags.PHYSICS_OBSERVER));
            // unused, to be removed and re-located when phase context is cleaned up
            // .add(NamedCause.of(InternalNamedCauses.General.BLOCK_BREAK_FORTUNE, fortune))
            // .add(NamedCause.of(InternalNamedCauses.General.BLOCK_BREAK_POSITION, pos));
            // use current notifier and owner if available
            User notifier = phaseTracker.getCurrentContext().getNotifier().orElse(null);
            User owner = phaseTracker.getCurrentContext().getOwner().orElse(null);
            if (notifier != null) {
                context.notifier(notifier);
            }
            if (owner != null) {
                context.owner(owner);
            }
            context.buildAndSwitch();
        }
    }
}
Also used : PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) User(org.spongepowered.api.entity.living.player.User) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 44 with IMixinWorldServer

use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.

the class MixinBlockDispenser method onDispenseHead.

@Inject(method = "dispense", at = @At(value = "HEAD"))
public void onDispenseHead(World worldIn, BlockPos pos, CallbackInfo ci) {
    final IBlockState state = worldIn.getBlockState(pos);
    final SpongeBlockSnapshot spongeBlockSnapshot = ((IMixinWorldServer) worldIn).createSpongeBlockSnapshot(state, state, pos, BlockChangeFlags.ALL);
    final IMixinChunk mixinChunk = (IMixinChunk) worldIn.getChunkFromBlockCoords(pos);
    this.context = BlockPhase.State.DISPENSE.createPhaseContext().source(spongeBlockSnapshot).owner(() -> mixinChunk.getBlockOwner(pos)).notifier(() -> mixinChunk.getBlockNotifier(pos)).buildAndSwitch();
}
Also used : SpongeBlockSnapshot(org.spongepowered.common.block.SpongeBlockSnapshot) IBlockState(net.minecraft.block.state.IBlockState) IMixinChunk(org.spongepowered.common.interfaces.IMixinChunk) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 45 with IMixinWorldServer

use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.

the class PacketState method spawnEntity.

/**
 * Defaulted method for packet phase states to spawn an entity directly.
 * This should be overridden by all packet phase states that are handling spawns
 * customarily with contexts and such. Captured entities are handled in
 * their respective {@link PacketState#unwind(PhaseContext)}s.
 *
 * @param context
 * @param entity
 * @param chunkX
 * @param chunkZ
 * @return True if the entity was spawned
 */
public boolean spawnEntity(P context, Entity entity, int chunkX, int chunkZ) {
    final net.minecraft.entity.Entity minecraftEntity = (net.minecraft.entity.Entity) entity;
    final WorldServer minecraftWorld = (WorldServer) minecraftEntity.world;
    final Player player = context.getSource(Player.class).orElseThrow(TrackingUtil.throwWithContext("Expected to be capturing a player", context));
    final ArrayList<Entity> entities = new ArrayList<>(1);
    entities.add(entity);
    try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
        Sponge.getCauseStackManager().pushCause(player);
        Sponge.getCauseStackManager().addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.PLACEMENT);
        Sponge.getCauseStackManager().addContext(EventContextKeys.NOTIFIER, player);
        Sponge.getCauseStackManager().addContext(EventContextKeys.OWNER, player);
        final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), entities);
        SpongeImpl.postEvent(event);
        if (!event.isCancelled()) {
            for (Entity newEntity : event.getEntities()) {
                EntityUtil.toMixin(newEntity).setCreator(player.getUniqueId());
                ((IMixinWorldServer) minecraftWorld).forceSpawnEntity(newEntity);
            }
            return true;
        }
    }
    return false;
}
Also used : Entity(org.spongepowered.api.entity.Entity) Player(org.spongepowered.api.entity.living.player.Player) ArrayList(java.util.ArrayList) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) WorldServer(net.minecraft.world.WorldServer) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) SpawnEntityEvent(org.spongepowered.api.event.entity.SpawnEntityEvent) CauseStackManager(org.spongepowered.api.event.CauseStackManager)

Aggregations

IMixinWorldServer (org.spongepowered.common.interfaces.world.IMixinWorldServer)61 WorldServer (net.minecraft.world.WorldServer)25 BlockPos (net.minecraft.util.math.BlockPos)19 ArrayList (java.util.ArrayList)17 Entity (org.spongepowered.api.entity.Entity)15 World (org.spongepowered.api.world.World)15 IBlockState (net.minecraft.block.state.IBlockState)13 SpawnEntityEvent (org.spongepowered.api.event.entity.SpawnEntityEvent)13 CauseStackManager (org.spongepowered.api.event.CauseStackManager)11 Overwrite (org.spongepowered.asm.mixin.Overwrite)11 BlockSnapshot (org.spongepowered.api.block.BlockSnapshot)9 IMixinEntity (org.spongepowered.common.interfaces.entity.IMixinEntity)9 EntityItem (net.minecraft.entity.item.EntityItem)8 User (org.spongepowered.api.entity.living.player.User)8 LocatableBlock (org.spongepowered.api.world.LocatableBlock)8 PhaseTracker (org.spongepowered.common.event.tracking.PhaseTracker)7 Entity (net.minecraft.entity.Entity)6 EntityPlayer (net.minecraft.entity.player.EntityPlayer)6 Chunk (net.minecraft.world.chunk.Chunk)6 IMixinChunk (org.spongepowered.common.interfaces.IMixinChunk)6