LiteLoader.java 29.9 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
package com.mumfrey.liteloader.core;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.*;
import java.util.logging.Formatter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import com.mumfrey.liteloader.*;
import com.mumfrey.liteloader.util.ModUtilities;
import com.mumfrey.liteloader.util.PrivateFields;
import com.sun.corba.se.impl.ior.ByteBuffer;

import net.minecraft.client.Minecraft;
import net.minecraft.src.*;
import net.minecraft.src.Timer;

/**
 * LiteLoader is a simple loader which provides tick events to loaded mods 
 *
 * @author Adam Mummery-Smith
 * @version 1.4.4
 */
@SuppressWarnings("rawtypes")
public final class LiteLoader implements FilenameFilter
{
	/**
	 * Liteloader version 
	 */
	private static final String LOADER_VERSION = "1.4.5";
	
	/**
	 * Loader revision, can be used by mods to determine whether the loader is sufficiently up-to-date 
	 */
	private static final int LOADER_REVISION = 6;
	
	/**
	 * Minecraft versions that we will load mods for, this will be compared
	 * against the version.txt value in mod files to prevent outdated mods being
	 * loaded!!!
	 */
	private static final String[] SUPPORTED_VERSIONS = { "1.4.4", "1.4.5" };
	
	/**
	 * LiteLoader is a singleton, this is the singleton instance
	 */
	private static LiteLoader instance;
	
	/**
	 * Logger for LiteLoader events
	 */
	public static Logger logger = Logger.getLogger("liteloader");
	
	/**
	 * "mods" folder which contains mods and config files
	 */
	private File modsFolder;
	
	/**
	 * Reference to the Minecraft game instance
	 */
	private Minecraft minecraft = Minecraft.getMinecraft();
	
	/**
	 * Reference to the minecraft timer
	 */
	private Timer minecraftTimer;

	/**
	 * List of loaded mods, for crash reporting
	 */
	private String loadedModsList = "none";
	
	/**
	 * Global list of mods which we have loaded
	 */
	private LinkedList<LiteMod> mods = new LinkedList<LiteMod>();
	
	/**
	 * List of mods which implement Tickable interface and will receive tick
	 * events
	 */
	private LinkedList<Tickable> tickListeners = new LinkedList<Tickable>();
	
	/**
	 * 
	 */
	private LinkedList<InitCompleteListener> initListeners = new LinkedList<InitCompleteListener>();
	
	/**
	 * List of mods which implement RenderListener interface and will receive render events
	 * events
	 */
	private LinkedList<RenderListener> renderListeners = new LinkedList<RenderListener>();
	
	/**
	 * List of mods which implement ChatListener interface and will receive chat
	 * events
	 */
	private LinkedList<ChatListener> chatListeners = new LinkedList<ChatListener>();
	
	/**
	 * List of mods which implement ChatFilter interface and will receive chat
	 * filter events
	 */
	private LinkedList<ChatFilter> chatFilters = new LinkedList<ChatFilter>();
	
	/**
	 * List of mods which implement LoginListener interface and will receive client login events
	 */
	private LinkedList<LoginListener> loginListeners = new LinkedList<LoginListener>();
	
	/**
	 * List of mods which implement LoginListener interface and will receive client login events
	 */
	private LinkedList<PreLoginListener> preLoginListeners = new LinkedList<PreLoginListener>();
	
	/**
	 * List of mods which implement PluginChannelListener interface
	 */
	private LinkedList<PluginChannelListener> pluginChannelListeners = new LinkedList<PluginChannelListener>();
	
	/**
	 * Mapping of plugin channel names to listeners 
	 */
	private HashMap<String,LinkedList<PluginChannelListener>> pluginChannels = new HashMap<String, LinkedList<PluginChannelListener>>();
	
	/**
	 * Reference to the addUrl method on URLClassLoader
	 */
	private Method mAddUrl;
	
