LiteLoaderEventBroker.java 17.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
/*
 * This file is part of LiteLoader.
 * Copyright (C) 2012-16 Adam Mummery-Smith
 * All Rights Reserved.
 */
package com.mumfrey.liteloader.core;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.mojang.authlib.GameProfile;
import com.mumfrey.liteloader.LiteMod;
import com.mumfrey.liteloader.PlayerInteractionListener;
import com.mumfrey.liteloader.PlayerInteractionListener.MouseButton;
import com.mumfrey.liteloader.PlayerMoveListener;
import com.mumfrey.liteloader.PluginChannelListener;
import com.mumfrey.liteloader.ServerCommandProvider;
import com.mumfrey.liteloader.ServerPlayerListener;
import com.mumfrey.liteloader.ServerPluginChannelListener;
import com.mumfrey.liteloader.ServerTickable;
import com.mumfrey.liteloader.ShutdownListener;
import com.mumfrey.liteloader.api.InterfaceProvider;
import com.mumfrey.liteloader.api.Listener;
import com.mumfrey.liteloader.api.ShutdownObserver;
import com.mumfrey.liteloader.common.GameEngine;
import com.mumfrey.liteloader.common.LoadingProgress;
import com.mumfrey.liteloader.common.ducks.IPacketClientSettings;
import com.mumfrey.liteloader.common.ducks.ITeleportHandler;
import com.mumfrey.liteloader.core.event.HandlerList;
import com.mumfrey.liteloader.core.event.HandlerList.ReturnLogicOp;
import com.mumfrey.liteloader.interfaces.FastIterable;
import com.mumfrey.liteloader.interfaces.FastIterableDeque;
import com.mumfrey.liteloader.launch.LoaderProperties;
import com.mumfrey.liteloader.util.Position;
import com.mumfrey.liteloader.util.log.LiteLoaderLogger;

import net.minecraft.command.ICommandManager;
import net.minecraft.command.ServerCommandManager;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.client.CPacketClientSettings;
import net.minecraft.network.play.client.CPacketPlayer;
import net.minecraft.network.play.server.SPacketBlockChange;
import net.minecraft.network.play.server.SPacketPlayerPosLook;
import net.minecraft.network.play.server.SPacketPlayerPosLook.EnumFlags;
import net.minecraft.profiler.Profiler;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerInteractionManager;
import net.minecraft.server.management.PlayerList;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult.Type;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;

/**
 * @author Adam Mummery-Smith
 *
 * @param <TClient> Type of the client runtime, "Minecraft" on client and null
 *      on the server
 * @param <TServer> Type of the server runtime, "IntegratedServer" on the client
 *      "MinecraftServer" on the server 
 */
public abstract class LiteLoaderEventBroker<TClient, TServer extends MinecraftServer> implements InterfaceProvider, ShutdownObserver
{
    /**
     * @author Adam Mummery-Smith
     *
     * @param <T>
     */
    public static class ReturnValue<T>
    {
        private T value;
        private boolean isSet;

        public ReturnValue(T value)
        {
            this.value = value;
        }

        public ReturnValue()
        {
        }

        public boolean isSet()
        {
            return this.isSet;
        }

        public T get()
        {
            return this.value;
        }

        public void set(T value)
        {
            this.isSet = true;
            this.value = value;
        }
    }

    public static enum InteractType
    {
        RIGHT_CLICK,
        LEFT_CLICK,
        LEFT_CLICK_BLOCK,
        PLACE_BLOCK_MAYBE,
        DIG_BLOCK_MAYBE,
        DIG_BLOCK_END
    }

    /**
     * Singleton
     */
    static LiteLoaderEventBroker<?, ?> broker; 

    /**
     * Reference to the loader instance
     */
    protected final LiteLoader loader;

    /**
     * Reference to the game
     */
    protected final GameEngine<TClient, TServer> engine;

    /**
     * Profiler 
     */
    protected final Profiler profiler;

    protected LiteLoaderMods mods;

    private Map<UUID, PlayerEventState> playerStates = new HashMap<UUID, PlayerEventState>();
    private FastIterableDeque<IEventState> playerStateList = new HandlerList<IEventState>(IEventState.class);

    /**
     * List of mods which provide server commands
     */
    private FastIterable<ServerCommandProvider> serverCommandProviders
            = new HandlerList<ServerCommandProvider>(ServerCommandProvider.class);

