Compare commits

...
300 Commits
Author SHA1 Message Date
Christian d5af053edb First draft 1.7.9 support.
This is not modding minecraft. It's performing an update. Go away!
2014-05-17 16:30:13 -04:00
Christian 43e3ee1af1 Swap Listenerlist constructor around. Should fix parent resizing issue? 2014-05-14 14:22:51 -04:00
Christian 70570a863f Fix up possible CME 2014-05-13 15:11:50 -04:00
Christian 503da3a257 Don't consider null NetworkDispatchers. This should fix a bunch of fakeplayer issues.
Nothing to see here. No modding being done.
2014-05-13 08:14:21 -04:00
cpw 42713c66e5 Merge pull request #426 from sfPlayer1/master
Fix ObjectIntIdentityMap sporadically matching non-identical objects.
2014-05-12 10:50:20 -04:00
Player 8dbd1ae0a1 Fix ObjectIntIdentityMap sporadically matching non-identical objects. 2014-05-12 16:29:37 +02:00
Christian a8cbef2321 Finally hopefully fully kills the race condition causing a classcast
on slow machines.

This is me bugfixing. NOT MODDING! No! Stop it! I'm not!
2014-05-11 22:15:29 -04:00
Christian 5275cea844 Try and see if there is anything to the identityHashCode collision hypothesis. If you see this in your error messages, kindly let us know! 2014-05-10 14:53:08 -04:00
Christian d8b6adb259 Add a helper for casting some common collection types into generic form 2014-05-10 13:36:24 -04:00
Lex Manos 0c36868f92 Fix network disconnect with message on the client side in NetworkDispatcher. 2014-05-09 13:23:24 -07:00
Lex Manos f2fe80dc36 Fixed default network mod checking to allow client side mods without the server side. Mods wishing to REQUIRE server side components must specify a custom check handler using @NetworkCheckHandler 2014-05-09 13:22:54 -07:00
Christian cd43eacbb2 Ensure that the loadcontroller is ready to preinit. 2014-05-08 10:40:52 -04:00
Christian de546bdf6c Clean up some missing generic info
PS: NOPE: still not modding.
2014-05-08 10:36:01 -04:00
Christian b0eb1ef7c6 Split loadmods into loadmods and preinitmods, to allow resource loading to occur *always* between the two phases. This should fix
mods not being able to access resources during preinit.

PS: I'm still not modding.
2014-05-08 10:23:05 -04:00
Christian 738ce1d7cd Re-add removed genericiterable to clean a warning 2014-05-08 09:58:03 -04:00
Christian b9de9ebc96 Revert "Fix refreshResources not happening if an error occurs."
This reverts commit fff86ee9d3.
2014-05-08 09:56:43 -04:00
LexManos 362ec8dee7 Merge pull request #419 from Thog92/master
updated wrapper to gradle 1.12
2014-05-07 15:41:05 -07:00
LexManos ddc2cfbe86 Merge pull request #402 from AbrarSyed/patch-1
Added dependency examples to the shipped example mod's build.gradle.
2014-05-07 15:40:50 -07:00
AbrarSyed 542e9acec1 documented dependencies 2014-05-07 17:34:44 -05:00
Lex Manos 1436ac2f14 Fine use FMLCommonHandler. 2014-05-07 14:36:00 -07:00
Lex Manos c73a2076e3 Fix potential rance condition in connecting to vanilla servers as well. And move latch into client side only. 2014-05-07 13:54:22 -07:00
Lex Manos 3612ad0c25 Attempt to fix another race condition related to reading NetClientHandler. 2014-05-07 13:31:16 -07:00
LexManos 1d5fc60f82 Merge pull request #411 from matthewprenger/master
Update ExampleMod mcmod.info
2014-05-07 12:39:12 -07:00
Thog92 8555344eb3 updated wrapper to gradle 1.12 2014-05-06 22:03:44 +02:00
Lex Manos 251af1d09d Fixed memory leak on the client caused by Netty holding references to the World. Closes #415 #417 2014-05-05 22:14:13 -07:00
Christian b84d0760ae Fix display of mod status at the server 2014-04-30 22:47:10 -04:00
Christian 76d8d0e870 Fix mod version checking 2014-04-30 22:26:16 -04:00
Christian fff86ee9d3 Fix refreshResources not happening if an error occurs. 2014-04-30 21:55:55 -04:00
Christian 810b1f3075 Clean some generic warnings up. Make a generic list handler. Helpful for others I think too. 2014-04-30 21:55:55 -04:00
LexManos d0f8073fa5 Merge pull request #413 from sfPlayer1/master
backup+default block use fix
2014-04-30 10:12:21 -07:00
Player 2c56c32c5a Fix saving backups with the raw name.
Fix air block not being assigned as the default.
2014-04-30 09:44:09 +02:00
Matthew Prenger a70308ef41 Update mcmod.info 2014-04-28 22:27:52 -05:00
Player 78248da399 Registry: Treat all 1.6 entries as items. 2014-04-26 21:56:25 +02:00
Player 7ba167c500 Registry: Misc tweaks 2014-04-26 21:56:25 +02:00
Player 9b1cbab03b Registry: Crash earlier with conflicting name/object registrations. 2014-04-26 21:56:25 +02:00
Player d88b2aa0c5 prevent the world from getting saved twice at shutdown 2014-04-26 21:56:25 +02:00
Player 59a5adfdb3 Registry: Fix Block-before-ItemBlock allocation when loading 1.6 world saves, more validation 2014-04-26 21:56:25 +02:00
Player ddee7eb117 Fix vanilla bug causing integrated server saving from 2 threads concurrently after a crash 2014-04-26 21:56:25 +02:00
Christian 2b8d0f6680 Fix SimpleNetworkWrapper - this is not me modding,
I didn't realize it was broken until Pahimar told me.

Put an example in the docs.
2014-04-26 09:33:09 -04:00
Christian 7f01cf549b I'm still not modding. Player has contributed greatly to the 1.7 release of FML. He needs authorship credit. 2014-04-19 11:38:46 -04:00
Christian 77c254a6d9 I am not modding, I am fixing an annoyance. The MCP version has long since been 9.03. Also, the JSON from MC updated.. 2014-04-19 10:46:04 -04:00
LexManos 3b42b33b6e Merge pull request #400 from sfPlayer1/master
Fix various registry issues
2014-04-07 09:57:13 -07:00
Player 294c93212c Registry: Add support for registering ItemBlocks before their Blocks 2014-04-07 17:30:38 +02:00
Player 8e44006f43 Registry: Protect against putObject misuse, handle duplicate registrations better 2014-04-06 17:11:23 +02:00
Player c8a0b72eba Registry: Complain about missing mods when repairing broken worlds
Registry: Reduce console spam
2014-04-06 14:49:59 +02:00
Player c8a245a985 Registry: Fix debug info 2014-04-05 01:54:07 +02:00
Player c7adb42199 Registry: Repair mismatched ItemBlocks as well
Fix a few misc issues
2014-04-05 01:47:19 +02:00
Player f77632df35 Remove unneeded entity spawn debug logging. 2014-04-03 21:00:42 +02:00
Player c47fc3b382 Enable custom gui rendering only as required 2014-04-03 17:58:53 +02:00
Player fd6d55afcc Registry: Allow ignoring missing mods from the GUI, with confirm+backup
Registry: Add confirm+backup for automated corrupted id table fixup
Require the user to confirm loading from a backup level.dat
2014-04-01 21:56:53 +02:00
Player 9be92dcfcb Registry: Complain about bogus registrations 2014-04-01 14:40:24 +02:00
Player 49c623f59c initial attempt at a better way to ask the user in case of startup issues 2014-04-01 14:30:47 +02:00
Player 038fa17ad3 Merge branch 'master' of https://github.com/MinecraftForge/FML
Conflicts:
	src/main/java/cpw/mods/fml/client/FMLClientHandler.java
	src/main/java/cpw/mods/fml/client/GuiModItemsMissing.java
	src/main/java/cpw/mods/fml/common/FMLContainer.java
	src/main/java/cpw/mods/fml/common/registry/FMLControlledNamespacedRegistry.java
	src/main/java/cpw/mods/fml/common/registry/GameData.java
2014-04-01 07:00:20 +02:00
Lex Manos 58a4095f56 Update patches for Fixed FF in FG 1.2. 2014-03-31 16:02:54 -07:00
Player 6fd3c12a4a Registry: allow handling missing blocks/items regardless of the mod id 2014-03-31 04:09:59 +02:00
Player eb29d651eb Fix old 1.7 worlds with broken ID mappings 2014-03-30 17:17:54 +02:00
Player 7325aa5033 Registry: cleanup, fix missing id error GUI formatting 2014-03-27 08:30:55 +01:00
LexManos 89cda92561 Merge pull request #392 from AbrarSyed/master
Updated to ForgeGradle 1.2
2014-03-26 16:04:30 -07:00
AbrarSyed 385beb504d updated wrapper to gradle 1.11 2014-03-26 13:34:25 -05:00
AbrarSyed 2b46906ac5 updated example a little 2014-03-26 13:34:01 -05:00
Player 5eebd4df71 Registry: Implement support for remapping blocks/items to a new name. 2014-03-25 00:36:37 +01:00
Player fd9389015f Fix FMLMissingMappingsEvent.get 2014-03-24 21:47:25 +01:00
Player a82195772e Registry: Block IDs after failing to find a mapping for them 2014-03-24 21:16:36 +01:00
Player e58562d3ed Fix remaining issue with autoassigned Block and Item IDs overlapping. 2014-03-20 23:41:01 +01:00
AbrarSyed c3912836dc updated for ForgeGradle 1.2 2014-03-19 02:15:53 -05:00
LexManos 40270c881a Update README.txt 2014-03-18 01:54:32 -05:00
Lex Manos c2143dbeb1 Fix network close events never getting called. Closes #381 #382 2014-03-15 18:16:27 -07:00
Lex Manos f08b485852 Fix long standing deobf issue that caused announce-player-achievements property to have no effect on dedicated servers. 2014-03-11 01:57:44 -07:00
Lex Manos ef07de4f65 Fix hard link to DedicatedSerever when opening a LAN connection causing stalls on connecting. 2014-03-11 00:50:55 -07:00
Lex Manos b7ad532ab5 Re-enable post initalize texture pack reloading to allow Icons to be registerd through any init phase. 2014-03-03 23:23:55 -08:00
Lex Manos 399770e572 Kill the modEventTypes list, register anything that extends FMLEvent, Fixes MissingMappingEvent handler, and any future events added. 2014-02-25 12:30:29 -08:00
Lex Manos e8b60441cc Reload game settings after mod loading is finished to capture mod keybindings. Closes #378 2014-02-22 20:59:25 -08:00
Christian d0dd05a15c FML expands S3F to support payloads up to 2 megs in size. Should be transparent 2014-02-16 18:30:27 -05:00
cpw 572d32358a Merge pull request #373 from bloodmc/master
Prevent player data getting reset during disconnects.
2014-02-14 10:57:50 -07:00
cpw 33100d6bab Merge pull request #371 from bl4ckscor3/patch-1
Fix ExampleMod.java for build #1024+
2014-02-14 10:57:32 -07:00
bloodshot 45409bfa0c Prevent player dat files getting reset during disconnects.
Since FML nulls out the player's playerNetServerHandler during login, we need to
make sure that writePlayerData does not attempt to overwrite the player's dat file
if the player disconnects during the "Logging In" process.
2014-02-13 02:44:18 -05:00
Christian fa5f4c8842 Some argumentation 2014-02-08 22:41:02 -05:00
Christian 995c204338 Fix failing to load a world with missing mod blocks and items. There will be a way to force worlds to load
when stuff is missing, but for right now, it will fail as this is "world safe".
2014-02-08 22:37:40 -05:00
Christian c890206268 Try and handle removal of mods a bit better. Currently no way to allow a world which has missing
blocks to load - but i have the code in place to allow it i think.
2014-02-08 12:18:34 -05:00
bl4ckscor3 2aa73afa15 Fix ExampleMod.java for build #1024+ 2014-02-08 12:34:01 +01:00
Dan Roque 064b66af3d Prevent players from logging in until server has finished starting.
This improves server security as it guarantees no players will be
allowed to connect until the server has fully initialized.
2014-02-05 20:49:10 -05:00
Lex Manos 8c9e8b5270 Fix isRemote, this is integral to so many parts of the code, everyone knows it by this name, People should not change it. 2014-02-04 23:40:50 -08:00
Lex Manos b7b3450dcd Update MCP mapping snapshot to latest crowdsourced names. 2014-02-04 22:56:27 -08:00
Christian 6bb9b8b953 Clean up FMLEventChannel. Closes #367. 2014-02-04 20:01:44 -05:00
Lex Manos 03fb1879d7 Fix obf error when right clicking a Empty Map. 2014-02-04 12:49:18 -08:00
Christian cee0f0b811 Tweak so that writing to the context will automatically send a message back to
the originator in handshakeestablished.
2014-02-02 12:11:57 -05:00
Christian 359ac3ca2a Ensure we check both item and block registries when finding valid IDs. Should fix #365 2014-02-01 11:05:33 +00:00
Lex Manos d87822ad85 Bump gradle wrapper to 1.10 2014-01-29 21:04:55 -08:00
Christian 8633d780c9 And make a loud message if there isn't a modcontainer found, substitute Minecraft. In general, this can only happen
for coremods not properly registering their code. Closes #363
2014-01-25 06:20:09 -05:00
Christian ab199c5811 Try harder to find a mod container. 2014-01-25 06:17:14 -05:00
Christian 544320b8d2 Beginning of a saveinspectionhandler. 2014-01-20 22:27:03 -05:00
Christian 741e172ffe Log4j2 doesn't need debug level logging for itself anymore 2014-01-20 22:01:20 -05:00
Christian a7ca131a33 And don't spam NONE everywhere 2014-01-20 22:00:24 -05:00
Christian 8692ca17d1 Log4j2 logging context for things. This should help add context when things go wrong in mods. 2014-01-20 21:58:39 -05:00
Christian b6d95d704b Name the log files properly. fml-junk is an early startup annoyance I can't kill because log4j2. 2014-01-20 21:31:20 -05:00
Christian 458b0620b4 Log the bad packet in a prettier way. Also, don't show the authlib debug data in the log file. 2014-01-20 17:29:17 -05:00
Christian 675b5a0778 And turn down some more logging, now we have useful logging back again.. 2014-01-20 16:09:34 -05:00
Christian 1c793abe0e Fix derp with networkcheck 2014-01-20 16:06:50 -05:00
Christian a355eecb2c Add in error logging for outbound messages. Fix bug with indexedcodec NPE 2014-01-20 16:02:26 -05:00
Christian 9a8d16b66e Fix log4j2 config. Fix server gui to *show* logging. Fix log spamminess in the console. Fix bug in servergui that can cause deadlock. 2014-01-20 15:09:24 -05:00
Christian 5719b9ec53 Fix reply handling. Make the proxy message available for subclasses of indexedcodec. Fire user events into the network
event firing.
2014-01-20 11:58:14 -05:00
Christian 16d33d2989 Clean up and document outbound handler a bit better. Add in dispatcher target. Closes #361 2014-01-20 11:26:54 -05:00
Christian 32bb7315cc Add in example assets dir. Closes #308 2014-01-20 08:15:55 -05:00
Christian 3dfb54e066 Merge branch 'trait-optional' of github.com:RainWarrior/FML 2014-01-20 08:14:27 -05:00
Christian 79b04898d4 And restore suppressions. ABRAR, DON'T TIDY CODE!!!! 2014-01-20 08:09:02 -05:00
Christian 9d2e089df6 Merge branch 'logging' of github.com:AbrarSyed/FML into abrar-borked 2014-01-20 08:06:45 -05:00
Christian 35a38d7840 Make sidedproxy support non-public fields. Closes #344 2014-01-20 07:55:26 -05:00
Christian 6a695c4348 Try and stop the epic channel closed spam at close time. Closes #353 2014-01-20 07:53:09 -05:00
Christian a62374d4ac findBlock should now return null, not the default block, if the thing being looked for is not found. Closes #352 2014-01-20 07:49:44 -05:00
Christian 3d26f28bcf Allow connection when server is apparently offline. Might allow :NOFML circumvention though. Hmmm. Closes #359 2014-01-20 07:46:17 -05:00
Christian 5adacc3b33 Check the mod, not it's container, in the check handler. Closes #358 2014-01-20 07:42:35 -05:00
Christian 7ac5bddbc3 Allow indexed messages to validate themselves. Also, catch exceptions from
an embedded channel, and cause them to close the connection. It's ugly, but
it means that the client doesn't crash if it connects to a screwy bungycord that's trying a 1.6 handshake for some reason.
2014-01-19 22:08:19 -05:00
Christian 7907e16e96 Add a type adapter for artifact version. Should fix #354 2014-01-19 10:49:28 -05:00
cpw 79d42fca8d Merge pull request #355 from jk-5/errorhandling
Throw an exception when discriminator is not found
2014-01-19 07:38:41 -08:00
cpw dfc0899ec6 Merge pull request #357 from jk-5/sharable
Make NetworkEventFiringHandler sharable
2014-01-19 07:37:52 -08:00
jk-5 2524045728 Make NetworkEventFiringHandler sharable
Fixes #356
2014-01-19 12:27:31 +01:00
jk-5 3557fe31c9 Throw an exception when discriminator is not found 2014-01-19 11:21:24 +01:00
Christian 449ac98b77 SSP Worlds updating from 1.6 will now pop a warning message before loading, and will capture a timestamped
zip file in the minecraft dir before starting to load. Allows for people to test updates.
2014-01-18 22:25:35 -05:00
Abrar Syed f23eba4352 put max number of FML log files to 3 2014-01-19 00:53:58 +00:00
Abrar Syed f0132a6f3b changed fml log level to all 2014-01-19 00:49:47 +00:00
Lex Manos 444a7d7fa1 Move placement of single player world load hook to fix NPEs. 2014-01-18 13:05:18 -08:00
Christian 2a5a8d0cd0 Fix memory leak?! 2014-01-17 23:36:03 -05:00
Christian 275ccac6f1 Fix NPE at startup 2014-01-17 23:35:53 -05:00
Christian ff7b5845e7 Clean up some warnings about @Override 2014-01-17 23:19:22 -05:00
Christian 7c5d62704a Make UniqueIdentifier final and add a hashCode. Closes #348
Clean up language registry. It can be used to access all translations of mods on client or server.
Auto loads from assets files.
2014-01-17 17:47:30 -05:00
Christian 53557dcd05 Put logging exception handlers on all channel inbounds. Fix problem with failure to login. Closes #350 2014-01-17 17:00:55 -05:00
Christian 9c96ca4402 Fire a custom packet channel registration/deregistration event, for any mods that care about that
kind of thing
2014-01-16 19:45:42 -05:00
Christian a429e106dd Fix bug with SSP, and hook so we can do confirmation of world loading, as well as other things 2014-01-16 18:15:45 -05:00
Christian 9cab2ab36e Add in some tests and examples for the "simple" network stuff 2014-01-16 18:07:25 -05:00
Christian 30882b0c1d Clean up some warnings. Add in simple network impl 2014-01-16 18:06:36 -05:00
Christian c013870b1d Merge branch 'simplenet' 2014-01-16 14:59:13 -05:00
Christian dd17979a2f Fix bukkit connectivity issue. 2014-01-16 14:58:28 -05:00
Christian e14efe786f Some fixes and tweaks 2014-01-16 09:14:39 -05:00
Lex Manos a4686b1261 Added basic Mojang account authentication support for development time login. 2014-01-14 16:49:03 -08:00
LexManos e344303ec7 Merge pull request #346 from Jezzadabomb338/master
At the request of AbrarSyed.
2014-01-13 23:11:42 -08:00
Jezzadabomb b362e8a273 At the request of AbrarSyed. 2014-01-14 15:39:24 +11:00
Christian 5da6dcc7e3 Divert connection through FML, so we can deny connections to servers that don't want us 2014-01-13 13:47:18 -05:00
Christian 10d056a494 Fix possible NPE derp 2014-01-13 13:46:22 -05:00
Christian fc69bcf280 Fix up privacy derp in TickEvent. Closes #343 2014-01-13 08:43:33 -05:00
Christian 80b00dc796 Fix openGui. Closes #342 2014-01-13 08:40:56 -05:00
Christian 28293b29ea Add in a simple(ish) event driven network handling system. Register using newEventDrivenChannel
and you'll get a simple network handler that will fire events at the subscriber(s) of your
choice, whenever a packet is received. You'll also get some convenience methods for sending
to things.
2014-01-12 13:20:41 -05:00
Christian 584c0f368b Fix potential ordering issue, clean up some imports 2014-01-11 22:01:01 -05:00
AbrarSyed fc025a7b73 Logging Changes 2014-01-11 16:43:14 +00:00
RainWarrior 4aa2416ce5 Propagate Optional method removal to trait implementation classes 2014-01-10 00:56:00 +04:00
Christian 717a8d6945 Fix csv string vs list of strings. Thanks immibis. Closes #334 2014-01-09 14:55:52 -05:00
cpw a89939e57e Merge pull request #336 from jadar/master
added override toString method for getting full name.
2014-01-09 11:54:54 -08:00
Christian 43068eb986 Fix TargetPoint to be static 2014-01-09 08:41:52 -05:00
Christian dd098854b0 Fix the keybinding array to the right one 2014-01-09 08:40:42 -05:00
Christian d5bfd69e35 Fix problem with connecting to vanilla.
SHOW what's modded and what's vanilla in the list. Hooks that make the blocking work to come
2014-01-06 23:48:53 -05:00
Jadar 96c19b3580 undid readme change 2014-01-06 15:58:42 -06:00
Jadar acf74a3403 changed the readme to reflect new setup task. 2014-01-06 11:09:34 -06:00
Jadar 1db3daa0e8 added override toString method for getting full name. 2014-01-06 10:25:13 -06:00
Lex Manos 0d810c01fa Mark jopt needed on the server, herp derp, blame Abrar! 2014-01-05 19:02:47 -08:00
Christian 9de9a15530 Fix stupid hardcoding derp 2014-01-03 23:04:24 -05:00
Christian 5317672631 Add a utility method for finding the channel handler name based on type. Should fix naming weirdnesses. 2014-01-03 22:57:36 -05:00
Christian 6f1da6550e Fix up mcpname derp in GuiScrollingList. 2014-01-02 22:44:26 -05:00
Christian b51fb91355 Merge branch 'patch-1' of github.com:airbreather/FML 2014-01-02 22:21:25 -05:00
Christian 779cd05aa1 Tweaks 2014-01-02 22:18:02 -05:00
Christian 7bf119e1e5 Fix up readmes and credits. We no longer support modloader. 2014-01-02 22:18:02 -05:00
iChun fa4f3015a0 Added transparent background for GuiIngameModOptions as per cpw's request. May not compile due to manual de-mcp-fication. 2014-01-02 22:18:02 -05:00
Christian fbc1f8f6f9 Config GUIs in the modlist now work. 2014-01-02 11:51:16 -05:00
airbreather c5e29b574a Avoiding redundant calls to LogManager 2014-01-01 11:40:32 -05:00
Christian 3113138bd1 Tweak button positions. 2014-01-01 02:09:40 -05:00
iChun ab5eb3ccff Fix button size for GuiModList 2014-01-01 14:16:23 +08:00
Christian cdd9d92a4f Starting work on the actual GUI. Still work to do. Needs an API. 2014-01-01 00:57:24 -05:00
Christian b3f98d1ee0 Fix derpiness with Mods button when Realms is available 2013-12-31 20:21:28 -05:00
Christian 21b13d6351 Lots of network cleanup. Gui packets now work too! 2013-12-31 19:55:41 -05:00
Christian 22ba6fda5e Expose the nethandler in a few places, and pull out FMLEmbeddedChannel, exposing a utility method on it.
More to come.
2013-12-31 09:45:26 -05:00
Christian f36152398d Add in the tweakclass, fix the json for lzma @ the server. 2013-12-30 13:06:59 -05:00
Christian 5d069629cf Allow itemstacks for furnace recipe inputs. Allow passing extra arguments through registerblock into the itemblock constructor. 2013-12-28 18:04:30 -05:00
Christian 061288909d Fire simple network connect/disconnect gameevents. 2013-12-28 17:51:40 -05:00
Christian 6a5f9e135f Fix example mod code for 1.7 2013-12-28 13:44:37 -05:00
Christian 53a1f98414 Attempt to load old pre-1.7 worlds. ENSURE YOU HAVE A BACKUP! 2013-12-27 11:48:55 -05:00
Christian 34819c9303 Make gradlew executable on linux 2013-12-27 11:26:46 -05:00
Christian ec316f113f AT for renderblocks 2013-12-27 00:08:49 -05:00
Christian f8d6213829 Update render registry 2013-12-27 00:07:48 -05:00
Christian 268bbabee6 Fix handling world reloads when new stuffs are added 2013-12-26 12:42:40 -05:00
Lex Manos c180d9b157 Add 1.7.2 base json, Gradle will automatically download updated versions of this. Keeping it in the repo allows us to see what base json we have built our jsons off of. And if it changes update accordingly. 2013-12-23 22:36:47 -08:00
Christian 7d3b1250e8 Fix handshaking properly. Also, fix ID syncup. It now will completely freeze the idmap after preinit.
This frozen map is used to inject "new" stuff into existing serverside worlds. Interesting sideeffect: remote
servers lacking things will change the client, to also LACK ids for those things. watch for -1 ids in your remap
events. Note: idmaps should be considered temporary per server instance. SERVERSTOPPED will restore "startup" state,
as will client logout.
2013-12-24 00:47:10 -05:00
Christian 156a9ae03a Fix build script 2013-12-23 20:24:54 -05:00
Lex Manos 58132ccda3 Add new required --accessToken to launch specs. 2013-12-22 18:35:50 -08:00
Christian f860c8ad3b bump to legacy launcher 1.9 with logging unification stuffs. 2013-12-18 11:15:53 -05:00
Christian 3e76dfba34 More tweaking on id stuffs at worldload 2013-12-18 11:15:03 -05:00
Christian 31ea100b29 Working on id missing handling 2013-12-18 08:34:44 -05:00
Lex Manos ef3856f9a3 Update patches for Gradle's rename rewrite: MinecraftForge/ForgeGradle@19e7acf2a2 2013-12-18 04:01:37 -08:00
Christian e4b63a1801 IWorldGenerator now has an ordering at registration time. This means the order of worldgen should be much more stable. 2013-12-17 11:42:54 -05:00
Christian 85516d9588 ICraftingHandler, IPickupHandler are now both events. 2013-12-17 11:24:57 -05:00
Christian a17489172c Code to disable mods at runtime, or other times. 2013-12-17 10:51:00 -05:00
Christian 32561265fc Ticks, Player events, keybindings, all migrated to the new event driven system. 2013-12-16 23:18:00 -05:00
Christian 0b419ac79c Fire a user event down the channels when a handshake has occured. 2013-12-16 20:00:01 -05:00
Christian 4071ff38af Patch some GUIs. We're gonna add some basic mod gui config support. 2013-12-16 11:48:39 -05:00
Christian a2b324beb2 Copy eventhandler from Forge into FML. It is going to replace a lot of the runtime event systems. 2013-12-16 11:48:09 -05:00
Christian 557357fe17 Update for log4j2 2013-12-16 11:47:48 -05:00
Christian 3b2994a3de Some patching touchups 2013-12-13 00:18:05 -05:00
LexManos 0098c57f94 Merge pull request #316 from AbrarSyed/patch-4
Update shiped ForgeGradle for 1.7
2013-12-12 17:23:04 -08:00
Lex Manos 55aa337f95 Rename synthetic bridge methods, these methods are not decompiled, but need to reobf correctly cross the recompile boundary. 2013-12-12 17:18:04 -08:00
Abrar Syed df870c1a33 Update shiped ForgeGradle for 1.7 2013-12-12 17:11:37 -06:00
Christian b852e30285 First functional release under reobfuscation. 2013-12-12 18:01:09 -05:00
Christian 7ea571f593 Fix AT, Fix exc. Almost works now! 2013-12-12 01:39:30 -05:00
Lex Manos 7a4ceebf5e Kill old patches and add rejects to ignore file. 2013-12-11 20:39:15 -08:00
Christian 31efcfc3b2 Clean up patches for latest exc. 2013-12-11 23:03:30 -05:00
Christian 49cb893d12 Fix exc this time *sigh* 2013-12-11 22:58:46 -05:00
Christian 009d4dee23 Fix the exc file. Fix the deobfremapper for handling inner classes. 2013-12-11 22:54:51 -05:00
Christian 3e278acb71 Fix stupid possible compiler error. 2013-12-11 20:17:08 -05:00
Christian d0d31d9575 SpawnAdjustment packet. Clean up stuffs. No more compile errors. 2013-12-11 19:29:52 -05:00
Christian ef492407ef Entity spawning works. 2013-12-11 18:46:25 -05:00
Christian cd417c6786 Fixed remote and local connections work with mods now. 2013-12-11 12:35:08 -05:00
Christian 89e4e483c2 Add in a remapping event for mods to consume. 2013-12-10 19:25:49 -05:00
Christian fd36f50d82 Cleanups 2013-12-10 17:29:26 -05:00
Christian 1d71c017f4 ID syncing. 2013-12-10 14:32:06 -05:00
Lex Manos 99c681ad87 Did it manually, forgot it needed the end comma 2013-12-09 20:49:37 -08:00
Lex Manos 57f7f1d7ab Update for fixed Enum cleaning and names. 2013-12-09 20:44:17 -08:00
Lex Manos b2550b8a69 Add mappings for Items/Blocks fields. 2013-12-09 20:43:57 -08:00
Lex Manos a30f173627 Add sonatype snapshots repo for SpecialSource snapshots. 2013-12-09 20:43:27 -08:00
Christian 2aaaeba15e ID loading from the server save now works. 2013-12-09 21:36:49 -05:00
Christian 9c96a0a10a More network stuff, partially done id syncing. 2013-12-09 01:22:24 -05:00
Christian f5c38e2359 OK, network channels appear to be working well for both dedi and integrated servers.
The beginnings of the new mod structure too.
2013-12-06 14:52:33 -05:00
Christian e544adba5c More cleanup. Bidirectional server <-> client network works for mods as well as FML|HS now. 2013-12-06 11:17:40 -05:00
Christian 58f7487cfa Check in patches. Add in some network timeout tweaking values so you can debug the network. 2013-12-06 08:07:09 -05:00
Christian 9f928963f2 A network design I like. It uses the netty embedded channel to allow mods to build channel pipelines on top of
custom payload packets.
2013-12-06 03:11:03 -05:00
Christian 38cec7a11f The basic network handshaking for FML is done. All scenarios seem to work. 2013-12-04 00:11:08 -05:00
Christian 7ab3c3a37c Update gitignore 2013-12-02 23:54:15 -05:00
Christian 53127eec30 Merge branch 'master' of github.com:MinecraftForge/FML
Conflicts:
	install/build.gradle
	patches/minecraft/net/minecraft/client/multiplayer/NetClientHandler.java.patch
	patches/minecraft/net/minecraft/network/NetServerHandler.java.patch
2013-12-02 23:52:27 -05:00
Christian 30d532f4fc Pass 1: Most patches are restored.
NOTES: 1. Network is completely broken. 2. GameRegistry is partially broken. 3. ID sync is not in.
2013-12-02 23:48:26 -05:00
cpw 01fb451b69 Merge pull request #311 from AbrarSyed/patch-3
fix derp in example builscript
2013-11-27 02:13:42 -08:00
Abrar Syed 3714426e19 fix derp in example builscript 2013-11-26 14:23:31 -06:00
Lex Manos c2b919d339 Don't validate signatures in dev env. 2013-11-20 13:18:26 -08:00
Lex Manos c4b8a393f9 Make the working directory the root of the eclipse workspace. 2013-11-17 19:26:21 -08:00
LexManos 30894f7afa Merge pull request #307 from AbrarSyed/master
updated samples
2013-11-17 17:58:01 -08:00
AbrarSyed e9a7660cb8 updated samples 2013-11-17 18:21:24 -06:00
LexManos 4d46abf761 Merge pull request #306 from MinecraftForge/1.6.4
Actually do it correctly. Should be more forge friendly now.
2013-11-17 10:04:27 -08:00
Christian 23baf3a8ce Actually do it correctly. Should be more forge friendly now. 2013-11-13 19:10:11 -05:00
Christian c6a21d0d62 Merge branch '1.6.4' 2013-11-13 07:55:12 -05:00
Christian da72640c7e Way to go, missing import. *sigh* 2013-11-13 07:45:37 -05:00
Christian b7f34629c3 Don't try and open GUIs on the server. 2013-11-12 18:04:25 -05:00
Christian 5500d69b77 Merge branch '1.6.4' 2013-11-12 17:02:08 -05:00
pahimar 6af42bc656 Add in null protection for client/server sides of handleChat 2013-11-11 14:12:02 -05:00
Christian e19fcb8844 Kill more references to modloader. 2013-11-10 13:15:26 -05:00
Christian 0a62333890 Remove all public all the time from Minecraft. It is unnecessary with ModLoader gone. DEAL WITH IT. File AT public requests, make a coremod, whatever. This needed to die. 2013-11-10 12:01:26 -05:00
Christian e7512f13e4 Deprecation cleanup. Bye bye more modloader stuffs 2013-11-10 11:58:34 -05:00
Christian 4708d77c98 First pass : kill modloader, clean up warnings 2013-11-10 11:49:06 -05:00
Lex Manos 9b1d2bdd13 Join the developers list in the pom and fix the client run configs in the workspace. 2013-11-09 19:22:17 -08:00
LexManos a6dc03aa7e Merge pull request #302 from AbrarSyed/patch-1
Update 1.6.4-rel.json
2013-11-09 19:15:34 -08:00
Abrar Syed 6cd8349542 Update 1.6.4-rel.json 2013-11-09 21:14:58 -06:00
Christian 976c589c78 Change the build to capture an MCP version, also, tweak the sources so mavenLocal can be used for ForgeGradle 2013-11-09 20:00:05 -05:00
Christian 24ec338a51 Fix license and naming 2013-11-09 14:28:54 -05:00
AbrarSyed 4f634855ac added src distribution gradle file 2013-11-09 14:28:54 -05:00
Lex Manos 9f01e3407e Move to install to not clutter root directory with the .bat and .sh files I know are coming. 2013-11-09 14:28:54 -05:00
Lex Manos adeaeb74aa Include eclipse template workspace, for packaging in src distro. 2013-11-09 14:28:54 -05:00
Lex Manos e13c3966e0 Add gradle wrapper 2013-11-09 14:28:53 -05:00
Lex Manos 02c3b4e74b Publish to repo folder for local testing. 2013-11-09 14:28:53 -05:00
AbrarSyed 89a07d3668 Step 3: The Rebirth 2013-11-09 14:28:53 -05:00
Lex Manos b52eb6d699 Step 2: The Reformation 2013-11-09 14:28:53 -05:00
AbrarSyed 3281faf2be Step 1: The Purge 2013-11-09 14:28:53 -05:00
Christian 3d25b4e793 Add in the ability to strip interface references for specific interfaces - this is probably mostly useful for
scala scenarios where sythetic methods are generated and is not a substitute for using Optional.Method where appropriate.
Closes #300
2013-11-09 14:27:15 -05:00
Christian f4532410ec Change a couple of warnings, as a prelude to 1.7- preinit is now required for all GameRegistry activity, and every item and block REQUIRES registration. 2013-11-06 16:18:41 -05:00
Christian 8f87021b0f Fix derp with custom properties. They work now! 2013-11-05 22:23:24 -05:00
Christian bc57ff9e83 Fix recursive API dependency resolution. Allows nested APIs, such as BuildCraft's 2013-10-31 09:39:34 -04:00
Christian de8ab934d8 Fix up duplicate entries 2013-10-30 22:46:19 -04:00
Christian 81fe1c9682 Add in an API marker for API type packages.
This does several things:
1. Packages marked as API will generate a new "modid" (the provides) that can be depended on.
2. Packages marked as API will be searched systemwide, and anything declaring that package (even without the API marker)
will get an implicit dependency on the API package.
3. The API package itself will get a soft dependency on the "owner" package.

@Optional elements can refer to the API packages instead of a concrete mod as well.
2013-10-30 22:20:28 -04:00
Christian 58a299aabc Attempt to inject coremods as tweakers, so both can share a dependency ordering 2013-10-27 13:28:50 -04:00
Christian 243a21a353 Wrapping coremods as tweakers. Part 1. 2013-10-20 11:53:07 +02:00
Christian f0dc530b28 Fix up documentation of VersionCheckHandler - it only ever accepted a String and only works on the NetworkMod annotated class 2013-10-20 11:45:00 +02:00
Christian dac7f590ea Modify ordering of networkmod registration and mod instantiation. This fixes VersionCheckHandler logging an incorrect failure message due
to NPE.
2013-10-20 11:41:28 +02:00
Lex Manos bf54d4d667 Make each mod's EventBus log a child of it's main logger. 2013-10-19 18:24:24 -07:00
Christian da4337efbf Fix up handling the new method signature data for NetworkCheckHandlers 2013-10-14 21:28:15 -04:00
Christian f92962bbbb Use null to empty, so missing values work. *sigh* 2013-10-13 22:36:47 -04:00
Christian 2714da1022 Primitive capability for tweakers to order. Add a "TweakOrder" integer
property to your manifest, or accept the default of zero.
2013-10-12 10:28:11 -04:00
LexManos 96be82343c Merge pull request #280 from mc10/patch-1
Very minor style fixes
2013-10-09 20:56:05 -07:00
Kevin Ji 58577775d2 Very minor style fixes
Replacing tabs with spaces consistently, making brace styles consistent, etc.
2013-10-09 19:53:50 -07:00
Christian fc3e7647d2 Support, and fix up, interface lists for Optional 2013-10-09 13:58:14 -04:00
Lex Manos a381874bb9 Delay sound system backend initalization to speed up startup and prevent race condition on some computers. 2013-10-06 11:13:07 -07:00
Christian 55525f6d2e ModLoader is officially deprecated. It will all cease to be with 1.7. 2013-10-06 11:06:31 -04:00
Christian bc64ceabef Optional shouldn't be constructable itself. It's purely a wrapper thing. 2013-10-06 10:56:47 -04:00
Christian 63ba3aa009 Add in support for Optional interfaces and methods. Be gone coremods! 2013-10-04 17:20:05 -04:00
Christian 5265e34a35 Fix null killing the server 2013-09-29 15:51:38 -04:00
Lex Manos 35ab9f52b0 Fix md5s for new checksums.sha1 in scala libraries. 2013-09-28 19:47:32 -07:00
Christian 9b55f1f48f Attempt at a shared modlist implementation - should allow visibility between liteloader and fml for "mod list display" 2013-09-27 10:45:20 -04:00
Christian e356f4d713 Cross-modsystem compatibility fix with thanks to Mumfrey @ liteloader 2013-09-27 10:01:39 -04:00
Christian bfc25bc5da Add to both the classloader and the parent 2013-09-26 13:01:00 -04:00
Christian 9f0f9e7288 Fix deobf tweaker 2013-09-26 10:11:29 -04:00
Christian ce6404fd5b TYPOS!!! 2013-09-26 09:33:48 -04:00
Christian 8f18a3de9a Separate deobf tweaker so it runs last. Should fix problems with cascaded tweakers
expecting an obf environment.
2013-09-26 09:23:25 -04:00
Christian 9815d8c379 Update for launchwrapper 1.8 2013-09-25 16:40:59 -04:00
Christian 1d902df581 Use the negative cache in latest legacylauncher. 2013-09-25 11:46:11 -04:00
Christian 8e26c99de3 Add debugging for deobfuscation
Add negative caching for field and method maps. Should shortcut some work

Fix handling the case where a class doesn't exist, but still needs deobf

Ask the patch manager for the bytes for the class, not the classLoader

Fix up some more places where we should look for a patched class

Fix problem with empty source classes and runtime deobfuscation
2013-09-25 07:37:25 -04:00
Lex Manos fc8c3bef03 Update to new installer that uses xz compression and better support for non-standard jvms 2013-09-24 23:21:17 -07:00
Christian a4de22c1ad And use the parent that's actually going to be valid. *sigh* 2013-09-24 08:42:13 -04:00
Christian 70cffe6982 Herpaderp. Make addURL accessible. *sigh* 2013-09-24 07:33:11 -04:00
Christian 39620f1e41 Fix injection of tweaker into system 2013-09-23 13:33:16 -04:00
cpw 0e80fcb8f7 Merge pull request #284 from smcv/uninit
Fix NPE when loading second single-player world
2013-09-22 18:24:56 -07:00
Simon McVittie 4a94c2c71b Fix NPE when loading second single-player world
After leaving a single-player world, getServer() can return null, resulting
in the stack trace below, "Fatal errors were detected during the
transition from SERVER_STOPPING to SERVER_ABOUT_TO_START",
"The ForgeModLoader state engine has become corrupted" and the client
getting stuck forever.

Exception in thread "Server thread" java.lang.NullPointerException
at cpw.mods.fml.client.FMLClientHandler.serverStopped(FMLClientHandler.java:620)
at cpw.mods.fml.common.FMLCommonHandler.handleServerStopped(FMLCommonHandler.java:468)
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:471)
at net.minecraft.server.ThreadMinecraftServer.run(SourceFile:583)
2013-09-22 16:56:24 +01:00
Christian 79c39f8b7c Fix classpath for launchwrapper 1.7 2013-09-21 16:15:05 -04:00
Christian f6190e8752 Update workspaces for 1.6.4 2013-09-20 17:23:18 -04:00
Christian 0950b9fc84 Fix up a deep crash in the early server init hanging the client 2013-09-20 17:12:01 -04:00
Christian 25981706ef Update for MC 1.6.4 2013-09-20 16:25:12 -04:00
Lex Manos 82d896a35e Make final transformers actually work on methods as well. 2013-09-19 12:59:12 -07:00
Christian e7dd728f95 Format the log messages through MessageFormat. Thanks CovertJaguar for the pointer. Closes #282 2013-09-19 08:23:56 -04:00
Lex Manos 8f2e675581 Update the src distro's eclipse workspace. 2013-09-18 15:21:56 -07:00
Christian ff75416a32 Update mc_versions data and commands patch and eclipse workspace 2013-09-18 18:01:04 -04:00
500 changed files with 69342 additions and 68698 deletions

No files matched your search

+4
View File
@@ -1,9 +1,13 @@
* text eol=lf
*.bat text eol=crlf
*.patch text eol=lf
*.java text eol=lf
*.gradle text eol=crlf
*.png binary
*.exe binary
*.dll binary
*.jar binary
*.lzma binary
*.zip binary
*.pyd binary
*.cfg text eol=lf
+20 -19
View File
@@ -1,20 +1,21 @@
#eclipse
/bin
/minecraft_server
/mods
/fmlbuild.properties
/fmlversion.properties
/difflist.txt
/target
fmlbranding.properties
/fernflower.zip
/commands.py.bck
/mcp*.zip
/mcp
/eclipse
/deobfuscation_data*.zip
/binpatch
/mcp_data/
/map_client.txt
/*.lzma
**/*.lzma
/installer_base.jar
/.settings
/.classpath
#idea
/.idea
*.iml
#gradle
/build
/buildSrc
/.gradle
#occupational hazards
/eclipse/
/repo/
#Patch reject
*.rej
+4 -3
View File
@@ -2,13 +2,14 @@ This is Forge Mod Loader.
You can find the source code at all times at https://github.com/MinecraftForge/FML
This minecraft mod is a clean open source implementation of a mod loader for
minecraft servers, minecraft bukkit servers, and minecraft clients.
This minecraft mod is a clean open source implementation of a mod loader for minecraft servers
and minecraft clients.
The code is authored by cpw.
It (partially) implements API defined by the client side ModLoader, authored by Risugami.
It began by partially implementing an API defined by the client side ModLoader, authored by Risugami.
http://www.minecraftforum.net/topic/75440-
This support has been dropped as of Minecraft release 1.7, as Risugami no longer maintains ModLoader.
It also contains suggestions and hints and generous helpings of code from LexManos, author of MinecraftForge.
http://www.minecraftforge.net/
-69
View File
@@ -1,69 +0,0 @@
{
"id": "FML152",
"time": "2013-03-20T12:00:00-04:00",
"releaseTime": "2013-03-20T12:00:00-04:00",
"type": "release",
"minecraftArguments": "${auth_player_name} ${auth_session} --gameDir ${game_directory} --assetsDir ${game_assets} --tweakClass cpw.mods.fml.common.launcher.FMLTweaker",
"libraries": [
{
"name": "cpw.mods:fml:5.2"
},
{
"name": "net.minecraft:launchwrapper:1.3"
},
{
"name": "net.sf.jopt-simple:jopt-simple:4.5"
},
{
"name": "argo:argo:2.25_fixed"
},
{
"name": "org.ow2.asm:asm-all:4.1"
},
{
"name": "org.lwjgl.lwjgl:lwjgl:2.9.0"
},
{
"name": "org.lwjgl.lwjgl:lwjgl_util:2.9.0"
},
{
"name": "net.java.jinput:jinput:2.0.5"
},
{
"name": "org.bouncycastle:bcprov-jdk15on:1.47"
},
{
"name": "com.google.guava:guava:14.0"
},
{
"name": "net.java.jutils:jutils:1.0.0"
},
{
"name": "org.lwjgl.lwjgl:lwjgl-platform:2.9.0",
"natives": {
"linux": "natives-linux",
"windows": "natives-windows",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
}
},
{
"name": "net.java.jinput:jinput-platform:2.0.5",
"natives": {
"linux": "natives-linux",
"windows": "natives-windows",
"osx": "natives-osx"
},
"extract": {
"exclude": [
"META-INF/"
]
}
}
],
"mainClass": "net.minecraft.launchwrapper.Launch"
}
+94
View File
@@ -0,0 +1,94 @@
This is Forge Mod Loader, or FML for short, by cpw.
More information can be found at https://github.com/MinecraftForge/FML/wiki
It is a clean reimplementation of a mod loading system for client and server.
It can be installed on its own, or as part of Minecraft Forge.
----------------------
About Forge Mod Loader
----------------------
Environments and compatibility
==============================
FML covers two main environments: client and server. All environments share
the main mod loading code base, with additional varying hooks based on the
specific environment.
There are some very visible changes to the client when FML is installed.
There are some bukkit compatibility hooks available, consult MCPC+ for more
information.
Minecraft Forge in all cases bundles FML as it's modloading technology of choice
because FML is open source, freely distributable, and can be easily updated by
contributors through github.
Notable integrations
====================
Optifine has FML compatibility. It varies from Optifine release to release, however
in general it will work well alongside an FML or
Minecraft Forge installation. FML will detect and ensure the good operation of
Optifine (you can see it in your client as an additional data line on the
bottom left).
Mod information
===============
FML exposes the mod information through a mod list visible on the main screen as
well as some small branding enhancements. For full data mods need to provide an
information file. This file is a standard format so hopefully tools providing
launch capabilities can also leverage this content.
-------------------------------
Binary installation information
-------------------------------
If you have downloaded a binary zip file you can install it as follows (client
or server):
Installation
============
To install on a server, simply execute the FML or Forge jar file, with a copy of
minecraft_server-@[email protected] placed in the same directory. FML will launch
it's patched copy.
To install on a client, run the installer by executing java -jar <installer>.jar.
It will identify the location of you minecraft installation (this can be customized)
and create a new profile "FML" there.
Forge Installation
==================
This code also ships as a part of Minecraft Forge. You do not need to install it
separately from your Minecraft Forge installation. Minecraft Forge contains the
exact same code as this. You should not install FML if you are also installing
Minecraft Forge.
-------------------------------------------
Source installation information for modders
-------------------------------------------
This code follows the Minecraft Forge installation methodology. It will apply
some small patches to the vanilla MCP source code, giving you and it access
to some of the data and functions you need to build a successful mod.
Note also that the patches are built against "unrenamed" MCP source code (aka
srgnames) - this means that you will not be able to read them directly against
normal code.
Source pack installation information:
Standalone source installation
==============================
To install this source code for development purposes, extract this zip file.
It ships with a demonstration mod. Run "gradle setupDevWorkspace" to create
a gradle environment primed with FML. Run gradle eclipse or gradle idea to
create an IDE workspace of your choice.
Refer to ForgeGradle for more information about the gradle environment
Forge source installation
=========================
MinecraftForge ships with this code and installs it as part of the forge
installation process, no further action is required on your part.
For reference this is version @MAJOR@.@MINOR@.@REV@.@BUILD@ of FML
for Minecraft version @MCVERSION@.
-14
View File
@@ -1,14 +0,0 @@
import os, sys
def main():
fml_dir = os.path.abspath(sys.argv[1])
work_dir = os.path.normpath(sys.argv[2])
mcp_dir = os.path.normpath(sys.argv[3])
sys.path.append(os.path.join(fml_dir, 'install'))
from fml import apply_fml_patches
apply_fml_patches(fml_dir, mcp_dir, work_dir, False)
if __name__ == '__main__':
main()
+111
View File
@@ -0,0 +1,111 @@
buildscript {
repositories {
mavenCentral()
mavenLocal()
maven {
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT'
}
}
import static net.minecraftforge.gradle.dev.FmlDevPlugin.*
apply plugin: 'maven'
apply plugin: 'fmldev'
repositories {
flatDir {
name "fileRepo"
dirs "repo"
}
}
minecraft {
version = '1.7.9'
mcpVersion = '9.04'
fmlDir = projectDir.getAbsolutePath();
mainClass = 'cpw.mods.fml.relauncher.ServerLaunchWrapper'
tweakClass = 'cpw.mods.fml.common.launcher.FMLTweaker'
installerVersion = "1.4"
}
group = 'cpw.mods'
version = getVersionFromGit(getProject())
jenkins {
job = 'fml'
}
uploadArchives {
repositories {
if (project.hasProperty("filesmaven")) {
logger.info('Publishing to files server')
mavenDeployer {
configuration = configurations.deployJars
repository(url: project.filesmaven.url) {
authentication(userName: project.filesmaven.username, privateKey: project.filesmaven.key)
}
pom {
groupId = project.group
version = project.version
artifactId = project.archivesBaseName
project {
name project.archivesBaseName
packaging 'jar'
description 'ForgeModLoader'
url 'https://github.com/MinecraftForge/FML'
scm {
url 'https://github.com/MinecraftForge/FML'
connection 'scm:git:git://github.com/MinecraftForge/FML.git'
developerConnection 'scm:git:[email protected]:MinecraftForge/FML.git'
}
issueManagement {
system 'github'
url 'https://github.com/MinecraftForge/FML/issues'
}
licenses {
license {
name 'GNU Lesser Public License (LGPL), Version 2.1'
url 'http://www.gnu.org/licenses/lgpl-2.1.txt'
distribution 'repo'
}
}
developers {
developer {
id 'cpw'
name 'cpw'
roles { role 'developer' }
}
developer {
id 'LexManos'
name 'Lex Manos'
roles { role 'developer' }
}
}
}
}
}
} else {
logger.info('Publishing to repo folder')
mavenDeployer {
repository(url: 'file://localhost/' + project.file('repo').getAbsolutePath())
}
}
}
}
-473
View File
@@ -1,473 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- ======================================================================
30 Mar 2012 13:35:40
FML
The Forge Mod Loader
cpw
====================================================================== -->
<project name="FML" default="jenkinsbuild">
<description>The Forge Mod Loader</description>
<target name="writeversion" depends="buildenvsetup">
<exec executable="${python.exe}" dir="${basedir}" failonerror="true">
<arg value="${basedir}/getversion.py" />
<arg value="${mcp.home}" />
</exec>
<propertyfile file="fmlversion.properties">
<entry key="fmlbuild.build.number" type="int" value="${version.build}" />
<entry key="fmlbuild.deobfuscation.hash" type="string" value="${deobf.checksum}" />
</propertyfile>
</target>
<target name="buildenvsetup">
<tstamp>
<format pattern="yyMMddHHmmss" property="timestamp" />
</tstamp>
<property environment="env" />
<property name="modname" value="fml" />
<condition property="mcp.home" value="${env.WORKSPACE}/mcp" else="${basedir}/mcp">
<isset property="env.WORKSPACE" />
</condition>
<property name="fml.python.dir" location="${basedir}/python" />
<property name="fml.lzma.dir" location="${basedir}/lzmabin" />
<condition property="python.exe" value="${fml.python.dir}/python_fml" else="python">
<os family="Windows" />
</condition>
<condition property="lzma.exe" value="${fml.lzma.dir}/xz.exe" else="xz">
<os family="Windows" />
</condition>
<condition property="mcp.exists">
<available file="${mcp.home}/runtime/commands.py" />
</condition>
<condition property="signature.exists">
<available file="${env.JENKINS_HOME}/fmlsigned.properties" />
</condition>
<property name="mcp.obfoutput" location="${mcp.home}/reobf" />
<property name="client.mcp.obfoutput" location="${mcp.obfoutput}/minecraft" />
<property name="mcp.srcdir" location="${mcp.home}/src" />
<property name="client.mcp.srcdir" location="${mcp.srcdir}/minecraft" />
<property name="clean.mcp.srcdir" location="${mcp.home}/src-base" />
<property name="patch.mcp.srcdir" location="${mcp.home}/src-work" />
<property name="tmp.mcp.srcdir" location="${mcp.home}/src-tmp" />
<property name="renamed.mcp.srcdir" location="${mcp.home}/src-renamed" />
<property name="common.src.dir" location="${basedir}/common" />
<property name="client.src.dir" location="${basedir}/client" />
<property name="patch.src.dir" location="${basedir}/patches" />
<property name="fml.conf.dir" location="${basedir}/conf" />
<condition property="version.build" value="${env.BUILD_NUMBER}" else="1">
<isset property="env.BUILD_NUMBER" />
</condition>
<available file="eclipse" property="eclipse.exists" />
</target>
<target name="makeversion" depends="buildenvsetup">
<antcall target="writeversion" />
<property file="fmlversion.properties" />
<property name="build.number" value="${fmlbuild.major.number}.${fmlbuild.minor.number}.${fmlbuild.revision.number}" />
<property name="version.major" value="${fmlbuild.major.number}" />
<property name="version.minor" value="${fmlbuild.minor.number}" />
<property name="version.rev" value="${fmlbuild.revision.number}" />
<property name="version.minecraft" value="${fmlbuild.mcversion}" />
<property name="version.branch" value="${fmlbuild.branch}" />
<property name="version" value="${version.major}.${version.minor}.${version.rev}.${version.build}" />
</target>
<target name="makeclean" depends="buildenvsetup" if="mcp.exists">
<exec executable="${python.exe}" dir="${mcp.home}">
<arg value="${mcp.home}/runtime/cleanup.py" />
<arg value="-f" />
</exec>
</target>
<target name="clean" depends="buildenvsetup,makeclean" if="mcp.exists">
<exec executable="${python.exe}" dir="${mcp.home}">
<arg value="${basedir}/decompile.py" />
<arg value="--mcp-dir" />
<arg value="${mcp.home}" />
<arg value="--fml-dir" />
<arg value="${basedir}" />
<arg value="--gen-conf" />
</exec>
</target>
<target name="reobfuscate" depends="buildenvsetup,recompile">
<exec executable="${python.exe}" dir="${mcp.home}" failonerror="true">
<arg value="${mcp.home}/runtime/reobfuscate.py" />
</exec>
<fail message="Reobfuscation failed">
<condition>
<not>
<and>
<available file="${mcp.home}/temp/client.md5" />
<available file="${mcp.home}/temp/client_reobf.md5" />
</and>
</not>
</condition>
</fail>
<exec executable="${python.exe}" dir="${mcp.home}">
<arg value="${basedir}/generatechangedfilelist.py" />
<arg value="${mcp.home}" />
<arg value="${basedir}/difflist.txt" />
</exec>
</target>
<target name="recompile" depends="buildenvsetup">
<exec executable="${python.exe}" dir="${mcp.home}" failonerror="true">
<arg value="${mcp.home}/runtime/recompile.py" />
</exec>
<fail message="Compilation failed">
<condition>
<not>
<available file="${mcp.home}/bin/minecraft/net/minecraft/client/Minecraft.class" />
</not>
</condition>
</fail>
</target>
<target name="merge-client" depends="buildenvsetup">
<copy todir="${client.mcp.srcdir}" overwrite="true" verbose="true">
<fileset dir="${client.src.dir}" includes="**/*.java" />
</copy>
</target>
<target name="merge-common" depends="buildenvsetup,build-deobf-data">
<copy todir="${client.mcp.srcdir}" overwrite="true" verbose="true">
<fileset dir="${common.src.dir}" includes="**/*.java" />
<fileset dir="${basedir}" includes="deobfuscation_data-${version.minecraft}.lzma"/>
</copy>
</target>
<target name="merge-source" depends="buildenvsetup,merge-client,merge-common" />
<target name="build-universal" depends="buildenvsetup,merge-client,merge-common,reobfuscate,makeversion,makebinpatches">
<condition property="universal.jarname" value="${modname}-universal-${version.minecraft}-${version}" else="${modname}-universal-${version.minecraft}-${version}-${version.branch}">
<equals arg1="${version.branch}" arg2="master" />
</condition>
<mkdir dir="${basedir}/target" />
<path id="server.classpath">
<pathelement path="${mcp.home}/jars/libraries/net/minecraft/launchwrapper/1.3/launchwrapper-1.3.jar"/>
<pathelement path="${mcp.home}/jars/libraries/org/ow2/asm/asm-all/4.1/asm-all-4.1.jar"/>
<pathelement path="${mcp.home}/jars/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar"/>
<pathelement path="${mcp.home}/jars/libraries/net/sf/jopt-simple/jopt-simple/4.5/jopt-simple-4.5.jar"/>
<pathelement path="${mcp.home}/jars/libraries/org/scala-lang/scala-library/2.10.2/scala-library-2.10.2.jar"/>
<pathelement path="${mcp.home}/jars/libraries/org/scala-lang/scala-compiler/2.10.2/scala-compiler-2.10.2.jar"/>
<pathelement path="${mcp.home}/jars/minecraft_server.${version.minecraft}.jar"/>
</path>
<manifestclasspath property="server.jar.classpath" jarfile="${mcp.home}/jars/minecraft_server.jar">
<classpath refid="server.classpath" />
</manifestclasspath>
<jar destfile="${basedir}/target/${universal.jarname}.jar" duplicate="preserve">
<manifest>
<attribute name="Main-Class" value="cpw.mods.fml.relauncher.ServerLaunchWrapper" />
<attribute name="Class-Path" value="${server.jar.classpath}" />
</manifest>
<fileset dir="${client.mcp.obfoutput}" includes="**/*.class" excludes="*.class,net/minecraft/**/*.class" />
</jar>
<antcall target="signjar" />
<zip update="true" destfile="${basedir}/target/${universal.jarname}.jar">
<fileset dir="${basedir}" includes="binpatches.pack.lzma,deobfuscation_data-${version.minecraft}.lzma"/>
<fileset dir="${client.mcp.obfoutput}" includes="*.class" />
<zipfileset dir="${basedir}" includes="fmlversion.properties" />
<zipfileset dir="${basedir}" includes="LICENSE-fml.txt" />
<zipfileset dir="${common.src.dir}" includes="mcpmod.info" />
<zipfileset dir="${client.src.dir}" includes="mcplogo.png" />
<zipfileset dir="${basedir}" includes="install/CREDITS-fml.txt" fullpath="CREDITS-fml.txt" />
<zipfileset dir="${common.src.dir}" includes="*.cfg" />
<mappedresources>
<concat>
<fileset dir="${basedir}/install" includes="README.txt" />
<filterchain>
<replacetokens>
<token key="MAJOR" value="${version.major}" />
<token key="MINOR" value="${version.minor}" />
<token key="REV" value="${version.rev}" />
<token key="BUILD" value="${version.build}" />
<token key="MCVERSION" value="${version.minecraft}" />
</replacetokens>
</filterchain>
</concat>
<mergemapper to="README-fml.txt" />
</mappedresources>
</zip>
</target>
<target name="build-installer" depends="build-universal">
<condition property="version.fullname" value="${version.minecraft}-${version}" else="${version.minecraft}-${version}-${version.branch}">
<equals arg1="${version.branch}" arg2="master" />
</condition>
<tstamp>
<format property="current.time" pattern="yyyy-MM-dd'T'HH:mm:ssZ" />
</tstamp>
<delete file="${basedir}/installer_base.jar" />
<delete file="${basedir}/install_profile.json" />
<get src="http://files.minecraftforge.net/installer/forge-installer-1.3-shrunk.jar" dest="${basedir}/installer_base.jar" />
<copy file="${basedir}/jsons/${version.minecraft}-rel.json" tofile="${basedir}/install_profile.json" />
<copy file="${basedir}/installer_base.jar" tofile="${basedir}/target/${modname}-installer-${version.fullname}.jar" />
<replace file="${basedir}/install_profile.json">
<replaceFilter token="@version@" value="${version}" />
<replaceFilter token="@minecraft_version@" value="${version.minecraft}" />
<replaceFilter token="@timestamp@" value="${current.time}" />
<replaceFilter token="@universal_jar@" value="${modname}-universal-${version.fullname}.jar" />
</replace>
<jar destfile="${basedir}/target/${modname}-installer-${version.fullname}.jar" update="true">
<zipfileset dir="${basedir}" includes="install_profile.json" />
<zipfileset dir="${basedir}/jsons" includes="big_logo.png" />
<zipfileset dir="${basedir}/target" includes="${modname}-universal-${version.fullname}.jar" />
</jar>
<delete file="${basedir}/install_profile.json" />
</target>
<target name="build-source-pack" depends="makeversion">
<property name="srcpack.jarname" value="${modname}-src-${version.minecraft}-${version}-${version.branch}" />
<zip destfile="${basedir}/target/${srcpack.jarname}.zip">
<zipfileset dir="${basedir}" includes="LICENSE-fml.txt,difflist.txt,commands.patch,mcp_merge.cfg,mc_versions.cfg" prefix="fml" />
<zipfileset dir="${basedir}/jsons" includes="${version.minecraft}-dev.json" fullpath="fml/fml.json"/>
<zipfileset dir="${basedir}" includes="deobfuscation_data-${version.minecraft}.lzma" prefix="fml/common" />
<zipfileset dir="${common.src.dir}" includes="**/*.java" prefix="fml/common" />
<zipfileset dir="${client.src.dir}" includes="**/*.java" prefix="fml/client" />
<zipfileset dir="${client.src.dir}" includes="mcp.png" prefix="fml/client" />
<zipfileset dir="${basedir}" includes="fmlversion.properties" prefix="fml/common" />
<zipfileset dir="${common.src.dir}" includes="*.cfg" prefix="fml/common" />
<zipfileset dir="${common.src.dir}" includes="mcpmod.info" prefix="fml/common" />
<zipfileset dir="${patch.src.dir}" includes="**/*.patch" prefix="fml/patches" />
<zipfileset dir="${fml.conf.dir}" prefix="fml/conf" />
<zipfileset dir="${fml.python.dir}" prefix="fml/python" />
<mappedresources>
<concat>
<fileset dir="${basedir}/install" includes="README.txt" />
<filterchain>
<replacetokens>
<token key="MAJOR" value="${version.major}" />
<token key="MINOR" value="${version.minor}" />
<token key="REV" value="${version.rev}" />
<token key="BUILD" value="${version.build}" />
<token key="MCVERSION" value="${version.minecraft}" />
</replacetokens>
</filterchain>
</concat>
<mergemapper to="fml/README-fml.txt" />
</mappedresources>
<zipfileset dir="${basedir}/install" excludes="README.txt,fml.pyc" prefix="fml" />
</zip>
</target>
<target name="build-deobf-data" depends="makeversion">
<mkdir dir="build-tmp-deobf" />
<copy todir="build-tmp-deobf">
<mappedresources>
<fileset dir="${mcp.home}/conf" includes="packaged.srg" />
<globmapper from="packaged.srg" to="deobfuscation_data-${version.minecraft}" />
</mappedresources>
</copy>
<exec executable="${lzma.exe}">
<arg line="--format=lzma"/>
<arg line="build-tmp-deobf/deobfuscation_data-${version.minecraft}"/>
<arg line="-v"/>
</exec>
<copy todir="${basedir}">
<fileset dir="build-tmp-deobf" includes="*.lzma" />
</copy>
<antcall target="writeversion" />
<delete dir="build-tmp-deobf" />
</target>
<target name="build" depends="buildenvsetup,build-deobf-data,merge-client,merge-common,build-universal,build-installer,build-source-pack" />
<target name="jenkinsbuild" depends="buildenvsetup,jenkinsfmldecompile,patch,build" />
<target name="patch" depends="buildenvsetup">
<exec executable="${python.exe}" dir="${basedir}">
<arg value="${basedir}/applypatches.py" />
<arg value="${basedir}" />
<arg value="${mcp.srcdir}" />
<arg value="${mcp.home}" />
</exec>
</target>
<target name="setupenvironment" depends="buildenvsetup">
<input message="This will clean the mcp environment at ${mcp.home} and backup any src-work folder there (src-base will be erased). Continue?" validargs="y,n" addproperty="do.continue" />
<condition property="do.not.continue">
<equals arg1="n" arg2="${do.continue}" />
</condition>
<fail if="do.not.continue">You have decided not to continue. This script will stop now.</fail>
<echo>Preparing the MCP environment at ${mcp.home}</echo>
<antcall target="fmldecompile" />
<echo>Moving old patched sources at ${patch.mcp.srcdir} out of the way</echo>
<move todir="${mcp.home}/src-work${timestamp}" failonerror="false" verbose="true">
<fileset dir="${patch.mcp.srcdir}" />
</move>
<echo>Deleting old patch references at ${clean.mcp.srcdir}</echo>
<delete dir="${clean.mcp.srcdir}" failonerror="false" />
<echo>Creating new patch references at ${clean.mcp.srcdir}</echo>
<copy todir="${clean.mcp.srcdir}">
<fileset dir="${mcp.srcdir}" />
</copy>
<antcall target="cleanargo" />
<antcall target="patch" />
<echo>Creating clean patched references at ${patch.mcp.srcdir}</echo>
<copy todir="${patch.mcp.srcdir}">
<fileset dir="${mcp.srcdir}" />
</copy>
<antcall target="writeversion" />
<delete>
<fileset dir="${basedir}" includes="deobfuscation_data-*.lzma" />
</delete>
<antcall target="build-deobf-data" />
<copy todir="${common.src.dir}">
<fileset dir="${basedir}" includes="deobfuscation_data-*.lzma" />
</copy>
<antcall target="makeeclipse" />
<echo>Setup complete! You should now be able to open ${basedir}/eclipse as a workspace in eclipse and import/refresh the FML project</echo>
</target>
<target name="fmldecompile" depends="buildenvsetup,makeclean">
<exec executable="${python.exe}" dir="${basedir}">
<arg value="${basedir}/decompile.py" />
<arg value="--mcp-dir" />
<arg value="${mcp.home}" />
<arg value="--fml-dir" />
<arg value="${basedir}" />
<arg value="--gen-conf" />
</exec>
</target>
<target name="jenkinsfmldecompile" depends="buildenvsetup,makeclean">
<exec executable="${python.exe}" dir="${basedir}">
<arg value="${basedir}/decompile.py" />
<arg value="--mcp-dir" />
<arg value="${mcp.home}" />
<arg value="--fml-dir" />
<arg value="${basedir}" />
</exec>
</target>
<target name="repatch" depends="buildenvsetup,checkpatches">
<echo>Moving old patched sources at ${mcp.home}/src-work out of the way</echo>
<move todir="${mcp.home}/src-work${timestamp}" failonerror="false" verbose="true">
<fileset dir="${patch.mcp.srcdir}" />
</move>
<delete dir="${mcp.srcdir}" />
<copy todir="${mcp.srcdir}">
<fileset dir="${clean.mcp.srcdir}" />
</copy>
<antcall target="cleanargo" />
<antcall target="patch" />
<copy todir="${patch.mcp.srcdir}">
<fileset dir="${mcp.srcdir}" />
</copy>
</target>
<target name="repatchclean" depends="buildenvsetup">
<delete dir="${mcp.srcdir}" />
<copy todir="${mcp.srcdir}">
<fileset dir="${clean.mcp.srcdir}" />
</copy>
<antcall target="cleanargo" />
<antcall target="patch" />
</target>
<target name="cleanargo" depends="buildenvsetup">
<delete dir="${client.mcp.srcdir}/argo" />
<delete dir="${client.mcp.srcdir}/org" />
</target>
<target name="checkpatches" depends="buildenvsetup">
<uptodate property="checkUptodate.uptodate">
<srcfiles dir="${patch.mcp.srcdir}" includes="**/*.java">
<present targetdir="${patch.src.dir}">
<globmapper from="*.java" to="*.java.patch" />
</present>
</srcfiles>
<globmapper from="*.java" to="${patch.src.dir}/*.java.patch" />
</uptodate>
<fail unless="checkUptodate.uptodate">
A patch is out of date. Update your patches!
</fail>
</target>
<target name="updatepatches" depends="buildenvsetup">
<exec executable="${python.exe}" dir="${basedir}">
<arg value="${basedir}/update_patches.py" />
<arg value="${mcp.home}" />
<arg value="${basedir}" />
</exec>
</target>
<target name="makeeclipse" depends="buildenvsetup" unless="eclipse.exists">
<echo>
Extracting fresh eclipse workspace to ${basedir}/eclipse
</echo>
<unzip src="${basedir}/eclipse-workspace-dev.zip" dest="${basedir}" />
</target>
<target name="makerenamedsource" depends="buildenvsetup,repatch,merge-client,merge-common,reobfuscate">
<copy todir="${tmp.mcp.srcdir}">
<fileset dir="${mcp.srcdir}" />
</copy>
<exec executable="${python.exe}" dir="${mcp.home}">
<arg value="${mcp.home}/runtime/updatenames.py" />
<arg value="-f" />
</exec>
<copy todir="${renamed.mcp.srcdir}">
<fileset dir="${mcp.srcdir}" />
</copy>
<move todir="${mcp.srcdir}">
<fileset dir="${tmp.mcp.srcdir}" />
</move>
</target>
<target name="signjar" depends="buildenvsetup,makeversion" if="signature.exists">
<condition property="universal.jarname" value="${modname}-universal-${version.minecraft}-${version}" else="${modname}-universal-${version.minecraft}-${version}-${version.branch}">
<equals arg1="${version.branch}" arg2="master" />
</condition>
<property file="${env.JENKINS_HOME}/fmlsigned.properties" prefix="sign" />
<echo>${env.JENKINS_HOME} ${universal.jarname} ${sign.KEYPASS}</echo>
<signjar alias="FML" jar="${basedir}/target/${universal.jarname}.zip" keypass="${sign.KEYPASS}" keystore="${env.JENKINS_HOME}/${sign.KEYSTORE}" storepass="${sign.STOREPASS}" verbose="true" />
</target>
<target name="makebinpatches" depends="buildenvsetup,makeversion">
<path id="diffset.libs">
<pathelement path="${mcp.home}/jars/libraries/com/google/guava/guava/14.0/guava-14.0.jar"/>
<pathelement path="${mcp.home}/jars/libraries/org/ow2/asm/asm-debug-all/4.1/asm-debug-all-4.1.jar"/>
<pathelement path="${mcp.home}/jars/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar"/>
<pathelement path="${mcp.obfoutput}/minecraft"/>
</path>
<delete dir="${basedir}/binpatch" verbose="true"/>
<java classname="cpw.mods.fml.common.patcher.GenDiffSet" classpathref="diffset.libs">
<arg path="${mcp.home}/jars/versions/${version.minecraft}/${version.minecraft}.jar.backup"/>
<arg path="${mcp.obfoutput}/minecraft"/>
<arg path="${basedir}/deobfuscation_data-${version.minecraft}.lzma"/>
<arg path="${basedir}/binpatch/client"/>
<arg value="false"/>
</java>
<java classname="cpw.mods.fml.common.patcher.GenDiffSet" classpathref="diffset.libs">
<arg path="${mcp.home}/jars/minecraft_server.${version.minecraft}.jar.backup"/>
<arg path="${mcp.obfoutput}/minecraft"/>
<arg path="${basedir}/deobfuscation_data-${version.minecraft}.lzma"/>
<arg path="${basedir}/binpatch/server"/>
<arg value="true"/>
</java>
<mkdir dir="binpatch-tmp"/>
<zip destfile="binpatch-tmp/binpatches.jar" basedir="${basedir}">
<include name="binpatch/**/*.binpatch"/>
</zip>
<apply executable="pack200">
<arg line="--no-gzip"/>
<arg line="binpatch-tmp/binpatches.pack"/>
<fileset dir="binpatch-tmp" includes="binpatches.jar"/>
</apply>
<apply executable="${lzma.exe}">
<arg line="--format=lzma"/>
<arg line="-v"/>
<fileset dir="binpatch-tmp" includes="binpatches.pack"/>
</apply>
<move file="binpatch-tmp/binpatches.pack.lzma" todir="${basedir}"/>
<delete dir="binpatch-tmp" failonerror="false"/>
</target>
</project>
@@ -1,637 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.server;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Logger;
import org.bukkit.Material;
import net.minecraft.server.Block;
import net.minecraft.server.Item;
import net.minecraft.server.LocaleLanguage;
import net.minecraft.server.MLProp;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.BaseMod;
import net.minecraft.server.BiomeBase;
import net.minecraft.server.EntityItem;
import net.minecraft.server.EntityHuman;
import net.minecraft.server.IChunkProvider;
import net.minecraft.server.ICommandListener;
import net.minecraft.server.IInventory;
import net.minecraft.server.ItemStack;
import net.minecraft.server.NetworkManager;
import net.minecraft.server.Packet1Login;
import net.minecraft.server.Packet250CustomPayload;
import net.minecraft.server.Packet3Chat;
import net.minecraft.server.BukkitRegistry;
import net.minecraft.server.SidedProxy;
import net.minecraft.server.World;
import net.minecraft.server.WorldType;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.IFMLSidedHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.ProxyInjector;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.modloader.ModLoaderModContainer;
import cpw.mods.fml.common.modloader.ModProperty;
import cpw.mods.fml.common.registry.FMLRegistry;
/**
* Handles primary communication from hooked code into the system
*
* The FML entry point is {@link #onPreLoad(MinecraftServer)} called from {@link MinecraftServer}
*
* Obfuscated code should focus on this class and other members of the "server" (or "client") code
*
* The actual mod loading is handled at arms length by {@link Loader}
*
* It is expected that a similar class will exist for each target environment: Bukkit and Client side.
*
* It should not be directly modified.
*
* @author cpw
*
*/
public class FMLBukkitHandler implements IFMLSidedHandler
{
/**
* The singleton
*/
private static final FMLBukkitHandler INSTANCE = new FMLBukkitHandler();
/**
* A reference to the server itself
*/
private MinecraftServer server;
/**
* A handy list of the default overworld biomes
*/
private BiomeBase[] defaultOverworldBiomes;
FMLBukkitProfiler profiler;
/**
* Called to start the whole game off from {@link MinecraftServer#startServer}
* @param minecraftServer
*/
public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
MinecraftServer.log.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http://github.com/cpw/FML.\nPosting on the minecraft forums at\nhttp://www.minecraftforum.net/topic/86765- (the MLMP thread)\n"
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().beginLoading(this);
FMLRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
/**
* Called a bit later on during server initialization to finish loading mods
*/
public void onLoadComplete()
{
Loader.instance().initializeMods();
for (Item i : Item.byId) {
if (i!=null && Material.getMaterial(i.id).name().startsWith("X")) {
Material.setMaterialName(i.id, i.l());
}
}
}
public void onWorldLoadTick()
{
FMLCommonHandler.instance().tickStart(EnumSet.of(TickType.WORLDLOAD));
}
/**
* Every tick just before world and other ticks occur
*/
public void onPreWorldTick(World world)
{
FMLCommonHandler.instance().tickStart(EnumSet.of(TickType.WORLD),world);
}
/**
* Every tick just after world and other ticks occur
*/
public void onPostWorldTick(World world)
{
FMLCommonHandler.instance().tickEnd(EnumSet.of(TickType.WORLD), world);
}
/**
* Get the server instance
*
* @return
*/
public MinecraftServer getServer()
{
return server;
}
/**
* Get a handle to the server's logger instance
*/
public Logger getMinecraftLogger()
{
return MinecraftServer.log;
}
/**
* Called from ChunkProviderServer when a chunk needs to be populated
*
* To avoid polluting the worldgen seed, we generate a new random from the world seed and
* generate a seed from that
*
* @param chunkProvider
* @param chunkX
* @param chunkZ
* @param world
* @param generator
*/
public void onChunkPopulate(IChunkProvider chunkProvider, int chunkX, int chunkZ, World world, IChunkProvider generator)
{
FMLCommonHandler.instance().handleWorldGeneration(chunkX, chunkZ, world.getSeed(), world, generator, chunkProvider);
}
/**
* Called from the furnace to lookup fuel values
*
* @param itemId
* @param itemDamage
* @return
*/
public int fuelLookup(int itemId, int itemDamage)
{
int fv = 0;
for (ModContainer mod : Loader.getModList())
{
fv = Math.max(fv, mod.lookupFuelValue(itemId, itemDamage));
}
return fv;
}
/**
* Is the offered class and instance of BaseMod and therefore a ModLoader mod?
*/
public boolean isModLoaderMod(Class<?> clazz)
{
return BaseMod.class.isAssignableFrom(clazz);
}
/**
* Load the supplied mod class into a mod container
*/
public ModContainer loadBaseModMod(Class<?> clazz, File canonicalFile)
{
@SuppressWarnings("unchecked")
Class <? extends BaseMod > bmClazz = (Class <? extends BaseMod >) clazz;
return new ModLoaderModContainer(bmClazz, canonicalFile);
}
/**
* Called to notify that an item was picked up from the world
*
* @param entityItem
* @param entityPlayer
*/
public void notifyItemPickup(EntityItem entityItem, EntityHuman entityPlayer)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPickupNotification())
{
mod.getPickupNotifier().notifyPickup(entityItem, entityPlayer);
}
}
}
/**
* Raise an exception
*
* @param exception
* @param message
* @param stopGame
*/
public void raiseException(Throwable exception, String message, boolean stopGame)
{
FMLCommonHandler.instance().getFMLLogger().throwing("FMLHandler", "raiseException", exception);
throw new RuntimeException(exception);
}
/**
* Attempt to dispense the item as an entity other than just as a the item itself
*
* @param world
* @param x
* @param y
* @param z
* @param xVelocity
* @param zVelocity
* @param item
* @return
*/
public boolean tryDispensingEntity(World world, double x, double y, double z, byte xVelocity, byte zVelocity, ItemStack item)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsToDispense() && mod.getDispenseHandler().dispense(x, y, z, xVelocity, zVelocity, world, item))
{
return true;
}
}
return false;
}
/**
* @return the instance
*/
public static FMLBukkitHandler instance()
{
return INSTANCE;
}
/**
* Build a list of default overworld biomes
*
* @return
*/
public BiomeBase[] getDefaultOverworldBiomes()
{
if (defaultOverworldBiomes == null)
{
ArrayList<BiomeBase> biomes = new ArrayList<BiomeBase>(20);
for (int i = 0; i < 23; i++)
{
if ("Sky".equals(BiomeBase.biomes[i].y) || "Hell".equals(BiomeBase.biomes[i].y))
{
continue;
}
biomes.add(BiomeBase.biomes[i]);
}
defaultOverworldBiomes = new BiomeBase[biomes.size()];
biomes.toArray(defaultOverworldBiomes);
}
return defaultOverworldBiomes;
}
/**
* Called when an item is crafted
*
* @param player
* @param craftedItem
* @param craftingGrid
*/
public void onItemCrafted(EntityHuman player, ItemStack craftedItem, IInventory craftingGrid)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onCrafting(player, craftedItem, craftingGrid);
}
}
}
/**
* Called when an item is smelted
*
* @param player
* @param smeltedItem
*/
public void onItemSmelted(EntityHuman player, ItemStack smeltedItem)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onSmelting(player, smeltedItem);
}
}
}
/**
* Called when a chat packet is received
*
* @param chat
* @param player
* @return true if you want the packet to stop processing and not echo to the rest of the world
*/
public boolean handleChatPacket(Packet3Chat chat, EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsNetworkPackets() && mod.getNetworkHandler().onChat(chat, player))
{
return true;
}
}
return false;
}
/**
* Called when a packet 250 packet is received from the player
*
* @param packet
* @param player
*/
public void handlePacket250(Packet250CustomPayload packet, EntityHuman player)
{
if ("REGISTER".equals(packet.tag) || "UNREGISTER".equals(packet.tag))
{
handleClientRegistration(packet, player);
return;
}
ModContainer mod = FMLCommonHandler.instance().getModForChannel(packet.tag);
if (mod != null)
{
mod.getNetworkHandler().onPacket250Packet(packet, player);
}
}
/**
* Handle register requests for packet 250 channels
*
* @param packet
*/
private void handleClientRegistration(Packet250CustomPayload packet, EntityHuman player)
{
if (packet.data==null) {
return;
}
try
{
for (String channel : new String(packet.data, "UTF8").split("\0"))
{
// Skip it if we don't know it
if (FMLCommonHandler.instance().getModForChannel(channel) == null)
{
continue;
}
if ("REGISTER".equals(packet.tag))
{
FMLCommonHandler.instance().activateChannel(player, channel);
}
else
{
FMLCommonHandler.instance().deactivateChannel(player, channel);
}
}
}
catch (UnsupportedEncodingException e)
{
getMinecraftLogger().warning("Received invalid registration packet");
}
}
/**
* Handle a login
*
* @param loginPacket
* @param networkManager
*/
public void handleLogin(Packet1Login loginPacket, NetworkManager networkManager)
{
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.tag = "REGISTER";
packet.data = FMLCommonHandler.instance().getPacketRegistry();
packet.length = packet.data.length;
if (packet.length>0) {
networkManager.queue(packet);
}
}
public void announceLogin(EntityHuman player) {
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogin(player);
}
}
}
@Override
public File getMinecraftRootDirectory()
{
try {
return server.a(".").getCanonicalFile();
} catch (IOException ioe) {
return new File(".");
}
}
/**
* @param var2
* @return
*/
public boolean handleServerCommand(String command, String player, ICommandListener listener)
{
for (ModContainer mod : Loader.getModList()) {
if (mod.wantsConsoleCommands() && mod.getConsoleHandler().handleCommand(command, player, listener)) {
return true;
}
}
return false;
}
/**
* @param player
*/
public void announceLogout(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogout(player);
}
}
}
/**
* @param p_28168_1_
*/
public void announceDimensionChange(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerChangedDimension(player);
}
}
}
/**
* @param biome
*/
public void addBiomeToDefaultWorldGenerator(BiomeBase biome)
{
WorldType.NORMAL.addNewBiome(biome);
}
/**
* @param biome
*/
public void removeBiomeFromDefaultWorldGenerator(BiomeBase biome)
{
WorldType.NORMAL.removeBiome(biome);
}
@Override
public Object getMinecraftInstance() {
return server;
}
@Override
public String getCurrentLanguage()
{
return LocaleLanguage.a().getCurrentLanguage();
}
@Override
public Properties getCurrentLanguageTable()
{
return LocaleLanguage.a().getCurrentLanguageTable();
}
@Override
public String getObjectName(Object instance)
{
String objectName;
if (instance instanceof Item) {
objectName=((Item)instance).getName();
} else if (instance instanceof Block) {
objectName=((Block)instance).getName();
} else if (instance instanceof ItemStack) {
objectName=Item.byId[((ItemStack)instance).id].a((ItemStack)instance);
} else {
throw new IllegalArgumentException(String.format("Illegal object for naming %s",instance));
}
objectName+=".name";
return objectName;
}
@Override
public ModMetadata readMetadataFrom(InputStream input, ModContainer mod) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public void profileStart(String profileLabel) {
if (profiler!=null)
{
profiler.start(profileLabel);
}
}
@Override
public void profileEnd() {
if (profiler!=null)
{
profiler.end();
}
}
@Override
public ModProperty getModLoaderPropertyFor(Field f) {
if (f.isAnnotationPresent(MLProp.class)) {
MLProp prop = f.getAnnotation(MLProp.class);
return new ModProperty(prop.info(), prop.min(), prop.max(), prop.name());
}
return null;
}
@Override
public List<String> getAdditionalBrandingInformation() {
return null;
}
@Override
public Side getSide() {
return Side.BUKKIT;
}
@Override
public ProxyInjector findSidedProxyOn(cpw.mods.fml.common.modloader.BaseMod mod) {
for (Field f : mod.getClass().getDeclaredFields())
{
if (f.isAnnotationPresent(SidedProxy.class))
{
SidedProxy sp = f.getAnnotation(SidedProxy.class);
return new ProxyInjector(sp.clientSide(), sp.serverSide(), sp.bukkitSide(), f);
}
}
return null;
}
public void onServerPostTick() {
FMLCommonHandler.instance().tickEnd(EnumSet.of(TickType.GAME));
}
public void onServerPreTick() {
FMLCommonHandler.instance().tickStart(EnumSet.of(TickType.GAME));
}
}
@@ -1,131 +0,0 @@
package cpw.mods.fml.server;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.Multisets;
import com.google.common.collect.TreeMultiset;
import com.google.common.primitives.Ints;
public class FMLBukkitProfiler {
private static FMLBukkitProfiler lastInstance;
private static long endTime;
private LinkedList<String> profiles = new LinkedList<String>();
private TreeMultiset<String> hitCounter = TreeMultiset.create();
private TreeMultiset<String> timings = TreeMultiset.create();
private long timestamp;
public static long beginProfiling(int seconds)
{
long now = System.currentTimeMillis();
if (lastInstance == null)
{
lastInstance = new FMLBukkitProfiler();
FMLBukkitHandler.instance().profiler = lastInstance;
endTime = now + seconds * 1000;
}
if (endTime > now)
{
return (endTime - now) / 1000;
}
else
{
return 0;
}
}
public static long endProfiling()
{
FMLBukkitHandler.instance().profiler = null;
return endTime - System.currentTimeMillis();
}
public static void resetProfiling()
{
endProfiling();
lastInstance = null;
}
public void start(String profileLabel)
{
profiles.push(profileLabel);
timestamp = System.nanoTime();
}
public void end()
{
int timing = (int)((System.nanoTime() - timestamp)/1000L);
String label = Joiner.on('.').join(profiles);
profiles.pop();
hitCounter.add(label);
timings.add(label,timing);
if (System.currentTimeMillis()>endTime)
{
endProfiling();
}
}
public static String[] dumpProfileData(int count)
{
if (lastInstance == null)
{
return new String[] { "No profile data available" };
}
if (endTime > System.currentTimeMillis())
{
return new String[] { String.format("Timing is being gathered for another %d seconds", endTime - System.currentTimeMillis()) };
}
return lastInstance.profileData(count);
}
private String[] profileData(int count) {
List<Entry<String>> sortedTiming = getEntriesSortedByFrequency(timings, false);
ArrayList<String> timeLine = new ArrayList<String>();
double totalTime = timings.size();
for (Entry<String> hit : sortedTiming)
{
if (--count == 0)
{
break;
}
timeLine.add(String.format("%s : %d microseconds, %d invocations. %.2f %% of overall time",hit.getElement(), hit.getCount(), hitCounter.count(hit.getElement()), 100.0 * hit.getCount()/totalTime));
}
return timeLine.toArray(new String[0]);
}
/*
* Code from http://stackoverflow.com/questions/4345633/simplest-way-to-iterate-through-a-multiset-in-the-order-of-element-frequency
*/
private enum EntryComp implements Comparator<Multiset.Entry<?>>{
DESCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(b.getCount(), a.getCount());
}
},
ASCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(a.getCount(), b.getCount());
}
},
}
private static <E> List<Entry<E>> getEntriesSortedByFrequency(final Multiset<E> ms, final boolean ascending) {
final List<Entry<E>> entryList = Lists.newArrayList(ms.entrySet());
Collections.sort(entryList, ascending ? EntryComp.ASCENDING : EntryComp.DESCENDING);
return entryList;
}
}
-409
View File
@@ -1,409 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraft.server;
import java.util.Map;
import java.util.Random;
import org.bukkit.craftbukkit.generator.NetherChunkGenerator;
import org.bukkit.craftbukkit.generator.NormalChunkGenerator;
import cpw.mods.fml.common.TickType;
public abstract class BaseMod implements cpw.mods.fml.common.modloader.BaseMod
{
// CALLBACK MECHANISMS
/**
* @param minecraftInstance
* @return
*/
public final boolean doTickInGame(TickType tick, boolean tickEnd, Object minecraftInstance, Object... data)
{
if (tick==TickType.GAME && tickEnd) {
return onTickInGame((MinecraftServer)minecraftInstance);
} else {
return true;
}
}
@Override
public final void onCrafting(Object... craftingParameters)
{
takenFromCrafting((EntityHuman)craftingParameters[0], (ItemStack)craftingParameters[1], (IInventory)craftingParameters[2]);
}
@Override
public final void onSmelting(Object... smeltingParameters)
{
takenFromFurnace((EntityHuman)smeltingParameters[0], (ItemStack)smeltingParameters[1]);
}
@Override
public final boolean dispense(double x, double y, double z, byte xVelocity, byte zVelocity, Object... data)
{
return dispenseEntity((World)data[0], x, y, z, xVelocity, zVelocity, (ItemStack)data[1]);
}
@Override
public final boolean onChat(Object... data)
{
return onChatMessageReceived((EntityHuman)data[1], (Packet3Chat)data[0]);
}
@Override
public final void onServerLogin(Object handler) {
// NOOP
}
public final void onServerLogout() {
// NOOP
}
@Override
public final void onPlayerLogin(Object player)
{
onClientLogin((EntityHuman) player);
}
@Override
public final void onPlayerLogout(Object player)
{
onClientLogout((EntityHuman)player);
}
@Override
public final void onPlayerChangedDimension(Object player)
{
onClientDimensionChanged((EntityHuman)player);
}
@Override
public final void onPacket250Packet(Object... data)
{
onPacket250Received((EntityHuman)data[1], (Packet250CustomPayload)data[0]);
}
@Override
public final void notifyPickup(Object... pickupData)
{
EntityItem item = (EntityItem) pickupData[0];
EntityHuman player = (EntityHuman) pickupData[1];
onItemPickup(player, item.itemStack);
}
@Override
public final void generate(Random random, int chunkX, int chunkZ, Object... additionalData)
{
World w = (World) additionalData[0];
IChunkProvider cp = (IChunkProvider) additionalData[1];
if (cp instanceof ChunkProviderHell || cp instanceof NetherChunkGenerator)
{
generateNether(w, random, chunkX << 4, chunkZ << 4);
}
else if (cp instanceof ChunkProviderGenerate || cp instanceof NormalChunkGenerator)
{
generateSurface(w, random, chunkX << 4, chunkZ << 4);
}
}
/**
* NO-OP on client side
*/
@Override
public final boolean handleCommand(String command, Object... data)
{
return onServerCommand(command, (String)data[0], (ICommandListener)data[1]);
}
@Override
public void onRegisterAnimations() {
// NOOP on servers
}
@Override
public void onRenderHarvest(@SuppressWarnings("rawtypes") Map renderers) {
// NOOP on servers
}
// BASEMOD API
/**
* Override if you wish to provide a fuel item for the furnace and return the fuel value of the item
*
* @param id
* @param metadata
* @return
*/
public int addFuel(int id, int metadata)
{
return 0;
}
public void addRenderer(Map<Class<? extends Entity>, Object> renderers)
{
}
/**
* Override if you wish to perform some action other than just dispensing the item from the dispenser
*
* @param world
* @param x
* @param y
* @param z
* @param xVel
* @param zVel
* @param item
* @return
*/
public boolean dispenseEntity(World world, double x, double y, double z, int xVel, int zVel, ItemStack item)
{
return false;
}
/**
* Override if you wish to generate Nether (Hell biome) blocks
*
* @param world
* @param random
* @param chunkX
* @param chunkZ
*/
public void generateNether(World world, Random random, int chunkX, int chunkZ)
{
}
/**
* Override if you wish to generate Overworld (not hell or the end) blocks
*
* @param world
* @param random
* @param chunkX
* @param chunkZ
*/
public void generateSurface(World world, Random random, int chunkX, int chunkZ)
{
}
/**
* Return the name of your mod. Defaults to the class name
*
* @return
*/
public String getName()
{
return getClass().getSimpleName();
}
/**
* Get your mod priorities
*
* @return
*/
public String getPriorities()
{
return "";
}
/**
* Return the version of your mod
*
* @return
*/
public abstract String getVersion();
public void keyboardEvent(Object event)
{
}
/**
* Load your mod
*/
public abstract void load();
/**
* Finish loading your mod
*/
public void modsLoaded()
{
}
/**
* Handle item pickup
*
* @param player
* @param item
*/
public void onItemPickup(EntityHuman player, ItemStack item)
{
}
/**
* Ticked every game tick if you have subscribed to tick events through {@link ModLoader#setInGameHook(BaseMod, boolean, boolean)}
*
* @param minecraftServer the server
* @return true to continue receiving ticks
*/
public boolean onTickInGame(MinecraftServer minecraftServer)
{
return false;
}
public boolean onTickInGUI(float tick, Object game, Object gui)
{
return false;
}
/**
* Only implemented on the client side
* {@link #onChatMessageReceived(EntityPlayer, Packet3Chat)}
*
* @param text
*/
public void receiveChatPacket(String text)
{
}
/**
* Only called on the client side
* {@link #onPacket250Received(EntityPlayer, Packet250CustomPayload)}
*
* @param packet
*/
public void receiveCustomPacket(Packet250CustomPayload packet)
{
}
public void registerAnimation(Object game)
{
}
public void renderInvBlock(Object renderer, Block block, int metadata, int modelID)
{
}
public boolean renderWorldBlock(Object renderer, IBlockAccess world, int x, int y, int z, Block block, int modelID)
{
return false;
}
/**
* Called when someone crafts an item from a crafting table
*
* @param player
* @param item
* @param matrix
*/
public void takenFromCrafting(EntityHuman player, ItemStack item, IInventory matrix)
{
}
/**
* Called when someone takes a smelted item from a furnace
*
* @param player
* @param item
*/
public void takenFromFurnace(EntityHuman player, ItemStack item)
{
}
/**
* The identifier string for the mod- used in client<->server negotiation
*/
@Override
public String toString()
{
return getName() + " " + getVersion();
}
/**
* Called when a 250 packet is received on a channel registered to this mod
*
* @param source
* @param payload
*/
public void onPacket250Received(EntityHuman source, Packet250CustomPayload payload)
{
}
/**
* Called when a chat message is received. Return true to stop further processing
*
* @param source
* @param chat
* @return true if you want to consume the message so it is not available for further processing
*/
public boolean onChatMessageReceived(EntityHuman source, Packet3Chat chat)
{
return false;
}
/**
* Called when a server command is received
* @param command
* @return true if you want to consume the message so it is not available for further processing
*/
public boolean onServerCommand(String command, String sender, ICommandListener listener)
{
return false;
}
/**
* Called when a new client logs in.
*
* @param player
*/
public void onClientLogin(EntityHuman player)
{
}
/**
* Called when a client logs out of the server.
*
* @param player
*/
public void onClientLogout(EntityHuman player)
{
}
/**
*
* Called when a client changes dimensions on the server.
*
* @param player
*/
public void onClientDimensionChanged(EntityHuman player)
{
}
// Spare client junk
// -------
// void addRenderer(Map<Class<? extends Entity>, Render> renderers);
// void registerAnimation(Minecraft game);
// void renderInvBlock(RenderBlocks renderer, Block block, int metadata, int modelID);
// boolean renderWorldBlock(RenderBlocks renderer, IBlockAccess world, int x, int y, int z, Block block, int modelID);
// boolean onTickInGUI(float tick, Minecraft game, GuiScreen gui);
// void keyboardEvent(KeyBinding event);
@Override
public void keyBindingEvent(Object keybinding) {
// NOOP on server
}
}
@@ -1,164 +0,0 @@
package net.minecraft.server;
import java.util.Iterator;
import java.util.List;
import net.minecraft.src.BiomeGenBase;
import cpw.mods.fml.common.registry.IMinecraftRegistry;
import cpw.mods.fml.server.FMLBukkitHandler;
public class BukkitRegistry implements IMinecraftRegistry
{
@Override
public void addRecipe(net.minecraft.src.ItemStack output, Object... params)
{
CraftingManager.getInstance().registerShapedRecipe((ItemStack) output, params);
}
@Override
public void addShapelessRecipe(net.minecraft.src.ItemStack output, Object... params)
{
CraftingManager.getInstance().registerShapelessRecipe((ItemStack) output, params);
}
@SuppressWarnings("unchecked")
@Override
public void addRecipe(net.minecraft.src.IRecipe recipe)
{
CraftingManager.getInstance().getRecipies().add(recipe);
}
@Override
public void addSmelting(int input, net.minecraft.src.ItemStack output)
{
FurnaceRecipes.getInstance().registerRecipe(input, (ItemStack) output);
}
@Override
public void registerBlock(net.minecraft.src.Block block)
{
registerBlock(block, ItemBlock.class);
}
@Override
public void registerBlock(net.minecraft.src.Block block, Class <? extends net.minecraft.src.ItemBlock > itemclass)
{
try
{
assert block != null : "registerBlock: block cannot be null";
assert itemclass != null : "registerBlock: itemclass cannot be null";
int blockItemId = ((Block)block).id - 256;
itemclass.getConstructor(int.class).newInstance(blockItemId);
}
catch (Exception e)
{
//HMMM
}
}
@SuppressWarnings("unchecked")
@Override
public void registerEntityID(Class <? extends net.minecraft.src.Entity > entityClass, String entityName, int id)
{
EntityTypes.addNewEntityListMapping((Class<? extends Entity>) entityClass, entityName, id);
}
@SuppressWarnings("unchecked")
@Override
public void registerEntityID(Class <? extends net.minecraft.src.Entity > entityClass, String entityName, int id, int backgroundEggColour, int foregroundEggColour)
{
EntityTypes.addNewEntityListMapping((Class<? extends Entity>) entityClass, entityName, id, backgroundEggColour, foregroundEggColour);
}
@SuppressWarnings("unchecked")
@Override
public void registerTileEntity(Class <? extends net.minecraft.src.TileEntity > tileEntityClass, String id)
{
TileEntity.addNewTileEntityMapping((Class<? extends TileEntity>) tileEntityClass, id);
}
@Override
public void addBiome(BiomeGenBase biome)
{
FMLBukkitHandler.instance().addBiomeToDefaultWorldGenerator((BiomeBase) biome);
}
@Override
public void addSpawn(Class <? extends net.minecraft.src.EntityLiving > entityClass, int weightedProb, int min, int max, net.minecraft.src.EnumCreatureType typeOfCreature, BiomeGenBase... biomes)
{
BiomeBase[] realBiomes=(BiomeBase[]) biomes;
for (BiomeBase biome : realBiomes)
{
@SuppressWarnings("unchecked")
List<BiomeMeta> spawns = ((BiomeBase)biome).getMobs((EnumCreatureType)typeOfCreature);
for (BiomeMeta entry : spawns)
{
//Adjusting an existing spawn entry
if (entry.a == entityClass)
{
entry.d = weightedProb;
entry.b = min;
entry.c = max;
break;
}
}
spawns.add(new BiomeMeta(entityClass, weightedProb, min, max));
}
}
@Override
@SuppressWarnings("unchecked")
public void addSpawn(String entityName, int weightedProb, int min, int max, net.minecraft.src.EnumCreatureType spawnList, BiomeGenBase... biomes)
{
Class <? extends Entity > entityClazz = EntityTypes.getEntityToClassMapping().get(entityName);
if (EntityLiving.class.isAssignableFrom(entityClazz))
{
addSpawn((Class <? extends net.minecraft.src.EntityLiving >) entityClazz, weightedProb, min, max, spawnList, biomes);
}
}
@Override
public void removeBiome(BiomeGenBase biome)
{
FMLBukkitHandler.instance().removeBiomeFromDefaultWorldGenerator((BiomeBase)biome);
}
@Override
public void removeSpawn(Class <? extends net.minecraft.src.EntityLiving > entityClass, net.minecraft.src.EnumCreatureType typeOfCreature, BiomeGenBase... biomesO)
{
BiomeBase[] biomes=(BiomeBase[]) biomesO;
for (BiomeBase biome : biomes)
{
@SuppressWarnings("unchecked")
List<BiomeMeta> spawns = ((BiomeBase)biome).getMobs((EnumCreatureType) typeOfCreature);
Iterator<BiomeMeta> entries = spawns.iterator();
while (entries.hasNext())
{
BiomeMeta entry = entries.next();
if (entry.a == entityClass)
{
entries.remove();
}
}
}
}
@Override
@SuppressWarnings("unchecked")
public void removeSpawn(String entityName, net.minecraft.src.EnumCreatureType spawnList, BiomeGenBase... biomes)
{
Class <? extends Entity > entityClazz = EntityTypes.getEntityToClassMapping().get(entityName);
if (EntityLiving.class.isAssignableFrom(entityClazz))
{
removeSpawn((Class <? extends net.minecraft.src.EntityLiving >) entityClazz, spawnList, biomes);
}
}
}
-48
View File
@@ -1,48 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraft.server;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.*;
import static java.lang.annotation.ElementType.*;
/**
* @author cpw
*
*/
@Retention(value = RUNTIME)
@Target(value = FIELD)
public @interface MLProp
{
/**
* Adds additional help to top of configuration file.
*/
String info() default "";
/**
* Maximum value allowed if field is a number.
*/
double max() default Double.MAX_VALUE;
/**
* Minimum value allowed if field is a number.
*/
double min() default Double.MIN_VALUE;
/**
* Overrides the field name for property key.
*/
String name() default "";
}
-780
View File
@@ -1,780 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraft.server;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ReflectionHelper;
import cpw.mods.fml.common.modloader.ModLoaderHelper;
import cpw.mods.fml.common.modloader.ModLoaderModContainer;
import cpw.mods.fml.common.registry.FMLRegistry;
import cpw.mods.fml.server.FMLBukkitHandler;
public class ModLoader
{
/**
* Not used on the server.
*
* @param achievement
* @param name
* @param description
*/
public static void addAchievementDesc(Achievement achievement, String name, String description)
{
String achName=achievement.getName();
addLocalization(achName, name);
addLocalization(achName+".desc", description);
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
*
* {@link FMLCommonHandler#fuelLookup(int, int)}
*
* @param id
* @param metadata
* @return
*/
@Deprecated
public static int addAllFuel(int id, int metadata)
{
return 0;
}
public static void addAllRenderers(Map<Class<? extends Entity>, Object> renderers)
{
}
public static void addAnimation(Object anim)
{
}
/**
* This method is unimplemented in server versions to date.
*
* @param armor
* @return
*/
public static int addArmor(String armor)
{
return 0;
}
/**
* This method adds the supplied biome to the set of candidate biomes for the default world generator type.
*
* @param biome
*/
public static void addBiome(BiomeBase biome)
{
FMLRegistry.addBiome(biome);
}
/**
* Add localization for the specified string
*
* @param key
* @param value
*/
public static void addLocalization(String key, String value)
{
addLocalization(key, "en_US", value);
}
/**
* Add localization for the specified string
*
* @param key
* @param lang
* @param value
*/
public static void addLocalization(String key, String lang, String value)
{
FMLCommonHandler.instance().addStringLocalization(key, lang, value);
}
/**
* Name the specified minecraft object with the supplied name
*
* @param instance
* @param name
*/
public static void addName(Object instance, String name)
{
addName(instance,"en_US",name);
}
/**
* Unimplemented on the server as it does not generate names
*
* @param instance
* @param lang
* @param name
*/
public static void addName(Object instance, String lang, String name)
{
FMLCommonHandler.instance().addNameForObject(instance, lang, name);
}
/**
* Unimplemented on the server as it does not render textures
*
* @param fileToOverride
* @param fileToAdd
* @return
*/
public static int addOverride(String fileToOverride, String fileToAdd)
{
return 0;
}
/**
* Unimplemented on the server as it does not render textures
*
* @param path
* @param overlayPath
* @param index
*/
public static void addOverride(String path, String overlayPath, int index)
{
// NOOP
}
/**
* Add a Shaped Recipe
*
* @param output
* @param params
*/
public static void addRecipe(ItemStack output, Object... params)
{
FMLRegistry.addRecipe(output, params);
}
/**
* Add a shapeless recipe
*
* @param output
* @param params
*/
public static void addShapelessRecipe(ItemStack output, Object... params)
{
FMLRegistry.addShapelessRecipe(output, params);
}
/**
* Add a new product to be smelted
*
* @param input
* @param output
*/
public static void addSmelting(int input, ItemStack output)
{
FMLRegistry.addSmelting(input, output);
}
/**
* Add a mob to the spawn list
*
* @param entityClass
* @param weightedProb
* @param min
* @param max
* @param spawnList
*/
public static void addSpawn(Class <? extends EntityLiving > entityClass, int weightedProb, int min, int max, EnumCreatureType spawnList)
{
FMLRegistry.addSpawn(entityClass, weightedProb, min, max, spawnList, FMLBukkitHandler.instance().getDefaultOverworldBiomes());
}
/**
* Add a mob to the spawn list
* @param entityClass
* @param weightedProb
* @param min
* @param max
* @param spawnList
* @param biomes
*/
public static void addSpawn(Class <? extends EntityLiving > entityClass, int weightedProb, int min, int max, EnumCreatureType spawnList, BiomeBase... biomes)
{
FMLRegistry.addSpawn(entityClass, weightedProb, min, max, spawnList, biomes);
}
/**
* Add a mob to the spawn list
*
* @param entityName
* @param weightedProb
* @param min
* @param max
* @param spawnList
*/
public static void addSpawn(String entityName, int weightedProb, int min, int max, EnumCreatureType spawnList)
{
FMLRegistry.addSpawn(entityName, weightedProb, min, max, spawnList, FMLBukkitHandler.instance().getDefaultOverworldBiomes());
}
/**
* Add a mob to the spawn list
* @param entityName
* @param weightedProb
* @param min
* @param max
* @param spawnList
* @param biomes
*/
public static void addSpawn(String entityName, int weightedProb, int min, int max, EnumCreatureType spawnList, BiomeBase... biomes)
{
FMLRegistry.addSpawn(entityName, weightedProb, min, max, spawnList, biomes);
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
* {@link FMLBukkitHandler#tryDispensingEntity(World, double, double, double, byte, byte, ItemStack)}
*
* @param world
* @param x
* @param y
* @param z
* @param xVel
* @param zVel
* @param item
* @return
*/
@Deprecated
public static boolean dispenseEntity(World world, double x, double y, double z, int xVel, int zVel, ItemStack item)
{
return false;
}
/**
* Remove a container and drop all the items in it on the ground around
*
* @param world
* @param x
* @param y
* @param z
*/
public static void genericContainerRemoval(World world, int x, int y, int z)
{
TileEntity te = world.getTileEntity(x, y, z);
if (!(te instanceof IInventory))
{
return;
}
IInventory inv = (IInventory)te;
for (int l = 0; l < inv.getSize(); l++)
{
ItemStack itemstack = inv.getItem(l);
if (itemstack == null)
{
continue;
}
float f = world.random.nextFloat() * 0.8F + 0.1F;
float f1 = world.random.nextFloat() * 0.8F + 0.1F;
float f2 = world.random.nextFloat() * 0.8F + 0.1F;
while (itemstack.count > 0)
{
int i1 = world.random.nextInt(21) + 10;
if (i1 > itemstack.count)
{
i1 = itemstack.count ;
}
itemstack.count -= i1;
EntityItem entityitem = new EntityItem(world, (float)te.x + f, (float)te.y + f1, (float)te.z + f2, new ItemStack(itemstack.id, i1, itemstack.getData()));
float f3 = 0.05F;
entityitem.motX = (float)world.random.nextGaussian() * f3;
entityitem.motY = (float)world.random.nextGaussian() * f3 + 0.2F;
entityitem.motZ = (float)world.random.nextGaussian() * f3;
if (itemstack.hasTag())
{
entityitem.itemStack.setTag((NBTTagCompound)itemstack.getTag().clone());
}
world.addEntity(entityitem);
}
}
}
/**
* Get a list of all BaseMod loaded into the system
* {@link ModLoaderModContainer#findAll}
*
* @return
*/
public static List<BaseMod> getLoadedMods()
{
return ModLoaderModContainer.findAll(BaseMod.class);
}
/**
* Get a logger instance {@link FMLCommonHandler#getFMLLogger()}
*
* @return
*/
public static Logger getLogger()
{
return FMLCommonHandler.instance().getFMLLogger();
}
public static Object getMinecraftInstance()
{
return getMinecraftServerInstance();
}
/**
* Get the minecraft server instance
* {@link FMLServerHandler#getServer()}
* @return
*/
public static MinecraftServer getMinecraftServerInstance()
{
return FMLBukkitHandler.instance().getServer();
}
/**
* Get a value from a field using reflection
* {@link ReflectionHelper#getPrivateValue(Class, Object, int)}
*
* @param instanceclass
* @param instance
* @param fieldindex
* @return
*/
public static <T, E> T getPrivateValue(Class <? super E > instanceclass, E instance, int fieldindex)
{
return ReflectionHelper.getPrivateValue(instanceclass, instance, fieldindex);
}
/**
* Get a value from a field using reflection
* {@link ReflectionHelper#getPrivateValue(Class, Object, String)}
*
* @param instanceclass
* @param instance
* @param field
* @return
*/
public static <T, E> T getPrivateValue(Class <? super E > instanceclass, E instance, String field)
{
return ReflectionHelper.getPrivateValue(instanceclass, instance, field);
}
/**
* Stubbed method on the server to return a unique model id
*
*/
public static int getUniqueBlockModelID(BaseMod mod, boolean inventoryRenderer)
{
return -1;
}
/**
* Get a new unique entity id
* {@link Entity#getNextId()}
*
* @return
*/
public static int getUniqueEntityId()
{
return FMLCommonHandler.instance().nextUniqueEntityListId();
}
public static int getUniqueSpriteIndex(String path)
{
return -1;
}
/**
* To properly implement packet 250 protocol you should always check your
* channel is active prior to sending the packet
*
* @param player
* @param channel
* @return
*/
public static boolean isChannelActive(EntityPlayer player, String channel)
{
return FMLCommonHandler.instance().isChannelActive(channel, player);
}
public static boolean isGUIOpen(Class<?> gui)
{
return false;
}
/**
* Is the named mod loaded?
* {@link Loader#isModLoaded(String)}
*
* @param modname
* @return
*/
public static boolean isModLoaded(String modname)
{
return Loader.isModLoaded(modname);
}
/**
* Implemented elsewhere
*/
@Deprecated
public static void loadConfig()
{
}
public static Object loadImage(Object renderEngine, String path) throws Exception
{
return null;
}
/**
* Call in from elsewhere. Unimplemented here.
* @param player
* @param item
*/
@Deprecated
public static void onItemPickup(EntityPlayer player, ItemStack item)
{
}
/**
* Call in from elsewhere. Unimplemented here.
*/
@Deprecated
public static void onTick(float tick, Object game)
{
}
public static void openGUI(EntityPlayer player, Object gui)
{
// NOOP
}
@Deprecated
public static void populateChunk(IChunkProvider generator, int chunkX, int chunkZ, World world)
{
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
* {@link FMLBukkitHandler#handlePacket250(Packet250CustomPayload, EntityHuman)}
*
* @param packet
*/
@Deprecated
public static void receivePacket(Packet250CustomPayload packet)
{
}
@Deprecated
public static Object[] registerAllKeys(Object[] keys)
{
return keys;
}
@Deprecated
public static void registerAllTextureOverrides(Object cache)
{
}
/**
* Register a new block
*
* @param block
*/
public static void registerBlock(Block block)
{
FMLRegistry.registerBlock(block);
}
/**
* Register a new block
*
* @param block
* @param itemclass
*/
public static void registerBlock(Block block, Class <? extends ItemBlock > itemclass)
{
FMLRegistry.registerBlock(block, itemclass);
}
/**
* Register a new entity ID
*
* @param entityClass
* @param entityName
* @param id
*/
public static void registerEntityID(Class <? extends Entity > entityClass, String entityName, int id)
{
FMLRegistry.registerEntityID(entityClass, entityName, id);
}
/**
* Register a new entity ID
*
* @param entityClass
* @param entityName
* @param id
* @param background
* @param foreground
*/
public static void registerEntityID(Class <? extends Entity > entityClass, String entityName, int id, int background, int foreground)
{
FMLRegistry.registerEntityID(entityClass, entityName, id, background, foreground);
}
public static void registerKey(BaseMod mod, Object keyHandler, boolean allowRepeat)
{
// NOOP
}
/**
* Register the mod for packets on this channel. This only registers the
* channel with Forge Mod Loader, not with clients connecting- use
* BaseMod.onClientLogin to tell them about your custom channel
* {@link FMLCommonHandler#registerChannel(cpw.mods.fml.common.ModContainer, String)}
*
* @param mod
* @param channel
*/
public static void registerPacketChannel(BaseMod mod, String channel)
{
FMLCommonHandler.instance().registerChannel(ModLoaderModContainer.findContainerFor(mod), channel);
}
/**
* Register a new tile entity class
*
* @param tileEntityClass
* @param id
*/
public static void registerTileEntity(Class <? extends TileEntity > tileEntityClass, String id)
{
FMLRegistry.registerTileEntity(tileEntityClass, id);
}
public static void registerTileEntity(Class<? extends TileEntity> tileEntityClass, String id, Object renderer)
{
FMLRegistry.instance().registerTileEntity(tileEntityClass, id);
}
/**
* Remove a biome from the list of generated biomes
*
* @param biome
*/
public static void removeBiome(BiomeBase biome)
{
FMLRegistry.removeBiome(biome);
}
/**
* Remove a spawn
*
* @param entityClass
* @param spawnList
*/
public static void removeSpawn(Class <? extends EntityLiving > entityClass, EnumCreatureType spawnList)
{
FMLRegistry.removeSpawn(entityClass, spawnList, FMLBukkitHandler.instance().getDefaultOverworldBiomes());
}
/**
* Remove a spawn
*
* @param entityClass
* @param spawnList
* @param biomes
*/
public static void removeSpawn(Class <? extends EntityLiving > entityClass, EnumCreatureType spawnList, BiomeBase... biomes)
{
FMLRegistry.removeSpawn(entityClass, spawnList, biomes);
}
/**
* Remove a spawn
*
* @param entityName
* @param spawnList
*/
public static void removeSpawn(String entityName, EnumCreatureType spawnList)
{
FMLRegistry.removeSpawn(entityName, spawnList, FMLBukkitHandler.instance().getDefaultOverworldBiomes());
}
/**
* Remove a spawn
*
* @param entityName
* @param spawnList
* @param biomes
*/
public static void removeSpawn(String entityName, EnumCreatureType spawnList, BiomeBase... biomes)
{
FMLRegistry.removeSpawn(entityName, spawnList, biomes);
}
@Deprecated
public static boolean renderBlockIsItemFull3D(int modelID)
{
return false;
}
@Deprecated
public static void renderInvBlock(Object renderer, Block block, int metadata, int modelID)
{
// NOOP
}
@Deprecated
public static boolean renderWorldBlock(Object renderer, IBlockAccess world, int x, int y, int z, Block block, int modelID)
{
return false;
}
/**
* Configuration is handled elsewhere
* {@link ModLoaderModContainer}
*/
@Deprecated
public static void saveConfig()
{
}
/**
* Send a chat message to the server
* {@link FMLServerHandler#handleChatPacket(Packet3Chat, EntityPlayer)}
*
* @param text
*/
@Deprecated
public static void serverChat(String text)
{
//TODO
}
@Deprecated
public static void serverLogin(Object handler, Packet1Login loginPacket)
{
//TODO
}
/**
* Indicate that you want to receive ticks
*
* @param mod receiving the events
* @param enable indicates whether you want to recieve them or not
* @param useClock Not used in server side: all ticks are sent on the server side (no render subticks)
*/
public static void setInGameHook(BaseMod mod, boolean enable, boolean useClock)
{
ModLoaderHelper.updateStandardTicks(mod, enable, useClock);
}
public static void setInGUIHook(BaseMod mod, boolean enable, boolean useClock)
{
ModLoaderHelper.updateGUITicks(mod, enable, useClock);
}
/**
* Set a private field to a value using reflection
* {@link ReflectionHelper#setPrivateValue(Class, Object, int, Object)}
*
* @param instanceclass
* @param instance
* @param fieldindex
* @param value
*/
public static <T, E> void setPrivateValue(Class <? super T > instanceclass, T instance, int fieldindex, E value)
{
ReflectionHelper.setPrivateValue(instanceclass, instance, fieldindex, value);
}
/**
* Set a private field to a value using reflection
* {@link ReflectionHelper#setPrivateValue(Class, Object, String, Object)}
*
* @param instanceclass
* @param instance
* @param field
* @param value
*/
public static <T, E> void setPrivateValue(Class <? super T > instanceclass, T instance, String field, E value)
{
ReflectionHelper.setPrivateValue(instanceclass, instance, field, value);
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
* {@link FMLBukkitHandler#onItemCrafted(EntityHuman, ItemStack, IInventory)}
*
* @param player
* @param item
* @param matrix
*/
@Deprecated
public static void takenFromCrafting(EntityHuman player, ItemStack item, IInventory matrix)
{
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
* {@link FMLBukkitHandler#onItemSmelted(EntityHuman, ItemStack)}
*
* @param player
* @param item
*/
@Deprecated
public static void takenFromFurnace(EntityHuman player, ItemStack item)
{
}
/**
* Throw the offered exception. Likely will stop the game.
* {@link FMLBukkitHandler#raiseException(Throwable, String, boolean)}
* @param message
* @param e
*/
public static void throwException(String message, Throwable e)
{
FMLBukkitHandler.instance().raiseException(e, message, true);
}
/**
* To properly implement packet 250 protocol you should always check your channel
* is active prior to sending the packet
*
* @param player
* @param channel
* @return
*/
public static boolean isChannelActive(EntityHuman player, String channel)
{
return FMLCommonHandler.instance().isChannelActive(channel, player);
}
}
@@ -1,46 +0,0 @@
/*
* The FML Forge Mod Loader suite.
* Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraft.server;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SidedProxy
{
/**
* The name of the client side class to load and populate
* @return
*/
String clientSide() default "";
/**
* The name of the server side class to load and populate
* @return
*/
String serverSide() default "";
/**
* The name of the a special bukkit plugin class to load and populate
*/
String bukkitSide() default "";
}
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface BiomeGenBase {
}
-5
View File
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface Block {
}
-5
View File
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface Entity {
}
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface EntityLiving {
}
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface EnumCreatureType {
}
-5
View File
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface IRecipe {
}
-5
View File
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface ItemBlock {
}
-5
View File
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface ItemStack {
}
-5
View File
@@ -1,5 +0,0 @@
package net.minecraft.src;
public interface TileEntity {
}
-43
View File
@@ -1,43 +0,0 @@
import sys
import os, os.path, shutil
import fnmatch
import re
def main():
sys.stdout.flush()
for x in range(1, len(sys.argv)):
cleanup_source(sys.argv[x])
count = 0
def cleanup_source(path):
path = os.path.normpath(path)
regex_cases_before = re.compile(r'((case|default).+\r?\n)\r?\n', re.MULTILINE) #Fixes newline after case before case body
regex_cases_after = re.compile(r'\r?\n(\r?\n[ \t]+(case|default))', re.MULTILINE) #Fixes newline after case body before new case
def updatefile(src_file):
global count
tmp_file = src_file + '.tmp'
count = 0
with open(src_file, 'r') as fh:
buf = fh.read()
def fix_cases(match):
global count
count += 1
return match.group(1)
buf = regex_cases_before.sub(fix_cases, buf)
buf = regex_cases_after.sub(fix_cases, buf)
if count > 0:
with open(tmp_file, 'w') as fh:
fh.write(buf)
shutil.move(tmp_file, src_file)
for path, _, filelist in os.walk(path, followlinks=True):
sub_dir = os.path.relpath(path, path)
for cur_file in fnmatch.filter(filelist, '*.java'):
src_file = os.path.normpath(os.path.join(path, cur_file))
updatefile(src_file)
if __name__ == '__main__':
main()
@@ -1,615 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.client;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.multiplayer.GuiConnecting;
import net.minecraft.client.multiplayer.NetClientHandler;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.resources.FileResourcePack;
import net.minecraft.client.resources.FolderResourcePack;
import net.minecraft.client.resources.ReloadableResourceManager;
import net.minecraft.client.resources.ResourcePack;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
import net.minecraft.crash.CrashReport;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet131MapData;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import cpw.mods.fml.client.modloader.ModLoaderClientHelper;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.DummyModContainer;
import cpw.mods.fml.common.DuplicateModsFoundException;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.IFMLSidedHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderException;
import cpw.mods.fml.common.MetadataCollection;
import cpw.mods.fml.common.MissingModsException;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.common.WrongMinecraftVersionException;
import cpw.mods.fml.common.network.EntitySpawnAdjustmentPacket;
import cpw.mods.fml.common.network.EntitySpawnPacket;
import cpw.mods.fml.common.network.ModMissingPacket;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData;
import cpw.mods.fml.common.registry.IThrowableEntity;
import cpw.mods.fml.common.registry.ItemData;
import cpw.mods.fml.common.registry.LanguageRegistry;
import cpw.mods.fml.common.toposort.ModSortingException;
import cpw.mods.fml.relauncher.Side;
/**
* Handles primary communication from hooked code into the system
*
* The FML entry point is {@link #beginMinecraftLoading(Minecraft, List)} called from
* {@link Minecraft}
*
* Obfuscated code should focus on this class and other members of the "server"
* (or "client") code
*
* The actual mod loading is handled at arms length by {@link Loader}
*
* It is expected that a similar class will exist for each target environment:
* Bukkit and Client side.
*
* It should not be directly modified.
*
* @author cpw
*
*/
public class FMLClientHandler implements IFMLSidedHandler
{
/**
* The singleton
*/
private static final FMLClientHandler INSTANCE = new FMLClientHandler();
/**
* A reference to the server itself
*/
private Minecraft client;
private DummyModContainer optifineContainer;
private boolean guiLoaded;
private boolean serverIsRunning;
private MissingModsException modsMissing;
private ModSortingException modSorting;
private boolean loading = true;
private WrongMinecraftVersionException wrongMC;
private CustomModLoadingErrorDisplayException customError;
private DuplicateModsFoundException dupesFound;
private boolean serverShouldBeKilledQuietly;
private List<ResourcePack> resourcePackList;
private ReloadableResourceManager resourceManager;
private Map<String, ResourcePack> resourcePackMap;
/**
* Called to start the whole game off
*
* @param minecraft The minecraft instance being launched
* @param resourcePackList The resource pack list we will populate with mods
* @param resourceManager The resource manager
*/
public void beginMinecraftLoading(Minecraft minecraft, List resourcePackList, ReloadableResourceManager resourceManager)
{
client = minecraft;
this.resourcePackList = resourcePackList;
this.resourceManager = resourceManager;
this.resourcePackMap = Maps.newHashMap();
if (minecraft.func_71355_q())
{
FMLLog.severe("DEMO MODE DETECTED, FML will not work. Finishing now.");
haltGame("FML will not run in demo mode", new RuntimeException());
return;
}
// TextureFXManager.instance().setClient(client);
FMLCommonHandler.instance().beginLoading(this);
new ModLoaderClientHelper(client);
try
{
Class<?> optifineConfig = Class.forName("Config", false, Loader.instance().getModClassLoader());
String optifineVersion = (String) optifineConfig.getField("VERSION").get(null);
Map<String,Object> dummyOptifineMeta = ImmutableMap.<String,Object>builder().put("name", "Optifine").put("version", optifineVersion).build();
ModMetadata optifineMetadata = MetadataCollection.from(getClass().getResourceAsStream("optifinemod.info"),"optifine").getMetadataForId("optifine", dummyOptifineMeta);
optifineContainer = new DummyModContainer(optifineMetadata);
FMLLog.info("Forge Mod Loader has detected optifine %s, enabling compatibility features",optifineContainer.getVersion());
}
catch (Exception e)
{
optifineContainer = null;
}
try
{
Loader.instance().loadMods();
}
catch (WrongMinecraftVersionException wrong)
{
wrongMC = wrong;
}
catch (DuplicateModsFoundException dupes)
{
dupesFound = dupes;
}
catch (MissingModsException missing)
{
modsMissing = missing;
}
catch (ModSortingException sorting)
{
modSorting = sorting;
}
catch (CustomModLoadingErrorDisplayException custom)
{
FMLLog.log(Level.SEVERE, custom, "A custom exception was thrown by a mod, the game will now halt");
customError = custom;
}
catch (LoaderException le)
{
haltGame("There was a severe problem during mod loading that has caused the game to fail", le);
return;
}
}
@Override
public void haltGame(String message, Throwable t)
{
client.func_71377_b(new CrashReport(message, t));
throw Throwables.propagate(t);
}
/**
* Called a bit later on during initialization to finish loading mods
* Also initializes key bindings
*
*/
@SuppressWarnings("deprecation")
public void finishMinecraftLoading()
{
if (modsMissing != null || wrongMC != null || customError!=null || dupesFound!=null || modSorting!=null)
{
return;
}
try
{
Loader.instance().initializeMods();
}
catch (CustomModLoadingErrorDisplayException custom)
{
FMLLog.log(Level.SEVERE, custom, "A custom exception was thrown by a mod, the game will now halt");
customError = custom;
return;
}
catch (LoaderException le)
{
haltGame("There was a severe problem during mod loading that has caused the game to fail", le);
return;
}
// Reload resources
client.func_110436_a();
RenderingRegistry.instance().loadEntityRenderers((Map<Class<? extends Entity>, Render>)RenderManager.field_78727_a.field_78729_o);
loading = false;
KeyBindingRegistry.instance().uploadKeyBindingsToGame(client.field_71474_y);
}
public void onInitializationComplete()
{
if (wrongMC != null)
{
client.func_71373_a(new GuiWrongMinecraft(wrongMC));
}
else if (modsMissing != null)
{
client.func_71373_a(new GuiModsMissing(modsMissing));
}
else if (dupesFound != null)
{
client.func_71373_a(new GuiDupesFound(dupesFound));
}
else if (modSorting != null)
{
client.func_71373_a(new GuiSortingProblem(modSorting));
}
else if (customError != null)
{
client.func_71373_a(new GuiCustomModLoadingErrorScreen(customError));
}
else
{
// Force renderengine to reload and re-initialize all textures
// client.field_71446_o.func_78352_b();
// TextureFXManager.instance().loadTextures(client.field_71418_C.func_77292_e());
}
}
/**
* Get the server instance
*/
public Minecraft getClient()
{
return client;
}
/**
* Get a handle to the client's logger instance
* The client actually doesn't have one- so we return null
*/
public Logger getMinecraftLogger()
{
return null;
}
/**
* @return the instance
*/
public static FMLClientHandler instance()
{
return INSTANCE;
}
/**
* @param player
* @param gui
*/
public void displayGuiScreen(EntityPlayer player, GuiScreen gui)
{
if (client.field_71439_g==player && gui != null) {
client.func_71373_a(gui);
}
}
/**
* @param mods
*/
public void addSpecialModEntries(ArrayList<ModContainer> mods)
{
if (optifineContainer!=null) {
mods.add(optifineContainer);
}
}
@Override
public List<String> getAdditionalBrandingInformation()
{
if (optifineContainer!=null)
{
return Arrays.asList(String.format("Optifine %s",optifineContainer.getVersion()));
} else {
return ImmutableList.<String>of();
}
}
@Override
public Side getSide()
{
return Side.CLIENT;
}
public boolean hasOptifine()
{
return optifineContainer!=null;
}
@Override
public void showGuiScreen(Object clientGuiElement)
{
GuiScreen gui = (GuiScreen) clientGuiElement;
client.func_71373_a(gui);
}
@Override
public Entity spawnEntityIntoClientWorld(EntityRegistration er, EntitySpawnPacket packet)
{
WorldClient wc = client.field_71441_e;
Class<? extends Entity> cls = er.getEntityClass();
try
{
Entity entity;
if (er.hasCustomSpawning())
{
entity = er.doCustomSpawning(packet);
}
else
{
entity = (Entity)(cls.getConstructor(World.class).newInstance(wc));
int offset = packet.entityId - entity.field_70157_k;
entity.field_70157_k = packet.entityId;
entity.func_70012_b(packet.scaledX, packet.scaledY, packet.scaledZ, packet.scaledYaw, packet.scaledPitch);
if (entity instanceof EntityLiving)
{
((EntityLiving)entity).field_70759_as = packet.scaledHeadYaw;
}
Entity parts[] = entity.func_70021_al();
if (parts != null)
{
for (int j = 0; j < parts.length; j++)
{
parts[j].field_70157_k += offset;
}
}
}
entity.field_70118_ct = packet.rawX;
entity.field_70117_cu = packet.rawY;
entity.field_70116_cv = packet.rawZ;
if (entity instanceof IThrowableEntity)
{
Entity thrower = client.field_71439_g.field_70157_k == packet.throwerId ? client.field_71439_g : wc.func_73045_a(packet.throwerId);
((IThrowableEntity)entity).setThrower(thrower);
}
if (packet.metadata != null)
{
entity.func_70096_w().func_75687_a((List)packet.metadata);
}
if (packet.throwerId > 0)
{
entity.func_70016_h(packet.speedScaledX, packet.speedScaledY, packet.speedScaledZ);
}
if (entity instanceof IEntityAdditionalSpawnData)
{
((IEntityAdditionalSpawnData)entity).readSpawnData(packet.dataStream);
}
wc.func_73027_a(packet.entityId, entity);
return entity;
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "A severe problem occurred during the spawning of an entity");
throw Throwables.propagate(e);
}
}
@Override
public void adjustEntityLocationOnClient(EntitySpawnAdjustmentPacket packet)
{
Entity ent = client.field_71441_e.func_73045_a(packet.entityId);
if (ent != null)
{
ent.field_70118_ct = packet.serverX;
ent.field_70117_cu = packet.serverY;
ent.field_70116_cv = packet.serverZ;
}
else
{
FMLLog.fine("Attempted to adjust the position of entity %d which is not present on the client", packet.entityId);
}
}
@Override
public void beginServerLoading(MinecraftServer server)
{
serverShouldBeKilledQuietly = false;
// NOOP
}
@Override
public void finishServerLoading()
{
// NOOP
}
@Override
public MinecraftServer getServer()
{
return client.func_71401_C();
}
@Override
public void sendPacket(Packet packet)
{
if(client.field_71439_g != null)
{
client.field_71439_g.field_71174_a.func_72552_c(packet);
}
}
@Override
public void displayMissingMods(ModMissingPacket modMissingPacket)
{
client.func_71373_a(new GuiModsMissingForServer(modMissingPacket));
}
/**
* If the client is in the midst of loading, we disable saving so that custom settings aren't wiped out
*/
public boolean isLoading()
{
return loading;
}
@Override
public void handleTinyPacket(NetHandler handler, Packet131MapData mapData)
{
((NetClientHandler)handler).fmlPacket131Callback(mapData);
}
@Override
public void setClientCompatibilityLevel(byte compatibilityLevel)
{
NetClientHandler.setConnectionCompatibilityLevel(compatibilityLevel);
}
@Override
public byte getClientCompatibilityLevel()
{
return NetClientHandler.getConnectionCompatibilityLevel();
}
public void warnIDMismatch(MapDifference<Integer, ItemData> idDifferences, boolean mayContinue)
{
GuiIdMismatchScreen mismatch = new GuiIdMismatchScreen(idDifferences, mayContinue);
client.func_71373_a(mismatch);
}
public void callbackIdDifferenceResponse(boolean response)
{
if (response)
{
serverShouldBeKilledQuietly = false;
GameData.releaseGate(true);
client.continueWorldLoading();
}
else
{
serverShouldBeKilledQuietly = true;
GameData.releaseGate(false);
// Reset and clear the client state
client.func_71403_a((WorldClient)null);
client.func_71373_a(null);
}
}
@Override
public boolean shouldServerShouldBeKilledQuietly()
{
return serverShouldBeKilledQuietly;
}
@Override
public void disconnectIDMismatch(MapDifference<Integer, ItemData> s, NetHandler toKill, INetworkManager mgr)
{
boolean criticalMismatch = !s.entriesOnlyOnLeft().isEmpty();
for (Entry<Integer, ValueDifference<ItemData>> mismatch : s.entriesDiffering().entrySet())
{
ValueDifference<ItemData> vd = mismatch.getValue();
if (!vd.leftValue().mayDifferByOrdinal(vd.rightValue()))
{
criticalMismatch = true;
}
}
if (!criticalMismatch)
{
// We'll carry on with this connection, and just log a message instead
return;
}
// Nuke the connection
((NetClientHandler)toKill).func_72553_e();
// Stop GuiConnecting
GuiConnecting.forceTermination((GuiConnecting)client.field_71462_r);
// pulse the network manager queue to clear cruft
mgr.func_74428_b();
// Nuke the world client
client.func_71403_a((WorldClient)null);
// Show error screen
warnIDMismatch(s, false);
}
/**
* Is this GUI type open?
*
* @param gui The type of GUI to test for
* @return if a GUI of this type is open
*/
public boolean isGUIOpen(Class<? extends GuiScreen> gui)
{
return client.field_71462_r != null && client.field_71462_r.getClass().equals(gui);
}
@Override
public void addModAsResource(ModContainer container)
{
Class<?> resourcePackType = container.getCustomResourcePackClass();
if (resourcePackType != null)
{
try
{
ResourcePack pack = (ResourcePack) resourcePackType.getConstructor(ModContainer.class).newInstance(container);
resourcePackList.add(pack);
resourcePackMap.put(container.getModId(), pack);
}
catch (NoSuchMethodException e)
{
FMLLog.log(Level.SEVERE, "The container %s (type %s) returned an invalid class for it's resource pack.", container.getName(), container.getClass().getName());
return;
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "An unexpected exception occurred constructing the custom resource pack for %s", container.getName());
throw Throwables.propagate(e);
}
}
}
@Override
public void updateResourcePackList()
{
client.func_110436_a();
}
public ResourcePack getResourcePackFor(String modId)
{
return resourcePackMap.get(modId);
}
@Override
public String getCurrentLanguage()
{
return client.func_135016_M().func_135041_c().func_135034_a();
}
}
@@ -1,108 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.StringTranslate;
import com.google.common.collect.Lists;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import cpw.mods.fml.common.registry.ItemData;
import cpw.mods.fml.common.versioning.ArtifactVersion;
public class GuiIdMismatchScreen extends GuiYesNo {
private List<String> missingIds = Lists.newArrayList();
private List<String> mismatchedIds = Lists.newArrayList();
private boolean allowContinue;
public GuiIdMismatchScreen(MapDifference<Integer, ItemData> idDifferences, boolean allowContinue)
{
super(null,"ID mismatch", "Should I continue?", 1);
field_73942_a = this;
for (Entry<Integer, ItemData> entry : idDifferences.entriesOnlyOnLeft().entrySet())
{
missingIds.add(String.format("ID %d from Mod %s is missing", entry.getValue().getItemId(), entry.getValue().getModId(), entry.getValue().getItemType()));
}
for (Entry<Integer, ValueDifference<ItemData>> entry : idDifferences.entriesDiffering().entrySet())
{
ItemData world = entry.getValue().leftValue();
ItemData game = entry.getValue().rightValue();
mismatchedIds.add(String.format("ID %d is mismatched between world and game", world.getItemId()));
}
this.allowContinue = allowContinue;
}
@Override
public void func_73878_a(boolean choice, int p_73878_2_)
{
FMLClientHandler.instance().callbackIdDifferenceResponse(choice);
}
@Override
public void func_73863_a(int p_73863_1_, int p_73863_2_, float p_73863_3_)
{
this.func_73873_v_();
if (!allowContinue && field_73887_h.size() == 2)
{
field_73887_h.remove(0);
}
int offset = Math.max(85 - (missingIds.size() + mismatchedIds.size()) * 10, 30);
this.func_73732_a(this.field_73886_k, "Forge Mod Loader has found ID mismatches", this.field_73880_f / 2, 10, 0xFFFFFF);
this.func_73732_a(this.field_73886_k, "Complete details are in the log file", this.field_73880_f / 2, 20, 0xFFFFFF);
int maxLines = 20;
for (String s: missingIds) {
this.func_73732_a(this.field_73886_k, s, this.field_73880_f / 2, offset, 0xEEEEEE);
offset += 10;
maxLines --;
if (maxLines < 0) break;
if (offset >= this.field_73881_g - 30) break;
}
if (maxLines > 0 && offset < this.field_73881_g - 30)
{
for (String s: mismatchedIds) {
this.func_73732_a(this.field_73886_k, s, this.field_73880_f / 2, offset, 0xEEEEEE);
offset += 10;
maxLines --;
if (maxLines < 0) break;
if (offset >= this.field_73881_g - 30) break;
}
}
if (allowContinue)
{
this.func_73732_a(this.field_73886_k, "Do you wish to continue loading?", this.field_73880_f / 2, this.field_73881_g - 30, 0xFFFFFF);
}
else
{
this.func_73732_a(this.field_73886_k, "You cannot connect to this server", this.field_73880_f / 2, this.field_73881_g - 30, 0xFFFFFF);
}
// super.super. Grrr
for (int var4 = 0; var4 < this.field_73887_h.size(); ++var4)
{
GuiButton var5 = (GuiButton)this.field_73887_h.get(var4);
var5.field_73743_d = this.field_73881_g - 20;
if (!allowContinue)
{
var5.field_73746_c = this.field_73880_f / 2 - 75;
var5.field_73744_e = I18n.func_135053_a("gui.done");
}
var5.func_73737_a(this.field_73882_e, p_73863_1_, p_73863_2_);
}
}
}
-236
View File
@@ -1,236 +0,0 @@
/*
* The FML Forge Mod Loader suite.
* Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.client;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiSmallButton;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureObject;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.resources.ResourcePack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StringTranslate;
import org.lwjgl.opengl.GL11;
import com.google.common.base.Strings;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
/**
* @author cpw
*
*/
public class GuiModList extends GuiScreen
{
private GuiScreen mainMenu;
private GuiSlotModList modList;
private int selected = -1;
private ModContainer selectedMod;
private int listWidth;
private ArrayList<ModContainer> mods;
/**
* @param mainMenu
*/
public GuiModList(GuiScreen mainMenu)
{
this.mainMenu=mainMenu;
this.mods=new ArrayList<ModContainer>();
FMLClientHandler.instance().addSpecialModEntries(mods);
for (ModContainer mod : Loader.instance().getModList()) {
if (mod.getMetadata()!=null && mod.getMetadata().parentMod==null && !Strings.isNullOrEmpty(mod.getMetadata().parent)) {
String parentMod = mod.getMetadata().parent;
ModContainer parentContainer = Loader.instance().getIndexedModList().get(parentMod);
if (parentContainer != null)
{
mod.getMetadata().parentMod = parentContainer;
parentContainer.getMetadata().childMods.add(mod);
continue;
}
}
else if (mod.getMetadata()!=null && mod.getMetadata().parentMod!=null)
{
continue;
}
mods.add(mod);
}
}
@Override
public void func_73866_w_()
{
for (ModContainer mod : mods) {
listWidth=Math.max(listWidth,getFontRenderer().func_78256_a(mod.getName()) + 10);
listWidth=Math.max(listWidth,getFontRenderer().func_78256_a(mod.getVersion()) + 10);
}
listWidth=Math.min(listWidth, 150);
this.field_73887_h.add(new GuiSmallButton(6, this.field_73880_f / 2 - 75, this.field_73881_g - 38, I18n.func_135053_a("gui.done")));
this.modList=new GuiSlotModList(this, mods, listWidth);
this.modList.registerScrollButtons(this.field_73887_h, 7, 8);
}
@Override
protected void func_73875_a(GuiButton button) {
if (button.field_73742_g)
{
switch (button.field_73741_f)
{
case 6:
this.field_73882_e.func_71373_a(this.mainMenu);
return;
}
}
super.func_73875_a(button);
}
public int drawLine(String line, int offset, int shifty)
{
int r = this.field_73886_k.func_78276_b(line, offset, shifty, 0xd7edea);
return shifty + 10;
}
@Override
public void func_73863_a(int p_571_1_, int p_571_2_, float p_571_3_)
{
this.modList.drawScreen(p_571_1_, p_571_2_, p_571_3_);
this.func_73732_a(this.field_73886_k, "Mod List", this.field_73880_f / 2, 16, 0xFFFFFF);
int offset = this.listWidth + 20;
if (selectedMod != null) {
GL11.glEnable(GL11.GL_BLEND);
if (!selectedMod.getMetadata().autogenerated) {
int shifty = 35;
String logoFile = selectedMod.getMetadata().logoFile;
if (!logoFile.isEmpty())
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
TextureManager tm = field_73882_e.func_110434_K();
ResourcePack pack = FMLClientHandler.instance().getResourcePackFor(selectedMod.getModId());
try
{
BufferedImage logo = null;
if (pack!=null)
{
logo = pack.func_110586_a();
}
else
{
InputStream logoResource = getClass().getResourceAsStream(logoFile);
if (logoResource != null)
{
logo = ImageIO.read(logoResource);
}
}
if (logo != null)
{
ResourceLocation rl = tm.func_110578_a("modlogo", new DynamicTexture(logo));
this.field_73882_e.field_71446_o.func_110577_a(rl);
Dimension dim = new Dimension(logo.getWidth(), logo.getHeight());
double scaleX = dim.width / 200.0;
double scaleY = dim.height / 65.0;
double scale = 1.0;
if (scaleX > 1 || scaleY > 1)
{
scale = 1.0 / Math.max(scaleX, scaleY);
}
dim.width *= scale;
dim.height *= scale;
int top = 32;
Tessellator tess = Tessellator.field_78398_a;
tess.func_78382_b();
tess.func_78374_a(offset, top + dim.height, field_73735_i, 0, 1);
tess.func_78374_a(offset + dim.width, top + dim.height, field_73735_i, 1, 1);
tess.func_78374_a(offset + dim.width, top, field_73735_i, 1, 0);
tess.func_78374_a(offset, top, field_73735_i, 0, 0);
tess.func_78381_a();
shifty += 65;
}
}
catch (IOException e)
{
;
}
}
this.field_73886_k.func_78261_a(selectedMod.getMetadata().name, offset, shifty, 0xFFFFFF);
shifty += 12;
shifty = drawLine(String.format("Version: %s (%s)", selectedMod.getDisplayVersion(), selectedMod.getVersion()), offset, shifty);
shifty = drawLine(String.format("Mod ID: '%s' Mod State: %s", selectedMod.getModId(), Loader.instance().getModState(selectedMod)), offset, shifty);
if (!selectedMod.getMetadata().credits.isEmpty()) {
shifty = drawLine(String.format("Credits: %s", selectedMod.getMetadata().credits), offset, shifty);
}
shifty = drawLine(String.format("Authors: %s", selectedMod.getMetadata().getAuthorList()), offset, shifty);
shifty = drawLine(String.format("URL: %s", selectedMod.getMetadata().url), offset, shifty);
shifty = drawLine(selectedMod.getMetadata().childMods.isEmpty() ? "No child mods for this mod" : String.format("Child mods: %s", selectedMod.getMetadata().getChildModList()), offset, shifty);
int rightSide = this.field_73880_f - offset - 20;
if (rightSide > 20)
{
this.getFontRenderer().func_78279_b(selectedMod.getMetadata().description, offset, shifty + 10, rightSide, 0xDDDDDD);
}
} else {
offset = ( this.listWidth + this.field_73880_f ) / 2;
this.func_73732_a(this.field_73886_k, selectedMod.getName(), offset, 35, 0xFFFFFF);
this.func_73732_a(this.field_73886_k, String.format("Version: %s",selectedMod.getVersion()), offset, 45, 0xFFFFFF);
this.func_73732_a(this.field_73886_k, String.format("Mod State: %s",Loader.instance().getModState(selectedMod)), offset, 55, 0xFFFFFF);
this.func_73732_a(this.field_73886_k, "No mod information found", offset, 65, 0xDDDDDD);
this.func_73732_a(this.field_73886_k, "Ask your mod author to provide a mod mcmod.info file", offset, 75, 0xDDDDDD);
}
GL11.glDisable(GL11.GL_BLEND);
}
super.func_73863_a(p_571_1_, p_571_2_, p_571_3_);
}
Minecraft getMinecraftInstance() {
return field_73882_e;
}
FontRenderer getFontRenderer() {
return field_73886_k;
}
/**
* @param var1
*/
public void selectModIndex(int var1)
{
this.selected=var1;
if (var1>=0 && var1<=mods.size()) {
this.selectedMod=mods.get(selected);
} else {
this.selectedMod=null;
}
}
public boolean modIndexSelected(int var1)
{
return var1==selected;
}
}
@@ -1,64 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiSmallButton;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.StringTranslate;
import cpw.mods.fml.common.network.ModMissingPacket;
import cpw.mods.fml.common.versioning.ArtifactVersion;
public class GuiModsMissingForServer extends GuiScreen
{
private ModMissingPacket modsMissing;
public GuiModsMissingForServer(ModMissingPacket modsMissing)
{
this.modsMissing = modsMissing;
}
@Override
public void func_73866_w_()
{
this.field_73887_h.add(new GuiSmallButton(1, this.field_73880_f / 2 - 75, this.field_73881_g - 38, I18n.func_135053_a("gui.done")));
}
@Override
protected void func_73875_a(GuiButton p_73875_1_)
{
if (p_73875_1_.field_73742_g && p_73875_1_.field_73741_f == 1)
{
FMLClientHandler.instance().getClient().func_71373_a(null);
}
}
@Override
public void func_73863_a(int p_73863_1_, int p_73863_2_, float p_73863_3_)
{
this.func_73873_v_();
int offset = Math.max(85 - modsMissing.getModList().size() * 10, 10);
this.func_73732_a(this.field_73886_k, "Forge Mod Loader could not connect to this server", this.field_73880_f / 2, offset, 0xFFFFFF);
offset += 10;
this.func_73732_a(this.field_73886_k, "The mods and versions listed below could not be found", this.field_73880_f / 2, offset, 0xFFFFFF);
offset += 10;
this.func_73732_a(this.field_73886_k, "They are required to play on this server", this.field_73880_f / 2, offset, 0xFFFFFF);
offset += 5;
for (ArtifactVersion v : modsMissing.getModList())
{
offset += 10;
this.func_73732_a(this.field_73886_k, String.format("%s : %s", v.getLabel(), v.getRangeString()), this.field_73880_f / 2, offset, 0xEEEEEE);
}
super.func_73863_a(p_73863_1_, p_73863_2_, p_73863_3_);
}
}
@@ -1,48 +0,0 @@
package cpw.mods.fml.client;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.toposort.ModSortingException;
import cpw.mods.fml.common.toposort.ModSortingException.SortingExceptionData;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import net.minecraft.client.gui.GuiScreen;
public class GuiSortingProblem extends GuiScreen {
private ModSortingException modSorting;
private SortingExceptionData<ModContainer> failedList;
public GuiSortingProblem(ModSortingException modSorting)
{
this.modSorting = modSorting;
this.failedList = modSorting.getExceptionData();
}
@Override
public void func_73866_w_()
{
super.func_73866_w_();
}
@Override
public void func_73863_a(int p_73863_1_, int p_73863_2_, float p_73863_3_)
{
this.func_73873_v_();
int offset = Math.max(85 - (failedList.getVisitedNodes().size() + 3) * 10, 10);
this.func_73732_a(this.field_73886_k, "Forge Mod Loader has found a problem with your minecraft installation", this.field_73880_f / 2, offset, 0xFFFFFF);
offset+=10;
this.func_73732_a(this.field_73886_k, "A mod sorting cycle was detected and loading cannot continue", this.field_73880_f / 2, offset, 0xFFFFFF);
offset+=10;
this.func_73732_a(this.field_73886_k, String.format("The first mod in the cycle is %s", failedList.getFirstBadNode()), this.field_73880_f / 2, offset, 0xFFFFFF);
offset+=10;
this.func_73732_a(this.field_73886_k, "The remainder of the cycle involves these mods", this.field_73880_f / 2, offset, 0xFFFFFF);
offset+=5;
for (ModContainer mc : failedList.getVisitedNodes())
{
offset+=10;
this.func_73732_a(this.field_73886_k, String.format("%s : before: %s, after: %s", mc.toString(), mc.getDependants(), mc.getDependencies()), this.field_73880_f / 2, offset, 0xEEEEEE);
}
offset+=20;
this.func_73732_a(this.field_73886_k, "The file 'ForgeModLoader-client-0.log' contains more information", this.field_73880_f / 2, offset, 0xFFFFFF);
}
}
@@ -1,47 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client;
import net.minecraft.client.gui.GuiErrorScreen;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.WrongMinecraftVersionException;
import cpw.mods.fml.common.versioning.ArtifactVersion;
public class GuiWrongMinecraft extends GuiErrorScreen
{
private WrongMinecraftVersionException wrongMC;
public GuiWrongMinecraft(WrongMinecraftVersionException wrongMC)
{
super(null,null);
this.wrongMC = wrongMC;
}
@Override
public void func_73866_w_()
{
super.func_73866_w_();
}
@Override
public void func_73863_a(int p_73863_1_, int p_73863_2_, float p_73863_3_)
{
this.func_73873_v_();
int offset = 75;
this.func_73732_a(this.field_73886_k, "Forge Mod Loader has found a problem with your minecraft installation", this.field_73880_f / 2, offset, 0xFFFFFF);
offset+=10;
this.func_73732_a(this.field_73886_k, String.format("The mod listed below does not want to run in Minecraft version %s", Loader.instance().getMinecraftModContainer().getVersion()), this.field_73880_f / 2, offset, 0xFFFFFF);
offset+=5;
offset+=10;
this.func_73732_a(this.field_73886_k, String.format("%s (%s) wants Minecraft %s", wrongMC.mod.getName(), wrongMC.mod.getModId(), wrongMC.mod.acceptableMinecraftVersionRange()), this.field_73880_f / 2, offset, 0xEEEEEE);
offset+=20;
this.func_73732_a(this.field_73886_k, "The file 'ForgeModLoader-client-0.log' contains more information", this.field_73880_f / 2, offset, 0xFFFFFF);
}
}
@@ -1,142 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.imageio.ImageIO;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.GLContext;
import com.google.common.collect.Maps;
import cpw.mods.fml.common.FMLLog;
import net.minecraft.client.Minecraft;
public class TextureFXManager
{
private static final TextureFXManager INSTANCE = new TextureFXManager();
private Minecraft client;
private Map<Integer,TextureHolder> texturesById = Maps.newHashMap();
private Map<String, TextureHolder> texturesByName = Maps.newHashMap();
// private TextureHelper helper;
void setClient(Minecraft client)
{
this.client = client;
}
// public BufferedImage loadImageFromTexturePack(RenderEngine renderEngine, String path) throws IOException
// {
// InputStream image=client.field_71418_C.func_77292_e().func_77532_a(path);
// if (image==null) {
// throw new RuntimeException(String.format("The requested image path %s is not found",path));
// }
// BufferedImage result=ImageIO.read(image);
// if (result==null)
// {
// throw new RuntimeException(String.format("The requested image path %s appears to be corrupted",path));
// }
// return result;
// }
//
public static TextureFXManager instance()
{
return INSTANCE;
}
public void fixTransparency(BufferedImage loadedImage, String textureName)
{
if (textureName.matches("^/mob/.*_eyes.*.png$"))
{
for (int x = 0; x < loadedImage.getWidth(); x++) {
for (int y = 0; y < loadedImage.getHeight(); y++) {
int argb = loadedImage.getRGB(x, y);
if ((argb & 0xff000000) == 0 && argb != 0) {
loadedImage.setRGB(x, y, 0);
}
}
}
}
}
public void bindTextureToName(String name, int index)
{
TextureHolder holder = new TextureHolder();
holder.textureId = index;
holder.textureName = name;
texturesById.put(index,holder);
texturesByName.put(name,holder);
}
public void setTextureDimensions(int index, int j, int k)
{
TextureHolder holder = texturesById.get(index);
if (holder == null)
{
return;
}
holder.x = j;
holder.y = k;
}
private class TextureHolder {
private int textureId;
private String textureName;
private int x;
private int y;
}
public Dimension getTextureDimensions(String texture)
{
return texturesByName.containsKey(texture) ? new Dimension(texturesByName.get(texture).x, texturesByName.get(texture).y) : new Dimension(1,1);
}
// public TextureHelper getHelper()
// {
// if (helper == null)
// {
// ContextCapabilities capabilities = GLContext.getCapabilities();
// boolean has43 = false;
// try
// {
// has43 = capabilities.getClass().getField("GL_ARB_copy_image").getBoolean(capabilities);
// }
// catch (Exception e)
// {
// //e.printStackTrace();
// // NOOP - LWJGL needs updating
// FMLLog.info("Forge Mod Loader has detected an older LWJGL version, new advanced texture animation features are disabled");
// }
//// if (has43 && Boolean.parseBoolean(System.getProperty("fml.useGL43","true")))
//// {
//// FMLLog.info("Using the new OpenGL 4.3 advanced capability for animations");
//// helper = new OpenGL43TextureHelper();
//// }
//// else
// {
// FMLLog.info("Not using advanced OpenGL 4.3 advanced capability for animations : OpenGL 4.3 is %s", has43 ? "available" : "not available");
//// helper = new CopySubimageTextureHelper();
// }
// }
// return helper;
// }
}
@@ -1,81 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client.modloader;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.src.BaseMod;
import net.minecraft.world.IBlockAccess;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
/**
* @author cpw
*
*/
public class ModLoaderBlockRendererHandler implements ISimpleBlockRenderingHandler
{
private int renderId;
private boolean render3dInInventory;
private BaseMod mod;
/**
* @param mod
*
*/
public ModLoaderBlockRendererHandler(int renderId, boolean render3dInInventory, BaseMod mod)
{
this.renderId=renderId;
this.render3dInInventory=render3dInInventory;
this.mod=mod;
}
@Override
public int getRenderId()
{
return renderId;
}
@Override
public boolean shouldRender3DInInventory()
{
return render3dInInventory;
}
/**
* @param world
* @param x
* @param y
* @param z
* @param block
* @param modelId
* @param renderer
*/
@Override
public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
return mod.renderWorldBlock(renderer, world, x, y, z, block, modelId);
}
/**
* @param block
* @param metadata
* @param modelID
* @param renderer
*/
@Override
public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer)
{
mod.renderInvBlock(renderer, block, metadata, modelID);
}
}
@@ -1,190 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client.modloader;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import net.minecraft.client.Minecraft;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.src.BaseMod;
import net.minecraft.client.*;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.multiplayer.NetClientHandler;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import com.google.common.base.Equivalence;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.modloader.BaseModProxy;
import cpw.mods.fml.common.modloader.IModLoaderSidedHelper;
import cpw.mods.fml.common.modloader.ModLoaderHelper;
import cpw.mods.fml.common.modloader.ModLoaderModContainer;
import cpw.mods.fml.common.network.EntitySpawnPacket;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
public class ModLoaderClientHelper implements IModLoaderSidedHelper
{
public static int obtainBlockModelIdFor(BaseMod mod, boolean inventoryRenderer)
{
int renderId=RenderingRegistry.getNextAvailableRenderId();
ModLoaderBlockRendererHandler bri=new ModLoaderBlockRendererHandler(renderId, inventoryRenderer, mod);
RenderingRegistry.registerBlockHandler(bri);
return renderId;
}
public static void handleFinishLoadingFor(ModLoaderModContainer mc, Minecraft game)
{
FMLLog.log(mc.getModId(), Level.FINE, "Handling post startup activities for ModLoader mod %s", mc.getModId());
BaseMod mod = (BaseMod) mc.getMod();
Map<Class<? extends Entity>, Render> renderers = Maps.newHashMap(RenderManager.field_78727_a.field_78729_o);
try
{
FMLLog.log(mc.getModId(), Level.FINEST, "Requesting renderers from basemod %s", mc.getModId());
mod.addRenderer(renderers);
FMLLog.log(mc.getModId(), Level.FINEST, "Received %d renderers from basemod %s", renderers.size(), mc.getModId());
}
catch (Exception e)
{
FMLLog.log(mc.getModId(), Level.SEVERE, e, "A severe problem was detected with the mod %s during the addRenderer call. Continuing, but expect odd results", mc.getModId());
}
MapDifference<Class<? extends Entity>, Render> difference = Maps.difference(RenderManager.field_78727_a.field_78729_o, renderers, Equivalence.identity());
for ( Entry<Class<? extends Entity>, Render> e : difference.entriesOnlyOnLeft().entrySet())
{
FMLLog.log(mc.getModId(), Level.WARNING, "The mod %s attempted to remove an entity renderer %s from the entity map. This will be ignored.", mc.getModId(), e.getKey().getName());
}
for (Entry<Class<? extends Entity>, Render> e : difference.entriesOnlyOnRight().entrySet())
{
FMLLog.log(mc.getModId(), Level.FINEST, "Registering ModLoader entity renderer %s as instance of %s", e.getKey().getName(), e.getValue().getClass().getName());
RenderingRegistry.registerEntityRenderingHandler(e.getKey(), e.getValue());
}
for (Entry<Class<? extends Entity>, ValueDifference<Render>> e : difference.entriesDiffering().entrySet())
{
FMLLog.log(mc.getModId(), Level.FINEST, "Registering ModLoader entity rendering override for %s as instance of %s", e.getKey().getName(), e.getValue().rightValue().getClass().getName());
RenderingRegistry.registerEntityRenderingHandler(e.getKey(), e.getValue().rightValue());
}
try
{
mod.registerAnimation(game);
}
catch (Exception e)
{
FMLLog.log(mc.getModId(), Level.SEVERE, e, "A severe problem was detected with the mod %s during the registerAnimation call. Continuing, but expect odd results", mc.getModId());
}
}
public ModLoaderClientHelper(Minecraft client)
{
this.client = client;
ModLoaderHelper.sidedHelper = this;
keyBindingContainers = Multimaps.newMultimap(Maps.<ModLoaderModContainer, Collection<ModLoaderKeyBindingHandler>>newHashMap(), new Supplier<Collection<ModLoaderKeyBindingHandler>>()
{
@Override
public Collection<ModLoaderKeyBindingHandler> get()
{
return Collections.singleton(new ModLoaderKeyBindingHandler());
}
});
}
private Minecraft client;
private static Multimap<ModLoaderModContainer, ModLoaderKeyBindingHandler> keyBindingContainers;
@Override
public void finishModLoading(ModLoaderModContainer mc)
{
handleFinishLoadingFor(mc, client);
}
public static void registerKeyBinding(BaseModProxy mod, KeyBinding keyHandler, boolean allowRepeat)
{
ModLoaderModContainer mlmc = (ModLoaderModContainer) Loader.instance().activeModContainer();
ModLoaderKeyBindingHandler handler = Iterables.getOnlyElement(keyBindingContainers.get(mlmc));
handler.setModContainer(mlmc);
handler.addKeyBinding(keyHandler, allowRepeat);
KeyBindingRegistry.registerKeyBinding(handler);
}
@Override
public Object getClientGui(BaseModProxy mod, EntityPlayer player, int ID, int x, int y, int z)
{
return ((net.minecraft.src.BaseMod)mod).getContainerGUI((EntityClientPlayerMP) player, ID, x, y, z);
}
@Override
public Entity spawnEntity(BaseModProxy mod, EntitySpawnPacket input, EntityRegistration er)
{
return ((net.minecraft.src.BaseMod)mod).spawnEntity(er.getModEntityId(), client.field_71441_e, input.scaledX, input.scaledY, input.scaledZ);
}
@Override
public void sendClientPacket(BaseModProxy mod, Packet250CustomPayload packet)
{
((net.minecraft.src.BaseMod)mod).clientCustomPayload(client.field_71439_g.field_71174_a, packet);
}
private Map<INetworkManager,NetHandler> managerLookups = new MapMaker().weakKeys().weakValues().makeMap();
@Override
public void clientConnectionOpened(NetHandler netClientHandler, INetworkManager manager, BaseModProxy mod)
{
managerLookups.put(manager, netClientHandler);
((BaseMod)mod).clientConnect((NetClientHandler)netClientHandler);
}
@Override
public boolean clientConnectionClosed(INetworkManager manager, BaseModProxy mod)
{
if (managerLookups.containsKey(manager))
{
((BaseMod)mod).clientDisconnect((NetClientHandler) managerLookups.get(manager));
return true;
}
return false;
}
}
@@ -1,110 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client.modloader;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import org.lwjgl.input.Mouse;
import com.google.common.collect.ObjectArrays;
import com.google.common.primitives.Booleans;
import net.minecraft.client.settings.KeyBinding;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.modloader.ModLoaderModContainer;
/**
* @author cpw
*
*/
public class ModLoaderKeyBindingHandler extends KeyBindingRegistry.KeyHandler
{
private ModLoaderModContainer modContainer;
private List<KeyBinding> helper;
private boolean[] active = new boolean[0];
private boolean[] mlRepeats = new boolean[0];
private boolean[] armed = new boolean[0];
public ModLoaderKeyBindingHandler()
{
super(new KeyBinding[0], new boolean[0]);
}
void setModContainer(ModLoaderModContainer modContainer)
{
this.modContainer = modContainer;
}
public void fireKeyEvent(KeyBinding kb)
{
((net.minecraft.src.BaseMod)modContainer.getMod()).keyboardEvent(kb);
}
@Override
public void keyDown(EnumSet<TickType> type, KeyBinding kb, boolean end, boolean repeats)
{
if (!end)
{
return;
}
int idx = helper.indexOf(kb);
if (type.contains(TickType.CLIENT))
{
armed[idx] = true;
}
if (armed[idx] && type.contains(TickType.RENDER) && (!active[idx] || mlRepeats[idx]))
{
fireKeyEvent(kb);
active[idx] = true;
armed[idx] = false;
}
}
@Override
public void keyUp(EnumSet<TickType> type, KeyBinding kb, boolean end)
{
if (!end)
{
return;
}
int idx = helper.indexOf(kb);
active[idx] = false;
}
@Override
public EnumSet<TickType> ticks()
{
return EnumSet.of(TickType.CLIENT, TickType.RENDER);
}
@Override
public String getLabel()
{
return modContainer.getModId() +" KB "+keyBindings[0].field_74512_d;
}
void addKeyBinding(KeyBinding binding, boolean repeats)
{
this.keyBindings = ObjectArrays.concat(this.keyBindings, binding);
this.repeatings = new boolean[this.keyBindings.length];
Arrays.fill(this.repeatings, true);
this.active = new boolean[this.keyBindings.length];
this.armed = new boolean[this.keyBindings.length];
this.mlRepeats = Booleans.concat(this.mlRepeats, new boolean[] { repeats });
this.keyDown = new boolean[this.keyBindings.length];
this.helper = Arrays.asList(this.keyBindings);
}
}
@@ -1,203 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.client.registry;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Set;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
public class KeyBindingRegistry
{
/**
* Register a KeyHandler to the game. This handler will be called on certain tick events
* if any of its key is inactive or has recently changed state
*
* @param handler
*/
public static void registerKeyBinding(KeyHandler handler) {
instance().keyHandlers.add(handler);
if (!handler.isDummy)
{
TickRegistry.registerTickHandler(handler, Side.CLIENT);
}
}
/**
* Extend this class to register a KeyBinding and recieve callback
* when the key binding is triggered
*
* @author cpw
*
*/
public static abstract class KeyHandler implements ITickHandler
{
protected KeyBinding[] keyBindings;
protected boolean[] keyDown;
protected boolean[] repeatings;
private boolean isDummy;
/**
* Pass an array of keybindings and a repeat flag for each one
*
* @param keyBindings
* @param repeatings
*/
public KeyHandler(KeyBinding[] keyBindings, boolean[] repeatings)
{
assert keyBindings.length == repeatings.length : "You need to pass two arrays of identical length";
this.keyBindings = keyBindings;
this.repeatings = repeatings;
this.keyDown = new boolean[keyBindings.length];
}
/**
* Register the keys into the system. You will do your own keyboard management elsewhere. No events will fire
* if you use this method
*
* @param keyBindings
*/
public KeyHandler(KeyBinding[] keyBindings)
{
this.keyBindings = keyBindings;
this.isDummy = true;
}
public KeyBinding[] getKeyBindings()
{
return this.keyBindings;
}
/**
* Not to be overridden - KeyBindings are tickhandlers under the covers
*/
@Override
public final void tickStart(EnumSet<TickType> type, Object... tickData)
{
keyTick(type, false);
}
/**
* Not to be overridden - KeyBindings are tickhandlers under the covers
*/
@Override
public final void tickEnd(EnumSet<TickType> type, Object... tickData)
{
keyTick(type, true);
}
private void keyTick(EnumSet<TickType> type, boolean tickEnd)
{
for (int i = 0; i < keyBindings.length; i++)
{
KeyBinding keyBinding = keyBindings[i];
int keyCode = keyBinding.field_74512_d;
boolean state = (keyCode < 0 ? Mouse.isButtonDown(keyCode + 100) : Keyboard.isKeyDown(keyCode));
if (state != keyDown[i] || (state && repeatings[i]))
{
if (state)
{
keyDown(type, keyBinding, tickEnd, state!=keyDown[i]);
}
else
{
keyUp(type, keyBinding, tickEnd);
}
if (tickEnd)
{
keyDown[i] = state;
}
}
}
}
/**
* Called when the key is first in the down position on any tick from the {@link #ticks()}
* set. Will be called subsequently with isRepeat set to true
*
* @see #keyUp(EnumSet, KeyBinding, boolean)
*
* @param types the type(s) of tick that fired when this key was first down
* @param tickEnd was it an end or start tick which fired the key
* @param isRepeat is it a repeat key event
*/
public abstract void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat);
/**
* Fired once when the key changes state from down to up
*
* @see #keyDown(EnumSet, KeyBinding, boolean, boolean)
*
* @param types the type(s) of tick that fired when this key was first down
* @param tickEnd was it an end or start tick which fired the key
*/
public abstract void keyUp(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd);
/**
* This is the list of ticks for which the key binding should trigger. The only
* valid ticks are client side ticks, obviously.
*
* @see cpw.mods.fml.common.ITickHandler#ticks()
*/
public abstract EnumSet<TickType> ticks();
}
private static final KeyBindingRegistry INSTANCE = new KeyBindingRegistry();
private Set<KeyHandler> keyHandlers = Sets.newLinkedHashSet();
/**
* Deprecated as it should not be used by client code
* @return
*/
@Deprecated
public static KeyBindingRegistry instance()
{
return INSTANCE;
}
public void uploadKeyBindingsToGame(GameSettings settings)
{
ArrayList<KeyBinding> harvestedBindings = Lists.newArrayList();
for (KeyHandler key : keyHandlers)
{
for (KeyBinding kb : key.keyBindings)
{
harvestedBindings.add(kb);
}
}
KeyBinding[] modKeyBindings = harvestedBindings.toArray(new KeyBinding[harvestedBindings.size()]);
KeyBinding[] allKeys = new KeyBinding[settings.field_74324_K.length + modKeyBindings.length];
System.arraycopy(settings.field_74324_K, 0, allKeys, 0, settings.field_74324_K.length);
System.arraycopy(modKeyBindings, 0, allKeys, settings.field_74324_K.length, modKeyBindings.length);
settings.field_74324_K = allKeys;
settings.func_74300_a();
}
}
-457
View File
@@ -1,457 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraft.src;
import static cpw.mods.fml.relauncher.Side.CLIENT;
import java.util.Map;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.client.*;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.multiplayer.NetClientHandler;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.NetServerHandler;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.relauncher.SideOnly;
public abstract class BaseMod implements cpw.mods.fml.common.modloader.BaseModProxy
{
// CALLBACK MECHANISMS
public final boolean doTickInGame(TickType tick, boolean tickEnd, Object... data)
{
Minecraft mc = FMLClientHandler.instance().getClient();
boolean hasWorld = mc.field_71441_e != null;
// World and render ticks
if (tickEnd && ( tick==TickType.RENDER || tick==TickType.CLIENT ) && hasWorld) {
return onTickInGame((Float) data[0], mc);
}
return true;
}
public final boolean doTickInGUI(TickType tick, boolean tickEnd, Object... data)
{
Minecraft mc = FMLClientHandler.instance().getClient();
boolean hasWorld = mc.field_71441_e != null;
if (tickEnd && ( tick==TickType.RENDER || ( tick==TickType.CLIENT && hasWorld))) {
return onTickInGUI((Float) data[0], mc, mc.field_71462_r);
}
return true;
}
/*
public final void onRenderHarvest(Map renderers)
{
addRenderer((Map<Class<? extends Entity>,Render>)renderers);
}
public final void onRegisterAnimations()
{
registerAnimation(FMLClientHandler.instance().getClient());
}
@Override
public final void onCrafting(Object... craftingParameters)
{
takenFromCrafting((EntityPlayer)craftingParameters[0], (ItemStack)craftingParameters[1], (IInventory)craftingParameters[2]);
}
@Override
public final void onSmelting(Object... smeltingParameters)
{
takenFromFurnace((EntityPlayer)smeltingParameters[0], (ItemStack)smeltingParameters[1]);
}
@Override
public final boolean dispense(double x, double y, double z, int xVelocity, int zVelocity, Object... data)
{
return dispenseEntity((World)data[0], x, y, z, xVelocity, zVelocity, (ItemStack)data[1]);
}
@Override
public final boolean onChat(Object... data)
{
receiveChatPacket(((Packet3Chat)data[0]).field_73476_b);
return true;
}
@Override
public final void onServerLogin(Object handler) {
serverConnect((NetClientHandler) handler);
}
public final void onServerLogout() {
serverDisconnect();
}
@Override
public final void onPlayerLogin(Object player)
{
onClientLogin((EntityPlayer) player);
}
@Override
public final void onPlayerLogout(Object player)
{
onClientLogout((EntityPlayer)player);
}
@Override
public final void onPlayerChangedDimension(Object player)
{
onClientDimensionChanged((EntityPlayer)player);
}
@Override
public final void onPacket250Packet(Object... data)
{
receiveCustomPacket((Packet250CustomPayload)data[0]);
}
@Override
public final void notifyPickup(Object... pickupData)
{
EntityItem item = (EntityItem) pickupData[0];
EntityPlayer player = (EntityPlayer) pickupData[1];
onItemPickup(player, item.field_70294_a);
}
@Override
public final void generate(Random random, int chunkX, int chunkZ, Object... additionalData)
{
World w = (World) additionalData[0];
IChunkProvider cp = (IChunkProvider) additionalData[1];
if (cp instanceof ChunkProviderGenerate)
{
generateSurface(w, random, chunkX << 4, chunkZ << 4);
}
else if (cp instanceof ChunkProviderHell)
{
generateNether(w, random, chunkX << 4, chunkZ << 4);
}
}
@Override
public final boolean handleCommand(String command, Object... data)
{
return false;
}
*/
// BASEMOD API
/**
* Override if you wish to provide a fuel item for the furnace and return the fuel value of the item
*
* @param id
* @param metadata
*/
public int addFuel(int id, int metadata)
{
return 0;
}
@SideOnly(CLIENT)
public void addRenderer(Map<Class<? extends Entity>, Render> renderers)
{
}
/**
* Override if you wish to generate Nether (Hell biome) blocks
*
* @param world
* @param random
* @param chunkX
* @param chunkZ
*/
public void generateNether(World world, Random random, int chunkX, int chunkZ)
{
}
/**
* Override if you wish to generate Overworld (not hell or the end) blocks
*
* @param world
* @param random
* @param chunkX
* @param chunkZ
*/
public void generateSurface(World world, Random random, int chunkX, int chunkZ)
{
}
/**
* Callback to return a gui screen to display
* @param player
* @param containerID
* @param x
* @param y
* @param z
*/
@SideOnly(CLIENT)
public GuiContainer getContainerGUI(EntityClientPlayerMP player, int containerID, int x, int y, int z)
{
return null;
}
/**
* Return the name of your mod. Defaults to the class name
*/
public String getName()
{
return getClass().getSimpleName();
}
/**
* Get your mod priorities
*/
public String getPriorities()
{
return "";
}
/**
* Return the version of your mod
*/
public abstract String getVersion();
@SideOnly(CLIENT)
public void keyboardEvent(KeyBinding event)
{
}
/**
* Load your mod
*/
public abstract void load();
/**
* Finish loading your mod
*/
public void modsLoaded()
{
}
/**
* Handle item pickup
*
* @param player
* @param item
*/
public void onItemPickup(EntityPlayer player, ItemStack item)
{
}
/**
* Ticked every game tick if you have subscribed to tick events through {@link ModLoader#setInGameHook(BaseMod, boolean, boolean)}
*
* @param time the rendering subtick time (0.0-1.0)
* @param minecraftInstance the client
* @return true to continue receiving ticks
*/
@SideOnly(CLIENT)
public boolean onTickInGame(float time, Minecraft minecraftInstance)
{
return false;
}
public boolean onTickInGame(MinecraftServer minecraftServer)
{
return false;
}
@SideOnly(CLIENT)
public boolean onTickInGUI(float tick, Minecraft game, GuiScreen gui)
{
return false;
}
/**
* Only implemented on the client side
* {@link #serverChat(NetServerHandler, String)}
*
* @param text
*/
@Override
public void clientChat(String text)
{
}
/**
* Called when a client connects
* @param handler
*/
@SideOnly(CLIENT)
public void clientConnect(NetClientHandler handler)
{
}
/**
* Called when the client disconnects
* @param handler
*/
@SideOnly(CLIENT)
public void clientDisconnect(NetClientHandler handler)
{
}
/**
* Called client side to receive a custom payload for this mod
*
* NOTE: this method is not provided in Risugami's implementation of BaseMod!
*
* @param packet
*/
@Override
public void receiveCustomPacket(Packet250CustomPayload packet)
{
}
@SideOnly(CLIENT)
public void registerAnimation(Minecraft game)
{
}
@SideOnly(CLIENT)
public void renderInvBlock(RenderBlocks renderer, Block block, int metadata, int modelID)
{
}
@SideOnly(CLIENT)
public boolean renderWorldBlock(RenderBlocks renderer, IBlockAccess world, int x, int y, int z, Block block, int modelID)
{
return false;
}
/*
* NOTE: this method is not provided in Risugami's implementation of BaseMod!
*/
@Override
public void serverConnect(NetHandler handler) {
}
@Override
public void serverCustomPayload(NetServerHandler handler, Packet250CustomPayload packet)
{
}
/*
* NOTE: this method is not provided in Risugami's implementation of BaseMod!
*/
@Override
public void serverDisconnect() {
}
/**
* Called when someone crafts an item from a crafting table
*
* @param player
* @param item
* @param matrix
*/
public void takenFromCrafting(EntityPlayer player, ItemStack item, IInventory matrix)
{
}
/**
* Called when someone takes a smelted item from a furnace
*
* @param player
* @param item
*/
public void takenFromFurnace(EntityPlayer player, ItemStack item)
{
}
/**
* The identifier string for the mod- used in client<->server negotiation
*/
@Override
public String toString()
{
return getName() + " " + getVersion();
}
/**
* Called when a chat message is received. Return true to stop further processing
*/
@Override
public void serverChat(NetServerHandler source, String message)
{
}
/**
* Called when a new client logs in.
*
* NOTE: this method is not provided in Risugami's implementation of BaseMod!
*
* @param player
*/
@Override
public void onClientLogin(EntityPlayer player)
{
}
/**
* Called when a client logs out of the server.
*
* NOTE: this method is not provided in Risugami's implementation of BaseMod!
*/
@Override
public void onClientLogout(INetworkManager mgr)
{
}
/**
* Spawn the entity of the supplied type, if it is your mod's
*/
@SideOnly(CLIENT)
public Entity spawnEntity(int entityId, World world, double scaledX, double scaledY, double scaledZ)
{
return null;
}
@SideOnly(CLIENT)
public void clientCustomPayload(NetClientHandler handler, Packet250CustomPayload packet)
{
}
}
@@ -1,35 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package net.minecraft.src;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
public class EntityRendererProxy extends EntityRenderer
{
public static final String fmlMarker = "This is an FML marker";
private Minecraft game;
public EntityRendererProxy(Minecraft minecraft)
{
super(minecraft);
game = minecraft;
}
@Override
public void func_78480_b(float tick)
{
super.func_78480_b(tick);
//This is where ModLoader does all of it's ticking
}
}
-49
View File
@@ -1,49 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraft.src;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* @author cpw
*
*/
@Retention(value = RUNTIME)
@Target(value = FIELD)
public @interface MLProp
{
/**
* Adds additional help to top of configuration file.
*/
String info() default "";
/**
* Maximum value allowed if field is a number.
*/
double max() default Double.MAX_VALUE;
/**
* Minimum value allowed if field is a number.
*/
double min() default Double.MIN_VALUE;
/**
* Overrides the field name for property key.
*/
String name() default "";
}
-918
View File
@@ -1,918 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraft.src;
import static cpw.mods.fml.relauncher.Side.CLIENT;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDispenser;
import net.minecraft.client.*;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.multiplayer.NetClientHandler;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.command.ICommand;
import net.minecraft.dispenser.IBehaviorDispenseItem;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.network.NetServerHandler;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet1Login;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.server.*;
import net.minecraft.stats.Achievement;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.WorldType;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.IChunkProvider;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.client.TextureFXManager;
import cpw.mods.fml.client.modloader.ModLoaderClientHelper;
import cpw.mods.fml.client.modloader.ModLoaderKeyBindingHandler;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.common.modloader.ModLoaderHelper;
import cpw.mods.fml.common.modloader.ModLoaderModContainer;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import cpw.mods.fml.relauncher.SideOnly;
import cpw.mods.fml.server.FMLServerHandler;
public class ModLoader
{
public static final String fmlMarker = "This is an FML marker";
// TODO dirty workaround for millinaire
@Deprecated
public static final Map<String,Map<String,String>> localizedStrings=Collections.emptyMap();
/**
* Adds localization info for an achievement, Not used on the server.
*
* @param achievement The achievement to name
* @param name The name
* @param description The description
*/
public static void addAchievementDesc(Achievement achievement, String name, String description)
{
String achName=achievement.func_75970_i();
addLocalization(achName, name);
addLocalization(achName+".desc", description);
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
*
* {@link GameRegistry#getFuelValue(ItemStack)}
*
* @param id The Item ID
* @param metadata The Item Metadata
* @return The fuel strength, in ticks, 0 if unhandled
*/
@Deprecated
public static int addAllFuel(int id, int metadata)
{
return 0;
}
@Deprecated
@SideOnly(CLIENT)
public static void addAllRenderers(Map<Class<? extends Entity>, Render> renderers)
{
}
/**
* Adds a new prefix to the armor texture list
*
* {@link RenderingRegistry#addNewArmourRendererPrefix(String)}
*
* @param armor The new armor prefix
* @return The new armor index
*/
@SideOnly(CLIENT)
public static int addArmor(String armor)
{
return RenderingRegistry.addNewArmourRendererPrefix(armor);
}
/**
* This method adds the supplied biome to the set of candidate biomes for the default world generator type.
*
* @param biome The biome to add
*/
public static void addBiome(BiomeGenBase biome)
{
GameRegistry.addBiome(biome);
}
public static void addEntityTracker(BaseMod mod, Class<? extends Entity> entityClass, int entityTypeId, int updateRange, int updateInterval, boolean sendVelocityInfo)
{
ModLoaderHelper.buildEntityTracker(mod, entityClass, entityTypeId, updateRange, updateInterval, sendVelocityInfo);
}
public static void addCommand(ICommand command)
{
ModLoaderHelper.addCommand(command);
}
/**
* Add a behaviour to the dispenser
*
* @param item
* @param behavior
*/
public static void addDispenserBehavior(Item item, IBehaviorDispenseItem behavior)
{
BlockDispenser.field_82527_a.func_82595_a(item, behavior);
}
/**
* Add localization for the specified string
*
* @param key Key
* @param value Value
*/
public static void addLocalization(String key, String value)
{
addLocalization(key, "en_US", value);
}
/**
* Add localization for the specified string
*
* @param key Key
* @param lang Language identifier
* @param value Value
*/
public static void addLocalization(String key, String lang, String value)
{
LanguageRegistry.instance().addStringLocalization(key, lang, value);
}
/**
* Name the specified minecraft object with the supplied name
*
* @param instance Item to name
* @param name The name to give it
*/
public static void addName(Object instance, String name)
{
addName(instance,"en_US",name);
}
/**
* Unimplemented on the server as it does not generate names
*
* @param instance Item to name
* @param lang Languge identifier
* @param name Name to give it
*/
public static void addName(Object instance, String lang, String name)
{
LanguageRegistry.instance().addNameForObject(instance, lang, name);
}
/**
* Attempts to register a small image to be applied to a larger texture image,
* typically how old ModLoader mods add custom Item/Block textures.
*
* Forge mods should use setTextureFile in Item/Block
*
* Will return the icon index it was applied to.
*
* Unimplemented on the server as it does not render textures
*
* @param fileToOverride The texture to apply the new image to
* @param fileToAdd The new image
* @return The 'icon index' in the main image that the new image will be applied to
*/
@Deprecated
@SideOnly(CLIENT)
public static int addOverride(String fileToOverride, String fileToAdd)
{
return RenderingRegistry.addTextureOverride(fileToOverride, fileToAdd);
}
/**
* Attempts to register a small image to be applied to a larger texture image,
* typically how old ModLoader mods add custom Item/Block textures.
*
* Forge mods should use setTextureFile in Item/Block
*
* Unimplemented on the server as it does not render textures
*
* @param path The texture to apply the new image to
* @param overlayPath The new image
* @param index Where on the texture to apply it
*/
@SideOnly(CLIENT)
public static void addOverride(String path, String overlayPath, int index)
{
RenderingRegistry.addTextureOverride(path, overlayPath, index);
}
/**
* Add a Shaped Recipe
*
* @param output The result
* @param params The input
*/
public static void addRecipe(ItemStack output, Object... params)
{
GameRegistry.addRecipe(output, params);
}
/**
* Add a shapeless recipe
*
* @param output The result
* @param params The input
*/
public static void addShapelessRecipe(ItemStack output, Object... params)
{
GameRegistry.addShapelessRecipe(output, params);
}
/**
* Add a new product to be smelted
*
* @param input
* @param output
*/
public static void addSmelting(int input, ItemStack output)
{
GameRegistry.addSmelting(input, output, 1.0f);
}
/**
* Add a new product to be smelted
*
* @param input
* @param output
*/
public static void addSmelting(int input, ItemStack output, float experience)
{
GameRegistry.addSmelting(input, output, experience);
}
/**
* Add a mob to the spawn list
*
* @param entityClass
* @param weightedProb
* @param min
* @param max
* @param spawnList
*/
public static void addSpawn(Class<? extends EntityLiving> entityClass, int weightedProb, int min, int max, EnumCreatureType spawnList)
{
EntityRegistry.addSpawn(entityClass, weightedProb, min, max, spawnList, WorldType.base12Biomes);
}
/**
* Add a mob to the spawn list
*
* @param entityClass
* @param weightedProb
* @param min
* @param max
* @param spawnList
* @param biomes
*/
public static void addSpawn(Class<? extends EntityLiving> entityClass, int weightedProb, int min, int max, EnumCreatureType spawnList, BiomeGenBase... biomes)
{
EntityRegistry.addSpawn(entityClass, weightedProb, min, max, spawnList, biomes);
}
/**
* Add a mob to the spawn list
*
* @param entityName
* @param weightedProb
* @param min
* @param max
* @param spawnList
*/
public static void addSpawn(String entityName, int weightedProb, int min, int max, EnumCreatureType spawnList)
{
EntityRegistry.addSpawn(entityName, weightedProb, min, max, spawnList, WorldType.base12Biomes);
}
/**
* Add a mob to the spawn list
*
* @param entityName
* @param weightedProb
* @param min
* @param max
* @param spawnList
* @param biomes
*/
public static void addSpawn(String entityName, int weightedProb, int min, int max, EnumCreatureType spawnList, BiomeGenBase... biomes)
{
EntityRegistry.addSpawn(entityName, weightedProb, min, max, spawnList, biomes);
}
public static void addTrade(int profession, TradeEntry entry)
{
ModLoaderHelper.registerTrade(profession, entry);
}
/**
* Send a packet from the client
* @param packet
*/
public static void clientSendPacket(Packet packet)
{
PacketDispatcher.sendPacketToServer(packet);
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
*
* @param world
* @param x
* @param y
* @param z
* @param xVel
* @param zVel
* @param item
* @return Always false, not implemented here
*/
@Deprecated
public static boolean dispenseEntity(World world, double x, double y, double z, int xVel, int zVel, ItemStack item)
{
return false;
}
/**
* Remove a container and drop all the items in it on the ground around
*
* @param world
* @param x
* @param y
* @param z
*/
public static void genericContainerRemoval(World world, int x, int y, int z)
{
/* TileEntity te = world.func_603_b(x, y, z);
if (!(te instanceof IInventory))
{
return;
}
IInventory inv = (IInventory)te;
for (int l = 0; l < inv.func_469_c(); l++)
{
ItemStack itemstack = inv.func_468_c(l);
if (itemstack == null)
{
continue;
}
float f = world.field_1037_n.nextFloat() * 0.8F + 0.1F;
float f1 = world.field_1037_n.nextFloat() * 0.8F + 0.1F;
float f2 = world.field_1037_n.nextFloat() * 0.8F + 0.1F;
while (itemstack.field_1615_a > 0)
{
int i1 = world.field_1037_n.nextInt(21) + 10;
if (i1 > itemstack.field_1615_a)
{
i1 = itemstack.field_1615_a;
}
itemstack.field_1615_a -= i1;
EntityItem entityitem = new EntityItem(world, (float)te.field_823_f + f, (float)te.field_822_g + f1, (float)te.field_821_h + f2, new ItemStack(itemstack.field_1617_c, i1, itemstack.func_21181_i()));
float f3 = 0.05F;
entityitem.field_608_an = (float) world.field_1037_n.nextGaussian() * f3;
entityitem.field_607_ao = (float) world.field_1037_n.nextGaussian() * f3 + 0.2F;
entityitem.field_606_ap = (float) world.field_1037_n.nextGaussian() * f3;
if (itemstack.func_40710_n())
{
entityitem.field_801_a.func_40706_d((NBTTagCompound) itemstack.func_40709_o().func_40195_b());
}
world.func_674_a(entityitem);
}
}
*/ }
/**
* Get a list of all BaseMod loaded into the system
* {@link ModLoaderModContainer#findAll}
*
* @return A list containing all loaded ModLoader mods
*/
public static List<BaseMod> getLoadedMods()
{
return ModLoaderModContainer.findAll(BaseMod.class);
}
/**
* Get a logger instance {@link FMLCommonHandler#getFMLLogger()}
*
* @return The current logger
*/
public static Logger getLogger()
{
return FMLLog.getLogger();
}
@SideOnly(CLIENT)
public static Minecraft getMinecraftInstance()
{
return FMLClientHandler.instance().getClient();
}
public static MinecraftServer getMinecraftServerInstance()
{
return FMLCommonHandler.instance().getMinecraftServerInstance();
}
/**
* Get a value from a field using reflection
* {@link ObfuscationReflectionHelper#getPrivateValue(Class, Object, int)}
*
* @param instanceclass
* @param instance
* @param fieldindex
* @return The value in the specified field.
*/
public static <T, E> T getPrivateValue(Class<? super E> instanceclass, E instance, int fieldindex)
{
return ObfuscationReflectionHelper.getPrivateValue(instanceclass, instance, fieldindex);
}
/**
* Get a value from a field using reflection
* {@link ObfuscationReflectionHelper#getPrivateValue(Class, Object, String[])}
*
* @param instanceclass
* @param instance
* @param field
* @return The value in the specified field.
*/
public static <T, E> T getPrivateValue(Class<? super E> instanceclass, E instance, String field)
{
return ObfuscationReflectionHelper.getPrivateValue(instanceclass, instance, field);
}
/**
* Stubbed method on the server to return a unique model id
*
*/
@SideOnly(CLIENT)
public static int getUniqueBlockModelID(BaseMod mod, boolean inventoryRenderer)
{
return ModLoaderClientHelper.obtainBlockModelIdFor(mod, inventoryRenderer);
}
/**
* Get a new unique entity id
* {@link EntityRegistry#findGlobalUniqueEntityId()}
*
* @return A unique entity ID
*/
public static int getUniqueEntityId()
{
return EntityRegistry.findGlobalUniqueEntityId();
}
@Deprecated
@SideOnly(CLIENT)
public static int getUniqueSpriteIndex(String path)
{
return -1;
}
/**
* To properly implement packet 250 protocol you should always check your
* channel is active prior to sending the packet
*
* @param player
* @param channel
* @return If the channel is registered to the current connection.
*/
public static boolean isChannelActive(EntityPlayer player, String channel)
{
return NetworkRegistry.instance().isChannelActive(channel, (Player)player);
}
@SideOnly(CLIENT)
public static boolean isGUIOpen(Class<? extends GuiScreen> gui)
{
return FMLClientHandler.instance().isGUIOpen(gui);
}
/**
* Is the named mod loaded?
* {@link Loader#isModLoaded(String)}
*
* @param modname
* @return If the specified mod is loaded
*/
public static boolean isModLoaded(String modname)
{
return Loader.isModLoaded(modname);
}
/**
* Implemented elsewhere
*/
@Deprecated
public static void loadConfig()
{
}
// @SideOnly(CLIENT)
// public static BufferedImage loadImage(RenderEngine renderEngine, String path) throws Exception
// {
// return TextureFXManager.instance().loadImageFromTexturePack(renderEngine, path);
// }
/**
* Call in from elsewhere. Unimplemented here.
* @param player
* @param item
*/
@Deprecated
public static void onItemPickup(EntityPlayer player, ItemStack item)
{
}
/**
* Call in from elsewhere. Unimplemented here.
*/
@Deprecated
@SideOnly(CLIENT)
public static void onTick(float tick, Minecraft game)
{
}
@SideOnly(CLIENT)
public static void openGUI(EntityPlayer player, GuiScreen gui)
{
FMLClientHandler.instance().displayGuiScreen(player, gui);
}
@Deprecated
public static void populateChunk(IChunkProvider generator, int chunkX, int chunkZ, World world)
{
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
*
* @param packet
*/
@Deprecated
public static void receivePacket(Packet250CustomPayload packet)
{
}
@Deprecated
@SideOnly(CLIENT)
public static KeyBinding[] registerAllKeys(KeyBinding[] keys)
{
return keys;
}
// @Deprecated
// @SideOnly(CLIENT)
// public static void registerAllTextureOverrides(RenderEngine cache)
// {
// }
/**
* Register a new block
*
* @param block
*/
@SuppressWarnings("deprecation")
public static void registerBlock(Block block)
{
GameRegistry.registerBlock(block);
}
/**
* Register a new block
*
* @param block
* @param itemclass
*/
@SuppressWarnings("deprecation")
public static void registerBlock(Block block, Class<? extends ItemBlock> itemclass)
{
GameRegistry.registerBlock(block, itemclass);
}
public static void registerContainerID(BaseMod mod, int id)
{
ModLoaderHelper.buildGuiHelper(mod, id);
}
/**
* Register a new entity ID
*
* @param entityClass
* @param entityName
* @param id
*/
public static void registerEntityID(Class<? extends Entity> entityClass, String entityName, int id)
{
EntityRegistry.registerGlobalEntityID(entityClass, entityName, id);
}
/**
* Register a new entity ID
*
* @param entityClass
* @param entityName
* @param id
* @param background
* @param foreground
*/
public static void registerEntityID(Class<? extends Entity> entityClass, String entityName, int id, int background, int foreground)
{
EntityRegistry.registerGlobalEntityID(entityClass, entityName, id, background, foreground);
}
@SideOnly(CLIENT)
public static void registerKey(BaseMod mod, KeyBinding keyHandler, boolean allowRepeat)
{
ModLoaderClientHelper.registerKeyBinding(mod, keyHandler, allowRepeat);
}
/**
* Register the mod for packets on this channel.
* {@link NetworkRegistry#registerChannel(IPacketHandler, String)}
*
* @param mod
* @param channel
*/
public static void registerPacketChannel(BaseMod mod, String channel)
{
NetworkRegistry.instance().registerChannel(ModLoaderHelper.buildPacketHandlerFor(mod), channel);
}
/**
* Register a new tile entity class
*
* @param tileEntityClass
* @param id
*/
public static void registerTileEntity(Class<? extends TileEntity> tileEntityClass, String id)
{
GameRegistry.registerTileEntity(tileEntityClass, id);
}
@SideOnly(CLIENT)
public static void registerTileEntity(Class<? extends TileEntity> tileEntityClass, String id, TileEntitySpecialRenderer renderer)
{
ClientRegistry.registerTileEntity(tileEntityClass, id, renderer);
}
/**
* Remove a biome from the list of generated biomes
*
* @param biome
*/
public static void removeBiome(BiomeGenBase biome)
{
GameRegistry.removeBiome(biome);
}
/**
* Remove a spawn
*
* @param entityClass
* @param spawnList
*/
public static void removeSpawn(Class<? extends EntityLiving> entityClass, EnumCreatureType spawnList)
{
EntityRegistry.removeSpawn(entityClass, spawnList, WorldType.base12Biomes);
}
/**
* Remove a spawn
*
* @param entityClass
* @param spawnList
* @param biomes
*/
public static void removeSpawn(Class<? extends EntityLiving> entityClass, EnumCreatureType spawnList, BiomeGenBase... biomes)
{
EntityRegistry.removeSpawn(entityClass, spawnList, biomes);
}
/**
* Remove a spawn
*
* @param entityName
* @param spawnList
*/
public static void removeSpawn(String entityName, EnumCreatureType spawnList)
{
EntityRegistry.removeSpawn(entityName, spawnList, WorldType.base12Biomes);
}
/**
* Remove a spawn
*
* @param entityName
* @param spawnList
* @param biomes
*/
public static void removeSpawn(String entityName, EnumCreatureType spawnList, BiomeGenBase... biomes)
{
EntityRegistry.removeSpawn(entityName, spawnList, biomes);
}
@Deprecated
@SideOnly(CLIENT)
public static boolean renderBlockIsItemFull3D(int modelID)
{
return RenderingRegistry.instance().renderItemAsFull3DBlock(modelID);
}
@Deprecated
@SideOnly(CLIENT)
public static void renderInvBlock(RenderBlocks renderer, Block block, int metadata, int modelID)
{
RenderingRegistry.instance().renderInventoryBlock(renderer, block, metadata, modelID);
}
@Deprecated
@SideOnly(CLIENT)
public static boolean renderWorldBlock(RenderBlocks renderer, IBlockAccess world, int x, int y, int z, Block block, int modelID)
{
return RenderingRegistry.instance().renderWorldBlock(renderer, world, x, y, z, block, modelID);
}
/**
* Configuration is handled elsewhere
* {@link ModLoaderModContainer}
*/
@Deprecated
public static void saveConfig()
{
}
/**
* Send a packet from client to server
*
* @param packet
*/
public static void sendPacket(Packet packet) {
PacketDispatcher.sendPacketToServer(packet);
}
/**
* Send a chat message to the server
*
* @param text
*/
@Deprecated
public static void serverChat(String text)
{
}
@Deprecated
@SideOnly(CLIENT)
public static void serverLogin(NetClientHandler handler, Packet1Login loginPacket)
{
}
public static void serverSendPacket(NetServerHandler handler, Packet packet)
{
if (handler != null)
{
PacketDispatcher.sendPacketToPlayer(packet, (Player)handler.getPlayer());
}
}
public static void serverOpenWindow(EntityPlayerMP player, Container container, int ID, int x, int y, int z)
{
ModLoaderHelper.openGui(ID, player, container, x, y, z);
}
/**
* Indicate that you want to receive ticks
*
* @param mod receiving the events
* @param enable indicates whether you want to recieve them or not
* @param useClock don't receive render subticks, just world ticks
*/
public static void setInGameHook(BaseMod mod, boolean enable, boolean useClock)
{
ModLoaderHelper.updateStandardTicks(mod, enable, useClock);
}
public static void setInGUIHook(BaseMod mod, boolean enable, boolean useClock)
{
ModLoaderHelper.updateGUITicks(mod, enable, useClock);
}
/**
* Set a private field to a value using reflection
* {@link ObfuscationReflectionHelper#setPrivateValue(Class, Object, int, Object)}
*
* @param instanceclass
* @param instance
* @param fieldindex
* @param value
*/
public static <T, E> void setPrivateValue(Class<? super T> instanceclass, T instance, int fieldindex, E value)
{
ObfuscationReflectionHelper.setPrivateValue(instanceclass, instance, value, fieldindex);
}
/**
* Set a private field to a value using reflection
* {@link ObfuscationReflectionHelper#setPrivateValue(Class, Object, String, Object)}
*
* @param instanceclass
* @param instance
* @param field
* @param value
*/
public static <T, E> void setPrivateValue(Class<? super T> instanceclass, T instance, String field, E value)
{
ObfuscationReflectionHelper.setPrivateValue(instanceclass, instance, value, field);
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
*
* @param player
* @param item
* @param matrix
*/
@Deprecated
public static void takenFromCrafting(EntityPlayer player, ItemStack item, IInventory matrix)
{
}
/**
* This method is a call in hook from modified external code. Implemented elsewhere.
*
* @param player
* @param item
*/
@Deprecated
public static void takenFromFurnace(EntityPlayer player, ItemStack item)
{
}
/**
* Throw the offered exception. Likely will stop the game.
*
* @param message
* @param e
*/
public static void throwException(String message, Throwable e)
{
FMLCommonHandler.instance().raiseException(e, message, true);
}
public static void throwException(Throwable e)
{
throwException("Exception in ModLoader", e);
}
}
-42
View File
@@ -1,42 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package net.minecraft.src;
/**
* Compatibility class for ModLoader -- do not use
*
* @author cpw
*
*/
public class TradeEntry
{
public final int id;
public float chance;
public boolean buying;
public int min = 0;
public int max = 0;
public TradeEntry(int id, float chance, boolean buying, int min, int max)
{
this.id = id;
this.chance = chance;
this.buying = buying;
this.min = min;
this.max = max;
}
public TradeEntry(int id, float chance, boolean buying)
{
this(id, chance, buying, 0, 0);
}
}
-136
View File
@@ -1,136 +0,0 @@
--- commands.py
+++ commands.py
@@ -126,8 +126,8 @@
def truncate(text, length):
- if len(text) > length:
- return text[:length] + '...'
+ #if len(text) > length:
+ # return text[:length] + '...'
return text
@@ -139,6 +139,8 @@
fieldnames = csvreader.fieldnames
return set(fieldnames)
+def commands_sanity_check():
+ print ' Commands patch applied successfully'
class Commands(object):
"""Contains the commands and initialisation for a full mcp run"""
@@ -950,6 +952,8 @@
binlk = {CLIENT: self.binclient, SERVER: self.binserver}
testlk = {CLIENT: self.testclient, SERVER: self.testserver}
+ if side == SERVER and not os.path.exists(os.path.join(binlk[side], os.path.normpath(testlk[side] + '.class'))):
+ return self.checkbins(CLIENT)
if not os.path.exists(os.path.join(binlk[side], os.path.normpath(testlk[side] + '.class'))):
return False
return True
@@ -1281,23 +1285,34 @@
pathbinlk = {CLIENT: self.binclient, SERVER: self.binserver}
pathsrclk = {CLIENT: self.srcclient, SERVER: self.srcserver}
pathlog = {CLIENT: self.clientrecomplog, SERVER: self.serverrecomplog}
+
+ if side == SERVER: #Warn about server because FML recombines it into client
+ self.logger.info('Server side recompiling might be skipped, this is normal, do not complain to FML/Forge team about server side.')
if not os.path.exists(pathbinlk[side]):
os.makedirs(pathbinlk[side])
# HINT: We create the list of source directories based on the list of packages
# on windows we just pass wildcards, otherwise we pass the full file list
- if self.osname == 'win':
+ if self.osname == 'win' and False == True: #FML: Disable for windows we write to file now
all_files = False
append_pattern = True
else:
all_files = True
append_pattern = False
pkglist = filterdirs(pathsrclk[side], '*.java', append_pattern=append_pattern, all_files=all_files)
+ from tempfile import NamedTemporaryFile
if self.cmdrecompscala: # Compile scala before java as scala scans java files, but not vice-versa
pkglistscala = pkglist[:]
pkglistscala.extend(filterdirs(pathsrclk[side], '*.scala', append_pattern=append_pattern, all_files=all_files))
- dirs = ' '.join(pkglistscala)
+ f = NamedTemporaryFile(mode='wb', suffix='.txt', prefix ='scala_src_path_', delete=False) #FML: We write to a temporary file just in case the command is to long
+ for line in pkglistscala:
+ if os.sep == '\\':
+ f.write('"%s"\n' % os.path.abspath(line).replace(os.sep, os.sep + os.sep))
+ else:
+ f.write('"%s"\n' % os.path.abspath(line))
+ f.close()
+ dirs = '@"%s"' % f.name
classpath = os.pathsep.join(cplk[side])
forkcmd = self.cmdrecompscala.format(classpath=classpath, sourcepath=pathsrclk[side], outpath=pathbinlk[side], pkgs=dirs)
try:
@@ -1317,7 +1332,15 @@
self.logger.error('================================')
self.logger.error('')
raise
- dirs = ' '.join(pkglist)
+ os.unlink(f.name)
+ f = NamedTemporaryFile(mode='wb', suffix='.txt', prefix ='java_src_path_', delete=False) #FML: We write to a temporary file just in case the command is to long
+ for line in pkglist:
+ if os.sep == '\\':
+ f.write('"%s"\n' % os.path.abspath(line).replace('\\', '\\\\'))
+ else:
+ f.write('"%s"\n' % os.path.abspath(line))
+ f.close()
+ dirs = '@"%s"' % f.name
classpath = os.pathsep.join(cplk[side])
forkcmd = self.cmdrecomp.format(classpath=classpath, sourcepath=pathsrclk[side], outpath=pathbinlk[side],
pkgs=dirs)
@@ -1336,9 +1359,10 @@
self.logger.error('==================')
self.logger.error('')
raise
+ os.unlink(f.name)
def startserver(self, mainclass, extraargs):
- classpath = [self.binserver] + self.cpathserver
+ classpath = [self.binclient, self.srcclient] + self.cpathserver + self.cpathclient
classpath = [os.path.join('..', p) for p in classpath]
classpath = os.pathsep.join(classpath)
os.chdir(self.dirjars)
@@ -1703,7 +1727,7 @@
self.runcmd(forkcmd)
return True
- def gathermd5s(self, side, reobf=False):
+ def gathermd5s(self, side, reobf=False, skip_fml=False):
if not reobf:
md5lk = {CLIENT: self.md5client, SERVER: self.md5server}
else:
@@ -1718,6 +1742,9 @@
class_path = ''
else:
class_path += '/'
+ if skip_fml:
+ if class_path.startswith('cpw/'):
+ continue
for class_file in fnmatch.filter(filelist, '*.class'):
class_name = class_path + os.path.splitext(class_file)[0]
bin_file = os.path.normpath(os.path.join(path, class_file))
@@ -1890,6 +1917,9 @@
sys.exit(1)
for entry in newfiles:
+ if 'commands.py' in entry[0]: #FML, Disable updating of Commands.py
+ print 'Update to runtime/commands.py found, but disbled due to using fml'
+ continue
if entry[3] == 'U':
self.logger.info('Retrieving file from server : %s', entry[0])
cur_file = os.path.normpath(entry[0])
@@ -1910,6 +1940,9 @@
md5reoblk = {CLIENT: self.md5reobfclient, SERVER: self.md5reobfserver}
outpathlk = {CLIENT: self.srcmodclient, SERVER: self.srcmodserver}
src = {CLIENT: self.srcclient, SERVER: self.srcserver}
+
+ if side == SERVER: #Noop out server side stuff
+ return
# HINT: We need a table for the old md5 and the new ones
md5table = {}
@@ -1,141 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import java.io.File;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import com.google.common.eventbus.EventBus;
import cpw.mods.fml.client.FMLFileResourcePack;
import cpw.mods.fml.client.FMLFolderResourcePack;
import cpw.mods.fml.common.asm.FMLSanityChecker;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.ItemData;
/**
* @author cpw
*
*/
public class FMLDummyContainer extends DummyModContainer implements WorldAccessContainer
{
public FMLDummyContainer()
{
super(new ModMetadata());
ModMetadata meta = getMetadata();
meta.modId="FML";
meta.name="Forge Mod Loader";
meta.version=Loader.instance().getFMLVersionString();
meta.credits="Made possible with help from many people";
meta.authorList=Arrays.asList("cpw, LexManos");
meta.description="The Forge Mod Loader provides the ability for systems to load mods " +
"from the file system. It also provides key capabilities for mods to be able " +
"to cooperate and provide a good modding environment. " +
"The mod loading system is compatible with ModLoader, all your ModLoader " +
"mods should work.";
meta.url="https://github.com/MinecraftForge/FML/wiki";
meta.updateUrl="https://github.com/MinecraftForge/FML/wiki";
meta.screenshots=new String[0];
meta.logoFile="";
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
return true;
}
@Override
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info)
{
NBTTagCompound fmlData = new NBTTagCompound();
NBTTagList list = new NBTTagList();
for (ModContainer mc : Loader.instance().getActiveModList())
{
NBTTagCompound mod = new NBTTagCompound();
mod.func_74778_a("ModId", mc.getModId());
mod.func_74778_a("ModVersion", mc.getVersion());
list.func_74742_a(mod);
}
fmlData.func_74782_a("ModList", list);
NBTTagList itemList = new NBTTagList();
GameData.writeItemData(itemList);
fmlData.func_74782_a("ModItemData", itemList);
return fmlData;
}
@Override
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag)
{
if (tag.func_74764_b("ModList"))
{
NBTTagList modList = tag.func_74761_m("ModList");
for (int i = 0; i < modList.func_74745_c(); i++)
{
NBTTagCompound mod = (NBTTagCompound) modList.func_74743_b(i);
String modId = mod.func_74779_i("ModId");
String modVersion = mod.func_74779_i("ModVersion");
ModContainer container = Loader.instance().getIndexedModList().get(modId);
if (container == null)
{
FMLLog.log("fml.ModTracker", Level.SEVERE, "This world was saved with mod %s which appears to be missing, things may not work well", modId);
continue;
}
if (!modVersion.equals(container.getVersion()))
{
FMLLog.log("fml.ModTracker", Level.INFO, "This world was saved with mod %s version %s and it is now at version %s, things may not work well", modId, modVersion, container.getVersion());
}
}
}
if (tag.func_74764_b("ModItemData"))
{
NBTTagList modList = tag.func_74761_m("ModItemData");
Set<ItemData> worldSaveItems = GameData.buildWorldItemData(modList);
GameData.validateWorldSave(worldSaveItems);
}
else
{
GameData.validateWorldSave(null);
}
}
@Override
public Certificate getSigningCertificate()
{
Certificate[] certificates = getClass().getProtectionDomain().getCodeSource().getCertificates();
return certificates != null ? certificates[0] : null;
}
@Override
public File getSource()
{
return FMLSanityChecker.fmlLocation;
}
@Override
public Class<?> getCustomResourcePackClass()
{
return getSource().isDirectory() ? FMLFolderResourcePack.class : FMLFileResourcePack.class;
}
}
@@ -1,22 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
/**
* @author cpw
*
*/
public interface IConsoleHandler
{
public boolean handleCommand(String command, Object... data);
}
@@ -1,42 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
/**
* Return a crafting handler for the mod container to call
*
* @author cpw
*
*/
public interface ICraftingHandler
{
/**
* The object array contains these three arguments
*
* @param player
* @param item
* @param craftMatrix
*/
void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix);
/**
* The object array contains these two arguments
* @param player
* @param item
*/
void onSmelting(EntityPlayer player, ItemStack item);
}
@@ -1,71 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import java.util.List;
import com.google.common.collect.MapDifference;
import net.minecraft.entity.Entity;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet131MapData;
import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.common.network.EntitySpawnAdjustmentPacket;
import cpw.mods.fml.common.network.EntitySpawnPacket;
import cpw.mods.fml.common.network.ModMissingPacket;
import cpw.mods.fml.common.registry.ItemData;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
import cpw.mods.fml.relauncher.Side;
public interface IFMLSidedHandler
{
List<String> getAdditionalBrandingInformation();
Side getSide();
void haltGame(String message, Throwable exception);
void showGuiScreen(Object clientGuiElement);
Entity spawnEntityIntoClientWorld(EntityRegistration registration, EntitySpawnPacket packet);
void adjustEntityLocationOnClient(EntitySpawnAdjustmentPacket entitySpawnAdjustmentPacket);
void beginServerLoading(MinecraftServer server);
void finishServerLoading();
MinecraftServer getServer();
void sendPacket(Packet packet);
void displayMissingMods(ModMissingPacket modMissingPacket);
void handleTinyPacket(NetHandler handler, Packet131MapData mapData);
void setClientCompatibilityLevel(byte compatibilityLevel);
byte getClientCompatibilityLevel();
boolean shouldServerShouldBeKilledQuietly();
void disconnectIDMismatch(MapDifference<Integer, ItemData> s, NetHandler toKill, INetworkManager mgr);
void addModAsResource(ModContainer container);
void updateResourcePackList();
String getCurrentLanguage();
}
@@ -1,26 +0,0 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.common;
/**
* @author cpw
*
*/
public interface INetworkHandler
{
boolean onChat(Object... data);
void onPacket250Packet(Object... data);
void onServerLogin(Object handler);
}
@@ -1,21 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
public interface IPickupNotifier
{
void notifyPickup(EntityItem item, EntityPlayer player);
}
@@ -1,30 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import net.minecraft.entity.player.EntityPlayer;
/**
* @author cpw
*
*/
public interface IPlayerTracker
{
void onPlayerLogin(EntityPlayer player);
void onPlayerLogout(EntityPlayer player);
void onPlayerChangedDimension(EntityPlayer player);
void onPlayerRespawn(EntityPlayer player);
}
@@ -1,24 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
public interface IScheduledTickHandler extends ITickHandler
{
/**
* Return the number of actual ticks that will pass
* before your next tick will fire. This will be called
* just after your last tick fired to compute the next delay.
* @return Time until next tick
*/
public int nextTickSpacing();
}
@@ -1,59 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import java.util.EnumSet;
/**
*
* Tick handler for mods to implement and register through the TickRegistry
*
* The data available to each tick is documented in the TickType
*
* @author cpw
*
*/
public interface ITickHandler
{
/**
* Called at the "start" phase of a tick
*
* Multiple ticks may fire simultaneously- you will only be called once with all the firing ticks
*
* @param type
* @param tickData
*/
public void tickStart(EnumSet<TickType> type, Object... tickData);
/**
* Called at the "end" phase of a tick
*
* Multiple ticks may fire simultaneously- you will only be called once with all the firing ticks
*
* @param type
* @param tickData
*/
public void tickEnd(EnumSet<TickType> type, Object... tickData);
/**
* Returns the list of ticks this tick handler is interested in receiving at the minute
*/
public EnumSet<TickType> ticks();
/**
* A profiling label for this tick handler
*/
public String getLabel();
}
@@ -1,103 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.logging.Level;
import argo.jdom.JdomParser;
import argo.jdom.JsonNode;
import argo.jdom.JsonRootNode;
import argo.saj.InvalidSyntaxException;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
public class MetadataCollection
{
private static JdomParser parser = new JdomParser();
private Map<String, ModMetadata> metadatas = Maps.newHashMap();
private int metadataVersion = 1;
public static MetadataCollection from(InputStream inputStream, String sourceName)
{
if (inputStream == null)
{
return new MetadataCollection();
}
InputStreamReader reader = new InputStreamReader(inputStream);
try
{
JsonRootNode root = parser.parse(reader);
if (root.hasElements())
{
return parse10ModInfo(root);
}
else
{
return parseModInfo(root);
}
}
catch (InvalidSyntaxException e)
{
FMLLog.log(Level.SEVERE, e, "The mcmod.info file in %s cannot be parsed as valid JSON. It will be ignored", sourceName);
return new MetadataCollection();
}
catch (Exception e)
{
throw Throwables.propagate(e);
}
}
private static MetadataCollection parseModInfo(JsonRootNode root)
{
MetadataCollection mc = new MetadataCollection();
mc.metadataVersion = Integer.parseInt(root.getNumberValue("modinfoversion"));
mc.parseModMetadataList(root.getNode("modlist"));
return mc;
}
private static MetadataCollection parse10ModInfo(JsonRootNode root)
{
MetadataCollection mc = new MetadataCollection();
mc.parseModMetadataList(root);
return mc;
}
private void parseModMetadataList(JsonNode metadataList)
{
for (JsonNode node : metadataList.getElements())
{
ModMetadata mmd = new ModMetadata(node);
metadatas.put(mmd.modId, mmd);
}
}
public ModMetadata getMetadataForId(String modId, Map<String, Object> extraData)
{
if (!metadatas.containsKey(modId))
{
ModMetadata dummy = new ModMetadata();
dummy.modId = modId;
dummy.name = (String) extraData.get("name");
dummy.version = (String) extraData.get("version");
dummy.autogenerated = true;
metadatas.put(modId, dummy);
}
return metadatas.get(modId);
}
}
-162
View File
@@ -1,162 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import static argo.jdom.JsonNodeBuilders.aStringBuilder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import argo.jdom.JsonNode;
import argo.jdom.JsonStringNode;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cpw.mods.fml.common.functions.ModNameFunction;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.VersionParser;
/**
* @author cpw
*
*/
public class ModMetadata
{
private static final class JsonStringConverter implements Function<JsonNode, Object>
{
public Object apply(JsonNode arg0)
{
if (arg0.hasElements())
{
return Lists.transform(arg0.getElements(), new JsonArrayConverter());
}
else
{
return arg0.getText();
}
}
}
private static final class JsonArrayConverter implements Function<JsonNode, String>
{
public String apply(JsonNode arg0)
{
return arg0.getText();
}
}
public String modId;
public String name;
public String description;
public String url = "";
public String updateUrl = "";
public String logoFile = "";
public String version = "";
public List<String> authorList = Lists.newArrayList();
public String credits = "";
public String parent = "";
public String[] screenshots;
public ModContainer parentMod;
public List<ModContainer> childMods = Lists.newArrayList();
public boolean useDependencyInformation;
public Set<ArtifactVersion> requiredMods;
public List<ArtifactVersion> dependencies;
public List<ArtifactVersion> dependants;
public boolean autogenerated;
public ModMetadata(JsonNode node)
{
Map<JsonStringNode, Object> processedFields = Maps.transformValues(node.getFields(), new JsonStringConverter());
modId = (String)processedFields.get(aStringBuilder("modid"));
if (Strings.isNullOrEmpty(modId))
{
FMLLog.log(Level.SEVERE, "Found an invalid mod metadata file - missing modid");
throw new LoaderException();
}
name = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("name")));
description = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("description")));
url = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("url")));
updateUrl = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("updateUrl")));
logoFile = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("logoFile")));
version = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("version")));
credits = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("credits")));
parent = Strings.nullToEmpty((String)processedFields.get(aStringBuilder("parent")));
authorList = Objects.firstNonNull(((List<String>)processedFields.get(aStringBuilder("authors"))),Objects.firstNonNull(((List<String>)processedFields.get(aStringBuilder("authorList"))), authorList));
requiredMods = processReferences(processedFields.get(aStringBuilder("requiredMods")), HashSet.class);
dependencies = processReferences(processedFields.get(aStringBuilder("dependencies")), ArrayList.class);
dependants = processReferences(processedFields.get(aStringBuilder("dependants")), ArrayList.class);
useDependencyInformation = Boolean.parseBoolean(Strings.nullToEmpty((String)processedFields.get(aStringBuilder("useDependencyInformation"))));
}
public ModMetadata()
{
}
private <T extends Collection<ArtifactVersion>> T processReferences(Object refs, Class<? extends T> retType)
{
T res = null;
try
{
res = retType.newInstance();
}
catch (Exception e)
{
// unpossible
}
if (refs == null)
{
return res;
}
for (String ref : ((List<String>)refs))
{
res.add(VersionParser.parseVersionReference(ref));
}
return res;
}
public String getChildModCountString()
{
return String.format("%d child mod%s", childMods.size(), childMods.size() != 1 ? "s" : "");
}
public String getAuthorList()
{
return Joiner.on(", ").join(authorList);
}
public String getChildModList()
{
return Joiner.on(", ").join(Lists.transform(childMods, new ModNameFunction()));
}
public String printableSortingRules()
{
return "";
}
}
@@ -1,55 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import java.util.EnumSet;
public class SingleIntervalHandler implements IScheduledTickHandler
{
private ITickHandler wrapped;
public SingleIntervalHandler(ITickHandler handler)
{
this.wrapped=handler;
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData)
{
wrapped.tickStart(type, tickData);
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData)
{
wrapped.tickEnd(type, tickData);
}
@Override
public EnumSet<TickType> ticks()
{
return wrapped.ticks();
}
@Override
public String getLabel()
{
return wrapped.getLabel();
}
@Override
public int nextTickSpacing()
{
return 1;
}
}
-64
View File
@@ -1,64 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import java.util.EnumSet;
public enum TickType {
/**
* Fired during the world evaluation loop
* server and client side
*
* arg 0 : The world that is ticking
*/
WORLD,
/**
* client side
* Fired during the render processing phase
* arg 0 : float "partial render time"
*/
RENDER,
/**
* server side
* Fired once as the world loads from disk
*/
WORLDLOAD,
/**
* client side only
* Fired once per client tick loop.
*/
CLIENT,
/**
* client and server side.
* Fired whenever the players update loop runs.
* arg 0 : the player
* arg 1 : the world the player is in
*/
PLAYER,
/**
* server side only.
* This is the server game tick.
* Fired once per tick loop on the server.
*/
SERVER;
/**
* Partner ticks that are also cancelled by returning false from onTickInGame
*/
public EnumSet<TickType> partnerTicks()
{
if (this==CLIENT) return EnumSet.of(RENDER);
if (this==RENDER) return EnumSet.of(CLIENT);
return EnumSet.noneOf(TickType.class);
}
}
@@ -1,44 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.asm;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import cpw.mods.fml.common.registry.BlockProxy;
public class ASMTransformer implements IClassTransformer
{
@Override
public byte[] transform(String name,String transformedName, byte[] bytes)
{
if ("net.minecraft.src.Block".equals(name))
{
ClassReader cr = new ClassReader(bytes);
ClassNode cn = new ClassNode(Opcodes.ASM4);
cr.accept(cn, ClassReader.EXPAND_FRAMES);
cn.interfaces.add(Type.getInternalName(BlockProxy.class));
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
cn.accept(cw);
return cw.toByteArray();
}
return bytes;
}
}
@@ -1,659 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.asm.transformers;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class MCPMerger
{
private static Hashtable<String, ClassInfo> clients = new Hashtable<String, ClassInfo>();
private static Hashtable<String, ClassInfo> shared = new Hashtable<String, ClassInfo>();
private static Hashtable<String, ClassInfo> servers = new Hashtable<String, ClassInfo>();
private static HashSet<String> copyToServer = new HashSet<String>();
private static HashSet<String> copyToClient = new HashSet<String>();
private static HashSet<String> dontAnnotate = new HashSet<String>();
private static HashSet<String> dontProcess = new HashSet<String>();
private static final boolean DEBUG = false;
public static void main(String[] args)
{
if (args.length != 3)
{
System.out.println("Usage: MCPMerger <MapFile> <minecraft.jar> <minecraft_server.jar>");
System.exit(1);
}
File map_file = new File(args[0]);
File client_jar = new File(args[1]);
File server_jar = new File(args[2]);
File client_jar_tmp = new File(args[1] + ".backup_merge");
File server_jar_tmp = new File(args[2] + ".backup_merge");
if (client_jar_tmp.exists() && !client_jar_tmp.delete())
{
System.out.println("Could not delete temp file: " + client_jar_tmp);
}
if (server_jar_tmp.exists() && !server_jar_tmp.delete())
{
System.out.println("Could not delete temp file: " + server_jar_tmp);
}
if (!client_jar.exists())
{
System.out.println("Could not find minecraft.jar: " + client_jar);
System.exit(1);
}
if (!server_jar.exists())
{
System.out.println("Could not find minecraft_server.jar: " + server_jar);
System.exit(1);
}
if (!client_jar.renameTo(client_jar_tmp))
{
System.out.println("Could not rename file: " + client_jar + " -> " + client_jar_tmp);
System.exit(1);
}
if (!server_jar.renameTo(server_jar_tmp))
{
System.out.println("Could not rename file: " + server_jar + " -> " + server_jar_tmp);
System.exit(1);
}
if (!readMapFile(map_file))
{
System.out.println("Could not read map file: " + map_file);
System.exit(1);
}
try
{
processJar(client_jar_tmp, server_jar_tmp, client_jar, server_jar);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
if (!client_jar_tmp.delete())
{
System.out.println("Could not delete temp file: " + client_jar_tmp);
}
if (!server_jar_tmp.delete())
{
System.out.println("Could not delete temp file: " + server_jar_tmp);
}
}
private static boolean readMapFile(File mapFile)
{
try
{
FileInputStream fstream = new FileInputStream(mapFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null)
{
line = line.split("#")[0];
char cmd = line.charAt(0);
line = line.substring(1).trim();
switch (cmd)
{
case '!': dontAnnotate.add(line); break;
case '<': copyToClient.add(line); break;
case '>': copyToServer.add(line); break;
case '^': dontProcess.add(line); break;
}
}
in.close();
return true;
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
return false;
}
}
public static void processJar(File clientInFile, File serverInFile, File clientOutFile, File serverOutFile) throws IOException
{
ZipFile cInJar = null;
ZipFile sInJar = null;
ZipOutputStream cOutJar = null;
ZipOutputStream sOutJar = null;
try
{
try
{
cInJar = new ZipFile(clientInFile);
sInJar = new ZipFile(serverInFile);
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open input file: " + e.getMessage());
}
try
{
cOutJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(clientOutFile)));
sOutJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(serverOutFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open output file: " + e.getMessage());
}
Hashtable<String, ZipEntry> cClasses = getClassEntries(cInJar, cOutJar);
Hashtable<String, ZipEntry> sClasses = getClassEntries(sInJar, sOutJar);
HashSet<String> cAdded = new HashSet<String>();
HashSet<String> sAdded = new HashSet<String>();
for (Entry<String, ZipEntry> entry : cClasses.entrySet())
{
String name = entry.getKey();
ZipEntry cEntry = entry.getValue();
ZipEntry sEntry = sClasses.get(name);
if (sEntry == null)
{
if (!copyToServer.contains(name))
{
copyClass(cInJar, cEntry, cOutJar, null, true);
cAdded.add(name);
}
else
{
if (DEBUG)
{
System.out.println("Copy class c->s : " + name);
}
copyClass(cInJar, cEntry, cOutJar, sOutJar, true);
cAdded.add(name);
sAdded.add(name);
}
continue;
}
sClasses.remove(name);
ClassInfo info = new ClassInfo(name);
shared.put(name, info);
byte[] cData = readEntry(cInJar, entry.getValue());
byte[] sData = readEntry(sInJar, sEntry);
byte[] data = processClass(cData, sData, info);
ZipEntry newEntry = new ZipEntry(cEntry.getName());
cOutJar.putNextEntry(newEntry);
cOutJar.write(data);
sOutJar.putNextEntry(newEntry);
sOutJar.write(data);
cAdded.add(name);
sAdded.add(name);
}
for (Entry<String, ZipEntry> entry : sClasses.entrySet())
{
if (DEBUG)
{
System.out.println("Copy class s->c : " + entry.getKey());
}
copyClass(sInJar, entry.getValue(), cOutJar, sOutJar, false);
}
for (String name : new String[]{SideOnly.class.getName(), Side.class.getName()})
{
String eName = name.replace(".", "/");
byte[] data = getClassBytes(name);
ZipEntry newEntry = new ZipEntry(name.replace(".", "/").concat(".class"));
if (!cAdded.contains(eName))
{
cOutJar.putNextEntry(newEntry);
cOutJar.write(data);
}
if (!sAdded.contains(eName))
{
sOutJar.putNextEntry(newEntry);
sOutJar.write(data);
}
}
}
finally
{
if (cInJar != null)
{
try { cInJar.close(); } catch (IOException e){}
}
if (sInJar != null)
{
try { sInJar.close(); } catch (IOException e) {}
}
if (cOutJar != null)
{
try { cOutJar.close(); } catch (IOException e){}
}
if (sOutJar != null)
{
try { sOutJar.close(); } catch (IOException e) {}
}
}
}
private static void copyClass(ZipFile inJar, ZipEntry entry, ZipOutputStream outJar, ZipOutputStream outJar2, boolean isClientOnly) throws IOException
{
ClassReader reader = new ClassReader(readEntry(inJar, entry));
ClassNode classNode = new ClassNode();
reader.accept(classNode, 0);
if (!dontAnnotate.contains(classNode.name))
{
if (classNode.visibleAnnotations == null) classNode.visibleAnnotations = new ArrayList<AnnotationNode>();
classNode.visibleAnnotations.add(getSideAnn(isClientOnly));
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
byte[] data = writer.toByteArray();
ZipEntry newEntry = new ZipEntry(entry.getName());
if (outJar != null)
{
outJar.putNextEntry(newEntry);
outJar.write(data);
}
if (outJar2 != null)
{
outJar2.putNextEntry(newEntry);
outJar2.write(data);
}
}
private static AnnotationNode getSideAnn(boolean isClientOnly)
{
AnnotationNode ann = new AnnotationNode(Type.getDescriptor(SideOnly.class));
ann.values = new ArrayList<Object>();
ann.values.add("value");
ann.values.add(new String[]{ Type.getDescriptor(Side.class), (isClientOnly ? "CLIENT" : "SERVER")});
return ann;
}
private static Hashtable<String, ZipEntry> getClassEntries(ZipFile inFile, ZipOutputStream outFile) throws IOException
{
Hashtable<String, ZipEntry> ret = new Hashtable<String, ZipEntry>();
for (ZipEntry entry : Collections.list(inFile.entries()))
{
if (entry.isDirectory())
{
outFile.putNextEntry(entry);
continue;
}
String entryName = entry.getName();
boolean filtered = false;
for (String filter : dontProcess)
{
if (entryName.startsWith(filter))
{
filtered = true;
break;
}
}
if (filtered || !entryName.endsWith(".class") || entryName.startsWith("."))
{
ZipEntry newEntry = new ZipEntry(entry.getName());
outFile.putNextEntry(newEntry);
outFile.write(readEntry(inFile, entry));
}
else
{
ret.put(entryName.replace(".class", ""), entry);
}
}
return ret;
}
private static byte[] readEntry(ZipFile inFile, ZipEntry entry) throws IOException
{
return readFully(inFile.getInputStream(entry));
}
private static byte[] readFully(InputStream stream) throws IOException
{
byte[] data = new byte[4096];
ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();
int len;
do
{
len = stream.read(data);
if (len > 0)
{
entryBuffer.write(data, 0, len);
}
} while (len != -1);
return entryBuffer.toByteArray();
}
private static class ClassInfo
{
public String name;
public ArrayList<FieldNode> cField = new ArrayList<FieldNode>();
public ArrayList<FieldNode> sField = new ArrayList<FieldNode>();
public ArrayList<MethodNode> cMethods = new ArrayList<MethodNode>();
public ArrayList<MethodNode> sMethods = new ArrayList<MethodNode>();
public ClassInfo(String name){ this.name = name; }
public boolean isSame() { return (cField.size() == 0 && sField.size() == 0 && cMethods.size() == 0 && sMethods.size() == 0); }
}
public static byte[] processClass(byte[] cIn, byte[] sIn, ClassInfo info)
{
ClassNode cClassNode = getClassNode(cIn);
ClassNode sClassNode = getClassNode(sIn);
processFields(cClassNode, sClassNode, info);
processMethods(cClassNode, sClassNode, info);
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cClassNode.accept(writer);
return writer.toByteArray();
}
private static ClassNode getClassNode(byte[] data)
{
ClassReader reader = new ClassReader(data);
ClassNode classNode = new ClassNode();
reader.accept(classNode, 0);
return classNode;
}
private static void processFields(ClassNode cClass, ClassNode sClass, ClassInfo info)
{
List<FieldNode> cFields = cClass.fields;
List<FieldNode> sFields = sClass.fields;
int sI = 0;
for (int x = 0; x < cFields.size(); x++)
{
FieldNode cF = cFields.get(x);
if (sI < sFields.size())
{
if (!cF.name.equals(sFields.get(sI).name))
{
boolean serverHas = false;
for (int y = sI + 1; y < sFields.size(); y++)
{
if (cF.name.equals(sFields.get(y).name))
{
serverHas = true;
break;
}
}
if (serverHas)
{
boolean clientHas = false;
FieldNode sF = sFields.get(sI);
for (int y = x + 1; y < cFields.size(); y++)
{
if (sF.name.equals(cFields.get(y).name))
{
clientHas = true;
break;
}
}
if (!clientHas)
{
if (sF.visibleAnnotations == null) sF.visibleAnnotations = new ArrayList<AnnotationNode>();
sF.visibleAnnotations.add(getSideAnn(false));
cFields.add(x++, sF);
info.sField.add(sF);
}
}
else
{
if (cF.visibleAnnotations == null) cF.visibleAnnotations = new ArrayList<AnnotationNode>();
cF.visibleAnnotations.add(getSideAnn(true));
sFields.add(sI, cF);
info.cField.add(cF);
}
}
}
else
{
if (cF.visibleAnnotations == null) cF.visibleAnnotations = new ArrayList<AnnotationNode>();
cF.visibleAnnotations.add(getSideAnn(true));
sFields.add(sI, cF);
info.cField.add(cF);
}
sI++;
}
if (sFields.size() != cFields.size())
{
for (int x = cFields.size(); x < sFields.size(); x++)
{
FieldNode sF = sFields.get(x);
if (sF.visibleAnnotations == null) sF.visibleAnnotations = new ArrayList<AnnotationNode>();
sF.visibleAnnotations.add(getSideAnn(true));
cFields.add(x++, sF);
info.sField.add(sF);
}
}
}
private static class MethodWrapper
{
private MethodNode node;
public boolean client;
public boolean server;
public MethodWrapper(MethodNode node)
{
this.node = node;
}
@Override
public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof MethodWrapper)) return false;
MethodWrapper mw = (MethodWrapper) obj;
boolean eq = Objects.equal(node.name, mw.node.name) && Objects.equal(node.desc, mw.node.desc);
if (eq)
{
mw.client = this.client | mw.client;
mw.server = this.server | mw.server;
this.client = this.client | mw.client;
this.server = this.server | mw.server;
if (DEBUG)
{
System.out.printf(" eq: %s %s\n", this, mw);
}
}
return eq;
}
@Override
public int hashCode()
{
return Objects.hashCode(node.name, node.desc);
}
@Override
public String toString()
{
return Objects.toStringHelper(this).add("name", node.name).add("desc",node.desc).add("server",server).add("client",client).toString();
}
}
private static void processMethods(ClassNode cClass, ClassNode sClass, ClassInfo info)
{
List<MethodNode> cMethods = (List<MethodNode>)cClass.methods;
List<MethodNode> sMethods = (List<MethodNode>)sClass.methods;
LinkedHashSet<MethodWrapper> allMethods = Sets.newLinkedHashSet();
int cPos = 0;
int sPos = 0;
int cLen = cMethods.size();
int sLen = sMethods.size();
String clientName = "";
String lastName = clientName;
String serverName = "";
while (cPos < cLen || sPos < sLen)
{
do
{
if (sPos>=sLen)
{
break;
}
MethodNode sM = sMethods.get(sPos);
serverName = sM.name;
if (!serverName.equals(lastName) && cPos != cLen)
{
if (DEBUG)
{
System.out.printf("Server -skip : %s %s %d (%s %d) %d [%s]\n", sClass.name, clientName, cLen - cPos, serverName, sLen - sPos, allMethods.size(), lastName);
}
break;
}
MethodWrapper mw = new MethodWrapper(sM);
mw.server = true;
allMethods.add(mw);
if (DEBUG)
{
System.out.printf("Server *add* : %s %s %d (%s %d) %d [%s]\n", sClass.name, clientName, cLen - cPos, serverName, sLen - sPos, allMethods.size(), lastName);
}
sPos++;
}
while (sPos < sLen);
do
{
if (cPos>=cLen)
{
break;
}
MethodNode cM = cMethods.get(cPos);
lastName = clientName;
clientName = cM.name;
if (!clientName.equals(lastName) && sPos != sLen)
{
if (DEBUG)
{
System.out.printf("Client -skip : %s %s %d (%s %d) %d [%s]\n", cClass.name, clientName, cLen - cPos, serverName, sLen - sPos, allMethods.size(), lastName);
}
break;
}
MethodWrapper mw = new MethodWrapper(cM);
mw.client = true;
allMethods.add(mw);
if (DEBUG)
{
System.out.printf("Client *add* : %s %s %d (%s %d) %d [%s]\n", cClass.name, clientName, cLen - cPos, serverName, sLen - sPos, allMethods.size(), lastName);
}
cPos++;
}
while (cPos < cLen);
}
cMethods.clear();
sMethods.clear();
for (MethodWrapper mw : allMethods)
{
if (DEBUG)
{
System.out.println(mw);
}
cMethods.add(mw.node);
sMethods.add(mw.node);
if (mw.server && mw.client)
{
// no op
}
else
{
if (mw.node.visibleAnnotations == null) mw.node.visibleAnnotations = Lists.newArrayListWithExpectedSize(1);
mw.node.visibleAnnotations.add(getSideAnn(mw.client));
if (mw.client)
{
info.sMethods.add(mw.node);
}
else
{
info.cMethods.add(mw.node);
}
}
}
}
public static byte[] getClassBytes(String name) throws IOException
{
InputStream classStream = null;
try
{
classStream = MCPMerger.class.getResourceAsStream("/" + name.replace('.', '/').concat(".class"));
return readFully(classStream);
}
finally
{
if (classStream != null)
{
try
{
classStream.close();
}
catch (IOException e){}
}
}
}
}
@@ -1,73 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.discovery.asm;
import java.util.LinkedList;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import com.google.common.collect.Lists;
public class ModMethodVisitor extends MethodVisitor
{
private ASMModParser discoverer;
private boolean inCode;
private LinkedList<Label> labels = Lists.newLinkedList();
private String foundProperties;
private boolean validProperties;
public ModMethodVisitor(String name, ASMModParser discoverer)
{
super(Opcodes.ASM4);
this.discoverer = discoverer;
}
@Override
public void visitCode()
{
labels.clear();
}
@Override
public void visitLdcInsn(Object cst)
{
if (cst instanceof String && labels.size() == 1)
{
foundProperties = (String) cst;
}
}
@Override
public void visitInsn(int opcode)
{
if (Opcodes.ARETURN == opcode && labels.size() == 1 && foundProperties != null)
{
validProperties = true;
}
}
@Override
public void visitLabel(Label label)
{
labels.push(label);
}
@Override
public void visitEnd()
{
if (validProperties)
{
discoverer.setBaseModProperties(foundProperties);
}
}
}
@@ -1,112 +0,0 @@
package cpw.mods.fml.common.launcher;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.NonOptionArgumentSpec;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.ObjectArrays;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
public class FMLTweaker implements ITweaker {
private List<String> args;
private File gameDir;
private File assetsDir;
private String profile;
private static URI jarLocation;
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile)
{
this.gameDir = (gameDir == null ? new File(".") : gameDir);
this.assetsDir = assetsDir;
this.profile = profile;
this.args = args;
try
{
jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
}
catch (URISyntaxException e)
{
Logger.getLogger("FMLTWEAK").log(Level.SEVERE, "Missing URI information for FML tweak");
throw Throwables.propagate(e);
}
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
classLoader.addTransformerExclusion("cpw.mods.fml.repackage.");
classLoader.addTransformerExclusion("cpw.mods.fml.relauncher.");
classLoader.addTransformerExclusion("cpw.mods.fml.common.asm.transformers.");
classLoader.addClassLoaderExclusion("LZMA.");
FMLLaunchHandler.configureForClientLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
@Override
public String getLaunchTarget()
{
return "net.minecraft.client.main.Main";
}
@Override
public String[] getLaunchArguments()
{
List<String> blackboardArgs = (List<String>) Launch.blackboard.get("ArgumentList");
String[] launchArgsArray = args.toArray(new String[args.size()]);
if (gameDir != null && !blackboardArgs.contains("--gameDir"))
{
launchArgsArray = ObjectArrays.concat(gameDir.getAbsolutePath(),launchArgsArray);
launchArgsArray = ObjectArrays.concat("--gameDir",launchArgsArray);
}
if (assetsDir != null && !blackboardArgs.contains("--assetsDir"))
{
launchArgsArray = ObjectArrays.concat(assetsDir.getAbsolutePath(),launchArgsArray);
launchArgsArray = ObjectArrays.concat("--assetsDir",launchArgsArray);
}
if (!blackboardArgs.contains("--version"))
{
launchArgsArray = ObjectArrays.concat(profile != null ? profile : "UnknownFMLProfile",launchArgsArray);
launchArgsArray = ObjectArrays.concat("--version",launchArgsArray);
}
return launchArgsArray;
}
public File getGameDir()
{
return gameDir;
}
public static URI getJarLocation()
{
return jarLocation;
}
public void injectCascadingTweak(String tweakClassName)
{
List<String> tweakClasses = (List<String>) Launch.blackboard.get("TweakClasses");
tweakClasses.add(tweakClassName);
}
}
@@ -1,74 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.util.Random;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.NetServerHandler;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.world.World;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/**
*
* Marker interface for BaseMod
*
* @author cpw
*
*/
public interface BaseModProxy
{
void modsLoaded();
void load();
String getName();
String getPriorities();
String getVersion();
boolean doTickInGUI(TickType type, boolean end, Object... tickData);
boolean doTickInGame(TickType type, boolean end, Object... tickData);
void generateSurface(World w, Random random, int i, int j);
void generateNether(World w, Random random, int i, int j);
int addFuel(int itemId, int damage);
void takenFromCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix);
void takenFromFurnace(EntityPlayer player, ItemStack item);
public abstract void onClientLogout(INetworkManager manager);
public abstract void onClientLogin(EntityPlayer player);
public abstract void serverDisconnect();
public abstract void serverConnect(NetHandler handler);
public abstract void receiveCustomPacket(Packet250CustomPayload packet);
public abstract void clientChat(String text);
public abstract void onItemPickup(EntityPlayer player, ItemStack item);
public abstract void serverCustomPayload(NetServerHandler handler, Packet250CustomPayload packet);
public abstract void serverChat(NetServerHandler source, String message);
}
@@ -1,127 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.util.EnumSet;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
/**
* @author cpw
*
*/
public class BaseModTicker implements ITickHandler
{
private BaseModProxy mod;
private EnumSet<TickType> ticks;
private boolean clockTickTrigger;
private boolean sendGuiTicks;
BaseModTicker(BaseModProxy mod, boolean guiTicker)
{
this.mod = mod;
this.ticks = EnumSet.of(TickType.WORLDLOAD);
this.sendGuiTicks = guiTicker;
}
BaseModTicker(EnumSet<TickType> ticks, boolean guiTicker)
{
this.ticks = ticks;
this.sendGuiTicks = guiTicker;
}
@Override
public void tickStart(EnumSet<TickType> types, Object... tickData)
{
tickBaseMod(types, false, tickData);
}
@Override
public void tickEnd(EnumSet<TickType> types, Object... tickData)
{
tickBaseMod(types, true, tickData);
}
private void tickBaseMod(EnumSet<TickType> types, boolean end, Object... tickData)
{
if (FMLCommonHandler.instance().getSide().isClient() && ( ticks.contains(TickType.CLIENT) || ticks.contains(TickType.WORLDLOAD)))
{
EnumSet cTypes=EnumSet.copyOf(types);
if ( ( end && types.contains(TickType.CLIENT)) || types.contains(TickType.WORLDLOAD))
{
clockTickTrigger = true;
cTypes.remove(TickType.CLIENT);
cTypes.remove(TickType.WORLDLOAD);
}
if (end && clockTickTrigger && types.contains(TickType.RENDER))
{
clockTickTrigger = false;
cTypes.remove(TickType.RENDER);
cTypes.add(TickType.CLIENT);
}
sendTick(cTypes, end, tickData);
}
else
{
sendTick(types, end, tickData);
}
}
private void sendTick(EnumSet<TickType> types, boolean end, Object... tickData)
{
for (TickType type : types)
{
if (!ticks.contains(type))
{
continue;
}
boolean keepTicking=true;
if (sendGuiTicks)
{
keepTicking = mod.doTickInGUI(type, end, tickData);
}
else
{
keepTicking = mod.doTickInGame(type, end, tickData);
}
if (!keepTicking) {
ticks.remove(type);
ticks.removeAll(type.partnerTicks());
}
}
}
@Override
public EnumSet<TickType> ticks()
{
return (clockTickTrigger ? EnumSet.of(TickType.RENDER) : ticks);
}
@Override
public String getLabel()
{
return mod.getClass().getSimpleName();
}
public void setMod(BaseModProxy mod)
{
this.mod = mod;
}
}
@@ -1,38 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.network.EntitySpawnPacket;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
public interface IModLoaderSidedHelper
{
void finishModLoading(ModLoaderModContainer mc);
Object getClientGui(BaseModProxy mod, EntityPlayer player, int iD, int x, int y, int z);
Entity spawnEntity(BaseModProxy mod, EntitySpawnPacket input, EntityRegistration registration);
void sendClientPacket(BaseModProxy mod, Packet250CustomPayload packet);
void clientConnectionOpened(NetHandler netClientHandler, INetworkManager manager, BaseModProxy mod);
boolean clientConnectionClosed(INetworkManager manager, BaseModProxy mod);
}
@@ -1,43 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import net.minecraft.network.NetServerHandler;
import net.minecraft.network.packet.*;
import cpw.mods.fml.common.network.IChatListener;
public class ModLoaderChatListener implements IChatListener
{
private BaseModProxy mod;
public ModLoaderChatListener(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public Packet3Chat serverChat(NetHandler handler, Packet3Chat message)
{
mod.serverChat((NetServerHandler)handler, message.field_73476_b);
return message;
}
@Override
public Packet3Chat clientChat(NetHandler handler, Packet3Chat message)
{
mod.clientChat(message.field_73476_b);
return message;
}
}
@@ -1,73 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.NetLoginHandler;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet1Login;
import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.common.network.IConnectionHandler;
import cpw.mods.fml.common.network.Player;
public class ModLoaderConnectionHandler implements IConnectionHandler
{
private BaseModProxy mod;
public ModLoaderConnectionHandler(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager)
{
mod.onClientLogin((EntityPlayer)player);
}
@Override
public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager)
{
return null;
}
@Override
public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager)
{
ModLoaderHelper.sidedHelper.clientConnectionOpened(netClientHandler, manager, mod);
}
@Override
public void connectionClosed(INetworkManager manager)
{
if (ModLoaderHelper.sidedHelper==null || !ModLoaderHelper.sidedHelper.clientConnectionClosed(manager, mod))
{
mod.serverDisconnect();
mod.onClientLogout(manager);
}
}
@Override
public void clientLoggedIn(NetHandler nh, INetworkManager manager, Packet1Login login)
{
mod.serverConnect(nh);
}
@Override
public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager)
{
ModLoaderHelper.sidedHelper.clientConnectionOpened(netClientHandler, manager, mod);
}
}
@@ -1,42 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.ICraftingHandler;
public class ModLoaderCraftingHelper implements ICraftingHandler
{
private BaseModProxy mod;
public ModLoaderCraftingHelper(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
mod.takenFromCrafting(player, item, craftMatrix);
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item)
{
mod.takenFromFurnace(player, item);
}
}
@@ -1,43 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.util.concurrent.Callable;
import net.minecraft.entity.Entity;
import com.google.common.base.Function;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.network.EntitySpawnPacket;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
public class ModLoaderEntitySpawnCallback implements Function<EntitySpawnPacket, Entity>
{
private BaseModProxy mod;
private EntityRegistration registration;
private boolean isAnimal;
public ModLoaderEntitySpawnCallback(BaseModProxy mod, EntityRegistration er)
{
this.mod = mod;
this.registration = er;
}
@Override
public Entity apply(EntitySpawnPacket input)
{
return ModLoaderHelper.sidedHelper.spawnEntity(mod, input, registration);
}
}
@@ -1,34 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.IFuelHandler;
public class ModLoaderFuelHelper implements IFuelHandler
{
private BaseModProxy mod;
public ModLoaderFuelHelper(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public int getBurnTime(ItemStack fuel)
{
return mod.addFuel(fuel.field_77993_c, fuel.func_77960_j());
}
}
@@ -1,67 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.util.Set;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.world.World;
import com.google.common.collect.Sets;
import cpw.mods.fml.common.network.IGuiHandler;
public class ModLoaderGuiHelper implements IGuiHandler
{
private BaseModProxy mod;
private Set<Integer> ids;
private Container container;
private int currentID;
ModLoaderGuiHelper(BaseModProxy mod)
{
this.mod = mod;
this.ids = Sets.newHashSet();
}
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
return container;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
return ModLoaderHelper.getClientSideGui(mod, player, ID, x, y, z);
}
public void injectContainerAndID(Container container, int ID)
{
this.container = container;
this.currentID = ID;
}
public Object getMod()
{
return mod;
}
public void associateId(int additionalID)
{
this.ids.add(additionalID);
}
}
@@ -1,224 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import net.minecraft.command.ICommand;
import net.minecraft.entity.Entity;
import net.minecraft.entity.passive.IAnimals;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.src.BaseMod;
import net.minecraft.src.TradeEntry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ICraftingHandler;
import cpw.mods.fml.common.IFuelHandler;
import cpw.mods.fml.common.IPickupNotifier;
import cpw.mods.fml.common.IWorldGenerator;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.network.IChatListener;
import cpw.mods.fml.common.network.IConnectionHandler;
import cpw.mods.fml.common.network.IGuiHandler;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
import cpw.mods.fml.common.registry.VillagerRegistry.IVillageTradeHandler;
import cpw.mods.fml.common.registry.VillagerRegistry;
/**
* @author cpw
*
*/
@SuppressWarnings("deprecation")
public class ModLoaderHelper
{
public static IModLoaderSidedHelper sidedHelper;
private static Map<BaseModProxy, ModLoaderGuiHelper> guiHelpers = Maps.newHashMap();
private static Map<Integer, ModLoaderGuiHelper> guiIDs = Maps.newHashMap();
public static void updateStandardTicks(BaseModProxy mod, boolean enable, boolean useClock)
{
ModLoaderModContainer mlmc = (ModLoaderModContainer) Loader.instance().getReversedModObjectList().get(mod);
if (mlmc==null)
{
mlmc = (ModLoaderModContainer) Loader.instance().activeModContainer();
}
if (mlmc == null)
{
FMLLog.severe("Attempted to register ModLoader ticking for invalid BaseMod %s",mod);
return;
}
BaseModTicker ticker = mlmc.getGameTickHandler();
EnumSet<TickType> ticks = ticker.ticks();
// If we're enabled we get render ticks
if (enable && !useClock) {
ticks.add(TickType.RENDER);
} else {
ticks.remove(TickType.RENDER);
}
// If we're enabled but we want clock ticks, or we're server side we get game ticks
if (enable && (useClock || FMLCommonHandler.instance().getSide().isServer())) {
ticks.add(TickType.CLIENT);
ticks.add(TickType.WORLDLOAD);
} else {
ticks.remove(TickType.CLIENT);
ticks.remove(TickType.WORLDLOAD);
}
}
public static void updateGUITicks(BaseModProxy mod, boolean enable, boolean useClock)
{
ModLoaderModContainer mlmc = (ModLoaderModContainer) Loader.instance().getReversedModObjectList().get(mod);
if (mlmc==null)
{
mlmc = (ModLoaderModContainer) Loader.instance().activeModContainer();
}
if (mlmc == null)
{
FMLLog.severe("Attempted to register ModLoader ticking for invalid BaseMod %s",mod);
return;
}
EnumSet<TickType> ticks = mlmc.getGUITickHandler().ticks();
// If we're enabled and we don't want clock ticks we get render ticks
if (enable && !useClock) {
ticks.add(TickType.RENDER);
} else {
ticks.remove(TickType.RENDER);
}
// If we're enabled but we want clock ticks, or we're server side we get world ticks
if (enable && useClock) {
ticks.add(TickType.CLIENT);
ticks.add(TickType.WORLDLOAD);
} else {
ticks.remove(TickType.CLIENT);
ticks.remove(TickType.WORLDLOAD);
}
}
public static IPacketHandler buildPacketHandlerFor(BaseModProxy mod)
{
return new ModLoaderPacketHandler(mod);
}
public static IWorldGenerator buildWorldGenHelper(BaseModProxy mod)
{
return new ModLoaderWorldGenerator(mod);
}
public static IFuelHandler buildFuelHelper(BaseModProxy mod)
{
return new ModLoaderFuelHelper(mod);
}
public static ICraftingHandler buildCraftingHelper(BaseModProxy mod)
{
return new ModLoaderCraftingHelper(mod);
}
public static void finishModLoading(ModLoaderModContainer mc)
{
if (sidedHelper != null)
{
sidedHelper.finishModLoading(mc);
}
}
public static IConnectionHandler buildConnectionHelper(BaseModProxy mod)
{
return new ModLoaderConnectionHandler(mod);
}
public static IPickupNotifier buildPickupHelper(BaseModProxy mod)
{
return new ModLoaderPickupNotifier(mod);
}
public static void buildGuiHelper(BaseModProxy mod, int id)
{
ModLoaderGuiHelper handler = guiHelpers.get(mod);
if (handler == null)
{
handler = new ModLoaderGuiHelper(mod);
guiHelpers.put(mod,handler);
NetworkRegistry.instance().registerGuiHandler(mod, handler);
}
handler.associateId(id);
guiIDs.put(id, handler);
}
public static void openGui(int id, EntityPlayer player, Container container, int x, int y, int z)
{
ModLoaderGuiHelper helper = guiIDs.get(id);
helper.injectContainerAndID(container, id);
player.openGui(helper.getMod(), id, player.field_70170_p, x, y, z);
}
public static Object getClientSideGui(BaseModProxy mod, EntityPlayer player, int ID, int x, int y, int z)
{
if (sidedHelper != null)
{
return sidedHelper.getClientGui(mod, player, ID, x, y, z);
}
return null;
}
public static void buildEntityTracker(BaseModProxy mod, Class<? extends Entity> entityClass, int entityTypeId, int updateRange, int updateInterval,
boolean sendVelocityInfo)
{
EntityRegistration er = EntityRegistry.registerModLoaderEntity(mod, entityClass, entityTypeId, updateRange, updateInterval, sendVelocityInfo);
er.setCustomSpawning(new ModLoaderEntitySpawnCallback(mod, er), EntityDragon.class.isAssignableFrom(entityClass) || IAnimals.class.isAssignableFrom(entityClass));
}
private static ModLoaderVillageTradeHandler[] tradeHelpers = new ModLoaderVillageTradeHandler[6];
public static void registerTrade(int profession, TradeEntry entry)
{
assert profession < tradeHelpers.length : "The profession is out of bounds";
if (tradeHelpers[profession] == null)
{
tradeHelpers[profession] = new ModLoaderVillageTradeHandler();
VillagerRegistry.instance().registerVillageTradeHandler(profession, tradeHelpers[profession]);
}
tradeHelpers[profession].addTrade(entry);
}
public static void addCommand(ICommand command)
{
ModLoaderModContainer mlmc = (ModLoaderModContainer) Loader.instance().activeModContainer();
if (mlmc!=null)
{
mlmc.addServerCommand(command);
}
}
public static IChatListener buildChatListener(BaseModProxy mod)
{
return new ModLoaderChatListener(mod);
}
}
@@ -1,630 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import net.minecraft.command.ICommand;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ILanguageAdapter;
import cpw.mods.fml.common.LoadController;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderException;
import cpw.mods.fml.common.MetadataCollection;
import cpw.mods.fml.common.ModClassLoader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.ProxyInjector;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.discovery.ASMDataTable.ASMData;
import cpw.mods.fml.common.discovery.ContainerType;
import cpw.mods.fml.common.event.FMLConstructionEvent;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.network.FMLNetworkHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import cpw.mods.fml.common.versioning.VersionRange;
import cpw.mods.fml.relauncher.Side;
public class ModLoaderModContainer implements ModContainer
{
public BaseModProxy mod;
private File modSource;
public Set<ArtifactVersion> requirements = Sets.newHashSet();
public ArrayList<ArtifactVersion> dependencies = Lists.newArrayList();
public ArrayList<ArtifactVersion> dependants = Lists.newArrayList();
private ContainerType sourceType;
private ModMetadata metadata;
private ProxyInjector sidedProxy;
private BaseModTicker gameTickHandler;
private BaseModTicker guiTickHandler;
private String modClazzName;
private String modId;
private EventBus bus;
private LoadController controller;
private boolean enabled = true;
private String sortingProperties;
private ArtifactVersion processedVersion;
private boolean isNetworkMod;
private List<ICommand> serverCommands = Lists.newArrayList();
public ModLoaderModContainer(String className, File modSource, String sortingProperties)
{
this.modClazzName = className;
this.modSource = modSource;
this.modId = className.contains(".") ? className.substring(className.lastIndexOf('.')+1) : className;
this.sortingProperties = Strings.isNullOrEmpty(sortingProperties) ? "" : sortingProperties;
}
/**
* We only instantiate this for "not mod mods"
* @param instance
*/
ModLoaderModContainer(BaseModProxy instance) {
this.mod=instance;
this.gameTickHandler = new BaseModTicker(instance, false);
this.guiTickHandler = new BaseModTicker(instance, true);
}
/**
*
*/
private void configureMod(Class<? extends BaseModProxy> modClazz, ASMDataTable asmData)
{
File configDir = Loader.instance().getConfigDir();
File modConfig = new File(configDir, String.format("%s.cfg", getModId()));
Properties props = new Properties();
boolean existingConfigFound = false;
boolean mlPropFound = false;
if (modConfig.exists())
{
try
{
FMLLog.fine("Reading existing configuration file for %s : %s", getModId(), modConfig.getName());
FileReader configReader = new FileReader(modConfig);
props.load(configReader);
configReader.close();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Error occured reading mod configuration file %s", modConfig.getName());
throw new LoaderException(e);
}
existingConfigFound = true;
}
StringBuffer comments = new StringBuffer();
comments.append("MLProperties: name (type:default) min:max -- information\n");
List<ModProperty> mlPropFields = Lists.newArrayList();
try
{
for (ASMData dat : Sets.union(asmData.getAnnotationsFor(this).get("net.minecraft.src.MLProp"), asmData.getAnnotationsFor(this).get("MLProp")))
{
if (dat.getClassName().equals(modClazzName))
{
try
{
mlPropFields.add(new ModProperty(modClazz.getDeclaredField(dat.getObjectName()), dat.getAnnotationInfo()));
FMLLog.finest("Found an MLProp field %s in %s", dat.getObjectName(), getModId());
}
catch (Exception e)
{
FMLLog.log(Level.WARNING, e, "An error occured trying to access field %s in mod %s", dat.getObjectName(), getModId());
}
}
}
for (ModProperty property : mlPropFields)
{
if (!Modifier.isStatic(property.field().getModifiers()))
{
FMLLog.info("The MLProp field %s in mod %s appears not to be static", property.field().getName(), getModId());
continue;
}
FMLLog.finest("Considering MLProp field %s", property.field().getName());
Field f = property.field();
String propertyName = !Strings.nullToEmpty(property.name()).isEmpty() ? property.name() : f.getName();
String propertyValue = null;
Object defaultValue = null;
try
{
defaultValue = f.get(null);
propertyValue = props.getProperty(propertyName, extractValue(defaultValue));
Object currentValue = parseValue(propertyValue, property, f.getType(), propertyName);
FMLLog.finest("Configuration for %s.%s found values default: %s, configured: %s, interpreted: %s", modClazzName, propertyName, defaultValue, propertyValue, currentValue);
if (currentValue != null && !currentValue.equals(defaultValue))
{
FMLLog.finest("Configuration for %s.%s value set to: %s", modClazzName, propertyName, currentValue);
f.set(null, currentValue);
}
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Invalid configuration found for %s in %s", propertyName, modConfig.getName());
throw new LoaderException(e);
}
finally
{
comments.append(String.format("MLProp : %s (%s:%s", propertyName, f.getType().getName(), defaultValue));
if (property.min() != Double.MIN_VALUE)
{
comments.append(",>=").append(String.format("%.1f", property.min()));
}
if (property.max() != Double.MAX_VALUE)
{
comments.append(",<=").append(String.format("%.1f", property.max()));
}
comments.append(")");
if (!Strings.nullToEmpty(property.info()).isEmpty())
{
comments.append(" -- ").append(property.info());
}
if (propertyValue != null)
{
props.setProperty(propertyName, extractValue(propertyValue));
}
comments.append("\n");
}
mlPropFound = true;
}
}
finally
{
if (!mlPropFound && !existingConfigFound)
{
FMLLog.fine("No MLProp configuration for %s found or required. No file written", getModId());
return;
}
if (!mlPropFound && existingConfigFound)
{
File mlPropBackup = new File(modConfig.getParent(),modConfig.getName()+".bak");
FMLLog.fine("MLProp configuration file for %s found but not required. Attempting to rename file to %s", getModId(), mlPropBackup.getName());
boolean renamed = modConfig.renameTo(mlPropBackup);
if (renamed)
{
FMLLog.fine("Unused MLProp configuration file for %s renamed successfully to %s", getModId(), mlPropBackup.getName());
}
else
{
FMLLog.fine("Unused MLProp configuration file for %s renamed UNSUCCESSFULLY to %s", getModId(), mlPropBackup.getName());
}
return;
}
try
{
FileWriter configWriter = new FileWriter(modConfig);
props.store(configWriter, comments.toString());
configWriter.close();
FMLLog.fine("Configuration for %s written to %s", getModId(), modConfig.getName());
}
catch (IOException e)
{
FMLLog.log(Level.SEVERE, e, "Error trying to write the config file %s", modConfig.getName());
throw new LoaderException(e);
}
}
}
private Object parseValue(String val, ModProperty property, Class<?> type, String propertyName)
{
if (type.isAssignableFrom(String.class))
{
return (String)val;
}
else if (type.isAssignableFrom(Boolean.TYPE) || type.isAssignableFrom(Boolean.class))
{
return Boolean.parseBoolean(val);
}
else if (Number.class.isAssignableFrom(type) || type.isPrimitive())
{
Number n = null;
if (type.isAssignableFrom(Double.TYPE) || Double.class.isAssignableFrom(type))
{
n = Double.parseDouble(val);
}
else if (type.isAssignableFrom(Float.TYPE) || Float.class.isAssignableFrom(type))
{
n = Float.parseFloat(val);
}
else if (type.isAssignableFrom(Long.TYPE) || Long.class.isAssignableFrom(type))
{
n = Long.parseLong(val);
}
else if (type.isAssignableFrom(Integer.TYPE) || Integer.class.isAssignableFrom(type))
{
n = Integer.parseInt(val);
}
else if (type.isAssignableFrom(Short.TYPE) || Short.class.isAssignableFrom(type))
{
n = Short.parseShort(val);
}
else if (type.isAssignableFrom(Byte.TYPE) || Byte.class.isAssignableFrom(type))
{
n = Byte.parseByte(val);
}
else
{
throw new IllegalArgumentException(String.format("MLProp declared on %s of type %s, an unsupported type",propertyName, type.getName()));
}
double dVal = n.doubleValue();
if ((property.min()!=Double.MIN_VALUE && dVal < property.min()) || (property.max()!=Double.MAX_VALUE && dVal > property.max()))
{
FMLLog.warning("Configuration for %s.%s found value %s outside acceptable range %s,%s", modClazzName,propertyName, n, property.min(), property.max());
return null;
}
else
{
return n;
}
}
throw new IllegalArgumentException(String.format("MLProp declared on %s of type %s, an unsupported type",propertyName, type.getName()));
}
private String extractValue(Object value)
{
if (String.class.isInstance(value))
{
return (String)value;
}
else if (Number.class.isInstance(value) || Boolean.class.isInstance(value))
{
return String.valueOf(value);
}
else
{
throw new IllegalArgumentException("MLProp declared on non-standard type");
}
}
@Override
public String getName()
{
return mod != null ? mod.getName() : modId;
}
@Override
public String getSortingRules()
{
return sortingProperties;
}
@Override
public boolean matches(Object mod)
{
return this.mod == mod;
}
/**
* Find all the BaseMods in the system
* @param <A>
*/
public static <A extends BaseModProxy> List<A> findAll(Class<A> clazz)
{
ArrayList<A> modList = new ArrayList<A>();
for (ModContainer mc : Loader.instance().getActiveModList())
{
if (mc instanceof ModLoaderModContainer && mc.getMod()!=null)
{
modList.add((A)((ModLoaderModContainer)mc).mod);
}
}
return modList;
}
@Override
public File getSource()
{
return modSource;
}
@Override
public Object getMod()
{
return mod;
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return requirements;
}
@Override
public List<ArtifactVersion> getDependants()
{
return dependants;
}
@Override
public List<ArtifactVersion> getDependencies()
{
return dependencies;
}
public String toString()
{
return modId;
}
@Override
public ModMetadata getMetadata()
{
return metadata;
}
@Override
public String getVersion()
{
if (mod == null || mod.getVersion() == null)
{
return "Not available";
}
return mod.getVersion();
}
public BaseModTicker getGameTickHandler()
{
return this.gameTickHandler;
}
public BaseModTicker getGUITickHandler()
{
return this.guiTickHandler;
}
@Override
public String getModId()
{
return modId;
}
@Override
public void bindMetadata(MetadataCollection mc)
{
Map<String, Object> dummyMetadata = ImmutableMap.<String,Object>builder().put("name", modId).put("version", "1.0").build();
this.metadata = mc.getMetadataForId(modId, dummyMetadata);
Loader.instance().computeDependencies(sortingProperties, getRequirements(), getDependencies(), getDependants());
}
@Override
public void setEnabledState(boolean enabled)
{
this.enabled = enabled;
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
if (this.enabled)
{
FMLLog.fine("Enabling mod %s", getModId());
this.bus = bus;
this.controller = controller;
bus.register(this);
return true;
}
else
{
return false;
}
}
// Lifecycle mod events
@Subscribe
public void constructMod(FMLConstructionEvent event)
{
try
{
ModClassLoader modClassLoader = event.getModClassLoader();
modClassLoader.addFile(modSource);
EnumSet<TickType> ticks = EnumSet.noneOf(TickType.class);
this.gameTickHandler = new BaseModTicker(ticks, false);
this.guiTickHandler = new BaseModTicker(ticks.clone(), true);
Class<? extends BaseModProxy> modClazz = (Class<? extends BaseModProxy>) modClassLoader.loadBaseModClass(modClazzName);
configureMod(modClazz, event.getASMHarvestedData());
isNetworkMod = FMLNetworkHandler.instance().registerNetworkMod(this, modClazz, event.getASMHarvestedData());
ModLoaderNetworkHandler dummyHandler = null;
if (!isNetworkMod)
{
FMLLog.fine("Injecting dummy network mod handler for BaseMod %s", getModId());
dummyHandler = new ModLoaderNetworkHandler(this);
FMLNetworkHandler.instance().registerNetworkMod(dummyHandler);
}
Constructor<? extends BaseModProxy> ctor = modClazz.getConstructor();
ctor.setAccessible(true);
mod = modClazz.newInstance();
if (dummyHandler != null)
{
dummyHandler.setBaseMod(mod);
}
ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), new ILanguageAdapter.JavaAdapter());
}
catch (Exception e)
{
controller.errorOccurred(this, e);
Throwables.propagateIfPossible(e);
}
}
@Subscribe
public void preInit(FMLPreInitializationEvent event)
{
try
{
this.gameTickHandler.setMod(mod);
this.guiTickHandler.setMod(mod);
TickRegistry.registerTickHandler(this.gameTickHandler, Side.CLIENT);
TickRegistry.registerTickHandler(this.guiTickHandler, Side.CLIENT);
GameRegistry.registerWorldGenerator(ModLoaderHelper.buildWorldGenHelper(mod));
GameRegistry.registerFuelHandler(ModLoaderHelper.buildFuelHelper(mod));
GameRegistry.registerCraftingHandler(ModLoaderHelper.buildCraftingHelper(mod));
GameRegistry.registerPickupHandler(ModLoaderHelper.buildPickupHelper(mod));
NetworkRegistry.instance().registerChatListener(ModLoaderHelper.buildChatListener(mod));
NetworkRegistry.instance().registerConnectionHandler(ModLoaderHelper.buildConnectionHelper(mod));
}
catch (Exception e)
{
controller.errorOccurred(this, e);
Throwables.propagateIfPossible(e);
}
}
@Subscribe
public void init(FMLInitializationEvent event)
{
try
{
mod.load();
}
catch (Throwable t)
{
controller.errorOccurred(this, t);
Throwables.propagateIfPossible(t);
}
}
@Subscribe
public void postInit(FMLPostInitializationEvent event)
{
try
{
mod.modsLoaded();
}
catch (Throwable t)
{
controller.errorOccurred(this, t);
Throwables.propagateIfPossible(t);
}
}
@Subscribe
public void loadComplete(FMLLoadCompleteEvent complete)
{
ModLoaderHelper.finishModLoading(this);
}
@Subscribe
public void serverStarting(FMLServerStartingEvent evt)
{
for (ICommand cmd : serverCommands)
{
evt.registerServerCommand(cmd);
}
}
@Override
public ArtifactVersion getProcessedVersion()
{
if (processedVersion == null)
{
processedVersion = new DefaultArtifactVersion(modId, getVersion());
}
return processedVersion;
}
@Override
public boolean isImmutable()
{
return false;
}
@Override
public boolean isNetworkMod()
{
return this.isNetworkMod;
}
@Override
public String getDisplayVersion()
{
return metadata!=null ? metadata.version : getVersion();
}
public void addServerCommand(ICommand command)
{
serverCommands .add(command);
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return Loader.instance().getMinecraftModContainer().getStaticVersionRange();
}
@Override
public Certificate getSigningCertificate()
{
return null;
}
@Override
public Map<String, String> getCustomModProperties()
{
return EMPTY_PROPERTIES;
}
@Override
public Class<?> getCustomResourcePackClass()
{
return null;
}
}
@@ -1,56 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkModHandler;
public class ModLoaderNetworkHandler extends NetworkModHandler
{
private BaseModProxy baseMod;
public ModLoaderNetworkHandler(ModLoaderModContainer mlmc)
{
super(mlmc, null);
}
public void setBaseMod(BaseModProxy baseMod)
{
this.baseMod = baseMod;
}
@Override
public boolean requiresClientSide()
{
return false;
}
@Override
public boolean requiresServerSide()
{
return false;
}
@Override
public boolean acceptVersion(String version)
{
return baseMod.getVersion().equals(version);
}
@Override
public boolean isNetworkMod()
{
return true;
}
}
@@ -1,43 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;
public class ModLoaderPacketHandler implements IPacketHandler
{
private BaseModProxy mod;
public ModLoaderPacketHandler(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player)
{
if (player instanceof EntityPlayerMP)
{
mod.serverCustomPayload(((EntityPlayerMP)player).field_71135_a, packet);
}
else
{
ModLoaderHelper.sidedHelper.sendClientPacket(mod, packet);
}
}
}
@@ -1,35 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import cpw.mods.fml.common.IPickupNotifier;
public class ModLoaderPickupNotifier implements IPickupNotifier
{
private BaseModProxy mod;
public ModLoaderPickupNotifier(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public void notifyPickup(EntityItem item, EntityPlayer player)
{
mod.onItemPickup(player, item.func_92059_d());
}
}
@@ -1,51 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.item.Item;
import net.minecraft.src.TradeEntry;
import net.minecraft.village.MerchantRecipeList;
import cpw.mods.fml.common.registry.VillagerRegistry;
import cpw.mods.fml.common.registry.VillagerRegistry.IVillageTradeHandler;
public class ModLoaderVillageTradeHandler implements IVillageTradeHandler
{
private List<TradeEntry> trades = Lists.newArrayList();
@Override
public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random)
{
for (TradeEntry ent : trades)
{
if (ent.buying)
{
VillagerRegistry.addEmeraldBuyRecipe(villager, recipeList, random, Item.field_77698_e[ent.id], ent.chance, ent.min, ent.max);
}
else
{
VillagerRegistry.addEmeraldSellRecipe(villager, recipeList, random, Item.field_77698_e[ent.id], ent.chance, ent.min, ent.max);
}
}
}
public void addTrade(TradeEntry entry)
{
trades.add(entry);
}
}
@@ -1,45 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.ChunkProviderGenerate;
import net.minecraft.world.gen.ChunkProviderHell;
import cpw.mods.fml.common.IWorldGenerator;
public class ModLoaderWorldGenerator implements IWorldGenerator
{
private BaseModProxy mod;
public ModLoaderWorldGenerator(BaseModProxy mod)
{
this.mod = mod;
}
@Override
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
if (chunkGenerator instanceof ChunkProviderGenerate)
{
mod.generateSurface(world, random, chunkX << 4, chunkZ << 4);
}
else if (chunkGenerator instanceof ChunkProviderHell)
{
mod.generateNether(world, random, chunkX << 4, chunkZ << 4);
}
}
}
@@ -1,67 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.modloader;
import java.lang.reflect.Field;
import java.util.Map;
/**
* @author cpw
*
*/
public class ModProperty
{
private String info;
private double min;
private double max;
private String name;
private Field field;
public ModProperty(Field f, String info, Double min, Double max, String name)
{
this.field = f;
this.info = info;
this.min = min != null ? min : Double.MIN_VALUE;
this.max = max != null ? max : Double.MAX_VALUE;
this.name = name;
}
public ModProperty(Field field, Map<String, Object> annotationInfo)
{
this(field, (String)annotationInfo.get("info"), (Double)annotationInfo.get("min"), (Double)annotationInfo.get("max"), (String)annotationInfo.get("name"));
}
public String name()
{
return name;
}
public double min()
{
return min;
}
public double max()
{
return max;
}
public String info()
{
return info;
}
public Field field()
{
return field;
}
}
@@ -1,65 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.FMLCommonHandler;
public class EntitySpawnAdjustmentPacket extends FMLPacket
{
public EntitySpawnAdjustmentPacket()
{
super(Type.ENTITYSPAWNADJUSTMENT);
}
public int entityId;
public int serverX;
public int serverY;
public int serverZ;
@Override
public byte[] generatePacket(Object... data)
{
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
dat.writeInt((Integer) data[0]);
dat.writeInt((Integer) data[1]);
dat.writeInt((Integer) data[2]);
dat.writeInt((Integer) data[3]);
return dat.toByteArray();
}
@Override
public FMLPacket consumePacket(byte[] data)
{
ByteArrayDataInput dat = ByteStreams.newDataInput(data);
entityId = dat.readInt();
serverX = dat.readInt();
serverY = dat.readInt();
serverZ = dat.readInt();
return this;
}
@Override
public void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
FMLCommonHandler.instance().adjustEntityLocationOnClient(this);
}
}
@@ -1,197 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import net.minecraft.entity.*;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.util.MathHelper;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData;
import cpw.mods.fml.common.registry.IThrowableEntity;
public class EntitySpawnPacket extends FMLPacket
{
public int networkId;
public int modEntityId;
public int entityId;
public double scaledX;
public double scaledY;
public double scaledZ;
public float scaledYaw;
public float scaledPitch;
public float scaledHeadYaw;
public List metadata;
public int throwerId;
public double speedScaledX;
public double speedScaledY;
public double speedScaledZ;
public ByteArrayDataInput dataStream;
public int rawX;
public int rawY;
public int rawZ;
public EntitySpawnPacket()
{
super(Type.ENTITYSPAWN);
}
@Override
public byte[] generatePacket(Object... data)
{
EntityRegistration er = (EntityRegistration) data[0];
Entity ent = (Entity) data[1];
NetworkModHandler handler = (NetworkModHandler) data[2];
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
dat.writeInt(handler.getNetworkId());
dat.writeInt(er.getModEntityId());
// entity id
dat.writeInt(ent.field_70157_k);
// entity pos x,y,z
dat.writeInt(MathHelper.func_76128_c(ent.field_70165_t * 32D));
dat.writeInt(MathHelper.func_76128_c(ent.field_70163_u * 32D));
dat.writeInt(MathHelper.func_76128_c(ent.field_70161_v * 32D));
// yaw, pitch
dat.writeByte((byte) (ent.field_70177_z * 256.0F / 360.0F));
dat.writeByte((byte) (ent.field_70125_A * 256.0F / 360.0F));
// head yaw
if (ent instanceof EntityLiving)
{
dat.writeByte((byte) (((EntityLiving)ent).field_70759_as * 256.0F / 360.0F));
}
else
{
dat.writeByte(0);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try
{
ent.func_70096_w().func_75689_a(dos);
}
catch (IOException e)
{
// unpossible
}
dat.write(bos.toByteArray());
if (ent instanceof IThrowableEntity)
{
Entity owner = ((IThrowableEntity)ent).getThrower();
dat.writeInt(owner == null ? ent.field_70157_k : owner.field_70157_k);
double maxVel = 3.9D;
double mX = ent.field_70159_w;
double mY = ent.field_70181_x;
double mZ = ent.field_70179_y;
if (mX < -maxVel) mX = -maxVel;
if (mY < -maxVel) mY = -maxVel;
if (mZ < -maxVel) mZ = -maxVel;
if (mX > maxVel) mX = maxVel;
if (mY > maxVel) mY = maxVel;
if (mZ > maxVel) mZ = maxVel;
dat.writeInt((int)(mX * 8000D));
dat.writeInt((int)(mY * 8000D));
dat.writeInt((int)(mZ * 8000D));
}
else
{
dat.writeInt(0);
}
if (ent instanceof IEntityAdditionalSpawnData)
{
((IEntityAdditionalSpawnData)ent).writeSpawnData(dat);
}
return dat.toByteArray();
}
@Override
public FMLPacket consumePacket(byte[] data)
{
ByteArrayDataInput dat = ByteStreams.newDataInput(data);
networkId = dat.readInt();
modEntityId = dat.readInt();
entityId = dat.readInt();
rawX = dat.readInt();
rawY = dat.readInt();
rawZ = dat.readInt();
scaledX = rawX / 32D;
scaledY = rawY / 32D;
scaledZ = rawZ / 32D;
scaledYaw = dat.readByte() * 360F / 256F;
scaledPitch = dat.readByte() * 360F / 256F;
scaledHeadYaw = dat.readByte() * 360F / 256F;
ByteArrayInputStream bis = new ByteArrayInputStream(data, 27, data.length - 27);
DataInputStream dis = new DataInputStream(bis);
try
{
metadata = DataWatcher.func_75686_a(dis);
}
catch (IOException e)
{
// Nope
}
dat.skipBytes(data.length - bis.available() - 27);
throwerId = dat.readInt();
if (throwerId != 0)
{
speedScaledX = dat.readInt() / 8000D;
speedScaledY = dat.readInt() / 8000D;
speedScaledZ = dat.readInt() / 8000D;
}
this.dataStream = dat;
return this;
}
@Override
public void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
NetworkModHandler nmh = handler.findNetworkModHandler(networkId);
ModContainer mc = nmh.getContainer();
EntityRegistration registration = EntityRegistry.instance().lookupModSpawn(mc, modEntityId);
if (registration == null || registration.getEntityClass() == null)
{
FMLLog.log(Level.WARNING, "Missing mod entity information for %s : %d", mc.getModId(), modEntityId);
return;
}
Entity entity = FMLCommonHandler.instance().spawnEntityIntoClientWorld(registration, this);
}
}
@@ -1,443 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_LIST_REQUEST;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.network.*;
import net.minecraft.network.packet.*;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.ServerConfigurationManager;
import net.minecraft.world.EnumGameType;
import net.minecraft.world.World;
import net.minecraft.world.WorldType;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.InjectedModContainer;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.network.FMLPacket.Type;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration;
public class FMLNetworkHandler
{
private static final int FML_HASH = Hashing.murmur3_32().hashString("FML").asInt();
private static final int PROTOCOL_VERSION = 0x2;
private static final FMLNetworkHandler INSTANCE = new FMLNetworkHandler();
// List of states for connections from clients to server
static final int LOGIN_RECEIVED = 1;
static final int CONNECTION_VALID = 2;
static final int FML_OUT_OF_DATE = -1;
static final int MISSING_MODS_OR_VERSIONS = -2;
private Map<NetLoginHandler, Integer> loginStates = Maps.newHashMap();
private Map<ModContainer, NetworkModHandler> networkModHandlers = Maps.newHashMap();
private Map<Integer, NetworkModHandler> networkIdLookup = Maps.newHashMap();
public static void handlePacket250Packet(Packet250CustomPayload packet, INetworkManager network, NetHandler handler)
{
String target = packet.field_73630_a;
if (target.startsWith("MC|"))
{
handler.handleVanilla250Packet(packet);
}
if (target.equals("FML"))
{
instance().handleFMLPacket(packet, network, handler);
}
else
{
NetworkRegistry.instance().handleCustomPacket(packet, network, handler);
}
}
public static void onConnectionEstablishedToServer(NetHandler clientHandler, INetworkManager manager, Packet1Login login)
{
NetworkRegistry.instance().clientLoggedIn(clientHandler, manager, login);
}
private void handleFMLPacket(Packet250CustomPayload packet, INetworkManager network, NetHandler netHandler)
{
FMLPacket pkt = FMLPacket.readPacket(network, packet.field_73629_c);
// Part of an incomplete multipart packet
if (pkt == null)
{
return;
}
String userName = "";
if (netHandler instanceof NetLoginHandler)
{
userName = ((NetLoginHandler) netHandler).field_72543_h;
}
else
{
EntityPlayer pl = netHandler.getPlayer();
if (pl != null)
{
userName = pl.func_70005_c_();
}
}
pkt.execute(network, this, netHandler, userName);
}
public static void onConnectionReceivedFromClient(NetLoginHandler netLoginHandler, MinecraftServer server, SocketAddress address, String userName)
{
instance().handleClientConnection(netLoginHandler, server, address, userName);
}
private void handleClientConnection(NetLoginHandler netLoginHandler, MinecraftServer server, SocketAddress address, String userName)
{
if (!loginStates.containsKey(netLoginHandler))
{
if (handleVanillaLoginKick(netLoginHandler, server, address, userName))
{
// No FML on the client
FMLLog.fine("Connection from %s rejected - no FML packet received from client", userName);
netLoginHandler.completeConnection("You don't have FML installed, you cannot connect to this server");
return;
}
else
{
// Vanilla kicked us for some reason - bye now!
FMLLog.fine("Connection from %s was closed by vanilla minecraft", userName);
return;
}
}
switch (loginStates.get(netLoginHandler))
{
case LOGIN_RECEIVED:
// mods can try and kick undesireables here
String modKick = NetworkRegistry.instance().connectionReceived(netLoginHandler, netLoginHandler.field_72538_b);
if (modKick != null)
{
netLoginHandler.completeConnection(modKick);
loginStates.remove(netLoginHandler);
return;
}
// The vanilla side wanted to kick
if (!handleVanillaLoginKick(netLoginHandler, server, address, userName))
{
loginStates.remove(netLoginHandler);
return;
}
// Reset the "connection completed" flag so processing can continue
NetLoginHandler.func_72531_a(netLoginHandler, false);
// Send the mod list request packet to the client from the server
netLoginHandler.field_72538_b.func_74429_a(getModListRequestPacket());
loginStates.put(netLoginHandler, CONNECTION_VALID);
break;
case CONNECTION_VALID:
netLoginHandler.completeConnection(null);
loginStates.remove(netLoginHandler);
break;
case MISSING_MODS_OR_VERSIONS:
netLoginHandler.completeConnection("The server requires mods that are absent or out of date on your client");
loginStates.remove(netLoginHandler);
break;
case FML_OUT_OF_DATE:
netLoginHandler.completeConnection("Your client is not running a new enough version of FML to connect to this server");
loginStates.remove(netLoginHandler);
break;
default:
netLoginHandler.completeConnection("There was a problem during FML negotiation");
loginStates.remove(netLoginHandler);
break;
}
}
/**
* @param netLoginHandler
* @param server
* @param address
* @param userName
* @return if the user can carry on
*/
private boolean handleVanillaLoginKick(NetLoginHandler netLoginHandler, MinecraftServer server, SocketAddress address, String userName)
{
// Vanilla reasons first
ServerConfigurationManager playerList = server.func_71203_ab();
String kickReason = playerList.func_72399_a(address, userName);
if (kickReason != null)
{
netLoginHandler.completeConnection(kickReason);
}
return kickReason == null;
}
public static void handleLoginPacketOnServer(NetLoginHandler handler, Packet1Login login)
{
if (login.field_73561_a == FML_HASH)
{
if (login.field_73558_e == PROTOCOL_VERSION)
{
FMLLog.finest("Received valid FML login packet from %s", handler.field_72538_b.func_74430_c());
instance().loginStates.put(handler, LOGIN_RECEIVED);
}
else if (login.field_73558_e != PROTOCOL_VERSION)
{
FMLLog.finest("Received incorrect FML (%x) login packet from %s", login.field_73558_e, handler.field_72538_b.func_74430_c());
instance().loginStates.put(handler, FML_OUT_OF_DATE);
}
}
else
{
FMLLog.fine("Received invalid login packet (%x, %x) from %s", login.field_73561_a, login.field_73558_e,
handler.field_72538_b.func_74430_c());
}
}
static void setHandlerState(NetLoginHandler handler, int state)
{
instance().loginStates.put(handler, state);
}
public static FMLNetworkHandler instance()
{
return INSTANCE;
}
public static Packet1Login getFMLFakeLoginPacket()
{
// Always reset compat to zero before sending our fake packet
FMLCommonHandler.instance().getSidedDelegate().setClientCompatibilityLevel((byte) 0);
Packet1Login fake = new Packet1Login();
// Hash FML using a simple function
fake.field_73561_a = FML_HASH;
// The FML protocol version
fake.field_73558_e = PROTOCOL_VERSION;
fake.field_73557_d = EnumGameType.NOT_SET;
fake.field_73559_b = WorldType.field_77139_a[0];
return fake;
}
public Packet250CustomPayload getModListRequestPacket()
{
return PacketDispatcher.getPacket("FML", FMLPacket.makePacket(MOD_LIST_REQUEST));
}
public void registerNetworkMod(NetworkModHandler handler)
{
networkModHandlers.put(handler.getContainer(), handler);
networkIdLookup.put(handler.getNetworkId(), handler);
}
public boolean registerNetworkMod(ModContainer container, Class<?> networkModClass, ASMDataTable asmData)
{
NetworkModHandler handler = new NetworkModHandler(container, networkModClass, asmData);
if (handler.isNetworkMod())
{
registerNetworkMod(handler);
}
return handler.isNetworkMod();
}
public NetworkModHandler findNetworkModHandler(Object mc)
{
if (mc instanceof InjectedModContainer)
{
return networkModHandlers.get(((InjectedModContainer)mc).wrappedContainer);
}
if (mc instanceof ModContainer)
{
return networkModHandlers.get(mc);
}
else if (mc instanceof Integer)
{
return networkIdLookup.get(mc);
}
else
{
return networkModHandlers.get(FMLCommonHandler.instance().findContainerFor(mc));
}
}
public Set<ModContainer> getNetworkModList()
{
return networkModHandlers.keySet();
}
public static void handlePlayerLogin(EntityPlayerMP player, NetServerHandler netHandler, INetworkManager manager)
{
NetworkRegistry.instance().playerLoggedIn(player, netHandler, manager);
GameRegistry.onPlayerLogin(player);
}
public Map<Integer, NetworkModHandler> getNetworkIdMap()
{
return networkIdLookup;
}
public void bindNetworkId(String key, Integer value)
{
Map<String, ModContainer> mods = Loader.instance().getIndexedModList();
NetworkModHandler handler = findNetworkModHandler(mods.get(key));
if (handler != null)
{
handler.setNetworkId(value);
networkIdLookup.put(value, handler);
}
}
public static void onClientConnectionToRemoteServer(NetHandler netClientHandler, String server, int port, INetworkManager networkManager)
{
NetworkRegistry.instance().connectionOpened(netClientHandler, server, port, networkManager);
}
public static void onClientConnectionToIntegratedServer(NetHandler netClientHandler, MinecraftServer server, INetworkManager networkManager)
{
NetworkRegistry.instance().connectionOpened(netClientHandler, server, networkManager);
}
public static void onConnectionClosed(INetworkManager manager, EntityPlayer player)
{
NetworkRegistry.instance().connectionClosed(manager, player);
}
public static void openGui(EntityPlayer player, Object mod, int modGuiId, World world, int x, int y, int z)
{
ModContainer mc = FMLCommonHandler.instance().findContainerFor(mod);
if (mc == null)
{
NetworkModHandler nmh = instance().findNetworkModHandler(mod);
if (nmh != null)
{
mc = nmh.getContainer();
}
else
{
FMLLog.warning("A mod tried to open a gui on the server without being a NetworkMod");
return;
}
}
if (player instanceof EntityPlayerMP)
{
NetworkRegistry.instance().openRemoteGui(mc, (EntityPlayerMP) player, modGuiId, world, x, y, z);
}
else
{
NetworkRegistry.instance().openLocalGui(mc, player, modGuiId, world, x, y, z);
}
}
public static Packet getEntitySpawningPacket(Entity entity)
{
EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entity.getClass(), false);
if (er == null)
{
return null;
}
if (er.usesVanillaSpawning())
{
return null;
}
return PacketDispatcher.getPacket("FML", FMLPacket.makePacket(Type.ENTITYSPAWN, er, entity, instance().findNetworkModHandler(er.getContainer())));
}
public static void makeEntitySpawnAdjustment(int entityId, EntityPlayerMP player, int serverX, int serverY, int serverZ)
{
Packet250CustomPayload pkt = PacketDispatcher.getPacket("FML", FMLPacket.makePacket(Type.ENTITYSPAWNADJUSTMENT, entityId, serverX, serverY, serverZ));
player.field_71135_a.func_72567_b(pkt);
}
public static InetAddress computeLocalHost() throws IOException
{
InetAddress add = null;
List<InetAddress> addresses = Lists.newArrayList();
InetAddress localHost = InetAddress.getLocalHost();
for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces()))
{
if (!ni.isLoopback() && ni.isUp())
{
addresses.addAll(Collections.list(ni.getInetAddresses()));
if (addresses.contains(localHost))
{
add = localHost;
break;
}
}
}
if (add == null && !addresses.isEmpty())
{
for (InetAddress addr: addresses)
{
if (addr.getAddress().length == 4)
{
add = addr;
break;
}
}
}
if (add == null)
{
add = localHost;
}
return add;
}
public static Packet3Chat handleChatMessage(NetHandler handler, Packet3Chat chat)
{
return NetworkRegistry.instance().handleChat(handler, chat);
}
public static void handlePacket131Packet(NetHandler handler, Packet131MapData mapData)
{
if (handler instanceof NetServerHandler || mapData.field_73438_a != Item.field_77744_bd.field_77779_bT)
{
// Server side and not "map" packets are always handled by us
NetworkRegistry.instance().handleTinyPacket(handler, mapData);
}
else
{
// Fallback to the net client handler implementation
FMLCommonHandler.instance().handleTinyPacket(handler, mapData);
}
}
public static int getCompatibilityLevel()
{
return PROTOCOL_VERSION;
}
public static boolean vanillaLoginPacketCompatibility()
{
return FMLCommonHandler.instance().getSidedDelegate().getClientCompatibilityLevel() == 0;
}
}
@@ -1,161 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import java.util.Arrays;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import com.google.common.base.Throwables;
import com.google.common.collect.MapMaker;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Ints;
import com.google.common.primitives.UnsignedBytes;
import cpw.mods.fml.common.FMLLog;
public abstract class FMLPacket
{
enum Type
{
/**
* Opening salutation from the server to the client -> request all mods from the client
*/
MOD_LIST_REQUEST(ModListRequestPacket.class, false),
/**
* The client responds with the list of mods and versions it has. This is verified by the server.
*/
MOD_LIST_RESPONSE(ModListResponsePacket.class, false),
/**
* At which point the server tells the client the mod identifiers for this session.
*/
MOD_IDENTIFIERS(ModIdentifiersPacket.class, false),
/**
* Or, if there is missing stuff, the server tells the client what's missing and drops the connection.
*/
MOD_MISSING(ModMissingPacket.class, false),
/**
* Open a GUI on the client from the server
*/
GUIOPEN(OpenGuiPacket.class, false),
/**
* Spawn an entity on the client from the server
*/
ENTITYSPAWN(EntitySpawnPacket.class, false),
/**
* Fixes entity location data after spawning
*/
ENTITYSPAWNADJUSTMENT(EntitySpawnAdjustmentPacket.class, false),
/**
* The ID map to send to the client
*/
MOD_IDMAP(ModIdMapPacket.class, true);
private Class<? extends FMLPacket> packetType;
private boolean isMultipart;
private ConcurrentMap<INetworkManager, FMLPacket> partTracker;
private Type(Class<? extends FMLPacket> clazz, boolean isMultipart)
{
this.packetType = clazz;
this.isMultipart = isMultipart;
}
FMLPacket make()
{
try
{
return this.packetType.newInstance();
}
catch (Exception e)
{
Throwables.propagateIfPossible(e);
FMLLog.log(Level.SEVERE, e, "A bizarre critical error occured during packet encoding");
throw new FMLNetworkException(e);
}
}
public boolean isMultipart()
{
return isMultipart;
}
private FMLPacket findCurrentPart(INetworkManager network)
{
if (partTracker == null)
{
partTracker = new MapMaker().weakKeys().weakValues().makeMap();
}
if (!partTracker.containsKey(network))
{
partTracker.put(network, make());
}
return partTracker.get(network);
}
}
private Type type;
public static byte[][] makePacketSet(Type type, Object... data)
{
if (!type.isMultipart())
{
return new byte[0][];
}
byte[] packetData = type.make().generatePacket(data);
byte[][] chunks = new byte[packetData.length / 32000 + 1][];
for (int i = 0; i < packetData.length / 32000 + 1; i++)
{
int len = Math.min(32000, packetData.length - i* 32000);
chunks[i] = Bytes.concat(new byte[] { UnsignedBytes.checkedCast(type.ordinal()), UnsignedBytes.checkedCast(i), UnsignedBytes.checkedCast(chunks.length)}, Ints.toByteArray(len), Arrays.copyOfRange(packetData, i * 32000, len + i * 32000));
}
return chunks;
}
public static byte[] makePacket(Type type, Object... data)
{
byte[] packetData = type.make().generatePacket(data);
return Bytes.concat(new byte[] { UnsignedBytes.checkedCast(type.ordinal()) }, packetData );
}
public static FMLPacket readPacket(INetworkManager network, byte[] payload)
{
int type = UnsignedBytes.toInt(payload[0]);
Type eType = Type.values()[type];
FMLPacket pkt;
if (eType.isMultipart())
{
pkt = eType.findCurrentPart(network);
}
else
{
pkt = eType.make();
}
return pkt.consumePacket(Arrays.copyOfRange(payload, 1, payload.length));
}
public FMLPacket(Type type)
{
this.type = type;
}
public abstract byte[] generatePacket(Object... data);
public abstract FMLPacket consumePacket(byte[] data);
public abstract void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName);
}
@@ -1,33 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import net.minecraft.network.packet.*;
public interface IChatListener
{
/**
* Called when there is a chat message received on the server
* @param handler
* @param message
*/
public Packet3Chat serverChat(NetHandler handler, Packet3Chat message);
/**
* Called when there is a chat message recived on the client
*
* @param handler
* @param message
*/
public Packet3Chat clientChat(NetHandler handler, Packet3Chat message);
}
@@ -1,84 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.NetLoginHandler;
import net.minecraft.network.packet.NetHandler;
import net.minecraft.network.packet.Packet1Login;
import net.minecraft.server.MinecraftServer;
public interface IConnectionHandler
{
/**
* Called when a player logs into the server
* SERVER SIDE
*
* @param player
* @param netHandler
* @param manager
*/
void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager);
/**
* If you don't want the connection to continue, return a non-empty string here
* If you do, you can do other stuff here- note no FML negotiation has occured yet
* though the client is verified as having FML installed
*
* SERVER SIDE
*
* @param netHandler
* @param manager
*/
String connectionReceived(NetLoginHandler netHandler, INetworkManager manager);
/**
* Fired when a remote connection is opened
* CLIENT SIDE
*
* @param netClientHandler
* @param server
* @param port
*/
void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager);
/**
*
* Fired when a local connection is opened
*
* CLIENT SIDE
*
* @param netClientHandler
* @param server
*/
void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager);
/**
* Fired when a connection closes
*
* ALL SIDES
*
* @param manager
*/
void connectionClosed(INetworkManager manager);
/**
* Fired when the client established the connection to the server
*
* CLIENT SIDE
* @param clientHandler
* @param manager
* @param login
*/
void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login);
}
@@ -1,27 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
public interface IPacketHandler
{
/**
* Recieve a packet from one of the registered channels for this packet handler
* @param manager The network manager this packet arrived from
* @param packet The packet itself
* @param player A dummy interface representing the player - it can be cast into a real player instance if needed
*/
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player);
}
@@ -1,20 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import net.minecraft.network.packet.*;
public interface ITinyPacketHandler
{
void handle(NetHandler handler, Packet131MapData mapData);
}
@@ -1,110 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import java.io.IOException;
import java.util.BitSet;
import java.util.Set;
import java.util.logging.Level;
import net.minecraft.nbt.*;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import com.google.common.collect.MapDifference;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Ints;
import com.google.common.primitives.UnsignedBytes;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.ItemData;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_IDMAP;
public class ModIdMapPacket extends FMLPacket {
private byte[][] partials;
public ModIdMapPacket()
{
super(MOD_IDMAP);
}
@Override
public byte[] generatePacket(Object... data)
{
NBTTagList completeList = (NBTTagList) data[0];
NBTTagCompound wrap = new NBTTagCompound();
wrap.func_74782_a("List", completeList);
try
{
return CompressedStreamTools.func_74798_a(wrap);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "A critical error writing the id map");
throw new FMLNetworkException(e);
}
}
@Override
public FMLPacket consumePacket(byte[] data)
{
ByteArrayDataInput bdi = ByteStreams.newDataInput(data);
int chunkIdx = UnsignedBytes.toInt(bdi.readByte());
int chunkTotal = UnsignedBytes.toInt(bdi.readByte());
int chunkLength = bdi.readInt();
if (partials == null)
{
partials = new byte[chunkTotal][];
}
partials[chunkIdx] = new byte[chunkLength];
bdi.readFully(partials[chunkIdx]);
for (int i = 0; i < partials.length; i++)
{
if (partials[i] == null)
{
return null;
}
}
return this;
}
@Override
public void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
byte[] allData = Bytes.concat(partials);
GameData.initializeServerGate(1);
try
{
NBTTagCompound serverList = CompressedStreamTools.func_74792_a(allData);
NBTTagList list = serverList.func_74761_m("List");
Set<ItemData> itemData = GameData.buildWorldItemData(list);
GameData.validateWorldSave(itemData);
MapDifference<Integer, ItemData> serverDifference = GameData.gateWorldLoadingForValidation();
if (serverDifference!=null)
{
FMLCommonHandler.instance().disconnectIDMismatch(serverDifference, netHandler, network);
}
}
catch (IOException e)
{
}
}
}
@@ -1,79 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_IDENTIFIERS;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import com.google.common.collect.Maps;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
public class ModIdentifiersPacket extends FMLPacket
{
private Map<String, Integer> modIds = Maps.newHashMap();
public ModIdentifiersPacket()
{
super(MOD_IDENTIFIERS);
}
@Override
public byte[] generatePacket(Object... data)
{
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
Collection<NetworkModHandler >networkMods = FMLNetworkHandler.instance().getNetworkIdMap().values();
dat.writeInt(networkMods.size());
for (NetworkModHandler handler : networkMods)
{
dat.writeUTF(handler.getContainer().getModId());
dat.writeInt(handler.getNetworkId());
}
// TODO send the other id maps as well
return dat.toByteArray();
}
@Override
public FMLPacket consumePacket(byte[] data)
{
ByteArrayDataInput dat = ByteStreams.newDataInput(data);
int listSize = dat.readInt();
for (int i = 0; i < listSize; i++)
{
String modId = dat.readUTF();
int networkId = dat.readInt();
modIds.put(modId, networkId);
}
return this;
}
@Override
public void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
for (Entry<String,Integer> idEntry : modIds.entrySet())
{
handler.bindNetworkId(idEntry.getKey(), idEntry.getValue());
}
// TODO other id maps
}
}
@@ -1,129 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_LIST_REQUEST;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_LIST_RESPONSE;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
public class ModListRequestPacket extends FMLPacket
{
private List<String> sentModList;
private byte compatibilityLevel;
public ModListRequestPacket()
{
super(MOD_LIST_REQUEST);
}
@Override
public byte[] generatePacket(Object... data)
{
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
Set<ModContainer> activeMods = FMLNetworkHandler.instance().getNetworkModList();
dat.writeInt(activeMods.size());
for (ModContainer mc : activeMods)
{
dat.writeUTF(mc.getModId());
}
dat.writeByte(FMLNetworkHandler.getCompatibilityLevel());
return dat.toByteArray();
}
@Override
public FMLPacket consumePacket(byte[] data)
{
sentModList = Lists.newArrayList();
ByteArrayDataInput in = ByteStreams.newDataInput(data);
int listSize = in.readInt();
for (int i = 0; i < listSize; i++)
{
sentModList.add(in.readUTF());
}
try
{
compatibilityLevel = in.readByte();
}
catch (IllegalStateException e)
{
FMLLog.fine("No compatibility byte found - the server is too old");
}
return this;
}
/**
*
* This packet is executed on the client to evaluate the server's mod list against
* the client
*
* @see cpw.mods.fml.common.network.FMLPacket#execute(INetworkManager, FMLNetworkHandler, NetHandler, String)
*/
@Override
public void execute(INetworkManager mgr, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
List<String> missingMods = Lists.newArrayList();
Map<String,String> modVersions = Maps.newHashMap();
Map<String, ModContainer> indexedModList = Maps.newHashMap(Loader.instance().getIndexedModList());
for (String m : sentModList)
{
ModContainer mc = indexedModList.get(m);
if (mc == null)
{
missingMods.add(m);
continue;
}
indexedModList.remove(m);
modVersions.put(m, mc.getVersion());
}
if (indexedModList.size()>0)
{
for (Entry<String, ModContainer> e : indexedModList.entrySet())
{
if (e.getValue().isNetworkMod())
{
NetworkModHandler missingHandler = FMLNetworkHandler.instance().findNetworkModHandler(e.getValue());
if (missingHandler.requiresServerSide())
{
// TODO : what should we do if a mod is marked "serverSideRequired"? Stop the connection?
FMLLog.warning("The mod %s was not found on the server you connected to, but requested that the server side be present", e.getKey());
}
}
}
}
FMLLog.fine("The server has compatibility level %d", compatibilityLevel);
FMLCommonHandler.instance().getSidedDelegate().setClientCompatibilityLevel(compatibilityLevel);
mgr.func_74429_a(PacketDispatcher.getPacket("FML", FMLPacket.makePacket(MOD_LIST_RESPONSE, modVersions, missingMods)));
}
}
@@ -1,153 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_IDENTIFIERS;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_LIST_RESPONSE;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_MISSING;
import static cpw.mods.fml.common.network.FMLPacket.Type.MOD_IDMAP;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.*;
import net.minecraft.network.packet.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.common.registry.GameRegistry;
public class ModListResponsePacket extends FMLPacket
{
private Map<String,String> modVersions;
private List<String> missingMods;
public ModListResponsePacket()
{
super(MOD_LIST_RESPONSE);
}
@Override
public byte[] generatePacket(Object... data)
{
Map<String,String> modVersions = (Map<String, String>) data[0];
List<String> missingMods = (List<String>) data[1];
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
dat.writeInt(modVersions.size());
for (Entry<String, String> version : modVersions.entrySet())
{
dat.writeUTF(version.getKey());
dat.writeUTF(version.getValue());
}
dat.writeInt(missingMods.size());
for (String missing : missingMods)
{
dat.writeUTF(missing);
}
return dat.toByteArray();
}
@Override
public FMLPacket consumePacket(byte[] data)
{
ByteArrayDataInput dat = ByteStreams.newDataInput(data);
int versionListSize = dat.readInt();
modVersions = Maps.newHashMapWithExpectedSize(versionListSize);
for (int i = 0; i < versionListSize; i++)
{
String modName = dat.readUTF();
String modVersion = dat.readUTF();
modVersions.put(modName, modVersion);
}
int missingModSize = dat.readInt();
missingMods = Lists.newArrayListWithExpectedSize(missingModSize);
for (int i = 0; i < missingModSize; i++)
{
missingMods.add(dat.readUTF());
}
return this;
}
@Override
public void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
Map<String, ModContainer> indexedModList = Maps.newHashMap(Loader.instance().getIndexedModList());
List<String> missingClientMods = Lists.newArrayList();
List<String> versionIncorrectMods = Lists.newArrayList();
for (String m : missingMods)
{
ModContainer mc = indexedModList.get(m);
NetworkModHandler networkMod = handler.findNetworkModHandler(mc);
if (networkMod.requiresClientSide())
{
missingClientMods.add(m);
}
}
for (Entry<String,String> modVersion : modVersions.entrySet())
{
ModContainer mc = indexedModList.get(modVersion.getKey());
NetworkModHandler networkMod = handler.findNetworkModHandler(mc);
if (!networkMod.acceptVersion(modVersion.getValue()))
{
versionIncorrectMods.add(modVersion.getKey());
}
}
Packet250CustomPayload pkt = new Packet250CustomPayload();
pkt.field_73630_a = "FML";
if (missingClientMods.size()>0 || versionIncorrectMods.size() > 0)
{
pkt.field_73629_c = FMLPacket.makePacket(MOD_MISSING, missingClientMods, versionIncorrectMods);
Logger.getLogger("Minecraft").info(String.format("User %s connection failed: missing %s, bad versions %s", userName, missingClientMods, versionIncorrectMods));
FMLLog.info("User %s connection failed: missing %s, bad versions %s", userName, missingClientMods, versionIncorrectMods);
// Mark this as bad
FMLNetworkHandler.setHandlerState((NetLoginHandler) netHandler, FMLNetworkHandler.MISSING_MODS_OR_VERSIONS);
pkt.field_73628_b = pkt.field_73629_c.length;
network.func_74429_a(pkt);
}
else
{
pkt.field_73629_c = FMLPacket.makePacket(MOD_IDENTIFIERS, netHandler);
Logger.getLogger("Minecraft").info(String.format("User %s connecting with mods %s", userName, modVersions.keySet()));
FMLLog.info("User %s connecting with mods %s", userName, modVersions.keySet());
pkt.field_73628_b = pkt.field_73629_c.length;
network.func_74429_a(pkt);
NBTTagList itemList = new NBTTagList();
GameData.writeItemData(itemList);
byte[][] registryPackets = FMLPacket.makePacketSet(MOD_IDMAP, itemList);
for (int i = 0; i < registryPackets.length; i++)
{
network.func_74429_a(PacketDispatcher.getPacket("FML", registryPackets[i]));
}
}
// reset the continuation flag - we have completed extra negotiation and the login should complete now
NetLoginHandler.func_72531_a((NetLoginHandler) netHandler, true);
}
}
@@ -1,120 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Lists;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import cpw.mods.fml.common.versioning.VersionRange;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
public class ModMissingPacket extends FMLPacket
{
private List<ModData> missing;
private List<ModData> badVersion;
public ModMissingPacket()
{
super(Type.MOD_MISSING);
}
@Override
public byte[] generatePacket(Object... data)
{
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
List<String> missing = (List<String>) data[0];
List<String> badVersion = (List<String>) data[1];
dat.writeInt(missing.size());
for (String missed : missing)
{
ModContainer mc = Loader.instance().getIndexedModList().get(missed);
dat.writeUTF(missed);
dat.writeUTF(mc.getVersion());
}
dat.writeInt(badVersion.size());
for (String bad : badVersion)
{
ModContainer mc = Loader.instance().getIndexedModList().get(bad);
dat.writeUTF(bad);
dat.writeUTF(mc.getVersion());
}
return dat.toByteArray();
}
private static class ModData
{
String modId;
String modVersion;
}
@Override
public FMLPacket consumePacket(byte[] data)
{
ByteArrayDataInput dat = ByteStreams.newDataInput(data);
int missingLen = dat.readInt();
missing = Lists.newArrayListWithCapacity(missingLen);
for (int i = 0; i < missingLen; i++)
{
ModData md = new ModData();
md.modId = dat.readUTF();
md.modVersion = dat.readUTF();
missing.add(md);
}
int badVerLength = dat.readInt();
badVersion = Lists.newArrayListWithCapacity(badVerLength);
for (int i = 0; i < badVerLength; i++)
{
ModData md = new ModData();
md.modId = dat.readUTF();
md.modVersion = dat.readUTF();
badVersion.add(md);
}
return this;
}
@Override
public void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
FMLCommonHandler.instance().getSidedDelegate().displayMissingMods(this);
}
public List<ArtifactVersion> getModList()
{
Builder<ArtifactVersion> builder = ImmutableList.<ArtifactVersion>builder();
for (ModData md : missing)
{
builder.add(new DefaultArtifactVersion(md.modId, VersionRange.createFromVersion(md.modVersion, null)));
}
for (ModData md : badVersion)
{
builder.add(new DefaultArtifactVersion(md.modId, VersionRange.createFromVersion(md.modVersion, null)));
}
return builder.build();
}
}
@@ -1,97 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface NetworkMod
{
/**
* Does this mod require the client side to be present when installed on a server?
*/
boolean clientSideRequired() default false;
/**
* Does this mod require the server side to be present when installed on a client?
*/
boolean serverSideRequired() default false;
/**
* A list of Packet250 network channels to register for this mod - these channels
* will be universal and will require a universal packethandler to handle them
*/
String[] channels() default {};
/**
* An optional range check for client to server communication version compatibility
*/
String versionBounds() default "";
/**
* A packet handler implementation for channels registered through this annotation
* - this packet handler will be universal and handle both client and server
* requests.
*/
Class<? extends IPacketHandler> packetHandler() default NULL.class;
/**
* A tiny packet handler implementation based on {@link net.minecraft.network.packet.Packet131MapData} for "small"
* data packet loads.
*/
Class<? extends ITinyPacketHandler> tinyPacketHandler() default NULL.class;
/**
* A connection handler implementation for this network mod
*/
Class<? extends IConnectionHandler> connectionHandler() default NULL.class;
/**
* A packet handler and channels to register for the client side
*/
SidedPacketHandler clientPacketHandlerSpec() default @SidedPacketHandler(channels = {}, packetHandler = NULL.class );
/**
* A packet handler and channels to register for the server side
*/
SidedPacketHandler serverPacketHandlerSpec() default @SidedPacketHandler(channels = {}, packetHandler = NULL.class );
/**
* Special dummy class for handling stupid annotation default values
* @author cpw
*
*/
static interface NULL extends IPacketHandler, IConnectionHandler, ITinyPacketHandler {};
/**
* A marker for a method that will be offered the client's version string
* if more sophisticated version rejection handling is required:
* The method should accept a "String", a "NetworkManager" and return a boolean true
* if the version can be accepted.
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface VersionCheckHandler { }
/**
* Bundles together a packet handler and it's associated channels for the sided packet handlers
* @author cpw
*
*/
public @interface SidedPacketHandler {
String[] channels();
Class<? extends IPacketHandler> packetHandler();
}
}
@@ -1,369 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.logging.Level;
import net.minecraft.item.Item;
import com.google.common.base.Strings;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.discovery.ASMDataTable.ASMData;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import cpw.mods.fml.common.versioning.InvalidVersionSpecificationException;
import cpw.mods.fml.common.versioning.VersionRange;
import cpw.mods.fml.relauncher.Side;
public class NetworkModHandler
{
private static Object connectionHandlerDefaultValue;
private static Object packetHandlerDefaultValue;
private static Object clientHandlerDefaultValue;
private static Object serverHandlerDefaultValue;
private static Object tinyPacketHandlerDefaultValue;
private static int assignedIds = 1;
private int localId;
private int networkId;
private ModContainer container;
private NetworkMod mod;
private Method checkHandler;
private VersionRange acceptableRange;
private ITinyPacketHandler tinyPacketHandler;
public NetworkModHandler(ModContainer container, NetworkMod modAnnotation)
{
this.container = container;
this.mod = modAnnotation;
this.localId = assignedIds++;
this.networkId = this.localId;
// Skip over the map object because it has special network id meaning
if (Item.field_77744_bd.field_77779_bT == assignedIds)
{
assignedIds++;
}
}
public NetworkModHandler(ModContainer container, Class<?> networkModClass, ASMDataTable table)
{
this(container, networkModClass.getAnnotation(NetworkMod.class));
if (this.mod == null)
{
return;
}
Set<ASMData> versionCheckHandlers = table.getAnnotationsFor(container).get(NetworkMod.VersionCheckHandler.class.getName());
String versionCheckHandlerMethod = null;
for (ASMData vch : versionCheckHandlers)
{
if (vch.getClassName().equals(networkModClass.getName()))
{
versionCheckHandlerMethod = vch.getObjectName();
break;
}
}
if (versionCheckHandlerMethod != null)
{
try
{
Method checkHandlerMethod = networkModClass.getDeclaredMethod(versionCheckHandlerMethod, String.class);
if (checkHandlerMethod.isAnnotationPresent(NetworkMod.VersionCheckHandler.class))
{
this.checkHandler = checkHandlerMethod;
}
}
catch (Exception e)
{
FMLLog.log(Level.WARNING, e, "The declared version check handler method %s on network mod id %s is not accessible", versionCheckHandlerMethod, container.getModId());
}
}
configureNetworkMod(container);
}
protected void configureNetworkMod(ModContainer container)
{
if (this.checkHandler == null)
{
String versionBounds = mod.versionBounds();
if (!Strings.isNullOrEmpty(versionBounds))
{
try
{
this.acceptableRange = VersionRange.createFromVersionSpec(versionBounds);
}
catch (InvalidVersionSpecificationException e)
{
FMLLog.log(Level.WARNING, e, "Invalid bounded range %s specified for network mod id %s", versionBounds, container.getModId());
}
}
}
FMLLog.finest("Testing mod %s to verify it accepts its own version in a remote connection", container.getModId());
boolean acceptsSelf = acceptVersion(container.getVersion());
if (!acceptsSelf)
{
FMLLog.severe("The mod %s appears to reject its own version number (%s) in its version handling. This is likely a severe bug in the mod!", container.getModId(), container.getVersion());
}
else
{
FMLLog.finest("The mod %s accepts its own version (%s)", container.getModId(), container.getVersion());
}
tryCreatingPacketHandler(container, mod.packetHandler(), mod.channels(), null);
if (FMLCommonHandler.instance().getSide().isClient())
{
if (mod.clientPacketHandlerSpec() != getClientHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.clientPacketHandlerSpec().packetHandler(), mod.clientPacketHandlerSpec().channels(), Side.CLIENT);
}
}
if (mod.serverPacketHandlerSpec() != getServerHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.serverPacketHandlerSpec().packetHandler(), mod.serverPacketHandlerSpec().channels(), Side.SERVER);
}
if (mod.connectionHandler() != getConnectionHandlerDefaultValue())
{
IConnectionHandler instance;
try
{
instance = mod.connectionHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create connection handler instance %s", mod.connectionHandler().getName());
throw new FMLNetworkException(e);
}
NetworkRegistry.instance().registerConnectionHandler(instance);
}
if (mod.tinyPacketHandler()!=getTinyPacketHandlerDefaultValue())
{
try
{
tinyPacketHandler = mod.tinyPacketHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create tiny packet handler instance %s", mod.tinyPacketHandler().getName());
throw new FMLNetworkException(e);
}
}
}
/**
* @param container
*/
private void tryCreatingPacketHandler(ModContainer container, Class<? extends IPacketHandler> clazz, String[] channels, Side side)
{
if (side!=null && side.isClient() && ! FMLCommonHandler.instance().getSide().isClient())
{
return;
}
if (clazz!=getPacketHandlerDefaultValue())
{
if (channels.length==0)
{
FMLLog.log(Level.WARNING, "The mod id %s attempted to register a packet handler without specifying channels for it", container.getModId());
}
else
{
IPacketHandler instance;
try
{
instance = clazz.newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create a packet handler instance %s for mod %s", clazz.getName(), container.getModId());
throw new FMLNetworkException(e);
}
for (String channel : channels)
{
NetworkRegistry.instance().registerChannel(instance, channel, side);
}
}
}
else if (channels.length > 0)
{
FMLLog.warning("The mod id %s attempted to register channels without specifying a packet handler", container.getModId());
}
}
/**
* @return the default {@link NetworkMod#connectionHandler()} annotation value
*/
private Object getConnectionHandlerDefaultValue()
{
try {
if (connectionHandlerDefaultValue == null)
{
connectionHandlerDefaultValue = NetworkMod.class.getMethod("connectionHandler").getDefaultValue();
}
return connectionHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
/**
* @return the default {@link NetworkMod#packetHandler()} annotation value
*/
private Object getPacketHandlerDefaultValue()
{
try {
if (packetHandlerDefaultValue == null)
{
packetHandlerDefaultValue = NetworkMod.class.getMethod("packetHandler").getDefaultValue();
}
return packetHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
/**
* @return the default {@link NetworkMod#tinyPacketHandler()} annotation value
*/
private Object getTinyPacketHandlerDefaultValue()
{
try {
if (tinyPacketHandlerDefaultValue == null)
{
tinyPacketHandlerDefaultValue = NetworkMod.class.getMethod("tinyPacketHandler").getDefaultValue();
}
return tinyPacketHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
/**
* @return the {@link NetworkMod#clientPacketHandlerSpec()} default annotation value
*/
private Object getClientHandlerSpecDefaultValue()
{
try {
if (clientHandlerDefaultValue == null)
{
clientHandlerDefaultValue = NetworkMod.class.getMethod("clientPacketHandlerSpec").getDefaultValue();
}
return clientHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
/**
* @return the default {@link NetworkMod#serverPacketHandlerSpec()} annotation value
*/
private Object getServerHandlerSpecDefaultValue()
{
try {
if (serverHandlerDefaultValue == null)
{
serverHandlerDefaultValue = NetworkMod.class.getMethod("serverPacketHandlerSpec").getDefaultValue();
}
return serverHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
public boolean requiresClientSide()
{
return mod.clientSideRequired();
}
public boolean requiresServerSide()
{
return mod.serverSideRequired();
}
public boolean acceptVersion(String version)
{
if (checkHandler != null)
{
try
{
return (Boolean)checkHandler.invoke(container.getMod(), version);
}
catch (Exception e)
{
FMLLog.log(Level.WARNING, e, "There was a problem invoking the checkhandler method %s for network mod id %s", checkHandler.getName(), container.getModId());
return false;
}
}
if (acceptableRange!=null)
{
return acceptableRange.containsVersion(new DefaultArtifactVersion(version));
}
return container.getVersion().equals(version);
}
public int getLocalId()
{
return localId;
}
public int getNetworkId()
{
return networkId;
}
public ModContainer getContainer()
{
return container;
}
public NetworkMod getMod()
{
return mod;
}
public boolean isNetworkMod()
{
return mod != null;
}
public void setNetworkId(int value)
{
this.networkId = value;
}
public boolean hasTinyPacketHandler()
{
return tinyPacketHandler != null;
}
public ITinyPacketHandler getTinyPacketHandler()
{
return tinyPacketHandler;
}
}
@@ -1,361 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.network.*;
import net.minecraft.network.packet.*;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.network.FMLPacket.Type;
import cpw.mods.fml.relauncher.Side;
/**
* @author cpw
*
*/
public class NetworkRegistry
{
private static final NetworkRegistry INSTANCE = new NetworkRegistry();
/**
* A map of active channels per player
*/
private Multimap<Player, String> activeChannels = ArrayListMultimap.create();
/**
* A map of the packet handlers for packets
*/
private Multimap<String, IPacketHandler> universalPacketHandlers = ArrayListMultimap.create();
private Multimap<String, IPacketHandler> clientPacketHandlers = ArrayListMultimap.create();
private Multimap<String, IPacketHandler> serverPacketHandlers = ArrayListMultimap.create();
/**
* A linked set of registered connection handlers
*/
private Set<IConnectionHandler> connectionHandlers = Sets.newLinkedHashSet();
private Map<ModContainer, IGuiHandler> serverGuiHandlers = Maps.newHashMap();
private Map<ModContainer, IGuiHandler> clientGuiHandlers = Maps.newHashMap();
private List<IChatListener> chatListeners = Lists.newArrayList();
public static NetworkRegistry instance()
{
return INSTANCE;
}
/**
* Get the packet 250 channel registration string
* @return the {@link Packet250CustomPayload} channel registration string
*/
byte[] getPacketRegistry(Side side)
{
return Joiner.on('\0').join(Iterables.concat(Arrays.asList("FML"),universalPacketHandlers.keySet(), side.isClient() ? clientPacketHandlers.keySet() : serverPacketHandlers.keySet())).getBytes(Charsets.UTF_8);
}
/**
* Is the specified channel active for the player?
* @param channel
* @param player
*/
public boolean isChannelActive(String channel, Player player)
{
return activeChannels.containsEntry(player,channel);
}
/**
* register a channel to a mod
* @param handler the packet handler
* @param channelName the channel name to register it with
*/
public void registerChannel(IPacketHandler handler, String channelName)
{
if (Strings.isNullOrEmpty(channelName) || (channelName!=null && channelName.length()>16))
{
FMLLog.severe("Invalid channel name '%s' : %s", channelName, Strings.isNullOrEmpty(channelName) ? "Channel name is empty" : "Channel name is too long (16 chars is maximum)");
throw new RuntimeException("Channel name is invalid");
}
universalPacketHandlers.put(channelName, handler);
}
public void registerChannel(IPacketHandler handler, String channelName, Side side)
{
if (side == null)
{
registerChannel(handler, channelName);
return;
}
if (Strings.isNullOrEmpty(channelName) || (channelName!=null && channelName.length()>16))
{
FMLLog.severe("Invalid channel name '%s' : %s", channelName, Strings.isNullOrEmpty(channelName) ? "Channel name is empty" : "Channel name is too long (16 chars is maximum)");
throw new RuntimeException("Channel name is invalid");
}
if (side.isClient())
{
clientPacketHandlers.put(channelName, handler);
}
else
{
serverPacketHandlers.put(channelName, handler);
}
}
/**
* Activate the channel for the player
* @param player
*/
void activateChannel(Player player, String channel)
{
activeChannels.put(player, channel);
}
/**
* Deactivate the channel for the player
* @param player
* @param channel
*/
void deactivateChannel(Player player, String channel)
{
activeChannels.remove(player, channel);
}
/**
* Register a connection handler
*
* @param handler
*/
public void registerConnectionHandler(IConnectionHandler handler)
{
connectionHandlers.add(handler);
}
/**
* Register a chat listener
* @param listener
*/
public void registerChatListener(IChatListener listener)
{
chatListeners.add(listener);
}
void playerLoggedIn(EntityPlayerMP player, NetServerHandler netHandler, INetworkManager manager)
{
generateChannelRegistration(player, netHandler, manager);
for (IConnectionHandler handler : connectionHandlers)
{
handler.playerLoggedIn((Player)player, netHandler, manager);
}
}
String connectionReceived(NetLoginHandler netHandler, INetworkManager manager)
{
for (IConnectionHandler handler : connectionHandlers)
{
String kick = handler.connectionReceived(netHandler, manager);
if (!Strings.isNullOrEmpty(kick))
{
return kick;
}
}
return null;
}
void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager networkManager)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.connectionOpened(netClientHandler, server, port, networkManager);
}
}
void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager networkManager)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.connectionOpened(netClientHandler, server, networkManager);
}
}
void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login)
{
generateChannelRegistration(clientHandler.getPlayer(), clientHandler, manager);
for (IConnectionHandler handler : connectionHandlers)
{
handler.clientLoggedIn(clientHandler, manager, login);
}
}
void connectionClosed(INetworkManager manager, EntityPlayer player)
{
for (IConnectionHandler handler : connectionHandlers)
{
handler.connectionClosed(manager);
}
activeChannels.removeAll(player);
}
void generateChannelRegistration(EntityPlayer player, NetHandler netHandler, INetworkManager manager)
{
Packet250CustomPayload pkt = new Packet250CustomPayload();
pkt.field_73630_a = "REGISTER";
pkt.field_73629_c = getPacketRegistry(player instanceof EntityPlayerMP ? Side.SERVER : Side.CLIENT);
pkt.field_73628_b = pkt.field_73629_c.length;
manager.func_74429_a(pkt);
}
void handleCustomPacket(Packet250CustomPayload packet, INetworkManager network, NetHandler handler)
{
if ("REGISTER".equals(packet.field_73630_a))
{
handleRegistrationPacket(packet, (Player)handler.getPlayer());
}
else if ("UNREGISTER".equals(packet.field_73630_a))
{
handleUnregistrationPacket(packet, (Player)handler.getPlayer());
}
else
{
handlePacket(packet, network, (Player)handler.getPlayer());
}
}
private void handlePacket(Packet250CustomPayload packet, INetworkManager network, Player player)
{
String channel = packet.field_73630_a;
for (IPacketHandler handler : Iterables.concat(universalPacketHandlers.get(channel), player instanceof EntityPlayerMP ? serverPacketHandlers.get(channel) : clientPacketHandlers.get(channel)))
{
handler.onPacketData(network, packet, player);
}
}
private void handleRegistrationPacket(Packet250CustomPayload packet, Player player)
{
List<String> channels = extractChannelList(packet);
for (String channel : channels)
{
activateChannel(player, channel);
}
}
private void handleUnregistrationPacket(Packet250CustomPayload packet, Player player)
{
List<String> channels = extractChannelList(packet);
for (String channel : channels)
{
deactivateChannel(player, channel);
}
}
private List<String> extractChannelList(Packet250CustomPayload packet)
{
String request = new String(packet.field_73629_c, Charsets.UTF_8);
List<String> channels = Lists.newArrayList(Splitter.on('\0').split(request));
return channels;
}
public void registerGuiHandler(Object mod, IGuiHandler handler)
{
ModContainer mc = FMLCommonHandler.instance().findContainerFor(mod);
if (mc == null)
{
mc = Loader.instance().activeModContainer();
FMLLog.log(Level.WARNING, "Mod %s attempted to register a gui network handler during a construction phase", mc.getModId());
}
NetworkModHandler nmh = FMLNetworkHandler.instance().findNetworkModHandler(mc);
if (nmh == null)
{
FMLLog.log(Level.FINE, "The mod %s needs to be a @NetworkMod to register a Networked Gui Handler", mc.getModId());
}
else
{
serverGuiHandlers.put(mc, handler);
}
clientGuiHandlers.put(mc, handler);
}
void openRemoteGui(ModContainer mc, EntityPlayerMP player, int modGuiId, World world, int x, int y, int z)
{
IGuiHandler handler = serverGuiHandlers.get(mc);
NetworkModHandler nmh = FMLNetworkHandler.instance().findNetworkModHandler(mc);
if (handler != null && nmh != null)
{
Container container = (Container)handler.getServerGuiElement(modGuiId, player, world, x, y, z);
if (container != null)
{
player.func_71117_bO();
player.func_71128_l();
int windowId = player.field_71139_cq;
Packet250CustomPayload pkt = new Packet250CustomPayload();
pkt.field_73630_a = "FML";
pkt.field_73629_c = FMLPacket.makePacket(Type.GUIOPEN, windowId, nmh.getNetworkId(), modGuiId, x, y, z);
pkt.field_73628_b = pkt.field_73629_c.length;
player.field_71135_a.func_72567_b(pkt);
player.field_71070_bA = container;
player.field_71070_bA.field_75152_c = windowId;
player.field_71070_bA.func_75132_a(player);
}
}
}
void openLocalGui(ModContainer mc, EntityPlayer player, int modGuiId, World world, int x, int y, int z)
{
IGuiHandler handler = clientGuiHandlers.get(mc);
FMLCommonHandler.instance().showGuiScreen(handler.getClientGuiElement(modGuiId, player, world, x, y, z));
}
public Packet3Chat handleChat(NetHandler handler, Packet3Chat chat)
{
Side s = Side.CLIENT;
if (handler instanceof NetServerHandler)
{
s = Side.SERVER;
}
for (IChatListener listener : chatListeners)
{
chat = s.isClient() ? listener.clientChat(handler, chat) : listener.serverChat(handler, chat);
}
return chat;
}
public void handleTinyPacket(NetHandler handler, Packet131MapData mapData)
{
NetworkModHandler nmh = FMLNetworkHandler.instance().findNetworkModHandler((int)mapData.field_73438_a);
if (nmh == null)
{
FMLLog.info("Received a tiny packet for network id %d that is not recognised here", mapData.field_73438_a);
return;
}
if (nmh.hasTinyPacketHandler())
{
nmh.getTinyPacketHandler().handle(handler, mapData);
}
else
{
FMLLog.info("Received a tiny packet for a network mod that does not accept tiny packets %s", nmh.getContainer().getModId());
}
}
}
@@ -1,71 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.NetHandler;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
public class OpenGuiPacket extends FMLPacket
{
private int windowId;
private int networkId;
private int modGuiId;
private int x;
private int y;
private int z;
public OpenGuiPacket()
{
super(Type.GUIOPEN);
}
@Override
public byte[] generatePacket(Object... data)
{
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
dat.writeInt((Integer) data[0]); // windowId
dat.writeInt((Integer) data[1]); // networkId
dat.writeInt((Integer) data[2]); // modGuiId
dat.writeInt((Integer) data[3]); // x
dat.writeInt((Integer) data[4]); // y
dat.writeInt((Integer) data[5]); // z
return dat.toByteArray();
}
@Override
public FMLPacket consumePacket(byte[] data)
{
ByteArrayDataInput dat = ByteStreams.newDataInput(data);
windowId = dat.readInt();
networkId = dat.readInt();
modGuiId = dat.readInt();
x = dat.readInt();
y = dat.readInt();
z = dat.readInt();
return this;
}
@Override
public void execute(INetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
{
EntityPlayer player = netHandler.getPlayer();
player.openGui(networkId, modGuiId, player.field_70170_p, x, y, z);
player.field_71070_bA.field_75152_c = windowId;
}
}
@@ -1,93 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet131MapData;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
/**
* A simple utility class to send packet 250 packets around the place
*
* @author cpw
*
*/
public class PacketDispatcher
{
public static Packet250CustomPayload getPacket(String type, byte[] data)
{
return new Packet250CustomPayload(type, data);
}
public static void sendPacketToServer(Packet packet)
{
FMLCommonHandler.instance().getSidedDelegate().sendPacket(packet);
}
public static void sendPacketToPlayer(Packet packet, Player player)
{
if (player instanceof EntityPlayerMP)
{
((EntityPlayerMP)player).field_71135_a.func_72567_b(packet);
}
}
public static void sendPacketToAllAround(double X, double Y, double Z, double range, int dimensionId, Packet packet)
{
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
if (server != null)
{
server.func_71203_ab().func_72393_a(X, Y, Z, range, dimensionId, packet);
}
else
{
FMLLog.fine("Attempt to send packet to all around without a server instance available");
}
}
public static void sendPacketToAllInDimension(Packet packet, int dimId)
{
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
if (server != null)
{
server.func_71203_ab().func_72396_a(packet, dimId);
}
else
{
FMLLog.fine("Attempt to send packet to all in dimension without a server instance available");
}
}
public static void sendPacketToAllPlayers(Packet packet)
{
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
if (server != null)
{
server.func_71203_ab().func_72384_a(packet);
}
else
{
FMLLog.fine("Attempt to send packet to all in dimension without a server instance available");
}
}
public static Packet131MapData getTinyPacket(Object mod, short tag, byte[] data)
{
NetworkModHandler nmh = FMLNetworkHandler.instance().findNetworkModHandler(mod);
return new Packet131MapData((short) nmh.getNetworkId(), tag, data);
}
}
@@ -1,23 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.network;
/**
*
* @author cpw
*
*/
public interface Player
{
}
@@ -1,5 +0,0 @@
package cpw.mods.fml.common.patcher;
public class ClassPatchingTransformer {
}
@@ -1,18 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.registry;
public interface BlockProxy
{
}
@@ -1,61 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.registry;
import java.util.BitSet;
import net.minecraft.block.Block;
class BlockTracker
{
private static final BlockTracker INSTANCE = new BlockTracker();
private BitSet allocatedBlocks;
private BlockTracker()
{
allocatedBlocks = new BitSet(4096);
allocatedBlocks.set(0, 4096);
for (int i = 0; i < Block.field_71973_m.length; i++)
{
if (Block.field_71973_m[i]!=null)
{
allocatedBlocks.clear(i);
}
}
}
public static int nextBlockId()
{
return instance().getNextBlockId();
}
private int getNextBlockId()
{
int idx = allocatedBlocks.nextSetBit(0);
allocatedBlocks.clear(idx);
return idx;
}
private static BlockTracker instance()
{
return INSTANCE;
}
public static void reserveBlockId(int id)
{
instance().doReserveId(id);
}
private void doReserveId(int id)
{
allocatedBlocks.clear(id);
}
}
@@ -1,390 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.registry;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import net.minecraft.block.Block;
import net.minecraft.block.BlockSand;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.ImmutableTable.Builder;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Tables;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import com.google.common.io.Files;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
public class GameData {
private static Map<Integer, ItemData> idMap = Maps.newHashMap();
private static CountDownLatch serverValidationLatch;
private static CountDownLatch clientValidationLatch;
private static MapDifference<Integer, ItemData> difference;
private static boolean shouldContinue = true;
private static boolean isSaveValid = true;
private static ImmutableTable<String, String, Integer> modObjectTable;
private static Table<String, String, ItemStack> customItemStacks = HashBasedTable.create();
private static Map<String,String> ignoredMods;
private static boolean isModIgnoredForIdValidation(String modId)
{
if (ignoredMods == null)
{
File f = new File(Loader.instance().getConfigDir(),"fmlIDChecking.properties");
if (f.exists())
{
Properties p = new Properties();
try
{
p.load(new FileInputStream(f));
ignoredMods = Maps.fromProperties(p);
if (ignoredMods.size()>0)
{
FMLLog.log("fml.ItemTracker", Level.WARNING, "Using non-empty ignored mods configuration file %s", ignoredMods.keySet());
}
}
catch (Exception e)
{
Throwables.propagateIfPossible(e);
FMLLog.log("fml.ItemTracker", Level.SEVERE, e, "Failed to read ignored ID checker mods properties file");
ignoredMods = ImmutableMap.<String, String>of();
}
}
else
{
ignoredMods = ImmutableMap.<String, String>of();
}
}
return ignoredMods.containsKey(modId);
}
public static void newItemAdded(Item item)
{
ModContainer mc = Loader.instance().activeModContainer();
if (mc == null)
{
mc = Loader.instance().getMinecraftModContainer();
if (Loader.instance().hasReachedState(LoaderState.AVAILABLE))
{
FMLLog.severe("It appears something has tried to allocate an Item outside of the initialization phase of Minecraft, this could be very bad for your network connectivity.");
}
}
String itemType = item.getClass().getName();
ItemData itemData = new ItemData(item, mc);
if (idMap.containsKey(item.field_77779_bT))
{
ItemData id = idMap.get(item.field_77779_bT);
FMLLog.log("fml.ItemTracker", Level.INFO, "The mod %s is overwriting existing item at %d (%s from %s) with %s", mc.getModId(), id.getItemId(), id.getItemType(), id.getModId(), itemType);
}
idMap.put(item.field_77779_bT, itemData);
if (!"Minecraft".equals(mc.getModId()))
{
FMLLog.log("fml.ItemTracker",Level.FINE, "Adding item %s(%d) owned by %s", item.getClass().getName(), item.field_77779_bT, mc.getModId());
}
}
public static void validateWorldSave(Set<ItemData> worldSaveItems)
{
isSaveValid = true;
shouldContinue = true;
// allow ourselves to continue if there's no saved data
if (worldSaveItems == null)
{
serverValidationLatch.countDown();
try
{
clientValidationLatch.await();
}
catch (InterruptedException e)
{
}
return;
}
Function<? super ItemData, Integer> idMapFunction = new Function<ItemData, Integer>() {
public Integer apply(ItemData input) {
return input.getItemId();
};
};
Map<Integer,ItemData> worldMap = Maps.uniqueIndex(worldSaveItems,idMapFunction);
difference = Maps.difference(worldMap, idMap);
FMLLog.log("fml.ItemTracker", Level.FINE, "The difference set is %s", difference);
if (!difference.entriesDiffering().isEmpty() || !difference.entriesOnlyOnLeft().isEmpty())
{
FMLLog.log("fml.ItemTracker", Level.SEVERE, "FML has detected item discrepancies");
FMLLog.log("fml.ItemTracker", Level.SEVERE, "Missing items : %s", difference.entriesOnlyOnLeft());
FMLLog.log("fml.ItemTracker", Level.SEVERE, "Mismatched items : %s", difference.entriesDiffering());
boolean foundNonIgnored = false;
for (ItemData diff : difference.entriesOnlyOnLeft().values())
{
if (!isModIgnoredForIdValidation(diff.getModId()))
{
foundNonIgnored = true;
}
}
for (ValueDifference<ItemData> diff : difference.entriesDiffering().values())
{
if (! ( isModIgnoredForIdValidation(diff.leftValue().getModId()) || isModIgnoredForIdValidation(diff.rightValue().getModId()) ) )
{
foundNonIgnored = true;
}
}
if (!foundNonIgnored)
{
FMLLog.log("fml.ItemTracker", Level.SEVERE, "FML is ignoring these ID discrepancies because of configuration. YOUR GAME WILL NOW PROBABLY CRASH. HOPEFULLY YOU WON'T HAVE CORRUPTED YOUR WORLD. BLAME %s", ignoredMods.keySet());
}
isSaveValid = !foundNonIgnored;
serverValidationLatch.countDown();
}
else
{
isSaveValid = true;
serverValidationLatch.countDown();
}
try
{
clientValidationLatch.await();
if (!shouldContinue)
{
throw new RuntimeException("This server instance is going to stop abnormally because of a fatal ID mismatch");
}
}
catch (InterruptedException e)
{
}
}
public static void writeItemData(NBTTagList itemList)
{
for (ItemData dat : idMap.values())
{
itemList.func_74742_a(dat.toNBT());
}
}
/**
* Initialize the server gate
* @param gateCount the countdown amount. If it's 2 we're on the client and the client and server
* will wait at the latch. 1 is a server and the server will proceed
*/
public static void initializeServerGate(int gateCount)
{
serverValidationLatch = new CountDownLatch(gateCount - 1);
clientValidationLatch = new CountDownLatch(gateCount - 1);
}
public static MapDifference<Integer, ItemData> gateWorldLoadingForValidation()
{
try
{
serverValidationLatch.await();
if (!isSaveValid)
{
return difference;
}
}
catch (InterruptedException e)
{
}
difference = null;
return null;
}
public static void releaseGate(boolean carryOn)
{
shouldContinue = carryOn;
clientValidationLatch.countDown();
}
public static Set<ItemData> buildWorldItemData(NBTTagList modList)
{
Set<ItemData> worldSaveItems = Sets.newHashSet();
for (int i = 0; i < modList.func_74745_c(); i++)
{
NBTTagCompound mod = (NBTTagCompound) modList.func_74743_b(i);
ItemData dat = new ItemData(mod);
worldSaveItems.add(dat);
}
return worldSaveItems;
}
static void setName(Item item, String name, String modId)
{
int id = item.field_77779_bT;
ItemData itemData = idMap.get(id);
itemData.setName(name,modId);
}
public static void buildModObjectTable()
{
if (modObjectTable != null)
{
throw new IllegalStateException("Illegal call to buildModObjectTable!");
}
Map<Integer, Cell<String, String, Integer>> map = Maps.transformValues(idMap, new Function<ItemData,Cell<String,String,Integer>>() {
public Cell<String,String,Integer> apply(ItemData data)
{
if ("Minecraft".equals(data.getModId()) || !data.isOveridden())
{
return null;
}
return Tables.immutableCell(data.getModId(), data.getItemType(), data.getItemId());
}
});
Builder<String, String, Integer> tBuilder = ImmutableTable.builder();
for (Cell<String, String, Integer> c : map.values())
{
if (c!=null)
{
tBuilder.put(c);
}
}
modObjectTable = tBuilder.build();
}
static Item findItem(String modId, String name)
{
if (modObjectTable == null || !modObjectTable.contains(modId, name))
{
return null;
}
return Item.field_77698_e[modObjectTable.get(modId, name)];
}
static Block findBlock(String modId, String name)
{
if (modObjectTable == null)
{
return null;
}
Integer blockId = modObjectTable.get(modId, name);
if (blockId == null || blockId >= Block.field_71973_m.length)
{
return null;
}
return Block.field_71973_m[blockId];
}
static ItemStack findItemStack(String modId, String name)
{
ItemStack is = customItemStacks.get(modId, name);
if (is == null)
{
Item i = findItem(modId, name);
if (i != null)
{
is = new ItemStack(i, 0 ,0);
}
}
if (is == null)
{
Block b = findBlock(modId, name);
if (b != null)
{
is = new ItemStack(b, 0, Short.MAX_VALUE);
}
}
return is;
}
static void registerCustomItemStack(String name, ItemStack itemStack)
{
customItemStacks.put(Loader.instance().activeModContainer().getModId(), name, itemStack);
}
public static void dumpRegistry(File minecraftDir)
{
if (customItemStacks == null)
{
return;
}
if (Boolean.valueOf(System.getProperty("fml.dumpRegistry", "false")).booleanValue())
{
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (String modId : customItemStacks.rowKeySet())
{
builder.putAll(modId, customItemStacks.row(modId).keySet());
}
File f = new File(minecraftDir, "itemStackRegistry.csv");
MapJoiner mapJoiner = Joiner.on("\n").withKeyValueSeparator(",");
try
{
Files.write(mapJoiner.join(builder.build().entries()), f, Charsets.UTF_8);
FMLLog.log(Level.INFO, "Dumped item registry data to %s", f.getAbsolutePath());
}
catch (IOException e)
{
FMLLog.log(Level.SEVERE, e, "Failed to write registry data to %s", f.getAbsolutePath());
}
}
}
static UniqueIdentifier getUniqueName(Block block)
{
if (block == null) return null;
ItemData itemData = idMap.get(block.field_71990_ca);
if (itemData == null || !itemData.isOveridden() || customItemStacks.contains(itemData.getModId(), itemData.getItemType()))
{
return null;
}
return new UniqueIdentifier(itemData.getModId(), itemData.getItemType());
}
static UniqueIdentifier getUniqueName(Item item)
{
if (item == null) return null;
ItemData itemData = idMap.get(item.field_77779_bT);
if (itemData == null || !itemData.isOveridden() || customItemStacks.contains(itemData.getModId(), itemData.getItemType()))
{
return null;
}
return new UniqueIdentifier(itemData.getModId(), itemData.getItemType());
}
}
@@ -1,167 +0,0 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.registry;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.nbt.NBTTagCompound;
import com.google.common.base.Objects;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderException;
import cpw.mods.fml.common.ModContainer;
public class ItemData {
private static Map<String, Multiset<String>> modOrdinals = Maps.newHashMap();
private final String modId;
private final String itemType;
private final int itemId;
private final int ordinal;
private String forcedModId;
private String forcedName;
public ItemData(Item item, ModContainer mc)
{
this.itemId = item.field_77779_bT;
if (item.getClass().equals(ItemBlock.class))
{
this.itemType = Block.field_71973_m[this.getItemId()].getClass().getName();
}
else
{
this.itemType = item.getClass().getName();
}
this.modId = mc.getModId();
if (!modOrdinals.containsKey(mc.getModId()))
{
modOrdinals.put(mc.getModId(), HashMultiset.<String>create());
}
this.ordinal = modOrdinals.get(mc.getModId()).add(itemType, 1);
}
public ItemData(NBTTagCompound tag)
{
this.modId = tag.func_74779_i("ModId");
this.itemType = tag.func_74779_i("ItemType");
this.itemId = tag.func_74762_e("ItemId");
this.ordinal = tag.func_74762_e("ordinal");
this.forcedModId = tag.func_74764_b("ForcedModId") ? tag.func_74779_i("ForcedModId") : null;
this.forcedName = tag.func_74764_b("ForcedName") ? tag.func_74779_i("ForcedName") : null;
}
public String getItemType()
{
return this.forcedName !=null ? forcedName : itemType;
}
public String getModId()
{
return this.forcedModId != null ? forcedModId : modId;
}
public int getOrdinal()
{
return ordinal;
}
public int getItemId()
{
return itemId;
}
public NBTTagCompound toNBT()
{
NBTTagCompound tag = new NBTTagCompound();
tag.func_74778_a("ModId", modId);
tag.func_74778_a("ItemType", itemType);
tag.func_74768_a("ItemId", itemId);
tag.func_74768_a("ordinal", ordinal);
if (forcedModId != null)
{
tag.func_74778_a("ForcedModId", forcedModId);
}
if (forcedName != null)
{
tag.func_74778_a("ForcedName", forcedName);
}
return tag;
}
@Override
public int hashCode()
{
return Objects.hashCode(itemId, ordinal);
}
@Override
public boolean equals(Object obj)
{
try
{
ItemData other = (ItemData) obj;
return Objects.equal(getModId(), other.getModId()) && Objects.equal(getItemType(), other.getItemType()) && Objects.equal(itemId, other.itemId) && ( isOveridden() || Objects.equal(ordinal, other.ordinal));
}
catch (ClassCastException cce)
{
return false;
}
}
@Override
public String toString()
{
return String.format("Item %d, Type %s, owned by %s, ordinal %d, name %s, claimedModId %s", itemId, itemType, modId, ordinal, forcedName, forcedModId);
}
public boolean mayDifferByOrdinal(ItemData rightValue)
{
return Objects.equal(getItemType(), rightValue.getItemType()) && Objects.equal(getModId(), rightValue.getModId());
}
public boolean isOveridden()
{
return forcedName != null;
}
public void setName(String name, String modId)
{
if (name == null)
{
this.forcedName = null;
this.forcedModId = null;
return;
}
String localModId = modId;
if (modId == null)
{
localModId = Loader.instance().activeModContainer().getModId();
}
if (modOrdinals.get(localModId).count(name)>0)
{
FMLLog.severe("The mod %s is attempting to redefine the item at id %d with a non-unique name (%s.%s)", Loader.instance().activeModContainer(), itemId, localModId, name);
throw new LoaderException();
}
modOrdinals.get(localModId).add(name);
this.forcedModId = modId;
this.forcedName = name;
}
}
Loaded 100 of 500 files, more files were not shown because too many files have changed in this diff. Show more