	/**
	 * Flag which keeps track of whether late initialisation has been done
	 */
	private boolean loaderStartupDone, loaderStartupComplete, lateInitDone;

	private boolean chatHooked, loginHooked, pluginChannelHooked, tickHooked;
	
	/**
	 * Get the singleton instance of LiteLoader, initialises the loader if necessary
	 * 
	 * @return LiteLoader instance
	 */
	public static final LiteLoader getInstance()
	{
		if (instance == null)
		{
			// Return immediately to stop calls to getInstance causing re-init if they arrive
			// before init is completed
			instance = new LiteLoader();
			instance.initLoader();
		}
		
		return instance;
	}
	
	/**
	 * Get the LiteLoader logger object
	 * 
	 * @return
	 */
	public static final Logger getLogger()
	{
		return logger;
	}
	
	/**
	 * Get LiteLoader version
	 * 
	 * @return
	 */
	public static final String getVersion()
	{
		return LOADER_VERSION;
	}
	
	/**
	 * Get the loader revision
	 * 
	 * @return
	 */
	public static final int getRevision()
	{
		return LOADER_REVISION;
	}
	
	/**
	 * LiteLoader constructor
	 */
	private LiteLoader()
	{
	}
	
	private void initLoader()
	{
		if (loaderStartupDone) return;
		loaderStartupDone = true;
		
		// Set up base class overrides
		prepareClassOverrides();
		
		// Set up loader, initialises any reflection methods needed
		if (prepareLoader())
		{
			logger.info("LiteLoader " + LOADER_VERSION + " starting up...");
			logger.info(String.format("Java reports OS=\"%s\"", System.getProperty("os.name").toLowerCase()));
	
			// Examines the class path and mods folder and locates loadable mods
			prepareMods();
			
			// Initialises enumerated mods
			initMods();
			
			// Initialises the required hooks for loaded mods
			initHooks();
			
			loaderStartupComplete = true;
		}
	}
	
	/**
	 * Do dirty non-base-clean overrides
	 */
	private void prepareClassOverrides()
	{
		registerBaseClassOverride(ModUtilities.getObfuscatedFieldName("net.minecraft.src.CallableJVMFlags", "g"), "g");
	}
	