    /**
     * List of mods which monitor server player events
     */
    private FastIterable<ServerPlayerListener> serverPlayerListeners
            = new HandlerList<ServerPlayerListener>(ServerPlayerListener.class);

    /**
     * List of mods which handle player interaction events 
     */
    private FastIterable<PlayerInteractionListener> playerInteractionListeners
            = new HandlerList<PlayerInteractionListener>(PlayerInteractionListener.class, ReturnLogicOp.AND);

    /**
     * List of mods which handle player movement events
     */
    private FastIterable<PlayerMoveListener> playerMoveListeners
            = new HandlerList<PlayerMoveListener>(PlayerMoveListener.class, ReturnLogicOp.AND_BREAK_ON_FALSE);

    /**
     * List of mods which monitor server ticks
     */
    private FastIterable<ServerTickable> serverTickListeners
            = new HandlerList<ServerTickable>(ServerTickable.class);

    /**
     * List of mods which want to be notified when the game is shutting down
     */
    private FastIterable<ShutdownListener> shutdownListeners
            = new HandlerList<ShutdownListener>(ShutdownListener.class);

    /**
     * ctor
     * 
     * @param loader
     * @param engine
     * @param properties
     */
    public LiteLoaderEventBroker(LiteLoader loader, GameEngine<TClient, TServer> engine, LoaderProperties properties)
    {
        this.loader   = loader;
        this.engine   = engine;
        this.profiler = engine.getProfiler();

        LiteLoaderEventBroker.broker = this;
    }

    /**
     * @param mods
     */
    void setMods(LiteLoaderMods mods)
    {
        this.mods = mods;
    }

    /**
     * 
     */
    protected void onStartupComplete()
    {
        LoadingProgress.setMessage("Checking mods...");
        this.mods.onStartupComplete();

        LoadingProgress.setMessage("Initialising CoreProviders...");
        this.loader.onStartupComplete();

        LoadingProgress.setMessage("Starting Game...");
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.api.InterfaceProvider#getListenerBaseType()
     */
    @Override
    public Class<? extends Listener> getListenerBaseType()
    {
        return LiteMod.class;
    }

    /* (non-Javadoc)
     * @see com.mumfrey.liteloader.api.InterfaceProvider#registerInterfaces(
     *      com.mumfrey.liteloader.core.InterfaceRegistrationDelegate)
     */
    @Override
    public void registerInterfaces(InterfaceRegistrationDelegate delegate)
    {
        delegate.registerInterface(ServerCommandProvider.class);
        delegate.registerInterface(ServerPlayerListener.class);
        delegate.registerInterface(PlayerInteractionListener.class);
        delegate.registerInterface(PlayerMoveListener.class);
        delegate.registerInterface(CommonPluginChannelListener.class);
        delegate.registerInterface(ServerTickable.class);
        delegate.registerInterface(ShutdownListener.class);
    }

    /**
     * Add a listener to the relevant listener lists
     * 
     * @param listener
     */
    public void addCommonPluginChannelListener(CommonPluginChannelListener listener)
    {
        if (!(listener instanceof PluginChannelListener) && !(listener instanceof ServerPluginChannelListener))
        {
            LiteLoaderLogger.warning("Interface error for mod '%1s'. Implementing CommonPluginChannelListener has no effect! "
                    + "Use PluginChannelListener or ServerPluginChannelListener instead", listener.getName());
        }
    }

    /**
     * @param serverCommandProvider
     */
    public void addServerCommandProvider(ServerCommandProvider serverCommandProvider)
    {
        this.serverCommandProviders.add(serverCommandProvider);
    }

    /**
     * @param serverPlayerListener
     */
    public void addServerPlayerListener(ServerPlayerListener serverPlayerListener)
    {
        this.serverPlayerListeners.add(serverPlayerListener);
    }

    /**
     * @param playerInteractionListener
     */
    public void addPlayerInteractionListener(PlayerInteractionListener playerInteractionListener)
    {
        this.playerInteractionListeners.add(playerInteractionListener);
    }

    /**
     * @param playerMoveListener
     */
    public void addPlayerMoveListener(PlayerMoveListener playerMoveListener)
    {
        this.playerMoveListeners.add(playerMoveListener);
    }

    /**
     * @param serverTickable
     */
    public void addServerTickable(ServerTickable serverTickable)
    {
        this.serverTickListeners.add(serverTickable);
    }

    /**
     * @param shutdownListener
     */
    public void addShutdownListener(ShutdownListener shutdownListener)
    {
        this.shutdownListeners.add(shutdownListener);
    }

    /**
     * @param instance
     * @param folderName
     * @param worldName
     * @param worldSettings
     */
    public void onStartServer(MinecraftServer instance, String folderName, String worldName, WorldSettings worldSettings)
    {
        ICommandManager commandManager = instance.getCommandManager();

        if (commandManager instanceof ServerCommandManager)
        {
            ServerCommandManager serverCommandManager = (ServerCommandManager)commandManager;
            this.serverCommandProviders.all().provideCommands(serverCommandManager);
        }

        LiteLoader.getServerPluginChannels().onServerStartup();

        this.playerStates.clear();
    }

    /**
     * @param scm
     * @param player
     * @param profile
     */
    public void onSpawnPlayer(PlayerList scm, EntityPlayerMP player, GameProfile profile)
    {
        this.serverPlayerListeners.all().onPlayerConnect(player, profile);
        PlayerEventState playerState = this.getPlayerState(player);
        playerState.onSpawned();
    }

    /**
     * @param scm
     * @param player
     */
    public void onPlayerLogin(PlayerList scm, EntityPlayerMP player)
    {
        LiteLoader.getServerPluginChannels().onPlayerJoined(player);
    }

    /**
     * @param scm
     * @param netManager
     * @param player
     */
    public void onInitializePlayerConnection(PlayerList scm, NetworkManager netManager, EntityPlayerMP player)
    {
        this.serverPlayerListeners.all().onPlayerLoggedIn(player);
    }

    /**
     * @param scm
     * @param player
     * @param oldPlayer
     * @param dimension
     * @param won
     */
    public void onRespawnPlayer(PlayerList scm, EntityPlayerMP player, EntityPlayerMP oldPlayer, int dimension, boolean won)
    {
        this.serverPlayerListeners.all().onPlayerRespawn(player, oldPlayer, dimension, won);
    }

    /**
     * @param scm
     * @param player
     */
    public void onPlayerLogout(PlayerList scm, EntityPlayerMP player)
    {
        this.serverPlayerListeners.all().onPlayerLogout(player);
        this.removePlayer(player);
    }

    /**
     * @param clock
     * @param partialTicks
     * @param inGame
     */
    protected void onTick(boolean clock, float partialTicks, boolean inGame)
    {
        this.loader.onTick(clock, partialTicks, inGame);
    }

    /**
     * @param mouseX
     * @param mouseY
     * @param partialTicks
     */
    protected void onPostRender(int mouseX, int mouseY, float partialTicks)
    {
        this.loader.onPostRender(mouseX, mouseY, partialTicks);
    }

    protected void onWorldChanged(World world)
    {
        this.loader.onWorldChanged(world);
    }

    public void onServerTick(MinecraftServer server)
    {
        this.playerStateList.all().onTick(server);
        this.serverTickListeners.all().onTick(server);
    }

    public boolean onPlaceBlock(NetHandlerPlayServer netHandler, EntityPlayerMP player, EnumHand hand, BlockPos pos, EnumFacing facing)
    {
        if (!this.onPlayerInteract(InteractType.PLACE_BLOCK_MAYBE, player, hand, player.getHeldItem(hand), pos, facing))
        {
            SPacketBlockChange cancellation = new SPacketBlockChange(player.world, pos.offset(facing));
            netHandler.playerEntity.connection.sendPacket(cancellation);
            player.sendContainerToPlayer(player.inventoryContainer);
            return false;
        }

        return true;
    }

    public boolean onClickedAir(InteractType action, EntityPlayerMP player, EnumHand hand)
    {
        return this.onPlayerInteract(action, player, hand, player.getHeldItem(hand), null, EnumFacing.SOUTH);
    }

    public boolean onPlayerDigging(InteractType action, EntityPlayerMP player, NetHandlerPlayServer netHandler, BlockPos pos)
    {
        if (!this.onPlayerInteract(action, player, EnumHand.MAIN_HAND, player.getHeldItemMainhand(), pos, EnumFacing.SOUTH))
        {
            SPacketBlockChange cancellation = new SPacketBlockChange(player.world, pos);
            netHandler.playerEntity.connection.sendPacket(cancellation);
            return false;
        }

        return true;
    }

    public boolean onUseItem(EntityPlayerMP player, EnumHand hand, ItemStack stack, BlockPos pos, EnumFacing side)
    {
        if (!this.onPlayerInteract(InteractType.PLACE_BLOCK_MAYBE, player, hand, stack, pos, side))
        {
            SPacketBlockChange cancellation = new SPacketBlockChange(player.world, pos);
            player.connection.sendPacket(cancellation);
            return false;
        }

        return true;
    }

    public boolean onBlockClicked(BlockPos pos, EnumFacing side, PlayerInteractionManager manager)
    {
        EntityPlayerMP player = manager.player;
        if (!this.onPlayerInteract(InteractType.LEFT_CLICK_BLOCK, player, EnumHand.MAIN_HAND, player.getHeldItemMainhand(), pos, side))
        {
            SPacketBlockChange cancellation = new SPacketBlockChange(manager.world, pos);
            player.connection.sendPacket(cancellation);
            return false;
        }

        return true;
    }
    
    public boolean onPlayerInteract(InteractType action, EntityPlayerMP player, EnumHand hand, ItemStack stack, BlockPos position, EnumFacing side)
    {
        return this.getPlayerState(player).onPlayerInteract(action, player, hand, stack, position, side);
    }

    public boolean onPlayerSwapItems(EntityPlayerMP player)
    {
        return this.playerInteractionListeners.all().onPlayerSwapItems(player);
    }

    void onPlayerClickedAir(EntityPlayerMP player, MouseButton button, EnumHand hand, BlockPos tracePos, EnumFacing traceSideHit, Type traceHitType)
    {
        this.playerInteractionListeners.all().onPlayerClickedAir(player, button, tracePos, traceSideHit, traceHitType);
    }

    boolean onPlayerClickedBlock(EntityPlayerMP player, MouseButton button, EnumHand hand, ItemStack stack, BlockPos hitPos, EnumFacing sideHit)
    {
        return this.playerInteractionListeners.all().onPlayerClickedBlock(player, button, hand, stack, hitPos, sideHit);
    }

    public boolean onPlayerMove(NetHandlerPlayServer netHandler, CPacketPlayer packet, EntityPlayerMP player, WorldServer world)
    {
        Position from = new Position(player, true);
        Position to = new Position(packet.getX(player.posX), packet.getY(player.posY), packet.getZ(player.posZ),
                packet.getYaw(player.rotationYaw), packet.getPitch(player.rotationPitch));
        
        ReturnValue<Position> pos = new ReturnValue<Position>(to);

        if (!this.playerMoveListeners.all().onPlayerMove(player, from, to, pos))
        {
            int teleportId = ((ITeleportHandler)player.connection).beginTeleport(from);
            player.setPositionAndRotation(from.xCoord, from.yCoord, from.zCoord, player.prevRotationYaw, player.prevRotationPitch);
            player.connection.sendPacket(new SPacketPlayerPosLook(from.xCoord, from.yCoord, from.zCoord,
                    player.prevRotationYaw, player.prevRotationPitch, Collections.<EnumFlags>emptySet(), teleportId));
            return false;
        }
        
        if (pos.isSet())
        {
            Position newPos = pos.get();
            netHandler.setPlayerLocation(newPos.xCoord, newPos.yCoord, newPos.zCoord, newPos.yaw, newPos.pitch);
            return false;
        }

        return true;
    }

    void onPlayerSettingsReceived(EntityPlayerMP player, CPacketClientSettings packet)
    {
        PlayerEventState playerState = this.getPlayerState(player);
        playerState.setTraceDistance(((IPacketClientSettings)packet).getViewDistance());
        playerState.setLocale(packet.getLang());
    }

    public PlayerEventState getPlayerState(EntityPlayerMP player)
    {
        PlayerEventState playerState = this.playerStates.get(player.getUniqueID());
        if (playerState == null)
        {
            playerState = new PlayerEventState(player, this);
            this.playerStates.put(player.getUniqueID(), playerState);
            this.playerStateList.add(playerState);
        }
        return playerState;
    }

    protected void removePlayer(EntityPlayerMP player)
    {
        PlayerEventState playerState = this.playerStates.remove(player.getUniqueID());
        if (playerState != null)
        {
            this.playerStateList.remove(playerState);
        }
    }

    @Override
    public void onShutDown()
    {
        for (ShutdownListener listener : this.shutdownListeners)
        {
            try
            {
                listener.onShutDown();
            }
            catch (Throwable th)
            {
                th.printStackTrace();
            }
        }
    }
}