	/**
	 * Reads a base class overrride from a resource file
	 * 
	 * @param binaryClassName
	 * @param fileName
	 */
	private void registerBaseClassOverride(String binaryClassName, String fileName)
	{
		try
		{
			Method mDefineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); 
			mDefineClass.setAccessible(true);
			
			InputStream resourceInputStream = LiteLoader.class.getResourceAsStream("/classes/" + fileName + ".bin");
			
			if (resourceInputStream != null)
			{
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				
				for (int readBytes = resourceInputStream.read(); readBytes >= 0; readBytes = resourceInputStream.read())
				{
			        outputStream.write(readBytes);
				}
			 
				byte[] data = outputStream.toByteArray();

				outputStream.close();
			    resourceInputStream.close();

			    logger.info("Defining class override for " + binaryClassName);
			    mDefineClass.invoke(Minecraft.class.getClassLoader(), binaryClassName, data, 0, data.length);
			}
			else
			{
			    logger.info("Error defining class override for " + binaryClassName + ", file not found");
			}
		}
		catch (Throwable th)
		{
		    logger.log(Level.WARNING, "Error defining class override for " + binaryClassName, th);
		}
	}
	
	/**
	 * Set up reflection methods required by the loader
	 */
	@SuppressWarnings("unchecked")
	private boolean prepareLoader()
	{
		try
		{
			// addURL method is used by the class loader to 
			mAddUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
			mAddUrl.setAccessible(true);
			
			Formatter minecraftLogFormatter = null;
			
			try
			{
				Class<? extends Formatter> formatterClass = (Class<? extends Formatter>)Minecraft.class.getClassLoader().loadClass(ModUtilities.getObfuscatedFieldName("net.minecraft.src.ConsoleLogFormatter", "em"));
				Constructor<? extends Formatter> defaultConstructor = formatterClass.getDeclaredConstructor();
				defaultConstructor.setAccessible(true);
				minecraftLogFormatter = defaultConstructor.newInstance();
			}
			catch (Exception ex)
			{
				ConsoleLogManager.init();
				minecraftLogFormatter = ConsoleLogManager.loggerLogManager.getHandlers()[0].getFormatter();
			}
			
			logger.setUseParentHandlers(false);
			
			StreamHandler consoleHandler = new ConsoleHandler();
			if (minecraftLogFormatter != null) consoleHandler.setFormatter(minecraftLogFormatter);
			logger.addHandler(consoleHandler);
			
			FileHandler logFileHandler = new FileHandler(new File(Minecraft.getMinecraftDir(), "LiteLoader.txt").getAbsolutePath());
			if (minecraftLogFormatter != null) logFileHandler.setFormatter(minecraftLogFormatter);
			logger.addHandler(logFileHandler);
		}
		catch (Throwable th)
		{
			logger.log(Level.SEVERE, "Error initialising LiteLoader", th);
			return false;
		}
		
		return true;
	}
	
	/**
	 * Get the "mods" folder
	 */
	public File getModsFolder()
	{
		if (modsFolder == null)
		{
			modsFolder = new File(Minecraft.getMinecraftDir(), "mods");
			
			if (!modsFolder.exists() || !modsFolder.isDirectory())
			{
				try
				{
					// Attempt to create the "mods" folder if it does not already exist
					modsFolder.mkdirs();
				}
				catch (Exception ex) {}
			}
		}
		
		return modsFolder;
	}
	
	/**
	 * Used for crash reporting
	 * 
	 * @return List of loaded mods as a string
	 */
	public String getLoadedModsList()
	{
		return loadedModsList;
	}
	
	/**
	 * Enumerate the java class path and "mods" folder to find mod classes, then load the classes
	 */
	private void prepareMods()
	{
		// List of mod files in the "mods" folder
		LinkedList<File> modFiles = new LinkedList<File>();
		
		// Find and enumerate the "mods" folder
		File modFolder = getModsFolder();
		if (modFolder.exists() && modFolder.isDirectory())
		{
			logger.info("Mods folder found, searching " + modFolder.getPath());
			findModFiles(modFolder, modFiles);
			logger.info("Found " + modFiles.size() + " mod file(s)");
		}

		// Find and enumerate classes on the class path
		HashMap<String, Class> modsToLoad = null;
		try
		{
			logger.info("Enumerating class path...");

			String classPath = System.getProperty("java.class.path");
			String classPathSeparator = System.getProperty("path.separator");
			String[] classPathEntries = classPath.split(classPathSeparator);
			
			logger.info(String.format("Class path separator=\"%s\"", classPathSeparator));
			logger.info(String.format("Class path entries=(\n   classpathEntry=%s\n)", classPath.replace(classPathSeparator, "\n   classpathEntry=")));
			
			logger.info("Loading mods from class path...");

			modsToLoad = findModClasses(classPathEntries, modFiles);

			logger.info("Mod class discovery completed");
		}
		catch (Throwable th)
		{
			logger.log(Level.WARNING, "Mod class discovery failed", th);
			return;
		}
		
		loadMods(modsToLoad);
	}
	
	/**
	 * Find mod files in the "mods" folder
	 * 
	 * @param modFolder Folder to search
	 * @param modFiles List of mod files to load
	 */
	protected void findModFiles(File modFolder, LinkedList<File> modFiles)
	{
		List<String> supportedVerions = Arrays.asList(SUPPORTED_VERSIONS);
		
		for (File modFile : modFolder.listFiles(this))
		{
			try
			{
				// Check for a version file
				ZipFile modZip = new ZipFile(modFile);
				ZipEntry version = modZip.getEntry("version.txt");
				
				if (version != null)
				{
					// Read the version string
					InputStream versionStream = modZip.getInputStream(version);
					BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream));
					String strVersion = versionReader.readLine();
					versionReader.close();
					
					// Only add the mod if the version matches and we were able to successfully add it to the class path
					if (supportedVerions.contains(strVersion) && addURLToClassPath(modFile.toURI().toURL()))
					{
						modFiles.add(modFile);
					}
				}
				
				modZip.close();
			}
			catch (Exception ex)
			{
				logger.warning("Error enumerating '" + modFile.getAbsolutePath() + "': Invalid zip file or error reading file");
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
	 */
	@Override
	public boolean accept(File dir, String fileName)
	{
		return fileName.toLowerCase().endsWith(".litemod");
	}
	
	/**
	 * Find mod classes in the class path and enumerated mod files list
	 * 
	 * @param classPathEntries Java class path split into string entries
	 * @return map of classes to load
	 */
	private HashMap<String, Class> findModClasses(String[] classPathEntries, LinkedList<File> modFiles)
	{
		// To try to avoid loading the same mod multiple times if it appears in more than one entry in the class path, we index
		// the mods by name and hopefully match only a single instance of a particular mod
		HashMap<String, Class> modsToLoad = new HashMap<String, Class>();

		try
		{
			logger.info("Searching protection domain code source...");
			
			File packagePath = new File(LiteLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI());
			LinkedList<Class> modClasses = getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");
			
			for (Class mod : modClasses)
			{
				modsToLoad.put(mod.getSimpleName(), mod);
			}

			if (modClasses.size() > 0) logger.info(String.format("Found %s potential matches", modClasses.size()));
		}
		catch (Throwable th)
		{
			logger.warning("Error loading from local class path: " + th.getMessage());
		}

		// Search through the class path and find mod classes
		for (String classPathPart : classPathEntries)
		{
			logger.info(String.format("Searching %s...", classPathPart));
			
			File packagePath = new File(classPathPart);
			LinkedList<Class> modClasses = getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");
			
			for (Class mod : modClasses)
			{
				modsToLoad.put(mod.getSimpleName(), mod);
			}
			
			if (modClasses.size() > 0) logger.info(String.format("Found %s potential matches", modClasses.size()));
		}
		
		// Search through mod files and find mod classes
		for (File modFile : modFiles)
		{
			logger.info(String.format("Searching %s...", modFile.getAbsolutePath()));
			
			LinkedList<Class> modClasses = getSubclassesFor(modFile, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");
			
			for (Class mod : modClasses)
			{
				modsToLoad.put(mod.getSimpleName(), mod);
			}

			if (modClasses.size() > 0) logger.info(String.format("Found %s potential matches", modClasses.size()));
		}
		
		return modsToLoad;
	}
	
	/**
	 * Create mod instances from the enumerated classes
	 * 
	 * @param modsToLoad List of mods to load
	 */
	private void loadMods(HashMap<String, Class> modsToLoad)
	{
		if (modsToLoad == null)
		{
			logger.info("Mod class discovery failed. Not loading any mods!");
			return;
		}
		
		logger.info("Discovered " + modsToLoad.size() + " total mod(s)");
		
		for (Class mod : modsToLoad.values())
		{
			try
			{
				logger.info("Loading mod from " + mod.getName());
				
				LiteMod newMod = (LiteMod)mod.newInstance();
				mods.add(newMod);
				
				logger.info("Successfully added mod " + newMod.getName() + " version " + newMod.getVersion());
			}
			catch (Throwable th)
			{
				logger.warning(th.toString());
				th.printStackTrace();
			}
		}
	}
	
	/**
	 * Initialise the mods which were loaded
	 */
	private void initMods()
	{
		loadedModsList = "";
		int loadedModsCount = 0;
		
		for (Iterator<LiteMod> iter = mods.iterator(); iter.hasNext();)
		{
			LiteMod mod = iter.next();
			
			try
			{
				logger.info("Initialising mod " + mod.getName() + " version " + mod.getVersion());
				
				mod.init();
				
				if (mod instanceof Tickable)
				{
					addTickListener((Tickable)mod);
				}

				if (mod instanceof InitCompleteListener)
				{
					addInitListener((InitCompleteListener)mod);
				}
				
				if (mod instanceof RenderListener)
				{
					addRenderListener((RenderListener)mod);
				}
				
				if (mod instanceof ChatFilter)
				{
					addChatFilter((ChatFilter)mod);
				}
				
				if (mod instanceof ChatListener && !(mod instanceof ChatFilter))
				{
					addChatListener((ChatListener)mod);
				}
				
				if (mod instanceof PreLoginListener)
				{
					addPreLoginListener((PreLoginListener)mod);
				}
				
				if (mod instanceof LoginListener)
				{
					addLoginListener((LoginListener)mod);
				}
				
				if (mod instanceof PluginChannelListener)
				{
					addPluginChannelListener((PluginChannelListener)mod);
				}
				
				loadedModsList += String.format("\n          - %s version %s", mod.getName(), mod.getVersion());
				loadedModsCount++;
			}
			catch (Throwable th)
			{
				logger.log(Level.WARNING, "Error initialising mod '" + mod.getName(), th);
				iter.remove();
			}
		}
		
		loadedModsList = String.format("%s loaded mod(s)%s", loadedModsCount, loadedModsList);
	}

	/**
	 * Initialise mod hooks
	 */
	private void initHooks()
	{
		try
		{
			// Chat hook
			if ((chatListeners.size() > 0 || chatFilters.size() > 0) && !chatHooked)
			{
				chatHooked = true;
				HookChat.Register();
				HookChat.RegisterPacketHandler(this);
			}
			
			// Login hook
			if ((preLoginListeners.size() > 0 || loginListeners.size() > 0) && !loginHooked)
			{
				loginHooked = true;
				ModUtilities.registerPacketOverride(1, HookLogin.class);
				HookLogin.loader = this;
			}
			
			// Plugin channels hook
			if (pluginChannelListeners.size() > 0 && !pluginChannelHooked)
			{
				pluginChannelHooked = true;
				HookPluginChannels.Register();
				HookPluginChannels.RegisterPacketHandler(this);
			}
			
			// Tick hook
			if (!tickHooked)
			{
				tickHooked = true;
				PrivateFields.minecraftProfiler.SetFinal(minecraft, new HookProfiler(this, logger));
			}
		}
		catch (Exception ex)
		{
			logger.log(Level.WARNING, "Error creating hooks", ex);
			ex.printStackTrace();
		}
	}

	/**
	 * @param tickable
	 */
	public void addTickListener(Tickable tickable)
	{
		if (!tickListeners.contains(tickable))
		{
			tickListeners.add(tickable);
			if (loaderStartupComplete) initHooks();
		}
	}
	
	/**
	 * @param initCompleteListener
	 */
	public void addInitListener(InitCompleteListener initCompleteListener)
	{
		if (!initListeners.contains(initCompleteListener))
		{
			initListeners.add(initCompleteListener);
			if (loaderStartupComplete) initHooks();
		}
	}

	/**
	 * @param tickable
	 */
	public void addRenderListener(RenderListener tickable)
	{
		if (!renderListeners.contains(tickable))
		{
			renderListeners.add(tickable);
			if (loaderStartupComplete) initHooks();
		}
	}

	/**
	 * @param chatFilter
	 */
	public void addChatFilter(ChatFilter chatFilter)
	{
		if (!chatFilters.contains(chatFilter))
		{
			chatFilters.add(chatFilter);
			if (loaderStartupComplete) initHooks();
		}
	}

	/**
	 * @param chatListener
	 */
	public void addChatListener(ChatListener chatListener)
	{
		if (!chatListeners.contains(chatListener))
		{
			chatListeners.add(chatListener);
			if (loaderStartupComplete) initHooks();
		}
	}

	/**
	 * @param loginListener
	 */
	public void addPreLoginListener(PreLoginListener loginListener)
	{
		if (!preLoginListeners.contains(loginListener))
		{
			preLoginListeners.add(loginListener);
			if (loaderStartupComplete) initHooks();
		}
	}

	/**
	 * @param loginListener
	 */
	public void addLoginListener(LoginListener loginListener)
	{
		if (!loginListeners.contains(loginListener))
		{
			loginListeners.add(loginListener);
			if (loaderStartupComplete) initHooks();
		}
	}

	/**
	 * @param pluginChannelListener
	 */
	public void addPluginChannelListener(PluginChannelListener pluginChannelListener)
	{
		if (!pluginChannelListeners.contains(pluginChannelListener))
		{
			pluginChannelListeners.add(pluginChannelListener);
			if (loaderStartupComplete) initHooks();
		}
	}

	/**
	 * Enumerate classes on the classpath which are subclasses of the specified
	 * class
	 * 
	 * @param superClass
	 * @return
	 */
	private static LinkedList<Class> getSubclassesFor(File packagePath, ClassLoader classloader, Class superClass, String prefix)
	{
		LinkedList<Class> classes = new LinkedList<Class>();
		
		try
		{
			if (packagePath.isDirectory())
			{
				enumerateDirectory(prefix, superClass, classloader, classes, packagePath);
			}
			else if (packagePath.isFile() && (packagePath.getName().endsWith(".jar") || packagePath.getName().endsWith(".zip") || packagePath.getName().endsWith(".litemod")))
			{
				enumerateCompressedPackage(prefix, superClass, classloader, classes, packagePath);
			}
		}
		catch (Throwable th)
		{
			logger.log(Level.WARNING, "Enumeration error", th);
		}
		
		return classes;
	}
	
	/**
	 * @param superClass
	 * @param classloader
	 * @param classes
	 * @param packagePath
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static void enumerateCompressedPackage(String prefix, Class superClass, ClassLoader classloader, LinkedList<Class> classes, File packagePath) throws FileNotFoundException, IOException
	{
		FileInputStream fileinputstream = new FileInputStream(packagePath);
		ZipInputStream zipinputstream = new ZipInputStream(fileinputstream);
		
		ZipEntry zipentry = null;
		
		do
		{
			zipentry = zipinputstream.getNextEntry();
			
			if (zipentry != null && zipentry.getName().endsWith(".class"))
			{
				String classFileName = zipentry.getName();
				String className = classFileName.lastIndexOf('/') > -1 ? classFileName.substring(classFileName.lastIndexOf('/') + 1) : classFileName;
				
				if (prefix == null || className.startsWith(prefix))
				{
					try
					{
						String fullClassName = classFileName.substring(0, classFileName.length() - 6).replaceAll("/", ".");
						checkAndAddClass(classloader, superClass, classes, fullClassName);
					}
					catch (Exception ex)
					{
					}
				}
			}
		} while (zipentry != null);
		
		fileinputstream.close();
	}
	
	/**
	 * Recursive function to enumerate classes inside a classpath folder
	 * 
	 * @param superClass
	 * @param classloader
	 * @param classes
	 * @param packagePath
	 * @param packageName
	 */
	private static void enumerateDirectory(String prefix, Class superClass, ClassLoader classloader, LinkedList<Class> classes, File packagePath)
	{
		enumerateDirectory(prefix, superClass, classloader, classes, packagePath, "");
	}
	
	/**
	 * Recursive function to enumerate classes inside a classpath folder
	 * 
	 * @param superClass
	 * @param classloader
	 * @param classes
	 * @param packagePath
	 * @param packageName
	 */
	private static void enumerateDirectory(String prefix, Class superClass, ClassLoader classloader, LinkedList<Class> classes, File packagePath, String packageName)
	{
		File[] classFiles = packagePath.listFiles();
		
		for (File classFile : classFiles)
		{
			if (classFile.isDirectory())
			{
				enumerateDirectory(prefix, superClass, classloader, classes, classFile, packageName + classFile.getName() + ".");
			}
			else
			{
				if (classFile.getName().endsWith(".class") && (prefix == null || classFile.getName().startsWith(prefix)))
				{
					String classFileName = classFile.getName();
					String className = packageName + classFileName.substring(0, classFileName.length() - 6);
					checkAndAddClass(classloader, superClass, classes, className);
				}
			}
		}
	}
	
	/**
	 * @param classloader
	 * @param superClass
	 * @param classes
	 * @param className
	 */
	@SuppressWarnings("unchecked")
	private static void checkAndAddClass(ClassLoader classloader, Class superClass, LinkedList<Class> classes, String className)
	{
		if (className.indexOf('$') > -1)
			return;
		
		try
		{
			Class subClass = classloader.loadClass(className);
			
			if (subClass != null && !superClass.equals(subClass) && superClass.isAssignableFrom(subClass) && !subClass.isInterface() && !classes.contains(subClass))
			{
				classes.add(subClass);
			}
		}
		catch (Throwable th)
		{
			logger.log(Level.WARNING, "checkAndAddClass error", th);
		}
	}
	
	/**
	 * Add a URL to the Minecraft classloader class path
	 * 
	 * @param classUrl URL of the resource to add
	 */
	private boolean addURLToClassPath(URL classUrl)
	{
		try
		{
			if (Minecraft.class.getClassLoader() instanceof URLClassLoader && mAddUrl != null && mAddUrl.isAccessible())
			{
				URLClassLoader classLoader = (URLClassLoader)Minecraft.class.getClassLoader();
				mAddUrl.invoke(classLoader, classUrl);
				return true;
			}
		}
		catch (Throwable th)
		{
			logger.log(Level.WARNING, "Error adding class path entry", th);
		}
		
		return false;
	}

	/**
	 * Late initialisation callback
	 */
	public void onInit()
	{
		if (!lateInitDone)
		{
			lateInitDone = true;
			
			for (InitCompleteListener initMod : initListeners)
			{
				try
				{
					logger.info("Calling late init for mod " + initMod.getName());
					initMod.onInitCompleted(minecraft, this);
				}
				catch (Throwable th)
				{
					logger.log(Level.WARNING, "Error initialising mod " + initMod.getName(), th);
				}
			}
		}
	}

	/**
	 * Callback from the tick hook, pre render
	 */
	public void onRender()
	{
		for (RenderListener renderListener : renderListeners)
			renderListener.onRender();
	}
	
	/**
	 * Callback from the tick hook, ticks all tickable mods
	 * 
	 * @param tick True if this is a new tick (otherwise it's just a new frame)
	 */
	public void onTick(Profiler profiler, boolean tick)
	{
		float partialTicks = 0.0F;
		
		// Try to get the minecraft timer object and determine the value of the partialTicks
		if (tick || minecraftTimer == null)
		{
			minecraftTimer = PrivateFields.minecraftTimer.Get(minecraft);
		}
			
		// Hooray, we got the timer reference
		if (minecraftTimer != null)
		{
			partialTicks = minecraftTimer.elapsedPartialTicks;
			tick = minecraftTimer.elapsedTicks > 0;
		}
	
		// Flag indicates whether we are in game at the moment
		boolean inGame = minecraft.renderViewEntity != null && minecraft.renderViewEntity.worldObj != null;
		
		// Iterate tickable mods
		for (Tickable tickable : tickListeners)
		{
			profiler.startSection(tickable.getClass().getSimpleName());
			tickable.onTick(minecraft, partialTicks, inGame, tick);
			profiler.endSection();
		}
	}
	
	/**
	 * Callback from the chat hook
	 * 
	 * @param chatPacket
	 * @return
	 */
	public boolean onChat(Packet3Chat chatPacket)
	{
		// Chat filters get a stab at the chat first, if any filter returns false the chat is discarded
		for (ChatFilter chatFilter : chatFilters)
			if (!chatFilter.onChat(chatPacket))
				return false;
		
		// Chat listeners get the chat if no filter removed it
		for (ChatListener chatListener : chatListeners)
			chatListener.onChat(chatPacket.message);
		
		return true;
	}

	/**
	 * Pre-login callback from the login hook
	 * 
	 * @param netHandler
	 * @param hookLogin
	 * @return
	 */
	public boolean onPreLogin(NetHandler netHandler, Packet1Login loginPacket)
	{
		boolean cancelled = false;
		
		for (PreLoginListener loginListener : preLoginListeners)
		{
			cancelled |= !loginListener.onPreLogin(netHandler, loginPacket);
		}
		
		return !cancelled;
	}
	
	/**
	 * Callback from the login hook
	 * 
	 * @param netHandler
	 * @param loginPacket
	 */
	public void onConnectToServer(NetHandler netHandler, Packet1Login loginPacket)
	{
		for (LoginListener loginListener : loginListeners)
			loginListener.onLogin(netHandler, loginPacket);
		
		setupPluginChannels();
	}
	
	/**
	 * Callback for the plugin channel hook
	 * 
	 * @param hookPluginChannels
	 */
	public void onPluginChannelMessage(HookPluginChannels hookPluginChannels)
	{
		if (hookPluginChannels != null && hookPluginChannels.channel != null && pluginChannels.containsKey(hookPluginChannels.channel))
		{
			for (PluginChannelListener pluginChannelListener : pluginChannels.get(hookPluginChannels.channel))
			{
				try
				{
					pluginChannelListener.onCustomPayload(hookPluginChannels.channel, hookPluginChannels.length, hookPluginChannels.data);
				}
				catch (Exception ex) {}
			}
		}
	}
	
	/**
	 * Delegate to ModUtilities.sendPluginChannelMessage
	 * 
	 * @param channel Channel to send data to
	 * @param data Data to send
	 */
	public void sendPluginChannelMessage(String channel, byte[] data)
	{
		ModUtilities.sendPluginChannelMessage(channel, data);
	}
	
	/**
	 * Query loaded mods for registered channels 
	 */
	protected void setupPluginChannels()
	{
		// Clear any channels from before
		pluginChannels.clear();
		
		// Enumerate mods for plugin channels
		for (PluginChannelListener pluginChannelListener : pluginChannelListeners)
		{
			List<String> channels = pluginChannelListener.getChannels();
			
			if (channels != null)
			{
				for (String channel : channels)
				{
					if (channel.length() > 16 || channel.toUpperCase().equals("REGISTER") || channel.toUpperCase().equals("UNREGISTER"))
						continue;
					
					if (!pluginChannels.containsKey(channel))
					{
						pluginChannels.put(channel, new LinkedList<PluginChannelListener>());
					}
					
					pluginChannels.get(channel).add(pluginChannelListener);
				}
			}
		}

		// If any mods have registered channels, send the REGISTER packet
		if (pluginChannels.keySet().size() > 0)
		{
			StringBuilder channelList = new StringBuilder();
			boolean separator = false;
			
			for (String channel : pluginChannels.keySet())
			{
				if (separator) channelList.append("\u0000");
				channelList.append(channel);
				separator = true;
			}
			
	        byte[] registrationData = channelList.toString().getBytes(Charset.forName("UTF8"));
        
	        sendPluginChannelMessage("REGISTER", registrationData);
		}
	}
}