Compare commits

...

183 commits

Author SHA1 Message Date
Timo Ley 22ebc12fc8 Added Magneticraft and Gregtech support
Some checks failed
continuous-integration/drone Build is failing
2020-04-09 23:52:49 +02:00
Timo Ley 7b056c057d build 37 2020-03-20 22:17:02 +01:00
Timo Ley 041395b06e Unified Categories 2020-03-20 22:16:00 +01:00
Timo Ley 10eb55bc74 Removed EnergyType.java 2020-03-20 22:15:39 +01:00
Timo Ley 77b3fb454e build.gradle fix 2020-03-20 22:14:53 +01:00
malte0811 9ea0b355a5 Build 1.7-36 2019-01-25 18:44:26 +01:00
malte0811 cf90f293a3 Merge branch 'feature/rgbLED' into MC1.12 2019-01-25 18:16:07 +01:00
malte0811 f9fe9de715 Finish up the RGB indicator component, closes #71 2019-01-25 18:14:59 +01:00
malte0811 ba69040855 Fixed some issues regarding the IE redstone controller on dedicated servers, closes #56, maybe #51 as well? 2019-01-25 17:15:32 +01:00
malte0811 5aea1281ca Add a RGB indicator component, see #71
ToDo: Recipe, Docs, Texture, localization including GUI
2019-01-20 21:18:09 +01:00
malte0811 507b5e11d8 Fix insulated and uninsulated IC2 wires producing the same coils, closes #64 2019-01-20 20:30:14 +01:00
malte0811 86cefa9162 Fix a control panel dupe bug, closes #69 2019-01-19 22:18:31 +01:00
malte0811 7c62332b57 Build 1.7-35 2019-01-15 08:32:08 +01:00
malte0811 0f3794e645 Fix crashes when placing chests in the crafting table, closes #67, closes #68 2019-01-15 08:25:29 +01:00
malte0811 e9a8225f77 Build 1.7-34 2019-01-12 21:09:16 +01:00
malte0811 c6d2a26a6d The resistor wires are returned when the marx generator is disassembled now, closes #62 2019-01-12 11:37:16 +01:00
malte0811 63d9fca789 Panels can have any texture now, textures are changed by crafting the unfinished panel with the block it should "imitate". Closes #54
ToDo documentation
2019-01-11 16:18:24 +01:00
malte0811 ceb28da474 Basics of "painted" panels 2019-01-11 15:05:39 +01:00
malte0811 c84a0476fd Fix weird behavior with multiple RS controller IDs, closes #59
Unfinished control panels can be copied like components can now (To create multiple panels with exact same height and angle)
2019-01-05 10:10:35 +01:00
malte0811 2f02fc5044 Fix the "other" RS controller not keeping its IO state across world reloads
Fix P:R wires showing as a too low signal strength
2019-01-04 20:49:46 +01:00
malte0811 961b325111 Build 1.7-33 2018-12-02 12:58:44 +01:00
malte0811 c7045eb9a8
Merge pull request #46 from StolenSoda/ru_lang
ru_RU.lang
2018-12-02 12:45:41 +01:00
malte0811 43bd502095 Fix the Marx generator not breaking/processing ores, closes #47
Fix panel wire connectors not working when connected directly to another one or the Marge generator
2018-11-27 21:26:43 +01:00
StolenSoda c433eb67b9
ru_RU.lang
This is complete translation of this mod into Russian.
2018-11-24 17:50:50 +03:00
malte0811 208fc0611e Build 1.7-32 2018-11-18 18:05:38 +01:00
malte0811 9fd6ec2d16 Adjusted a few values for the Mech MB sounds 2018-11-18 17:44:23 +01:00
malte0811 c5c1818749 Fix some mechanical multiblock parts not rendering properly with Optifine, closes #44 2018-11-17 12:55:19 +01:00
malte0811 88c10cdb81 Switch to the new data-driven connector models
Update to new mappings
2018-11-17 12:23:31 +01:00
malte0811 a60b55cad1 Build 1.7-31 2018-09-07 23:59:43 +02:00
malte0811 93f156da4e Fixed accidental conversion from FE to EU, closes #42
Fixed connectors not blowing up as intended
2018-09-07 23:55:50 +02:00
malte0811 51e139b568 Build 1.7-30 2018-09-03 21:15:33 +02:00
malte0811 9616e310a6
Merge pull request #37 from DepletedPrism/patch-1
Update zh_CN.lang
2018-09-03 21:05:23 +02:00
malte0811 39ebc86029 Add a config option for wire transfer rates, closes #40
Fix connectors blowing up when they shouldn't in some cases
2018-09-03 21:01:45 +02:00
malte0811 69c8713853 Finally fix the package name 2018-09-03 20:35:23 +02:00
malte0811 cbcc95a010 Fixed crashes when using the wires without IC2, closes #41 2018-09-03 20:10:38 +02:00
malte0811 a9a481c1cf Build 1.7-29 2018-08-25 17:59:06 +02:00
malte0811 8962cd1bcb Updated documentation/manual
Register the wires and connectors even if IC2 isn't installed
2018-08-25 17:51:07 +02:00
malte0811 0eb9a03185 Fixed the Marx generator not charging past a certain point, closes #39 2018-08-25 16:53:59 +02:00
malte0811 d51562b937 Probably actually works now 2018-08-25 16:25:43 +02:00
malte0811 c8bba65ad4 Relays/connectors need to be craftable as well 2018-08-22 10:38:43 +02:00
malte0811 220b74ab94 Recipes to make the wires when IC2 isn't installed 2018-08-11 21:30:19 +02:00
malte0811 1c24abda2c The wires now work with both FE and EU, but not at the same time 2018-08-11 20:58:58 +02:00
DepletedPrism e00881400b
Update zh_CN.lang
Update part of language file, but the part of the manual is not translated.
完善了部分汉化,但仍剩余手册的一部分未翻译。
2018-08-08 17:25:39 +08:00
malte0811 f48d277280 Build 1.7-28 2018-08-05 22:19:41 +02:00
malte0811 d548bd5cf3 Updated the manual entry on RS control panel interaction 2018-08-05 22:01:13 +02:00
malte0811 f228d2178d Recipe and better texture for the redstone controller 2018-08-05 21:21:05 +02:00
malte0811 4fef9f6a04 Added Charset compat to the redstone controller
TODO recipe
2018-08-05 16:49:55 +02:00
malte0811 7599b5cd31 Some fixes and a (possibly temporary) texture for the redstone controller 2018-08-04 14:46:50 +02:00
malte0811 fc2e9dca4d Initial version of a redstone controller for Project:Red bundled cables (no texture, localization, probably crashes without P:R) 2018-08-01 17:29:24 +02:00
malte0811 b5826d226b Single component panels work, fixed some bugs with normal ones 2018-07-31 17:34:18 +02:00
malte0811 bd26b2b358 Cleanup of the cleanup, standard panels should work now 2018-07-30 21:51:58 +02:00
malte0811 1cef97f260 Major cleanup of the redstone side of control panels. Not done yet. 2018-07-30 20:30:57 +02:00
malte0811 c48bbb2d63 Add localization for IW multiblocks, closes #33 2018-07-17 21:18:59 +02:00
malte0811 f94d73717f Fix zero-length mechanical multiblocks being allowed to form, as well as some crashes when one is formed/broken, closes #34 2018-07-17 21:03:14 +02:00
malte0811 0a67837965 Build 1.7-27 2018-07-16 20:05:48 +02:00
malte0811 dca94087a2 Added an update checker (Forge JSON) 2018-07-16 19:53:20 +02:00
malte0811 cb7aef646a Fix #31, fix #32, as well as some other potential issues on dedicated servers 2018-07-16 19:00:51 +02:00
malte0811 17598cc9e9 Use ObjectHolder's for IE items and blocks 2018-07-16 18:53:32 +02:00
malte0811 71716a722e Build 1.7-26
Some fixes
2018-06-27 22:49:20 +02:00
malte0811 16c01a8049 Some bugfixes for the small converters 2018-06-27 21:06:03 +02:00
malte0811 33cc33170e Fixed IO parts getting stuck with bad waveforms 2018-06-24 18:50:25 +02:00
malte0811 880d350720 Misc fixes for the mechanical multiblocks 2018-06-22 18:51:51 +02:00
malte0811 40eaa907ef Misc changes to the mechanical multiblocks 2018-06-17 21:06:15 +02:00
malte0811 311a498a90 Finished the separated energy inputs/outputs. Textures will need to change since they get blocked by most pipes/connectors 2018-06-16 23:08:38 +02:00
malte0811 3d2865aa93 Basic separated energy inputs/outputs for MechMB's 2018-06-16 19:15:15 +02:00
malte0811 5364b14f5b Some misc fixes
I may have to move to seperate inputs/outputs
2018-06-15 21:11:25 +02:00
malte0811 375c30d139 Some cleanup, fixed another issue along the lines of #28 2018-06-15 16:15:06 +02:00
malte0811 e377b77819 Fixed issues with energy loops through wires outside of mechanical multiblocks 2018-06-15 09:35:14 +02:00
malte0811 2b9ec80253 Not just the master block should be able to interact with the IC2 energy net 2018-06-14 22:01:39 +02:00
malte0811 7008f53faa Fixed some errors and issues on dedicated servers 2018-06-13 19:09:35 +02:00
malte0811 63603d12f1 Earmuffs work better with mechanical multiblocks now 2018-06-13 18:29:10 +02:00
malte0811 781ed3d773 Mechanical multiblock examples look mostly right when used with the IP projector 2018-06-08 21:11:06 +02:00
malte0811 bf8ea992b8 Fix some issues with wire energy loss, closes #28
Fix a crash on startup with IP since it makes assumptions about multiblocks
2018-06-08 20:56:17 +02:00
malte0811 8c16f44970 Fixed some UV's, minor changes to the Marx generator texture 2018-06-05 20:26:44 +02:00
malte0811 0cda304c56 Finished up the manual entry on MechMB's 2018-06-04 18:10:52 +02:00
malte0811 448489b01f Add a simplified version of MultiblockTemplate to display MechMB parts in the manual
Updated the text splitter with the changes from the manual rewrite, fixed some additional bugs
2018-06-02 21:22:26 +02:00
malte0811 7ebf25b3d5 Improve sound by using ITickableSound as opposed to starting and stopping the sound every tick 2018-05-27 13:32:43 +02:00
malte0811 b65cdc6fbe General cleanup 2018-05-26 18:46:40 +02:00
malte0811 b3fefaa078 New sound files!
Fixed broken parts spawning in wrong places sometimes
Some changes to sound volume/pitch calculation
2018-05-26 18:18:53 +02:00
malte0811 d5b537ea98 Misc cleanup, removed some comments on things I won't implement (for now) 2018-05-14 19:07:52 +02:00
malte0811 a756de6ace Pick block works on mechanical multiblocks now
Fix crashes without IC2
2018-05-14 18:51:42 +02:00
malte0811 b43150d6c9 Fixed UV's for the ends of the shaft 2018-05-13 18:54:56 +02:00
malte0811 eb7f73464f Misc fixes, mostly related to sound and the "broken parts" entities 2018-05-12 19:04:38 +02:00
malte0811 3f08c47a73 Sound system is mostly done, I'll probably record new versions of the sounds in a few weeks (to remove frequency changes within a segment) 2018-05-06 20:33:24 +02:00
malte0811 b12501a86c Mech MB sound, take 1 2018-04-22 22:14:08 +02:00
malte0811 1959b93f5b Fixed some potential CME's
IC2 feedthrough connectors properly disassemble now
2018-04-06 18:25:46 +02:00
malte0811 12510ecc5b The voltmeter can now measure the exact speed of a mechanical multiblock 2018-04-06 18:05:11 +02:00
malte0811 bd0c941ac8 Moved everything that can use EU and FE to using joules as an internal storage unit 2018-04-06 17:29:26 +02:00
malte0811 92a114d29d Proper bounding boxes for mech MB parts
Added the missing bits of axle at the ends of the MB
Added a versioning NBT tag to the mech MB to allow easy changing of the MB structure
2018-04-04 20:47:44 +02:00
malte0811 184d12b7cb Maybe fixed the last of the energy transmission issues? 2018-04-02 18:12:01 +02:00
malte0811 b7bc55a0a9 A lot of bugfixes, also new models and textures for some of the parts 2018-03-27 21:31:03 +02:00
malte0811 87f4dc8f93 More work
Changed waveform system to be more usable in code
Added some max speeds
2018-03-24 17:45:25 +01:00
malte0811 1fb01d9abd Started adding 4-phase stuff 2018-03-23 16:27:32 +01:00
malte0811 316cc2ab78 Added a speedometer for automatic speed control
Fixed variacs and sliders on dedicated panels not working on world reload
2018-03-02 22:05:27 +01:00
malte0811 b913e28271 Updated copyright to 2018 2018-02-28 21:06:33 +01:00
malte0811 8cca1b13e1 Added the commutator, the essential part for medium-power conversion
Also, textures! Some are s**t, esp the one for the magnet ring
2018-02-28 21:03:26 +01:00
malte0811 56fb9e3b3a Merge branch 'MC1.12' into mechStuff 2018-02-19 20:39:55 +01:00
malte0811 c3570a1273 Build 1.6-25 2018-02-19 18:11:45 +01:00
malte0811 23df4324ec Mechanical MB's disassemble properly now
Started implementing mechanical failure (currently only for flywheels)
Changed the waveforms. This is supposed to be efficient!
2018-02-17 20:37:53 +01:00
malte0811 8d98e30b04 More mech MB work
This is getting somewhere!
2018-02-13 19:23:02 +01:00
malte0811 b87b67b17f Fixed the redstone wire controller not connecting to RS wires 2018-02-09 21:17:14 +01:00
malte0811 8190a4c80e Prevent HV wires from connecting to manual breaker switches
The wire changes are on Maven now!
2018-02-04 17:00:31 +01:00
malte0811 129d8f732a Added textures for the insulated wire coils
Fixed incorrect/missing error messages when linking connectors
2018-02-02 18:08:33 +01:00
malte0811 d3508e42fe More TMP commits 2018-02-02 17:20:53 +01:00
malte0811 6c60b4562b Merge branch 'MC1.12' into mechStuff 2018-02-01 20:56:12 +01:00
malte0811 ced4704b14 Added insulated wires for tin, copper and gold (textures ToDo)
Added a recipe for the discharge meter
2018-01-31 21:51:34 +01:00
malte0811 93fb75a0b0 Adapted to the changes in wiring code for the next IE release 2018-01-30 21:59:09 +01:00
malte0811 ff3c391ac5 Added a discharge meter, a device that can measure the energy in a Marx discharge
Also some experimental stuff for wire coils
2018-01-28 21:30:53 +01:00
malte0811 534f844d0e Build 1.6-24
Changed the default maximum conversion amounts
2018-01-09 18:26:34 +01:00
malte0811 b09745a320 Fixed infinite kinetic energy being produced, closes #22 2018-01-09 17:55:25 +01:00
malte0811 58692ceb76 TMP commit 2018-01-01 20:07:20 +01:00
malte0811 b0156b70a0 Build 1.6-23
Panel components have to be shift-clicked to place them in the world
2017-12-08 20:15:02 +01:00
malte0811 8ff35f0ea4 Revert to the old buffer handling, reopens #18 2017-12-08 19:55:02 +01:00
malte0811 37233621bf Fixed things blowing up (see last commit), closes #18 2017-12-08 19:29:57 +01:00
malte0811 5b50013f68 Limit the connector buffer to the input power, see #18
This currently causes things to blow up for non-obvious reasons when cables are involved
2017-12-08 18:30:53 +01:00
malte0811 15cf1010aa Added a recipe for seven-segment displays 2017-12-08 17:17:15 +01:00
malte0811 14fde279be Added a command to make taking screenshots of Marx generator discharges easier/possible 2017-11-26 13:52:52 +01:00
malte0811 afccf9b677 Coil length crafting works again, see #19 2017-11-26 13:37:34 +01:00
malte0811 2df8bc4f29 Build 1.6-22
Stop using JavaFX vectors as they don't seem to exist in a normal instance
2017-10-31 17:16:25 +01:00
malte0811 d3b84e6823 Panel components update their color as soon as the value is changed in the GUI, rather than on closing the GUI 2017-10-31 16:44:29 +01:00
malte0811 09161bce5f Added a seven-segment display for control panels 2017-10-31 16:29:38 +01:00
malte0811 e21684818f Possibly fixed a race condition NPE with panel models 2017-10-29 13:59:27 +01:00
malte0811 6000203141 Fixed panel component raytracing sorting
Components can no longer be activated through the back of the panel
2017-10-28 18:53:21 +02:00
malte0811 543368ad7c Fixed crashes with 2-channel components where the second id is selected, but not the channel 2017-10-27 21:08:17 +02:00
malte0811 a35150f8e7 Possibly fixed a weird crash when placing control panels? 2017-10-27 18:52:08 +02:00
malte0811 f4884d23ba Build 1.6-21
Updated README.md+screenshot
Fixed the Marx generator not charging properly off an EU supply
Fixed the IE version detection. Stupid Java optimized out the field access to the version String since it's static final
2017-10-22 20:02:41 +02:00
malte0811 746a5d1b57 Improved rendering of the Marx generator in the manual
The mach converter entry isn't duplicated any more
2017-10-21 21:15:01 +02:00
malte0811 1b9bd041b0 Minor cleanup of the Marx generator disassembly code 2017-10-20 18:59:27 +02:00
malte0811 59527ba600 Added an auto-splitter for manual entries. Currently just used for the Marx generator entry. 2017-10-20 18:25:53 +02:00
malte0811 a4de0c800d Fixed issues with block breaking (Marx generator) 2017-10-10 18:42:44 +02:00
malte0811 d3b937433d Merge branch 'shaders' into MC1.12 2017-10-10 18:34:22 +02:00
malte0811 cc14d20595 Added shaders for the Marx generator and the Jacob's ladder 2017-10-10 18:31:32 +02:00
malte0811 9f6407e300 New ear damage distance formula. Manual and reality should match this time! 2017-10-09 20:31:01 +02:00
malte0811 f33650280e Fixed a race condition with Marx generator discharges (probably, as usual with race conditions) 2017-10-08 18:39:15 +02:00
malte0811 ab77d28bc9 Fixed invisible wires on dedicated servers 2017-10-07 18:51:28 +02:00
malte0811 e9449440fd Build 1.6-20
Fix some Marx crashes on dedicated servers
Fix wires attached to MG's sometimes not rendering
Fix issues with tinnitus when setting volume to 0
2017-09-15 20:03:23 +02:00
malte0811 67562ef296 Remove TE's that don't need to tick from the ticking TE list
Use IE uranium if IC2 isn't installed
2017-09-13 21:32:19 +02:00
malte0811 d5d0dca298 Replace Albedo by Mirage
Fix orientation of the Marx spark gap render
Fix lighting differences between mirrored and normal Marx gens
2017-09-06 21:18:59 +02:00
malte0811 c8c2b5bf88 Lots of small fixes for the Marx generator
Includes mirrored models. TODO: Recalculate normals for default models to fix lighting differences
2017-09-04 22:04:53 +02:00
malte0811 8d4c0fcad2 Merge branch 'marx' into MC1.12 2017-09-04 17:42:50 +02:00
malte0811 bd194462e1 Add a note to the MG manual entry that most analog panel components support dual-channel fine control 2017-09-04 17:03:43 +02:00
malte0811 ac7d36b5e7 Add documentation on the Marx generator
Add a command to get/set/regenerate the marx energy factor
2017-09-03 20:48:10 +02:00
malte0811 a732ffa6a9 Remove manual entries if IC2 isn't loaded 2017-09-02 18:03:16 +02:00
malte0811 2b3bad1149 Add signing info 2017-09-02 17:20:57 +02:00
malte0811 e5e400a1fa TR doesn't need special wires 2017-09-01 21:13:23 +02:00
malte0811 685a9058f6 Allow CT to remove marx recipes 2017-08-29 22:01:51 +02:00
malte0811 bc1ebc9fa5 Add JEI support for the Marx generator 2017-08-29 21:31:22 +02:00
malte0811 96aa3ec96a Add CraftTweaker support for the Marx generator 2017-08-27 22:45:52 +02:00
malte0811 e200185235 Add a separate sound for Marx misfirings
Add a texture for the tinnitus potion effect
2017-08-27 20:27:29 +02:00
malte0811 840869cd08 Fix some bugs&crashes when IC2 isn't installed
Some general cleanup
2017-08-23 22:30:24 +02:00
malte0811 ccc3c7ab12 IC2 is an optional dependency now, probably still buggy
Fix the TE names
2017-08-22 18:33:05 +02:00
malte0811 e003367bf7 Add a second snapping option to the panel creator. This allows snapping the left/right edge or center of a component to one of those of an existing component. 2017-08-21 21:08:30 +02:00
malte0811 f62a13596b Add second-channel support to the Variac, the Panel Meter and the slider 2017-08-18 22:41:33 +02:00
malte0811 2f609e9026 Add a second RS channel for each voltage signal to allow precise control 2017-08-16 21:15:26 +02:00
malte0811 a61639052e Fix Marx discharge and spark gap render rotation 2017-08-16 18:28:54 +02:00
malte0811 505464c002 Discharges can fail if the total voltage is too low
Added Albedo compat for the marx generator
2017-08-15 21:37:53 +02:00
malte0811 2b2f5ca6c1 Replace the ore-specific energy values with one global constant, to make it possible to determine the constant with cheap ores
Fix a crash when interacting with the top/bottom side of a HV capacitor
2017-08-14 21:56:44 +02:00
malte0811 bf74920482 Update changelog and contributing guidelines 2017-08-14 18:25:12 +02:00
malte0811 fdacf4129f Don't interact with other TE's in onChunkUnload, closes #12
(Ported from 1.11)
2017-08-14 17:38:33 +02:00
malte0811 c18d94899a Change the structure of the Marx generator to not include IC2 blocks
Finish up the texture/model
Fix some bugs where the energy storage goes negative and starts charging the marx to -Infinity V
2017-08-13 18:46:46 +02:00
malte0811 ea2355de28 Fix lighted buttons and toggle switches resetting on chunk reloads 2017-08-10 21:58:05 +02:00
malte0811 5667768420 Merge branch 'MC1.12' into marx
# Conflicts:
#	build.gradle
#	src/main/java/malte0811/industrialWires/IndustrialWires.java
#	src/main/java/malte0811/industrialWires/blocks/controlpanel/TileEntityPanel.java
#	src/main/java/malte0811/industrialWires/blocks/hv/BlockJacobsLadder.java
#	src/main/java/malte0811/industrialWires/blocks/hv/TileEntityJacobsLadder.java
#	src/main/java/malte0811/industrialWires/client/ClientProxy.java
#	src/main/java/malte0811/industrialWires/client/render/TileRenderJacobsLadder.java
#	src/main/java/malte0811/industrialWires/controlpanel/PanelComponent.java
2017-08-07 22:03:07 +02:00
malte0811 c53b09b6ce Merge branch 'MC1.12' into marx
# Conflicts:
#	build.gradle
#	src/main/java/malte0811/industrialWires/IndustrialWires.java
#	src/main/java/malte0811/industrialWires/blocks/controlpanel/TileEntityPanel.java
#	src/main/java/malte0811/industrialWires/blocks/hv/BlockJacobsLadder.java
#	src/main/java/malte0811/industrialWires/blocks/hv/TileEntityJacobsLadder.java
#	src/main/java/malte0811/industrialWires/client/ClientProxy.java
#	src/main/java/malte0811/industrialWires/client/render/TileRenderJacobsLadder.java
#	src/main/java/malte0811/industrialWires/controlpanel/PanelComponent.java
2017-08-06 18:15:08 +02:00
malte0811 1a304e169e Fixed GUI backgrounds not being darkened and item tooltips not showing in the Panel Creator GUI 2017-07-14 16:52:19 +02:00
malte0811 5911b6a49e Build 1.5-15
Fixed an issue with control panels on servers
2017-07-13 18:13:06 +02:00
malte0811 74c0115102 Added documentation on the key ring and fixed some bugs with it 2017-07-13 17:53:05 +02:00
malte0811 304c5e50a6 Added documentation on single-component panels 2017-07-13 17:14:37 +02:00
malte0811 1def161870 Single-component panels are complete, just docs and probably bugfixes to do 2017-07-13 09:23:41 +02:00
malte0811 92b00f199c Started adding single-component panel blocks. Very WIP 2017-07-12 20:20:11 +02:00
malte0811 2d06c96e46 Build 1.5-14 2017-07-10 21:13:37 +02:00
malte0811 107196ed1b One more fix for connecting panels using connectors after the panel and the controller have been placed 2017-07-10 20:50:16 +02:00
malte0811 6f6edab7b1 IW's items show up in the creative search now
Coil length crafting now leaves the correct coil behind if the length is over the maximum
2017-07-10 20:30:18 +02:00
malte0811 9ee44021bc Update to 1.12: Recipes
The recipe book is quite inconsistent about NBT...
2017-07-10 17:59:43 +02:00
malte0811 d0472b45b9 Update to 1.12: Everything except recipes done. Probably quite buggy 2017-07-09 18:10:06 +02:00
malte0811 d68eb801c3 Started implementing ore processing 2017-06-25 18:00:48 +02:00
malte0811 9ae4bad8b6 Misc Marx stuff:
-The bottom cap charges faster now
-Tinnitus can be replaced by damage or nausea in the config file
-If the first cap is charged higher than the charging voltage it will only be discharged if the yellow signal is 0
-Improved handling of low stored power
2017-06-23 17:40:49 +02:00
malte0811 5f8ef84e0f Merge branch 'MC1.11' into marx 2017-06-23 17:33:13 +02:00
malte0811 143311aecf Effects of Marx discharges on entities:
Damage for thos close to the discharge, tinnitus for those further out
Also added a nice bang for discharges (it is from a cap bank rather than a Marx though)
2017-06-16 22:04:30 +02:00
malte0811 d65621a0b5 Redstone control, other misc Marx generator details 2017-06-09 11:37:23 +02:00
malte0811 206c1170f1 Merge branch 'MC1.11' into marx 2017-06-05 17:23:18 +02:00
malte0811 963755af78 Wire connections and bounding boxes for the Marx generator
Some misc stuff
2017-06-03 21:06:25 +02:00
malte0811 d4bed0d324 Added a render for the Marx generator 2017-06-02 17:57:17 +02:00
malte0811 5a80b2626b Marx generator. It forms and breaks
Models for mirrored marx generators are broken
The IC2 cables drop as items due to missing IC2 API methods
2017-06-01 11:44:07 +02:00
350 changed files with 27362 additions and 4309 deletions

View file

@ -18,7 +18,7 @@ Some mods are not officially supported by IndustrialWires. They will probably wo
- **Fastcraft**: same as Optifine.
- **(K)Cauldron** and similar server software: While the source code of some of these is available on GitHub or similar platforms, it would require a lot of extra work to test everything with every server software.
- **Sponge(Forge)** and similar server software: While the source code of some of these is available on GitHub or similar platforms, it would require a lot of extra work to test everything with every server software.
- **Any version of IndustrialCraft2 that is not made by the official IC2 team** (more specifically, any IC2 version not available for download [here](http://jenkins.ic2.player.to/) or [here](https://minecraft.curseforge.com/projects/industrial-craft))

View file

@ -1,11 +1,15 @@
#Industrial Wires
![](Screenshot.png)
![An example of what Industrial Wires can do](Screenshot.png)
An addon for Immersive Engineering. Some features, like the EU-transmitting IE-style wires the mod is named after, will only be enabled if IC2 is installed. All devices added by IndustrialWires can run of IC2 EU as well as ForgeEnergy/RF.
An addon for Immersive Engineering and IndustrialCraft2. It adds IE-style wires that are able to transmit IC2 energy (EU). This is different from the IC2 compatibility IE had in MC 1.7.10 as it is not possible to convert IC2 power to RF/IF/Tesla/forge energy/etc.
The features can be split into to groups: IC2 compat and HV/electronics stuff
- IC2 compat:
- IE style wires that transmit EU. Check the manual for recipes
- Lossy converters between IE's rotational energy (windmills, watermills) and IC2's kinetic energy
- HV/electronics:
- [Control panels](https://www.youtube.com/watch?v=hV0cN20vCMY)
- Jacob's ladders. They don't do anything useful apart from looking nice (Shown in the control panel video)
- Marx generators. Ore processing using lightning/high voltage. You need to do a little bit of math to use it for that, but you can still use it to kill things/people without doing any!
Recipes for the relays, connectors and wires can be found in the Engineer's Manual.
All textures for the connectors are modified versions of the textures Immersive Engineering uses and the models are loaded out of IE, so all art for the wires is at least based on art Mr. Damien Hazard made.
The textures for the mechanical converters and the Rotational Motor were made by C8H8O4.
The textures and models are partially modified IE resources and partially made by C8H8O4 or me.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 320 KiB

After

Width:  |  Height:  |  Size: 392 KiB

View file

@ -1,81 +1,251 @@
def mainVersion = "1.5"
def buildNumber = "13"
// For those who want the bleeding edge
buildscript {
repositories {
jcenter()
maven {
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.2-SNAPSHOT'
}
}
apply plugin: 'net.minecraftforge.gradle.forge'
/*
// for people who want stable - not yet functional for MC 1.8.8 - we require the forgegradle 2.1 snapshot
plugins {
id "net.minecraftforge.gradle.forge" version "2.0.2"
}
*/
version = "${mainVersion}-${buildNumber}"
group= "malte0811"
archivesBaseName = "IndustrialWires"
sourceCompatibility = 1.8
targetCompatibility = 1.8
minecraft {
version = "13.20.0.2282"
runDir = "run"
replace '${version}', project.version
mappings = "snapshot_20170612"
}
repositories {
maven {
name 'ic2'
url 'http://maven.ic2.player.to/'
}
maven {
name 'jared maven'
url 'http://blamejared.com/maven'
}
}
dependencies {
compile "net.industrial-craft:industrialcraft-2:2.7.+"
deobfCompile "blusunrize:ImmersiveEngineering:0.11-+:deobf"
}
jar {
from 'LICENSE'
manifest {
}
}
processResources
{
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand 'version':project.version, 'mcversion':project.minecraft.version
}
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
import groovy.json.JsonOutput
def mainVersion = "1.7"
def buildNumber = "38"
// For those who want the bleeding edge
buildscript {
repositories {
jcenter()
maven {
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
}
}
apply plugin: 'net.minecraftforge.gradle.forge'
apply plugin: 'idea'
/*
// for people who want stable - not yet functional for MC 1.8.8 - we require the forgegradle 2.1 snapshot
plugins {
id "net.minecraftforge.gradle.forge" version "2.0.2"
}
*/
version = "${mainVersion}-${buildNumber}"
group= "malte0811"
archivesBaseName = "IndustrialWires"
sourceCompatibility = 1.8
targetCompatibility = 1.8
minecraft {
version = "1.12.2-14.23.5.2847"
runDir = "run"
replace '${version}', project.version
mappings = "stable_39"
}
repositories {
maven {
name 'ic2'
url 'http://maven.ic2.player.to/'
}
maven {
name 'tr'
url 'http://maven.modmuss50.me'
}
maven {
name 'jared maven'
url 'http://blamejared.com/maven'
}
maven { // Albedo/Mirage Lights
url 'https://repo.elytradev.com/'
}
maven { // JEI & Tinkers
name 'DVS1 Maven FS'
url 'http://dvs1.progwml6.com/files/maven'
}
// dependencies of TR...
maven {
url 'http://maven.mcmoddev.com'
}
maven {
// HWYLA
name "TehNut"
url "http://tehnut.info/maven/"
}
repositories {//Curseforge maven for project red
maven {
name = "CurseForge"
url = "https://minecraft.curseforge.com/api/maven/"
}
}
maven {
name = "chickenbones"
url = "http://chickenbones.net/maven"
}
}
dependencies {
compile 'net.industrial-craft:industrialcraft-2:2.8.+'
deobfCompile "blusunrize:ImmersiveEngineering:0.12-+"
compileOnly "pl.asie.charset:charset:0.5.6.4.19:full"
//Project red and runtime dependencies
compileOnly "project-red-base:ProjectRed-1.12.2:4.9.1.92:Base"
//runtime "project-red-integration:ProjectRed-1.12.2:4.9.1.92:integration"
//runtime "forge-multipart-cbe:ForgeMultipart-1.12.2:2.5.0.69:universal"
//runtime "codechicken:CodeChickenLib:1.12.2-3.2.1.349:universal"
//runtime "codechicken:ChickenASM:1.12-1.0.2.7"
//runtime "mrtjpcore:MrTJPCore-1.12.2:2.1.3.35:universal"
//Tech Reborn
compileOnly "TechReborn:TechReborn-1.12:2.6.9.7:universal"
compileOnly "RebornCore:RebornCore-1.12:3.2.+:universal"
//Others
//TODO do something about this
// compileOnly 'com.elytradev:mirage:2.0.1-SNAPSHOT'
compileOnly "mezz.jei:jei_1.12:4.+"
compileOnly "CraftTweaker2:CraftTweaker2-MC1120-Main:1.12-4.1.8.460"
compile 'com.elytradev:mirage:2.0.3-rc3-SNAPSHOT'
compile "gregtechce:gregtech:1.12.2:1.9.0.481"
compile "magneticraft:Magneticraft_1.12:2.8.2:dev"
}
jar {
from 'LICENSE'
manifest {
attributes 'Maven-Artifact': group+':'+archivesBaseName+':'+version
attributes "FMLAT": "industrialwires_at.cfg"
}
}
task signMain(type: SignJar) {
onlyIf {
project.hasProperty('keyStore')
}
dependsOn reobfJar
if (project.hasProperty('keyStore')) {
keyStore = project.keyStore
alias = project.storeAlias
storePass = project.storePass
keyPass = project.storePass
inputFile = jar.archivePath
outputFile = jar.archivePath
}
}
build.dependsOn signMain
processResources
{
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand 'version':project.version, 'mcversion':project.minecraft.version
}
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
//Code for automatic update JSON generation
class GenerateUpdateJSON extends DefaultTask {
static def IW_VERSION_PREFIX = "####Version "
static def MC_VERSION_PREFIX = "###Minecraft "
static def UNFINISHED_SUFFIX = " - UNFINISHED"
static def RECOMMENDED = "-recommended"
static def LATEST = "-latest"
static def CF_URL = "https://minecraft.curseforge.com/projects/industrial-wires"
int compareVersions(String vA, String vB) {
String[] vPartsA = vA.split("[\\D]")
String[] vPartsB = vB.split("[\\D]")
if (vPartsA.length==0&&vPartsB.length==0)
return vA <=> vB
else if (vPartsA.length==0)
return -1
else if (vPartsB.length==0)
return 1
int length = Math.min(vPartsA.length, vPartsB.length)
for (int i = 0;i<length;i++) {
int pA = Integer.parseInt(vPartsA[i])
int pB = Integer.parseInt(vPartsB[i])
if (pA!=pB) {
return pA<=>pB
}
}
if (vPartsA.length != vPartsB.length)
return vPartsA.length <=> vPartsB.length
return vA <=> vB
}
def addChangelog(Map<String, Map<String, String>> changelogForVersions, Map<String, String> promos,
String currentMCVersion, String currentVersion, String currentChangelog) {
if (!changelogForVersions.containsKey(currentMCVersion)) {
promos.put(currentMCVersion+RECOMMENDED, currentVersion)
promos.put(currentMCVersion+LATEST, currentVersion)
changelogForVersions[currentMCVersion] = new TreeMap<>({String s1, String s2->
compareVersions(s1, s2)})
}
changelogForVersions[currentMCVersion][currentVersion] = currentChangelog
}
@TaskAction
def generate() {
File changelog = new File("changelog.md")
if (!changelog.exists())
println "Changelog does not exist! Aborting!"
else {
String currentMCVersion = "";
Map<String, Map<String, String>> changelogForVersions = new HashMap<>()
Map<String, String> promos = new TreeMap<>({String s1, String s2->
compareVersions(s1, s2)})
String currentVersion = null
String currentChangelog = ""
changelog.eachLine {line ->
if (line.startsWith(IW_VERSION_PREFIX)) {
if (currentVersion!=null) {
addChangelog(changelogForVersions, promos, currentMCVersion, currentVersion, currentChangelog)
}
if (!line.endsWith(UNFINISHED_SUFFIX)) {
currentVersion = line.substring(IW_VERSION_PREFIX.length())
} else {
currentVersion = (String) null
}
currentChangelog = ""
} else if (line.startsWith(MC_VERSION_PREFIX)) {
if (currentVersion!=null) {
addChangelog(changelogForVersions, promos, currentMCVersion, currentVersion, currentChangelog)
}
currentChangelog = ""
currentVersion = (String) null
currentMCVersion = line.substring(MC_VERSION_PREFIX.length())
} else if (!line.isEmpty()) {
if (currentChangelog.length()==0)
currentChangelog += line
else
currentChangelog += "\n"+line
}
}
Map<String, Object> mainMap = new TreeMap<>({String s1, String s2->
compareVersions(s1, s2)})
mainMap.putAll(changelogForVersions)
mainMap["homepage"] = CF_URL
mainMap["promos"] = promos
def outJson = JsonOutput.toJson(mainMap)
outJson = JsonOutput.prettyPrint(outJson)
File outF = new File("changelog.json")
outF.delete()
outF << outJson
}
}
}
task updateJson(type: GenerateUpdateJSON)
build.finalizedBy updateJson

51
changelog.json Normal file
View file

@ -0,0 +1,51 @@
{
"homepage": "https://minecraft.curseforge.com/projects/industrial-wires",
"promos": {
"1.10.2-latest": "1.4-18",
"1.10.2-recommended": "1.4-18",
"1.11.2-latest": "1.5-19",
"1.11.2-recommended": "1.5-19",
"1.12.2-latest": "1.7-36",
"1.12.2-recommended": "1.7-36"
},
"1.10.2": {
"1.1-3": " - fixed incompatibility with IE build 48\n - reduced the amount of calls to core IE classes to make such incompatibilities less likely\n - fixed localization of the creative tab",
"1.1-4": " - fixed an insane amount of log-spam in an edgecase (probably a Vanilla or Forge bug)\n - added config values for wire length per connection and per coil item\n ",
"1.2-5 (10,000 download celebratory release)": " - added mechanical converters and the rotational motor\n - they convert between IE rotational energy (windmill, dynamo etc) and IC2 kinetic energy\n - Rotational motor: produces IE rotational energy from IF\n - No lossless conversion\n - Can be disabled in the config\n - wire coils show when they are out of range (to match the behavior of IE coils in the latest dev version)",
"1.2-6": " - reduced the discrepancies between IC2 cables and Industrial Wires\n - machines don't explode when they shouldn't except in some corner cases\n - potentially fixed missing textures on the mechanical converters\n - added Chinese translations (thanks SihenZhang)",
"1.3-7": " - added Jacob's Ladders/High voltage travelling arcs\n - they don't have a particular purpose aside from looking nice",
"1.3-8": " - the converters and the motor don't have missing textures any more when using Chisel",
"1.4-9": " - added Control Panels\n - They can be used to control and monitor a lot of redstone signals from a few blocks",
"1.4-10": " - added lock switches for control panels (backport from 1.11)\n - Can only be turned on by someone with the correct key to prevent unauthorized access\n - up to 10 keys can be added to a keyring to reduce inventory spam\n - IC2 items can be added to the appropriate sections of the engineers toolbox (backport from 1.11)\n - Components (lighted button, indicator light, etc.) on panels now actually light up (backport from 1.11)\n - Fixed power loss when no energy is being transmitted",
"1.4-16": " - Backported a lot of fixes from 1.11 and 1.12",
"1.4-18": " - Fixed a crash with SpongeForge, chunk loading issues without\n - Fixed some components resetting on chunk unload"
},
"1.11.2": {
"1.5-11": " - Updated to Minecraft 1.11.2\n - Added Panel Meters to monitor a redstone signal with reasonable accuracy\n - Multiple components on the same panel network can modify the same signal now without causing undefined behavior\n - Lock Switches no longer break the model cache",
"1.5-12": " - Added tilted control panels\n - Panels are no longer created from machine casings, there is a dedicated item for that now, the Unfinished Control Panel\n - Angle and height can be configured in the Engineer's Workbench\n - Fixed a CME when multi-threaded chunk rendering is enabled\n - Fixed control panels not connecting or disconnecting properly when a panel connector between the panel and the RS controller is broken/placed\n - Improved the performance of the control panel hitbox rendering",
"1.5-13": " - Labels no longer break the model cache and cause lag\n - Labels don't break on dedicated servers any more",
"1.5-17": " - Backported some fixes from 1.12",
"1.5-19": " - Fixed a crash with SpongeForge, chunk loading issues without\n - Fixed some components resetting on chunk unload"
},
"1.12.2": {
"1.5-14": " - Updated to Minecraft 1.12\n - Added a recipe for the key ring. Kind of forgot about adding one when I added the ring itself...\n - Fixed wire length crafting leaving wrong coils when the output has maximum length\n - Fixed some more connection issues with control panels",
"1.5-15": " - Components can be placed in the world now to use the as conventional levers/etc.\n - Added documentation on the key ring. It also shows all attached keys on the tooltip now\n - Fixed some bugs with key ring crafting\n - Fixed control panels causing disconnects on servers",
"1.6-20": " - Added the Marx Generator, an alternative ore processing method\n - Hearing protection absolutely required!\n - You may need to do some math and measurements for ore processing to work. It will kill entites just fine without any science\n - IC2 is no longer a hard dependency. The wires and converters will obviously be disabled without it\n - Vastly improved snapping in the panel creator\n - Added some Mirage (Albedo) compat\n - IW is signed now!\n - Analog panel components can interact with 2 channels now, rough and fine control\n - Fixed GUI background and item tooltips\n - Fixed some components resetting when the chunk is unloaded\n - Chunks with control panels properly unload now",
"1.6-21": " - Added shaders for the Marx generator and Jacob's ladder\n - Fixed wires connected to a Marx generator on a server being invisible\n - The Marx generator actually gives output when processing ores now. Oops...\n - The \"safe distance\" formulas for the Marx generator in the manual now match the real safe distance\n - Improved rendering of the Marx generator in the manual. Some of this is only enabled with maven build 275+ or official build 75+ (not released yet)",
"1.6-22": " - Added a Seven-Segment display for control panels\n - Panel components update their values as soon as they are changed in the GUI\n - Fixed a crash when breaking a panel with buttons, locks or toggle switches on it under special circumstances\n - Fixed server crashes when using panel components with a second controller id, but no channel set\n - Fixed various NPE crashes with control panel models under heavy load\n - Fixed wrong panel component ordering with raytracing",
"1.6-23": " - Added a command to allow taking screenshots of Marx generator discharges (/ciw triggermarxscreenshot)\n - Panel components have to be shift-clicked to place them in the world\n - Fixed wire coil crafting\n - Added a recipe for the Seven-Segment displays",
"1.6-24": " - Fixed an infinite energy bug\n - Changed the default value for maximum energy conversion",
"1.6-25": " - Updated to IE build 77\n - IC2 wires cause damage\n - Added insulated versions of gold, copper and tin wires. Due to heat sensitive insulation the transfer capacity is half of the normal capacity\n - Added feedthrough insulators for all IC2 wire types\n - Wire coils now automatically \"merge\" when picked up\n - Config values are applied to the game directly now",
"1.7-26": " - Added Mechanical Multiblocks (energy storage and EU<->FE conversion)\n - There will be an explanation video for these once I have time to make one\n - Fixed the small mechanical converter blowing up tin wires\n - Fixed wires not joining their outputs correctly\n - Fixed wire connectors not breaking when the block they're on is broken",
"1.7-27": " - Fixed panel components causing issues on dedicated servers\n - Added an automatic update checker (Using the Forge update JSON)",
"1.7-28": " - Added the Redstone Controller: Others, it allows control panels to interface with Project:Red and Charset wires\n - Rewrote the control panel redstone code\n - Added localization for IW's multiblocks\n - Fixed issues with zero-length mechanical multiblocks",
"1.7-29": " - The wires can now transmit FE as well as EU, but not both at once\n - Fixed the Marx generator not charging beyond a quite low voltage",
"1.7-30": " - Fixed crashes when IC2 isn't installed\n - Fixed connectors allowing too much power output\n - Added a config option for some of the wires' properties\n - Updated chinese translation (thanks @DepletedPrism)",
"1.7-31": " - Fixed accidental conversion from FE to EU\n - Fixed connectors not blowing up as intended\n ",
"1.7-32": " - Fixed connectors not rendering properly without IC2\n - Fixed parts of the mechanical multiblocks not rendering when Optifine is installed\n - Changed some values for the mechanical multiblock sound",
"1.7-33": " - Fixed the Marx generator not processing ores\n - Fixed control panels and the Marx generator not working when connected directly\n - Added Russian translation (thanks @StolenSoda)",
"1.7-34": " - Control panels can use the texture of any block now\n - Added a recipe to copy the settings of an unfinished control panel\n - The Marx generator now returns the wires used in its construction when disassembled\n - Fixed the RS controller for non-IE wires not keeping its IO state on world reload\n - Fixed control panels not working correctly with multiple controllers",
"1.7-35": " - Fixed a crash when placing certain items in the crafting grid",
"1.7-36": " - Added an RGB indicator light, controlled by 3 (independent) RS signals\n - Fixed a bug allowing for unfinished control panels to be duplicated\n - Fixed insulated and uninsulated wire producing the same wire coils\n - Fixed some issues (including a crash) with the IE RS controller on dedicated servers"
}
}

View file

@ -1,8 +1,134 @@
#####Version 1.5-13
###Minecraft 1.12.2
####Version 1.7-36
- Added an RGB indicator light, controlled by 3 (independent) RS signals
- Fixed a bug allowing for unfinished control panels to be duplicated
- Fixed insulated and uninsulated wire producing the same wire coils
- Fixed some issues (including a crash) with the IE RS controller on dedicated servers
####Version 1.7-35
- Fixed a crash when placing certain items in the crafting grid
####Version 1.7-34
- Control panels can use the texture of any block now
- Added a recipe to copy the settings of an unfinished control panel
- The Marx generator now returns the wires used in its construction when disassembled
- Fixed the RS controller for non-IE wires not keeping its IO state on world reload
- Fixed control panels not working correctly with multiple controllers
####Version 1.7-33
- Fixed the Marx generator not processing ores
- Fixed control panels and the Marx generator not working when connected directly
- Added Russian translation (thanks @StolenSoda)
####Version 1.7-32
- Fixed connectors not rendering properly without IC2
- Fixed parts of the mechanical multiblocks not rendering when Optifine is installed
- Changed some values for the mechanical multiblock sound
####Version 1.7-31
- Fixed accidental conversion from FE to EU
- Fixed connectors not blowing up as intended
####Version 1.7-30
- Fixed crashes when IC2 isn't installed
- Fixed connectors allowing too much power output
- Added a config option for some of the wires' properties
- Updated chinese translation (thanks @DepletedPrism)
####Version 1.7-29
- The wires can now transmit FE as well as EU, but not both at once
- Fixed the Marx generator not charging beyond a quite low voltage
####Version 1.7-28
- Added the Redstone Controller: Others, it allows control panels to interface with Project:Red and Charset wires
- Rewrote the control panel redstone code
- Added localization for IW's multiblocks
- Fixed issues with zero-length mechanical multiblocks
####Version 1.7-27
- Fixed panel components causing issues on dedicated servers
- Added an automatic update checker (Using the Forge update JSON)
####Version 1.7-26
- Added Mechanical Multiblocks (energy storage and EU<->FE conversion)
- There will be an explanation video for these once I have time to make one
- Fixed the small mechanical converter blowing up tin wires
- Fixed wires not joining their outputs correctly
- Fixed wire connectors not breaking when the block they're on is broken
####Version 1.6-25
- Updated to IE build 77
- IC2 wires cause damage
- Added insulated versions of gold, copper and tin wires. Due to heat sensitive insulation the transfer capacity is half of the normal capacity
- Added feedthrough insulators for all IC2 wire types
- Wire coils now automatically "merge" when picked up
- Config values are applied to the game directly now
####Version 1.6-24
- Fixed an infinite energy bug
- Changed the default value for maximum energy conversion
####Version 1.6-23
- Added a command to allow taking screenshots of Marx generator discharges (/ciw triggermarxscreenshot)
- Panel components have to be shift-clicked to place them in the world
- Fixed wire coil crafting
- Added a recipe for the Seven-Segment displays
####Version 1.6-22
- Added a Seven-Segment display for control panels
- Panel components update their values as soon as they are changed in the GUI
- Fixed a crash when breaking a panel with buttons, locks or toggle switches on it under special circumstances
- Fixed server crashes when using panel components with a second controller id, but no channel set
- Fixed various NPE crashes with control panel models under heavy load
- Fixed wrong panel component ordering with raytracing
####Version 1.6-21
- Added shaders for the Marx generator and Jacob's ladder
- Fixed wires connected to a Marx generator on a server being invisible
- The Marx generator actually gives output when processing ores now. Oops...
- The "safe distance" formulas for the Marx generator in the manual now match the real safe distance
- Improved rendering of the Marx generator in the manual. Some of this is only enabled with maven build 275+ or official build 75+ (not released yet)
####Version 1.6-20
- Added the Marx Generator, an alternative ore processing method
- Hearing protection absolutely required!
- You may need to do some math and measurements for ore processing to work. It will kill entites just fine without any science
- IC2 is no longer a hard dependency. The wires and converters will obviously be disabled without it
- Vastly improved snapping in the panel creator
- Added some Mirage (Albedo) compat
- IW is signed now!
- Analog panel components can interact with 2 channels now, rough and fine control
- Fixed GUI background and item tooltips
- Fixed some components resetting when the chunk is unloaded
- Chunks with control panels properly unload now
####Version 1.5-15
- Components can be placed in the world now to use the as conventional levers/etc.
- Added documentation on the key ring. It also shows all attached keys on the tooltip now
- Fixed some bugs with key ring crafting
- Fixed control panels causing disconnects on servers
####Version 1.5-14
- Updated to Minecraft 1.12
- Added a recipe for the key ring. Kind of forgot about adding one when I added the ring itself...
- Fixed wire length crafting leaving wrong coils when the output has maximum length
- Fixed some more connection issues with control panels
###Minecraft 1.11.2
####Version 1.5-19
- Fixed a crash with SpongeForge, chunk loading issues without
- Fixed some components resetting on chunk unload
####Version 1.5-17
- Backported some fixes from 1.12
####Version 1.5-13
- Labels no longer break the model cache and cause lag
- Labels don't break on dedicated servers any more
#####Version 1.5-12
####Version 1.5-12
- Added tilted control panels
- Panels are no longer created from machine casings, there is a dedicated item for that now, the Unfinished Control Panel
- Angle and height can be configured in the Engineer's Workbench
@ -10,36 +136,48 @@
- Fixed control panels not connecting or disconnecting properly when a panel connector between the panel and the RS controller is broken/placed
- Improved the performance of the control panel hitbox rendering
#####Version 1.5-11
####Version 1.5-11
- Updated to Minecraft 1.11.2
- Added Panel Meters to monitor a redstone signal with reasonable accuracy
- Multiple components on the same panel network can modify the same signal now without causing undefined behavior
- Lock Switches no longer break the model cache
#####Version 1.4-10
###Minecraft 1.10.2
####Version 1.4-18
- Fixed a crash with SpongeForge, chunk loading issues without
- Fixed some components resetting on chunk unload
####Version 1.4-16
- Backported a lot of fixes from 1.11 and 1.12
####Version 1.4-10
- added lock switches for control panels (backport from 1.11)
- Can only be turned on by someone with the correct key to prevent unauthorized access
- up to 10 keys can be added to a keyring to reduce inventory spam
- IC2 items can be added to the appropriate sections of the engineers toolbox (backport from 1.11)
- Components (lighted button, indicator light, etc.) on panels now actually light up (backport from 1.11)
- Fixed power loss when no energy is being transmitted
#####Version 1.4-9
####Version 1.4-9
- added Control Panels
- They can be used to control and monitor a lot of redstone signals from a few blocks
#####Version 1.3-8
####Version 1.3-8
- the converters and the motor don't have missing textures any more when using Chisel
#####Version 1.3-7
####Version 1.3-7
- added Jacob's Ladders/High voltage travelling arcs
- they don't have a particular purpose aside from looking nice
#####Version 1.2-6
####Version 1.2-6
- reduced the discrepancies between IC2 cables and Industrial Wires
- machines don't explode when they shouldn't except in some corner cases
- potentially fixed missing textures on the mechanical converters
- added Chinese translations (thanks SihenZhang)
#####Version 1.2-5 (10,000 download celebratory release)
####Version 1.2-5 (10,000 download celebratory release)
- added mechanical converters and the rotational motor
- they convert between IE rotational energy (windmill, dynamo etc) and IC2 kinetic energy
- Rotational motor: produces IE rotational energy from IF
@ -47,18 +185,18 @@
- Can be disabled in the config
- wire coils show when they are out of range (to match the behavior of IE coils in the latest dev version)
#####Version 1.1-4
####Version 1.1-4
- fixed an insane amount of log-spam in an edgecase (probably a Vanilla or Forge bug)
- added config values for wire length per connection and per coil item
#####Version 1.1-3
####Version 1.1-3
- fixed incompatibility with IE build 48
- reduced the amount of calls to core IE classes to make such incompatibilities less likely
- fixed localization of the creative tab
#####Version 1.1-2
####Version 1.1-2
- wire coils now use a different amount of wire depending on how long the connection is
- wire coils are crafted by placing any amount of IC2 cables and/or the corresponding wire coils in a crafting table now
- added Glass Fiber Wire
- changed license to GPL3
- changed the amount of connectors/relays the recipes yield
- changed the amount of connectors/relays the recipes yield

View file

@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.7-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

View file

@ -1,25 +0,0 @@
package malte0811.industrialWires;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.api.tool.ToolboxHandler;
import ic2.api.item.IBoxable;
import ic2.api.item.IC2Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class ExtraIC2Compat {
public static void addToolConmpat() {
Item tinnedFood = IC2Items.getItem("filled_tin_can").getItem();
ItemStack emptyMug = IC2Items.getItem("mug", "empty");
ToolboxHandler.addFoodType((s)->s.getItem()==tinnedFood);
ToolboxHandler.addFoodType((s)->
s.getItem()==emptyMug.getItem()&&!ItemStack.areItemStacksEqual(emptyMug, ApiUtils.copyStackWithAmount(s, 1))
);
Item cable = IC2Items.getItem("cable", "type:copper,insulation:0").getItem();
ToolboxHandler.addWiringType((s, w)->s.getItem()==cable);
ToolboxHandler.addToolType((s)-> {
Item a = s.getItem();
return a instanceof IBoxable && ((IBoxable) a).canBeStoredInToolbox(s);
});
}
}

View file

@ -1,146 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires;
import malte0811.industrialWires.blocks.BlockJacobsLadder;
import malte0811.industrialWires.blocks.TileEntityJacobsLadder;
import malte0811.industrialWires.blocks.controlpanel.*;
import malte0811.industrialWires.blocks.converter.BlockMechanicalConverter;
import malte0811.industrialWires.blocks.converter.TileEntityIEMotor;
import malte0811.industrialWires.blocks.converter.TileEntityMechICtoIE;
import malte0811.industrialWires.blocks.converter.TileEntityMechIEtoIC;
import malte0811.industrialWires.blocks.wire.*;
import malte0811.industrialWires.items.ItemIC2Coil;
import malte0811.industrialWires.items.ItemKey;
import malte0811.industrialWires.items.ItemPanelComponent;
import malte0811.industrialWires.network.MessageGUIInteract;
import malte0811.industrialWires.network.MessageItemSync;
import malte0811.industrialWires.network.MessagePanelInteract;
import malte0811.industrialWires.network.MessageTileSyncIW;
import malte0811.industrialWires.wires.IC2Wiretype;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLMissingMappingsEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
@Mod(modid = IndustrialWires.MODID, version = IndustrialWires.VERSION, dependencies = "required-after:immersiveengineering@[0.10-58,);required-after:ic2")
public class IndustrialWires {
public static final String MODID = "industrialwires";
public static final String VERSION = "${version}";
public static BlockIC2Connector ic2conn;
public static BlockMechanicalConverter mechConv;
public static BlockJacobsLadder jacobsLadder;
public static BlockPanel panel;
public static ItemIC2Coil coil;
public static ItemPanelComponent panelComponent;
public static ItemKey key;
public static final SimpleNetworkWrapper packetHandler = NetworkRegistry.INSTANCE.newSimpleChannel(MODID);
@Mod.Instance(MODID)
public static IndustrialWires instance = new IndustrialWires();
public static CreativeTabs creativeTab = new CreativeTabs(MODID) {
@Override
public ItemStack getTabIconItem() {
return new ItemStack(coil, 1, 2);
}
};
@SidedProxy(clientSide = "malte0811.industrialWires.client.ClientProxy", serverSide = "malte0811.industrialWires.CommonProxy")
public static CommonProxy proxy;
@EventHandler
public void preInit(FMLPreInitializationEvent e) {
new IWConfig();
ic2conn = new BlockIC2Connector();
if (IWConfig.enableConversion)
mechConv = new BlockMechanicalConverter();
jacobsLadder = new BlockJacobsLadder();
panel = new BlockPanel();
coil = new ItemIC2Coil();
panelComponent = new ItemPanelComponent();
key = new ItemKey();
GameRegistry.registerTileEntity(TileEntityIC2ConnectorTin.class, MODID + "ic2ConnectorTin");
GameRegistry.registerTileEntity(TileEntityIC2ConnectorCopper.class, MODID + "ic2ConnectorCopper");
GameRegistry.registerTileEntity(TileEntityIC2ConnectorGold.class, MODID + "ic2ConnectorGold");
GameRegistry.registerTileEntity(TileEntityIC2ConnectorHV.class, MODID + "ic2ConnectorHV");
GameRegistry.registerTileEntity(TileEntityIC2ConnectorGlass.class, MODID + "ic2ConnectorGlass");
GameRegistry.registerTileEntity(TileEntityJacobsLadder.class, MODID + ":jacobsLadder");
GameRegistry.registerTileEntity(TileEntityPanel.class, MODID + ":control_panel");
GameRegistry.registerTileEntity(TileEntityRSPanelConn.class, MODID + ":control_panel_rs");
GameRegistry.registerTileEntity(TileEntityPanelCreator.class, MODID + ":panel_creator");
GameRegistry.registerTileEntity(TileEntityUnfinishedPanel.class, MODID + ":unfinished_panel");
if (mechConv != null) {
GameRegistry.registerTileEntity(TileEntityIEMotor.class, MODID + ":ieMotor");
GameRegistry.registerTileEntity(TileEntityMechICtoIE.class, MODID + ":mechIcToIe");
GameRegistry.registerTileEntity(TileEntityMechIEtoIC.class, MODID + ":mechIeToIc");
}
if (IC2Wiretype.IC2_TYPES == null) {
throw new IllegalStateException("No IC2 wires registered");
}
proxy.preInit();
}
@EventHandler
public void init(FMLInitializationEvent e) {
Recipes.addRecipes();
ExtraIC2Compat.addToolConmpat();
packetHandler.registerMessage(MessageTileSyncIW.HandlerClient.class, MessageTileSyncIW.class, 0, Side.CLIENT);
packetHandler.registerMessage(MessagePanelInteract.HandlerServer.class, MessagePanelInteract.class, 1, Side.SERVER);
packetHandler.registerMessage(MessageGUIInteract.HandlerServer.class, MessageGUIInteract.class, 2, Side.SERVER);
packetHandler.registerMessage(MessageItemSync.HandlerServer.class, MessageItemSync.class, 3, Side.SERVER);
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
}
@EventHandler
public void postInit(FMLPostInitializationEvent e) {
proxy.postInit();
}
@EventHandler
public void remap(FMLMissingMappingsEvent ev) {
for (FMLMissingMappingsEvent.MissingMapping miss : ev.get()) {
String name = miss.resourceLocation.getResourcePath();
switch (name) {
case "ic2connector":
if (miss.type == GameRegistry.Type.ITEM) {
miss.remap(Item.getItemFromBlock(IndustrialWires.ic2conn));
} else {
miss.remap(IndustrialWires.ic2conn);
}
break;
case "ic2wirecoil":
miss.remap(IndustrialWires.coil);
break;
}
}
}
}

View file

@ -1,180 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires;
import blusunrize.immersiveengineering.api.tool.AssemblerHandler;
import blusunrize.immersiveengineering.common.IEContent;
import blusunrize.immersiveengineering.common.blocks.metal.BlockTypes_Connector;
import blusunrize.immersiveengineering.common.blocks.metal.BlockTypes_MetalDecoration0;
import blusunrize.immersiveengineering.common.blocks.stone.BlockTypes_StoneDecoration;
import ic2.api.item.IC2Items;
import malte0811.industrialWires.blocks.controlpanel.BlockTypes_Panel;
import malte0811.industrialWires.controlpanel.PanelUtils;
import malte0811.industrialWires.crafting.*;
import malte0811.industrialWires.wires.IC2Wiretype;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.NonNullList;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.RecipeSorter;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import java.util.ArrayList;
import java.util.List;
import static malte0811.industrialWires.IndustrialWires.*;
public class Recipes {
public static void addRecipes() {
addCustomRecipes();
addConnectors();
if (mechConv != null) {
addMechConverters();
}
addJacobs();
registerPanels();
}
private static void addConnectors() {
ItemStack glassCable = IC2Items.getItem("cable", "type:glass,insulation:0");
//CONNECTORS
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 0), " t ", "rtr", "rtr", 't', "ingotTin", 'r', "itemRubber"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 2), " c ", "rcr", "rcr", 'c', "ingotCopper", 'r', "itemRubber"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 4), " g ", "rgr", "rgr", 'g', "ingotGold", 'r', "itemRubber"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 6), " i ", "rir", "rir", 'i', "ingotIron", 'r', "itemRubber"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 8), " c ", "rcr", "rcr", 'c', glassCable, 'r', "itemRubber"));
//RELAYS
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 1), " t ", "rtr", 't', "ingotTin", 'r', "itemRubber"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 3), " c ", "rcr", 'c', "ingotCopper", 'r', "itemRubber"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 5), " g ", "rgr", 'g', "ingotGold", 'r', "itemRubber"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 4, 7), " i ", "gig", "gig", 'i', "ingotIron", 'g', new ItemStack(IEContent.blockStoneDecoration, 1, BlockTypes_StoneDecoration.INSULATING_GLASS.getMeta())));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ic2conn, 2, 9), " c ", "grg", "grg", 'r', "itemRubber", 'c', glassCable, 'g', new ItemStack(IEContent.blockStoneDecoration, 1, BlockTypes_StoneDecoration.INSULATING_GLASS.getMeta())));
}
private static void addMechConverters() {
ItemStack shaftIron = IC2Items.getItem("crafting", "iron_shaft");
ItemStack shaftSteel = IC2Items.getItem("crafting", "steel_shaft");
ItemStack ironMechComponent = new ItemStack(IEContent.itemMaterial, 1, 8);
ItemStack steelMechComponent = new ItemStack(IEContent.itemMaterial, 1, 9);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(mechConv, 1, 0), " s ", "ici", "mum", 's', "stickIron",
'i', "ingotIron", 'c', new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.COIL_LV.getMeta()),
'u', "ingotCopper", 'm', ironMechComponent));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(mechConv, 1, 2), "iIi", "sbS", "mrm", 's', "blockSheetmetalIron",
'i', "plateIron", 'I', shaftIron,
'b', "ingotBronze", 'm', steelMechComponent,
'S', "blockSheetmetalSteel", 'r', "stickSteel"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(mechConv, 1, 1), "mrm", "sbS", "iIi", 's', "blockSheetmetalIron",
'i', "plateSteel", 'I', shaftSteel,
'b', "ingotBronze", 'm', ironMechComponent,
'S', "blockSheetmetalSteel", 'r', "stickIron"));
}
private static void addCustomRecipes() {
RecipeSorter.register("industrialwires:key_ring", RecipeKeyRing.class, RecipeSorter.Category.SHAPELESS, "after:forge:shapelessore");
RecipeSorter.register("industrialwires:key_lock", RecipeKeyLock.class, RecipeSorter.Category.SHAPELESS, "after:forge:shapelessore");
RecipeSorter.register("industrialwires:cmp_copy", RecipeComponentCopy.class, RecipeSorter.Category.SHAPED, "after:forge:shapelessore");
RecipeSorter.register("industrialwires:coilLength", RecipeCoilLength.class, RecipeSorter.Category.SHAPELESS, "after:forge:shapelessore");
RecipeSorter.register("industrialwires:init_pc", RecipeInitPC.class, RecipeSorter.Category.SHAPED, "after:forge:shapedore");
GameRegistry.addRecipe(new RecipeKeyLock());
GameRegistry.addRecipe(new RecipeKeyRing());
GameRegistry.addRecipe(new RecipeComponentCopy());
for (int i = 0; i < IC2Wiretype.IC2_TYPES.length; i++) {
GameRegistry.addRecipe(new RecipeCoilLength(i));
}
AssemblerHandler.registerRecipeAdapter(RecipeCoilLength.class, new AllRecipeAdapter<>());
AssemblerHandler.registerRecipeAdapter(RecipeComponentCopy.class, new AllRecipeAdapter<>());
AssemblerHandler.registerRecipeAdapter(RecipeKeyLock.class, new AllRecipeAdapter<>());
AssemblerHandler.registerRecipeAdapter(RecipeKeyRing.class, new AllRecipeAdapter<>());
}
private static void registerPanels() {
// CONTROL PANELS
ItemStack drillHeadIron = new ItemStack(IEContent.itemDrillhead, 1, 1);
ItemStack motor = IC2Items.getItem("crafting", "electric_motor");
ItemStack advAlloy = IC2Items.getItem("crafting", "alloy");
ItemStack coil = IC2Items.getItem("crafting", "coil");
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(panel, 1, BlockTypes_Panel.CREATOR.ordinal()),
"rmr", "rdr", "rar", 'r', "stickSteel", 'm', motor, 'd', drillHeadIron, 'a', advAlloy));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(panel, 4, BlockTypes_Panel.DUMMY.ordinal()),
" r ", "rmr", " r ", 'r', "dustRedstone", 'm', PanelUtils.getPanelBase()));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(panel, 1, BlockTypes_Panel.RS_WIRE.ordinal()),
"c", "d", 'd', new ItemStack(panel, 1, BlockTypes_Panel.DUMMY.ordinal()), 'c',
new ItemStack(IEContent.blockConnectors, 1, BlockTypes_Connector.CONNECTOR_REDSTONE.ordinal())));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(panel, 1, BlockTypes_Panel.UNFINISHED.ordinal()),
"ppp", "www", "ppp", 'p', "plateIron", 'w', "wireCopper"));
// PANEL COMPONENTS
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(panelComponent, 1, 0),
"dustGlowstone", Blocks.STONE_BUTTON, "wireCopper"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(panelComponent, 4, 1),
"paper", "plateIron"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(panelComponent, 1, 2),
"dustGlowstone", "dustRedstone", "wireCopper"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(panelComponent, 1, 3),
Blocks.STONE_BUTTON, new ItemStack(IEContent.itemWireCoil, 1, 2), "wireCopper"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(panelComponent, 1, 4),
"r", "g", "c", 'r', "itemRubber", 'g', "ingotHOPGraphite", 'c', coil));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(panelComponent, 1, 5),
"stickIron", Blocks.LEVER, "wireCopper"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(panelComponent, 1, 6),
"aaa", "asa", 'a', "plateAluminum", 's', new ItemStack(panelComponent, 2, 5)));
GameRegistry.addRecipe(new RecipeInitPC(new ItemStack(panelComponent, 1, 7),
"rdr", " w ", 'r', "stickSteel", 'd', Items.IRON_DOOR, 'w', "wireCopper"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(key, 1, 0),
"rrp", 'r', "stickSteel", 'p', "plateSteel"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(panelComponent, 1, 8),
"wireCopper", new ItemStack(IEContent.itemTool, 1, 2)));
}
private static void addJacobs() {
ItemStack mvTransformer = IC2Items.getItem("te", "mv_transformer");
ItemStack copperCable = IC2Items.getItem("cable", "type:copper,insulation:0");
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(jacobsLadder, 1, 0), "c c", " h ", "sts", 'c', copperCable, 'h', Blocks.HARDENED_CLAY,
's', "ingotSteel", 't', mvTransformer));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(jacobsLadder, 1, 1), "c c", "h h", "sts", 'c', "ingotCopper", 'h', Blocks.HARDENED_CLAY,
's', "ingotSteel", 't', new ItemStack(IEContent.blockConnectors, 1, BlockTypes_Connector.TRANSFORMER.ordinal())));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(jacobsLadder, 1, 2), "c c", "hhh", "sts", 'c', "blockCopper", 'h', Blocks.HARDENED_CLAY,
's', "ingotSteel", 't', new ItemStack(IEContent.blockConnectors, 1, BlockTypes_Connector.TRANSFORMER_HV.ordinal())));
}
private static class AllRecipeAdapter<T extends IRecipe> implements AssemblerHandler.IRecipeAdapter<T> {
@Override
public AssemblerHandler.RecipeQuery[] getQueriedInputs(T recipe, NonNullList<ItemStack> in) {
List<AssemblerHandler.RecipeQuery> ret = new ArrayList<>();
for (int i = 0; i < in.size() - 1; i++) {
boolean added = false;
for (AssemblerHandler.RecipeQuery aRet : ret) {
if (ItemStack.areItemStacksEqual((ItemStack) aRet.query, in.get(i))) {
aRet.querySize++;
added = true;
break;
}
}
if (!added) {
ret.add(new AssemblerHandler.RecipeQuery(in.get(i), 1));
}
}
return ret.toArray(new AssemblerHandler.RecipeQuery[ret.size()]);
}
@Override
public AssemblerHandler.RecipeQuery[] getQueriedInputs(T arg0) {
return new AssemblerHandler.RecipeQuery[0];
}
}
}

View file

@ -1,390 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.controlpanel;
import blusunrize.immersiveengineering.api.TargetingInfo;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.api.energy.wires.TileEntityImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import blusunrize.immersiveengineering.api.energy.wires.redstone.IRedstoneConnector;
import blusunrize.immersiveengineering.api.energy.wires.redstone.RedstoneWireNetwork;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces;
import malte0811.industrialWires.blocks.IBlockBoundsIW;
import malte0811.industrialWires.blocks.INetGUI;
import malte0811.industrialWires.controlpanel.PanelComponent;
import malte0811.industrialWires.controlpanel.PanelUtils;
import malte0811.industrialWires.controlpanel.PropertyComponents;
import malte0811.industrialWires.util.TriConsumer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.function.Consumer;
public class TileEntityRSPanelConn extends TileEntityImmersiveConnectable implements IRedstoneConnector, ITickable, INetGUI, IEBlockInterfaces.IDirectionalTile, IBlockBoundsIW {
private byte[] out = new byte[16];
private boolean dirty = true;
private byte[] oldInput = new byte[16];
private Set<Consumer<byte[]>> changeListeners = new HashSet<>();
private Set<TileEntityPanel> connectedPanels = new HashSet<>();
private EnumFacing facing = EnumFacing.NORTH;
@Nonnull
private RedstoneWireNetwork network = new RedstoneWireNetwork().add(this);
private boolean hasConn = false;
private int id;
{
for (int i = 0; i < 16; i++) {
oldInput[i] = -1;
}
}
private boolean loaded = false;
@Override
public void update() {
if (hasWorld() && !world.isRemote) {
if (!loaded) {
loaded = true;
// completely reload the network
network.removeFromNetwork(null);
List<BlockPos> parts = PanelUtils.discoverPanelParts(world, pos, 100);
for (BlockPos bp : parts) {
TileEntity te = world.getTileEntity(bp);
if (te instanceof TileEntityPanel) {
registerPanel(((TileEntityPanel) te));
}
}
}
if (dirty) {
network.updateValues();
dirty = false;
}
}
}
@Override
public void writeCustomNBT(NBTTagCompound out, boolean updatePacket) {
super.writeCustomNBT(out, updatePacket);
out.setByteArray("out", this.out);
out.setBoolean("hasConn", hasConn);
out.setInteger("rsId", id);
out.setInteger("facing", facing.getIndex());
}
@Override
public void readCustomNBT(NBTTagCompound in, boolean updatePacket) {
super.readCustomNBT(in, updatePacket);
out = in.getByteArray("out");
hasConn = in.getBoolean("hasConn");
id = in.getInteger("rsId");
facing = EnumFacing.VALUES[in.getInteger("facing")];
aabb = null;
}
private final Map<PCWrapper, byte[]> outputs = new HashMap<>();
private TriConsumer<Integer, Byte, PanelComponent> rsOut = (channel, value, pc) -> {
PCWrapper wrapper = new PCWrapper(pc);
if (!outputs.containsKey(wrapper)) {
outputs.put(wrapper, new byte[16]);
}
if (outputs.get(wrapper)[channel] != value) {
outputs.get(wrapper)[channel] = value;
byte max = 0;
Iterator<Map.Entry<PCWrapper, byte[]>> it = outputs.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<PCWrapper, byte[]> curr = it.next();
if (curr.getKey().pc.get() == null) {
it.remove();
continue;
}
if (curr.getValue()[channel] > max) {
max = curr.getValue()[channel];
}
}
dirty = true;
out[channel] = max;
}
};
private class PCWrapper {
@Nonnull
private final WeakReference<PanelComponent> pc;
public PCWrapper(@Nonnull PanelComponent pc) {
this.pc = new WeakReference<>(pc);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PCWrapper pcWrapper = (PCWrapper) o;
return pcWrapper.pc.get() == pc.get();
}
@Override
public int hashCode() {
return System.identityHashCode(pc.get());
}
}
public void registerPanel(TileEntityPanel panel) {
PropertyComponents.PanelRenderProperties p = panel.getComponents();
for (PanelComponent pc : p) {
Consumer<byte[]> listener = pc.getRSInputHandler(id, panel);
if (listener != null) {
changeListeners.add(listener);
listener.accept(out);
}
pc.registerRSOutput(id, rsOut);
}
panel.registerRS(this);
connectedPanels.add(panel);
}
public void unregisterPanel(TileEntityPanel panel, boolean remove) {
out = new byte[16];
PropertyComponents.PanelRenderProperties p = panel.getComponents();
for (PanelComponent pc : p) {
Consumer<byte[]> listener = pc.getRSInputHandler(id, panel);
if (listener != null) {
listener.accept(out);
changeListeners.remove(listener);
}
pc.unregisterRSOutput(id, rsOut);
outputs.remove(new PCWrapper(pc));
}
panel.unregisterRS(this);
if (remove) {
connectedPanels.remove(panel);
}
for (TileEntityPanel te : connectedPanels) {
for (PanelComponent pc : te.getComponents()) {
pc.registerRSOutput(id, rsOut);
}
}
network.updateValues();
}
@Override
public void setNetwork(@Nonnull RedstoneWireNetwork net) {
network = net;
}
@Nonnull
@Override
public RedstoneWireNetwork getNetwork() {
return network;
}
@Override
public void onChange() {
if (!Arrays.equals(oldInput, network.channelValues)) {
oldInput = Arrays.copyOf(network.channelValues, 16);
for (Consumer<byte[]> c : changeListeners) {
c.accept(oldInput);
}
}
}
@Override
public void updateInput(byte[] currIn) {
for (int i = 0; i < 16; i++) {
currIn[i] = (byte) Math.max(currIn[i], out[i]);
}
}
@Override
public BlockPos getConnectionMaster(@Nullable WireType wire, TargetingInfo target) {
return pos;
}
@Override
public boolean canConnectCable(WireType wire, TargetingInfo targetingInfo) {
return wire == WireType.REDSTONE && !hasConn;
}
@Override
public void connectCable(WireType wireType, TargetingInfo targetingInfo, IImmersiveConnectable other) {
hasConn = true;
if (other instanceof IRedstoneConnector && ((IRedstoneConnector) other).getNetwork() != network) {
network.mergeNetwork(((IRedstoneConnector) other).getNetwork());
}
}
@Override
public WireType getCableLimiter(TargetingInfo targetingInfo) {
return WireType.REDSTONE;
}
@Override
public boolean allowEnergyToPass(ImmersiveNetHandler.Connection connection) {
return false;
}
@Override
public void removeCable(ImmersiveNetHandler.Connection connection) {
hasConn = false;
network.removeFromNetwork(this);
this.markDirty();
if (world != null) {
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state, state, 3);
}
}
@Override
public Vec3d getRaytraceOffset(IImmersiveConnectable other) {
EnumFacing side = facing.getOpposite();
return new Vec3d(.5 + side.getFrontOffsetX() * .0625, .5 + side.getFrontOffsetY() * .0625, .5 + side.getFrontOffsetZ() * .0625);
}
@Override
public Vec3d getConnectionOffset(ImmersiveNetHandler.Connection connection) {
EnumFacing side = facing.getOpposite();
double conRadius = connection.cableType.getRenderDiameter() / 2;
return new Vec3d(.5 - conRadius * side.getFrontOffsetX(), .5 - conRadius * side.getFrontOffsetY(), .5 - conRadius * side.getFrontOffsetZ());
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
for (TileEntityPanel panel : connectedPanels) {
unregisterPanel(panel, false);
}
}
@Override
public void invalidate() {
super.invalidate();
for (TileEntityPanel panel : connectedPanels) {
unregisterPanel(panel, false);
}
}
@Override
public void onChange(NBTTagCompound nbt, EntityPlayer p) {
if (nbt.hasKey("rsId")) {
List<BlockPos> parts = PanelUtils.discoverPanelParts(world, pos, 100);
List<TileEntityPanel> tes = new ArrayList<>(parts.size());
for (BlockPos bp : parts) {
TileEntity te = world.getTileEntity(bp);
if (te instanceof TileEntityPanel) {
tes.add((TileEntityPanel) te);
unregisterPanel((TileEntityPanel) te, true);
}
}
id = nbt.getInteger("rsId");
out = new byte[16];
for (TileEntityPanel panel : tes) {
registerPanel(panel);
}
network.updateValues();
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state, state, 3);
world.addBlockEvent(pos, state.getBlock(), 255, 0);
}
}
@Override
public World getConnectorWorld() {
return world;
}
public int getRsId() {
return id;
}
@Nonnull
@Override
public EnumFacing getFacing() {
return facing;
}
@Override
public void setFacing(@Nonnull EnumFacing facing) {
this.facing = facing;
}
@Override
public int getFacingLimitation() {
return 0;
}
@Override
public boolean mirrorFacingOnPlacement(@Nonnull EntityLivingBase placer) {
return true;
}
@Override
public boolean canHammerRotate(@Nonnull EnumFacing side, float hitX, float hitY, float hitZ, @Nonnull EntityLivingBase entity) {
return false;
}
@Override
public boolean canRotate(@Nonnull EnumFacing axis) {
return false;
}
private AxisAlignedBB aabb;
@Override
public AxisAlignedBB getBoundingBox() {
if (aabb == null) {
double h = 9 / 16D;
switch (facing) {
case DOWN:
aabb = new AxisAlignedBB(0, 0, 0, 1, h, 1);
break;
case UP:
aabb = new AxisAlignedBB(0, 1 - h, 0, 1, 1, 1);
break;
case NORTH:
aabb = new AxisAlignedBB(0, 0, 0, 1, 1, h);
break;
case SOUTH:
aabb = new AxisAlignedBB(0, 0, 1 - h, 1, 1, 1);
break;
case WEST:
aabb = new AxisAlignedBB(0, 0, 0, h, 1, 1);
break;
case EAST:
aabb = new AxisAlignedBB(1 - h, 0, 0, 1, 1, 1);
break;
}
}
return aabb;
}
}

View file

@ -1,58 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.wire;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.Connection;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import malte0811.industrialWires.wires.IC2Wiretype;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.Vec3d;
public class TileEntityIC2ConnectorGold extends TileEntityIC2ConnectorTin {
public TileEntityIC2ConnectorGold(boolean rel) {
super(rel);
}
public TileEntityIC2ConnectorGold() {
}
{
tier = 3;
maxStored = IC2Wiretype.IC2_TYPES[2].getTransferRate() / 8;
}
@Override
public boolean canConnect(WireType t) {
return t == IC2Wiretype.IC2_TYPES[2];
}
@Override
public Vec3d getRaytraceOffset(IImmersiveConnectable link) {
EnumFacing side = f.getOpposite();
return new Vec3d(.5 + side.getFrontOffsetX() * .125, .5 + side.getFrontOffsetY() * .125, .5 + side.getFrontOffsetZ() * .125);
}
@Override
public Vec3d getConnectionOffset(Connection con) {
EnumFacing side = f.getOpposite();
double conRadius = con.cableType.getRenderDiameter() / 2;
return new Vec3d(.5 + side.getFrontOffsetX() * (.0625 - conRadius), .5 + side.getFrontOffsetY() * (.0625 - conRadius), .5 + side.getFrontOffsetZ() * (.0625 - conRadius));
}
}

View file

@ -1,66 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.wire;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.Connection;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import malte0811.industrialWires.wires.IC2Wiretype;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.Vec3d;
public class TileEntityIC2ConnectorHV extends TileEntityIC2ConnectorTin {
public TileEntityIC2ConnectorHV(boolean rel) {
super(rel);
}
public TileEntityIC2ConnectorHV() {
}
{
tier = 4;
maxStored = IC2Wiretype.IC2_TYPES[3].getTransferRate() / 8;
}
@Override
public boolean canConnect(WireType t) {
return t == IC2Wiretype.IC2_TYPES[3];
}
@Override
public Vec3d getRaytraceOffset(IImmersiveConnectable link) {
EnumFacing side = f.getOpposite();
if (relay) {
return new Vec3d(.5 + side.getFrontOffsetX() * .4375, .5 + side.getFrontOffsetY() * .4375, .5 + side.getFrontOffsetZ() * .4375);
} else {
return new Vec3d(.5 + side.getFrontOffsetX() * .3125, .5 + side.getFrontOffsetY() * .3125, .5 + side.getFrontOffsetZ() * .3125);
}
}
@Override
public Vec3d getConnectionOffset(Connection con) {
EnumFacing side = f.getOpposite();
double conRadius = con.cableType.getRenderDiameter() / 2;
if (relay) {
return new Vec3d(.5 + side.getFrontOffsetX() * (.375 - conRadius), .5 + side.getFrontOffsetY() * (.375 - conRadius), .5 + side.getFrontOffsetZ() * (.375 - conRadius));
} else {
return new Vec3d(.5 + side.getFrontOffsetX() * (.25 - conRadius), .5 + side.getFrontOffsetY() * (.25 - conRadius), .5 + side.getFrontOffsetZ() * (.25 - conRadius));
}
}
}

View file

@ -1,378 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.wire;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.api.TargetingInfo;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.AbstractConnection;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.Connection;
import blusunrize.immersiveengineering.api.energy.wires.TileEntityImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.event.EnergyTileUnloadEvent;
import ic2.api.energy.tile.IEnergyAcceptor;
import ic2.api.energy.tile.IEnergyEmitter;
import ic2.api.energy.tile.IEnergySink;
import ic2.api.energy.tile.IEnergySource;
import malte0811.industrialWires.IIC2Connector;
import malte0811.industrialWires.blocks.IBlockBoundsIW;
import malte0811.industrialWires.wires.IC2Wiretype;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.common.MinecraftForge;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class TileEntityIC2ConnectorTin extends TileEntityImmersiveConnectable implements IEnergySource, IEnergySink, IDirectionalTile, ITickable, IIC2Connector, IBlockBoundsIW {
EnumFacing f = EnumFacing.NORTH;
boolean relay;
private boolean first = true;
//IC2 net to IE net buffer
private double inBuffer = 0;
private double maxToNet = 0;
//IE net to IC2 net buffer
private double outBuffer = 0;
private double maxToMachine = 0;
protected double maxStored = IC2Wiretype.IC2_TYPES[0].getTransferRate() / 8;
int tier = 1;
public TileEntityIC2ConnectorTin(boolean rel) {
relay = rel;
}
public TileEntityIC2ConnectorTin() {
}
@Override
public void update() {
if (first) {
if (!world.isRemote)
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
first = false;
}
if (!world.isRemote && inBuffer > .1)
transferPower();
}
public void transferPower() {
Set<AbstractConnection> conns = new HashSet<>(ImmersiveNetHandler.INSTANCE.getIndirectEnergyConnections(pos, world));
Map<AbstractConnection, Pair<IIC2Connector, Double>> maxOutputs = new HashMap<>();
double outputMax = Math.min(inBuffer, maxToNet);
double sum = 0;
for (AbstractConnection c : conns) {
IImmersiveConnectable iic = ApiUtils.toIIC(c.end, world);
if (iic instanceof IIC2Connector) {
double tmp = outputMax - ((IIC2Connector) iic).insertEnergy(outputMax, true);
if (tmp > .00000001) {
maxOutputs.put(c, new ImmutablePair<>((IIC2Connector) iic, tmp));
sum += tmp;
}
}
}
if (sum < .0001) {
return;
}
final double oldInBuf = outputMax;
HashMap<Connection, Integer> transferedPerConn = ImmersiveNetHandler.INSTANCE.getTransferedRates(world.provider.getDimension());
for (AbstractConnection c : maxOutputs.keySet()) {
Pair<IIC2Connector, Double> p = maxOutputs.get(c);
double out = oldInBuf * p.getRight() / sum;
double loss = getAverageLossRate(c);
double inserted = out - p.getLeft().insertEnergy(out - loss, false);
inBuffer -= inserted;
float intermediaryLoss = 0;
HashSet<IImmersiveConnectable> passedConnectors = new HashSet<>();
double energyAtConn = inserted + loss;
for (Connection sub : c.subConnections) {
int transferredPerCon = transferedPerConn.getOrDefault(sub, 0);
energyAtConn -= sub.cableType.getLossRatio() * sub.length;
ImmersiveNetHandler.INSTANCE.getTransferedRates(world.provider.getDimension()).put(sub, (int) (transferredPerCon + energyAtConn));
IImmersiveConnectable subStart = ApiUtils.toIIC(sub.start, world);
IImmersiveConnectable subEnd = ApiUtils.toIIC(sub.end, world);
if (subStart != null && passedConnectors.add(subStart))
subStart.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
if (subEnd != null && passedConnectors.add(subEnd))
subEnd.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
}
}
}
public double getAverageLossRate(AbstractConnection conn) {
double f = 0;
for (Connection c : conn.subConnections) {
f += c.length * c.cableType.getLossRatio();
}
return f;
}
//Input through the net
@Override
public double insertEnergy(double eu, boolean simulate) {
final double insert = Math.min(maxStored - outBuffer, eu);
if (insert > 0) {
if (outBuffer < maxToMachine) {
maxToMachine = outBuffer;
}
if (eu > maxToMachine) {
maxToMachine = eu;
}
}
if (!simulate) {
outBuffer += insert;
}
return eu - insert;
}
@Override
public void invalidate() {
if (!world.isRemote && !first)
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
first = true;
super.invalidate();
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
if (!world.isRemote && !first)
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
first = true;
}
@Override
public Vec3d getRaytraceOffset(IImmersiveConnectable link) {
EnumFacing side = f.getOpposite();
return new Vec3d(.5 + side.getFrontOffsetX() * .0625, .5 + side.getFrontOffsetY() * .0625, .5 + side.getFrontOffsetZ() * .0625);
}
@Override
public Vec3d getConnectionOffset(Connection con) {
EnumFacing side = f.getOpposite();
double conRadius = con.cableType.getRenderDiameter() / 2;
return new Vec3d(.5 - conRadius * side.getFrontOffsetX(), .5 - conRadius * side.getFrontOffsetY(), .5 - conRadius * side.getFrontOffsetZ());
}
@Override
public boolean canConnect() {
return true;
}
@Override
public boolean isEnergyOutput() {
return !relay;
}
@Override
public boolean canConnectCable(WireType cableType, TargetingInfo target) {
return (limitType == null || (this.isRelay() && limitType == cableType)) && canConnect(cableType);
}
public boolean canConnect(WireType t) {
return t == IC2Wiretype.IC2_TYPES[0];
}
@Override
protected boolean isRelay() {
return relay;
}
@Override
public boolean emitsEnergyTo(IEnergyAcceptor receiver, EnumFacing side) {
return !relay && side == f;
}
@Override
public boolean acceptsEnergyFrom(IEnergyEmitter emitter, EnumFacing side) {
return !relay && side == f;
}
@Override
public double getDemandedEnergy() {
double ret = maxStored + .5 - inBuffer;
if (ret < .1)
ret = 0;
return ret;
}
@Override
public int getSinkTier() {
return tier;
}
@Override
public double injectEnergy(EnumFacing directionFrom, double amount, double voltage) {
if (inBuffer < maxStored) {
if (inBuffer < maxToNet) {
maxToNet = inBuffer;
}
inBuffer += amount;
if (amount > maxToNet) {
maxToNet = amount;
}
markDirty();
return 0;
}
return amount;
}
@Override
public double getOfferedEnergy() {
return Math.min(maxToMachine, outBuffer);
}
@Override
public void drawEnergy(double amount) {
outBuffer -= amount;
markDirty();
}
@Override
public int getSourceTier() {
return tier;
}
@Override
public void readCustomNBT(NBTTagCompound nbt, boolean descPacket) {
super.readCustomNBT(nbt, descPacket);
f = EnumFacing.getFront(nbt.getInteger("facing"));
relay = nbt.getBoolean("relay");
inBuffer = nbt.getDouble("inBuffer");
outBuffer = nbt.getDouble("outBuffer");
if (nbt.hasKey("maxToNet")) {
maxToNet = nbt.getDouble("maxToNet");
} else {
maxToNet = inBuffer;
}
if (nbt.hasKey("maxToMachine")) {
maxToMachine = nbt.getDouble("maxToMachine");
} else {
maxToMachine = outBuffer;
}
}
@Override
public void writeCustomNBT(NBTTagCompound nbt, boolean descPacket) {
super.writeCustomNBT(nbt, descPacket);
nbt.setInteger("facing", f.getIndex());
nbt.setBoolean("relay", relay);
nbt.setDouble("inBuffer", inBuffer);
nbt.setDouble("outBuffer", outBuffer);
nbt.setDouble("maxToNet", maxToNet);
nbt.setDouble("maxToMachine", maxToMachine);
}
@Nonnull
@Override
public EnumFacing getFacing() {
return f;
}
@Override
public void setFacing(@Nonnull EnumFacing facing) {
f = facing;
}
@Override
public int getFacingLimitation() {
return 0;
}
@Override
public boolean mirrorFacingOnPlacement(@Nonnull EntityLivingBase placer) {
return true;
}
@Override
public boolean canHammerRotate(@Nonnull EnumFacing side, float hitX, float hitY, float hitZ, @Nonnull EntityLivingBase entity) {
return false;
}
@Override
public AxisAlignedBB getBoundingBox() {
float length = this instanceof TileEntityIC2ConnectorHV ? (relay ? .875f : .75f) : this instanceof TileEntityIC2ConnectorGold ? .5625f : .5f;
float wMin = .3125f;
float wMax = .6875f;
switch (f.getOpposite()) {
case UP:
return new AxisAlignedBB(wMin, 0, wMin, wMax, length, wMax);
case DOWN:
return new AxisAlignedBB(wMin, 1 - length, wMin, wMax, 1, wMax);
case SOUTH:
return new AxisAlignedBB(wMin, wMin, 0, wMax, wMax, length);
case NORTH:
return new AxisAlignedBB(wMin, wMin, 1 - length, wMax, wMax, 1);
case EAST:
return new AxisAlignedBB(0, wMin, wMin, length, wMax, wMax);
case WEST:
return new AxisAlignedBB(1 - length, wMin, wMin, 1, wMax, wMax);
}
return new AxisAlignedBB(0, 0, 0, 1, 1, 1);
}
/*
* regarding equals+hashCode
* TE's are considered equal if they have the same pos+dimension id
* This is necessary to work around a weird bug causing a lot of log spam (100GB and above are well possible).
* For further information see #1 (https://github.com/malte0811/IndustrialWires/issues/1)
*/
@Override
public int hashCode() {
int ret = world.provider.getDimension();
ret = 31 * ret + pos.hashCode();
return ret;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TileEntityIC2ConnectorTin)) {
return false;
}
if (obj.getClass() != getClass()) {
return false;
}
TileEntityIC2ConnectorTin te = (TileEntityIC2ConnectorTin) obj;
if (!te.pos.equals(pos)) {
return false;
}
if (te.world.provider.getDimension() != world.provider.getDimension()) {
return false;
}
return true;
}
@Override
public boolean canRotate(@Nonnull EnumFacing axis) {
return false;
}
}

View file

@ -1,103 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client;
import blusunrize.immersiveengineering.api.Lib;
import blusunrize.immersiveengineering.client.ClientUtils;
import blusunrize.immersiveengineering.common.util.ItemNBTHelper;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.controlpanel.TileEntityPanel;
import malte0811.industrialWires.client.panelmodel.PanelModel;
import malte0811.industrialWires.controlpanel.PanelComponent;
import malte0811.industrialWires.items.ItemIC2Coil;
import malte0811.industrialWires.wires.IC2Wiretype;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.RayTraceResult;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.commons.lang3.tuple.Pair;
public class ClientEventHandler {
@SubscribeEvent
public void renderOverlayPost(RenderGameOverlayEvent.Post e) {
if (ClientUtils.mc().player != null && e.getType() == RenderGameOverlayEvent.ElementType.TEXT) {
EntityPlayer player = ClientUtils.mc().player;
for (EnumHand hand : EnumHand.values()) {
if (!player.getHeldItem(hand).isEmpty()) {
ItemStack equipped = player.getHeldItem(hand);
if (OreDictionary.itemMatches(new ItemStack(IndustrialWires.coil, 1, OreDictionary.WILDCARD_VALUE), equipped, false)) {
IC2Wiretype type = IC2Wiretype.IC2_TYPES[equipped.getItemDamage()];
int color = type.getColour(null);
String s = I18n.format(IndustrialWires.MODID + ".desc.wireLength", ItemIC2Coil.getLength(equipped));
ClientUtils.font().drawString(s, e.getResolution().getScaledWidth() / 2 - ClientUtils.font().getStringWidth(s) / 2, e.getResolution().getScaledHeight() - GuiIngameForge.left_height - 40, color, true);
if (ItemNBTHelper.hasKey(equipped, "linkingPos")) {
int[] link = ItemNBTHelper.getIntArray(equipped, "linkingPos");
if (link != null && link.length > 3) {
s = I18n.format(Lib.DESC_INFO + "attachedTo", link[1], link[2], link[3]);
RayTraceResult focussedBlock = ClientUtils.mc().objectMouseOver;
double distSquared;
if (focussedBlock != null && focussedBlock.typeOfHit == RayTraceResult.Type.BLOCK) {
distSquared = focussedBlock.getBlockPos().distanceSq(link[1], link[2], link[3]);
} else {
distSquared = player.getDistanceSq(link[1], link[2], link[3]);
}
int length = Math.min(ItemIC2Coil.getLength(equipped), type.getMaxLength());
if (length * length < distSquared) {
color = 0xdd3333;
}
ClientUtils.font().drawString(s, e.getResolution().getScaledWidth() / 2 - ClientUtils.font().getStringWidth(s) / 2, e.getResolution().getScaledHeight() - GuiIngameForge.left_height - 20, color, true);
}
}
}
}
}
}
}
@SubscribeEvent
public void renderBoundingBoxes(DrawBlockHighlightEvent event) {
if (!event.isCanceled() && event.getSubID() == 0 && event.getTarget().typeOfHit == RayTraceResult.Type.BLOCK) {
TileEntity tile = event.getPlayer().world.getTileEntity(event.getTarget().getBlockPos());
if (tile instanceof TileEntityPanel) {
TileEntityPanel panel = (TileEntityPanel) tile;
Pair<PanelComponent, RayTraceResult> pc = panel.getSelectedComponent(Minecraft.getMinecraft().player, event.getTarget().hitVec, true);
if (pc != null) {
pc.getLeft().renderBox(panel);
event.setCanceled(true);
}
}
}
}
@SubscribeEvent
public void bakeModel(ModelBakeEvent event) {
event.getModelRegistry().putObject(new ModelResourceLocation(IndustrialWires.MODID + ":control_panel", "inventory,type=top"), new PanelModel());
event.getModelRegistry().putObject(new ModelResourceLocation(IndustrialWires.MODID + ":control_panel", "inventory,type=unfinished"), new PanelModel());
}
}

View file

@ -1,310 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client;
import blusunrize.immersiveengineering.api.ManualHelper;
import blusunrize.immersiveengineering.client.ClientUtils;
import blusunrize.immersiveengineering.client.models.smart.ConnLoader;
import blusunrize.immersiveengineering.common.Config;
import blusunrize.lib.manual.ManualInstance;
import blusunrize.lib.manual.ManualPages;
import blusunrize.lib.manual.ManualPages.PositionedItemStack;
import com.google.common.collect.ImmutableMap;
import ic2.api.item.IC2Items;
import malte0811.industrialWires.CommonProxy;
import malte0811.industrialWires.IWConfig;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.IMetaEnum;
import malte0811.industrialWires.blocks.TileEntityJacobsLadder;
import malte0811.industrialWires.blocks.controlpanel.BlockTypes_Panel;
import malte0811.industrialWires.blocks.controlpanel.TileEntityPanelCreator;
import malte0811.industrialWires.blocks.controlpanel.TileEntityRSPanelConn;
import malte0811.industrialWires.client.gui.GuiPanelComponent;
import malte0811.industrialWires.client.gui.GuiPanelCreator;
import malte0811.industrialWires.client.gui.GuiRSPanelConn;
import malte0811.industrialWires.client.gui.GuiRenameKey;
import malte0811.industrialWires.client.panelmodel.PanelModelLoader;
import malte0811.industrialWires.client.render.TileRenderJacobsLadder;
import malte0811.industrialWires.controlpanel.PanelComponent;
import malte0811.industrialWires.items.ItemIC2Coil;
import malte0811.industrialWires.items.ItemKey;
import malte0811.industrialWires.items.ItemPanelComponent;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.ISound;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.obj.OBJLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import java.util.Locale;
import java.util.Random;
import java.util.WeakHashMap;
public class ClientProxy extends CommonProxy {
@Override
public void preInit() {
super.preInit();
ConnLoader.baseModels.put("ic2_conn_tin", new ResourceLocation("immersiveengineering:block/connector/connector_lv.obj"));
ConnLoader.textureReplacements.put("ic2_conn_tin", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_lv",
IndustrialWires.MODID + ":blocks/ic2_conn_tin"));
ConnLoader.baseModels.put("ic2_relay_tin", new ResourceLocation("immersiveengineering:block/connector/connector_lv.obj"));
ConnLoader.textureReplacements.put("ic2_relay_tin", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_lv",
IndustrialWires.MODID + ":blocks/ic2_relay_tin"));
ConnLoader.baseModels.put("ic2_conn_copper", new ResourceLocation("immersiveengineering:block/connector/connector_lv.obj"));
ConnLoader.textureReplacements.put("ic2_conn_copper", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_lv",
IndustrialWires.MODID + ":blocks/ic2_conn_copper"));
ConnLoader.baseModels.put("ic2_relay_copper", new ResourceLocation("immersiveengineering:block/connector/connector_lv.obj"));
ConnLoader.textureReplacements.put("ic2_relay_copper", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_lv",
IndustrialWires.MODID + ":blocks/ic2_relay_copper"));
ConnLoader.baseModels.put("ic2_conn_gold", new ResourceLocation("immersiveengineering:block/connector/connector_mv.obj"));
ConnLoader.textureReplacements.put("ic2_conn_gold", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_mv",
IndustrialWires.MODID + ":blocks/ic2_conn_gold"));
ConnLoader.baseModels.put("ic2_relay_gold", new ResourceLocation("immersiveengineering:block/connector/connector_mv.obj"));
ConnLoader.textureReplacements.put("ic2_relay_gold", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_mv",
IndustrialWires.MODID + ":blocks/ic2_relay_gold"));
ConnLoader.baseModels.put("ic2_conn_hv", new ResourceLocation("immersiveengineering:block/connector/connector_hv.obj"));
ConnLoader.textureReplacements.put("ic2_conn_hv", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_hv",
IndustrialWires.MODID + ":blocks/ic2_conn_hv"));
ConnLoader.baseModels.put("ic2_relay_hv", new ResourceLocation("immersiveengineering:block/connector/relay_hv.obj"));
ConnLoader.baseModels.put("ic2_conn_glass", new ResourceLocation("immersiveengineering:block/connector/connector_hv.obj"));
ConnLoader.textureReplacements.put("ic2_conn_glass", ImmutableMap.of("#immersiveengineering:blocks/connector_connector_hv",
IndustrialWires.MODID + ":blocks/ic2_conn_glass"));
ConnLoader.baseModels.put("ic2_relay_glass", new ResourceLocation("immersiveengineering:block/connector/relay_hv.obj"));
ConnLoader.textureReplacements.put("ic2_relay_glass", ImmutableMap.of("#immersiveengineering:blocks/connector_relay_hv",
IndustrialWires.MODID + ":blocks/ic2_relay_glass"));
ConnLoader.baseModels.put("rs_panel_conn", new ResourceLocation("industrialwires:block/rs_panel_conn.obj"));
for (int meta = 0; meta < ItemIC2Coil.subNames.length; meta++) {
ResourceLocation loc = new ResourceLocation(IndustrialWires.MODID, "ic2_wire_coil/" + ItemIC2Coil.subNames[meta]);
ModelBakery.registerItemVariants(IndustrialWires.coil, loc);
ModelLoader.setCustomModelResourceLocation(IndustrialWires.coil, meta, new ModelResourceLocation(loc, "inventory"));
}
for (int meta = 0; meta < ItemPanelComponent.types.length; meta++) {
ResourceLocation loc = new ResourceLocation(IndustrialWires.MODID, "panel_component/" + ItemPanelComponent.types[meta]);
ModelBakery.registerItemVariants(IndustrialWires.panelComponent, loc);
ModelLoader.setCustomModelResourceLocation(IndustrialWires.panelComponent, meta, new ModelResourceLocation(loc, "inventory"));
}
for (int meta = 0; meta < ItemKey.types.length; meta++) {
ResourceLocation loc = new ResourceLocation(IndustrialWires.MODID, "key/" + ItemKey.types[meta]);
ModelBakery.registerItemVariants(IndustrialWires.key, loc);
ModelLoader.setCustomModelResourceLocation(IndustrialWires.key, meta, new ModelResourceLocation(loc, "inventory"));
}
Block[] blocks = {IndustrialWires.ic2conn, IndustrialWires.mechConv, IndustrialWires.jacobsLadder, IndustrialWires.panel};
for (Block b : blocks) {
if (b != null) {
Item blockItem = Item.getItemFromBlock(b);
final ResourceLocation loc = b.getRegistryName();
assert loc != null;
ModelLoader.setCustomMeshDefinition(blockItem, stack -> new ModelResourceLocation(loc, "inventory"));
Object[] v = ((IMetaEnum) b).getValues();
for (int meta = 0; meta < v.length; meta++) {
String location = loc.toString();
String prop = "inventory,type=" + v[meta].toString().toLowerCase(Locale.US);
try {
ModelLoader.setCustomModelResourceLocation(blockItem, meta, new ModelResourceLocation(location, prop));
} catch (NullPointerException npe) {
throw new RuntimeException(b + " lacks an item!", npe);
}
}
}
}
OBJLoader.INSTANCE.addDomain(IndustrialWires.MODID);
ModelLoaderRegistry.registerLoader(new PanelModelLoader());
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityJacobsLadder.class, new TileRenderJacobsLadder());
}
@Override
public void postInit() {
super.postInit();
ManualInstance m = ManualHelper.getManual();
PositionedItemStack[][] wireRecipes = new PositionedItemStack[3][10];
int xBase = 15;
ItemStack tinCable = IC2Items.getItem("cable", "type:tin,insulation:0");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
wireRecipes[0][3 * i + j] = new PositionedItemStack(tinCable.copy(), 18 * i + xBase, 18 * j);
}
}
ItemStack tmp = new ItemStack(IndustrialWires.coil);
ItemIC2Coil.setLength(tmp, 9);
wireRecipes[0][9] = new PositionedItemStack(tmp, 18 * 4 + xBase, 18);
Random r = new Random();
for (int i = 1; i < 3; i++) {
int lengthSum = 0;
for (int j1 = 0; j1 < 3; j1++) {
for (int j2 = 0; j2 < 3; j2++) {
if (r.nextBoolean()) {
// cable
lengthSum++;
wireRecipes[i][3 * j1 + j2] = new PositionedItemStack(tinCable.copy(), 18 * j1 + xBase, 18 * j2);
} else {
// wire coil
int length = r.nextInt(99) + 1;
tmp = new ItemStack(IndustrialWires.coil);
ItemIC2Coil.setLength(tmp, length);
wireRecipes[i][3 * j1 + j2] = new PositionedItemStack(tmp, 18 * j1 + xBase, 18 * j2);
lengthSum += length;
}
}
}
tmp = new ItemStack(IndustrialWires.coil);
ItemIC2Coil.setLength(tmp, lengthSum);
wireRecipes[i][9] = new PositionedItemStack(tmp, 18 * 4 + xBase, 18);
}
ClientUtils.mc().getItemColors().registerItemColorHandler((stack, pass) -> {
if (pass == 1) {
PanelComponent pc = ItemPanelComponent.componentFromStack(stack);
if (pc != null) {
return 0xff000000 | pc.getColor();
}
}
return ~0;
}, IndustrialWires.panelComponent);
m.addEntry("industrialwires.wires", "industrialwires",
new ManualPages.CraftingMulti(m, "industrialwires.wires0", new ItemStack(IndustrialWires.ic2conn, 1, 0), new ItemStack(IndustrialWires.ic2conn, 1, 1), new ItemStack(IndustrialWires.ic2conn, 1, 2), new ItemStack(IndustrialWires.ic2conn, 1, 3),
new ItemStack(IndustrialWires.ic2conn, 1, 4), new ItemStack(IndustrialWires.ic2conn, 1, 5), new ItemStack(IndustrialWires.ic2conn, 1, 6), new ItemStack(IndustrialWires.ic2conn, 1, 7)),
new ManualPages.Text(m, "industrialwires.wires1"),
new ManualPages.CraftingMulti(m, "industrialwires.wires2", (Object[]) wireRecipes)
);
if (IndustrialWires.mechConv != null) {
m.addEntry("industrialwires.mechConv", "industrialwires",
new ManualPages.Crafting(m, "industrialwires.mechConv0", new ItemStack(IndustrialWires.mechConv, 1, 1)),
new ManualPages.Crafting(m, "industrialwires.mechConv1", new ItemStack(IndustrialWires.mechConv, 1, 2)),
new ManualPages.Crafting(m, "industrialwires.mechConv2", new ItemStack(IndustrialWires.mechConv, 1, 0))
);
}
Config.manual_doubleA.put("iwJacobsUsage", IWConfig.HVStuff.jacobsUsageEU);
m.addEntry("industrialwires.jacobs", "industrialwires",
new ManualPages.CraftingMulti(m, "industrialwires.jacobs0", new ItemStack(IndustrialWires.jacobsLadder, 1, 0), new ItemStack(IndustrialWires.jacobsLadder, 1, 1), new ItemStack(IndustrialWires.jacobsLadder, 1, 2)),
new ManualPages.Text(m, "industrialwires.jacobs1"));
m.addEntry("industrialwires.intro", "control_panels",
new ManualPages.Text(m, "industrialwires.intro0"),
new ManualPages.Text(m, "industrialwires.intro1"),
new ManualPages.Crafting(m, "industrialwires.intro2", new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.DUMMY.ordinal())),
new ManualPages.Text(m, "industrialwires.intro3"),
new ManualPages.Crafting(m, "industrialwires.intro4", new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.UNFINISHED.ordinal())),
new ManualPages.Text(m, "industrialwires.intro5")
);
m.addEntry("industrialwires.panel_creator", "control_panels",
new ManualPages.Crafting(m, "industrialwires.panel_creator0", new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.CREATOR.ordinal())),
new ManualPages.Text(m, "industrialwires.panel_creator1"),
new ManualPages.Text(m, "industrialwires.panel_creator2")
);
m.addEntry("industrialwires.redstone", "control_panels",
new ManualPages.Crafting(m, "industrialwires.redstone0", new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.RS_WIRE.ordinal())),
new ManualPages.Text(m, "industrialwires.redstone1")
);
m.addEntry("industrialwires.components", "control_panels",
new ManualPages.Text(m, "industrialwires.components.general"),
new ManualPages.Crafting(m, "industrialwires.button", new ItemStack(IndustrialWires.panelComponent, 1, 0)),
new ManualPages.Crafting(m, "industrialwires.label", new ItemStack(IndustrialWires.panelComponent, 1, 1)),
new ManualPages.Crafting(m, "industrialwires.indicator_light", new ItemStack(IndustrialWires.panelComponent, 1, 2)),
new ManualPages.Crafting(m, "industrialwires.slider", new ItemStack(IndustrialWires.panelComponent, 1, 3)),
new ManualPages.CraftingMulti(m, "industrialwires.toggle_switch", new ItemStack(IndustrialWires.panelComponent, 1, 5), new ItemStack(IndustrialWires.panelComponent, 1, 6)),
new ManualPages.Text(m, "industrialwires.toggle_switch1"),
new ManualPages.Crafting(m, "industrialwires.variac", new ItemStack(IndustrialWires.panelComponent, 1, 4)),
new ManualPages.CraftingMulti(m, "industrialwires.lock", new ItemStack(IndustrialWires.panelComponent, 1, 7), new ItemStack(IndustrialWires.key)),
new ManualPages.Crafting(m, "industrialwires.panel_meter", new ItemStack(IndustrialWires.panelComponent, 1, 8))
);
}
@Override
public World getClientWorld() {
return Minecraft.getMinecraft().world;
}
private WeakHashMap<BlockPos, ISound> playingSounds = new WeakHashMap<>();
private static ResourceLocation jacobsStart = new ResourceLocation(IndustrialWires.MODID, "jacobs_ladder_start");//~470 ms ~=9 ticks
private static ResourceLocation jacobsMiddle = new ResourceLocation(IndustrialWires.MODID, "jacobs_ladder_middle");
private static ResourceLocation jacobsEnd = new ResourceLocation(IndustrialWires.MODID, "jacobs_ladder_end");//~210 ms ~= 4 ticks
@Override
public void playJacobsLadderSound(TileEntityJacobsLadder te, int phase, Vec3d soundPos) {
if (playingSounds.containsKey(te.getPos())) {
Minecraft.getMinecraft().getSoundHandler().stopSound(playingSounds.get(te.getPos()));
playingSounds.remove(te.getPos());
}
ResourceLocation event;
switch (phase) {
case 0:
event = jacobsStart;
break;
case 1:
event = jacobsMiddle;
break;
case 2:
event = jacobsEnd;
break;
default:
return;
}
PositionedSoundRecord sound = new PositionedSoundRecord(event, SoundCategory.BLOCKS, te.size.soundVolume, 1, false, 0, ISound.AttenuationType.LINEAR, (float) soundPos.x, (float) soundPos.y, (float) soundPos.z);
ClientUtils.mc().getSoundHandler().playSound(sound);
playingSounds.put(te.getPos(), sound);
}
@Override
public Gui getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
if (ID == 0) {
TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
if (te instanceof TileEntityRSPanelConn) {
return new GuiRSPanelConn((TileEntityRSPanelConn) te);
}
if (te instanceof TileEntityPanelCreator) {
return new GuiPanelCreator(player.inventory, (TileEntityPanelCreator) te);
}
} else if (ID == 1) {
EnumHand h = z == 1 ? EnumHand.MAIN_HAND : EnumHand.OFF_HAND;
ItemStack held = player.getHeldItem(h);
if (!held.isEmpty()) {
if (held.getItem() == IndustrialWires.panelComponent) {
return new GuiPanelComponent(h, ItemPanelComponent.componentFromStack(held));
} else if (held.getItem() == IndustrialWires.key) {
return new GuiRenameKey(h);
}
}
}
return null;
}
}

View file

@ -1,102 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.crafting;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.items.ItemIC2Coil;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.oredict.OreDictionary;
import javax.annotation.Nonnull;
public class RecipeCoilLength implements IRecipe {
public final ItemStack coil;
public final ItemStack cable;
private final int maxLength;
public RecipeCoilLength(int meta) {
coil = new ItemStack(IndustrialWires.coil, 1, meta);
cable = ItemIC2Coil.getUninsulatedCable(coil);
maxLength = ItemIC2Coil.getMaxWireLength(coil);
}
@Override
public boolean matches(@Nonnull InventoryCrafting inv, @Nonnull World worldIn) {
int l = getLength(inv);
return l > 0;
}
@Nonnull
@Override
public ItemStack getCraftingResult(@Nonnull InventoryCrafting inv) {
ItemStack ret = new ItemStack(IndustrialWires.coil, 1, coil.getItemDamage());
ItemIC2Coil.setLength(ret, Math.min(maxLength, getLength(inv)));
return ret;
}
@Override
public int getRecipeSize() {
return 1;
}
@Nonnull
@Override
public ItemStack getRecipeOutput() {
return ItemStack.EMPTY;
}
@Nonnull
@Override
public NonNullList<ItemStack> getRemainingItems(@Nonnull InventoryCrafting inv) {
NonNullList<ItemStack> ret = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY);
int length = Math.min(getLength(inv), maxLength);
for (int i = 0; i < ret.size() && length > 0; i++) {
ItemStack curr = inv.getStackInSlot(i);
if (OreDictionary.itemMatches(curr, coil, false)) {
length -= ItemIC2Coil.getLength(curr);
if (length < 0) {
ItemStack currStack = new ItemStack(IndustrialWires.coil, 1);
ret.set(i, currStack);
ItemIC2Coil.setLength(currStack, -length);
}
} else if (OreDictionary.itemMatches(curr, cable, false)) {
length--;
}
}
return ret;
}
private int getLength(InventoryCrafting inv) {
int cableLength = 0;
for (int i = 0; i < inv.getSizeInventory(); i++) {
ItemStack curr = inv.getStackInSlot(i);
if (OreDictionary.itemMatches(curr, coil, false)) {
cableLength += ItemIC2Coil.getLength(curr);
} else if (OreDictionary.itemMatches(curr, cable, false)) {
cableLength++;
} else if (!curr.isEmpty()) {
return -1;
}
}
return cableLength;
}
}

View file

@ -1,243 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.items;
import blusunrize.immersiveengineering.api.Lib;
import blusunrize.immersiveengineering.api.TargetingInfo;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.IWireCoil;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.Connection;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import blusunrize.immersiveengineering.common.IESaveData;
import blusunrize.immersiveengineering.common.util.IEAchievements;
import blusunrize.immersiveengineering.common.util.ItemNBTHelper;
import blusunrize.immersiveengineering.common.util.Utils;
import ic2.api.item.IC2Items;
import malte0811.industrialWires.IWConfig;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.wires.IC2Wiretype;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.I18n;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ItemIC2Coil extends Item implements IWireCoil {
public final static String[] subNames = {"tin", "copper", "gold", "hv", "glass"};
public final static String lengthKey = "wireLength";
public ItemIC2Coil() {
setUnlocalizedName(IndustrialWires.MODID + ".ic2_wire_coil");
setHasSubtypes(true);
this.setCreativeTab(IndustrialWires.creativeTab);
setMaxStackSize(64);
setRegistryName(new ResourceLocation(IndustrialWires.MODID, "ic2_wire_coil"));
GameRegistry.register(this);
}
@Override
public void getSubItems(@Nonnull Item itemIn, CreativeTabs tab, NonNullList<ItemStack> subItems) {
for (int i = 0; i < subNames.length; i++) {
ItemStack tmp = new ItemStack(this, 1, i);
setLength(tmp, getMaxWireLength(tmp));
subItems.add(tmp);
}
}
@Nonnull
@Override
public String getUnlocalizedName(ItemStack stack) {
return this.getUnlocalizedName() + "." + subNames[stack.getMetadata()];
}
@Override
public WireType getWireType(ItemStack stack) {
return IC2Wiretype.IC2_TYPES[stack.getMetadata()];
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List<String> list, boolean adv) {
list.add(I18n.format(IndustrialWires.MODID + ".desc.wireLength", getLength(stack)));
int transferRate = IC2Wiretype.IC2_TYPES[stack.getMetadata()].getTransferRate();
list.add(I18n.format(IndustrialWires.MODID + ".tooltip.transfer_rate", transferRate));
list.add(I18n.format(IndustrialWires.MODID + ".tooltip.input_rate", transferRate / 8));
if (stack.getTagCompound() != null && stack.getTagCompound().hasKey("linkingPos")) {
int[] link = stack.getTagCompound().getIntArray("linkingPos");
if (link.length > 3) {
list.add(I18n.format(Lib.DESC_INFO + "attachedToDim", link[1], link[2], link[3], link[0]));
}
}
list.add(I18n.format(IndustrialWires.MODID + ".desc.recipe"));
}
//mostly copied from IE
@Nonnull
@Override
public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) {
ItemStack stack = player.getHeldItem(hand);
if (!world.isRemote && !stack.isEmpty()) {
if (stack.getCount() > 1) {
player.sendMessage(new TextComponentTranslation(IndustrialWires.MODID + ".chat.stackSize"));
return EnumActionResult.FAIL;
}
TileEntity tileEntity = world.getTileEntity(pos);
if (tileEntity instanceof IImmersiveConnectable && ((IImmersiveConnectable) tileEntity).canConnect()) {
TargetingInfo target = new TargetingInfo(side, hitX, hitY, hitZ);
WireType wire = getWireType(stack);
BlockPos masterPos = ((IImmersiveConnectable) tileEntity).getConnectionMaster(wire, target);
tileEntity = world.getTileEntity(masterPos);
if (!(tileEntity instanceof IImmersiveConnectable) || !((IImmersiveConnectable) tileEntity).canConnect()) {
return EnumActionResult.PASS;
}
if (!((IImmersiveConnectable) tileEntity).canConnectCable(wire, target)) {
player.sendMessage(new TextComponentTranslation(Lib.CHAT_WARN + "wrongCable"));
return EnumActionResult.FAIL;
}
if (!ItemNBTHelper.hasKey(stack, "linkingPos")) {
ItemNBTHelper.setIntArray(stack, "linkingPos", new int[]{world.provider.getDimension(), masterPos.getX(), masterPos.getY(), masterPos.getZ()});
target.writeToNBT(stack.getTagCompound());
} else {
WireType type = getWireType(stack);
int[] array = ItemNBTHelper.getIntArray(stack, "linkingPos");
BlockPos linkPos = new BlockPos(array[1], array[2], array[3]);
TileEntity tileEntityLinkingPos = world.getTileEntity(linkPos);
int distanceSq = (int) Math.ceil(linkPos.distanceSq(masterPos));
if (array[0] != world.provider.getDimension()) {
player.sendMessage(new TextComponentTranslation(Lib.CHAT_WARN + "wrongDimension"));
} else if (linkPos.equals(masterPos)) {
player.sendMessage(new TextComponentTranslation(Lib.CHAT_WARN + "sameConnection"));
} else if (distanceSq > (type.getMaxLength() * type.getMaxLength())) {
player.sendMessage(new TextComponentTranslation(Lib.CHAT_WARN + "tooFar"));
} else if (!(tileEntityLinkingPos instanceof IImmersiveConnectable) || !((IImmersiveConnectable) tileEntityLinkingPos).canConnectCable(type, TargetingInfo.readFromNBT(stack.getTagCompound()))) {
player.sendMessage(new TextComponentTranslation(Lib.CHAT_WARN + "invalidPoint"));
} else {
IImmersiveConnectable nodeHere = (IImmersiveConnectable) tileEntity;
IImmersiveConnectable nodeLink = (IImmersiveConnectable) tileEntityLinkingPos;
boolean connectionExists = false;
Set<Connection> outputs = ImmersiveNetHandler.INSTANCE.getConnections(world, Utils.toCC(nodeHere));
if (outputs != null) {
for (Connection con : outputs) {
if (con.end.equals(Utils.toCC(nodeLink))) {
connectionExists = true;
}
}
}
if (connectionExists) {
player.sendMessage(new TextComponentTranslation(Lib.CHAT_WARN + "connectionExists"));
} else {
Vec3d rtOff0 = nodeHere.getRaytraceOffset(nodeLink).addVector(masterPos.getX(), masterPos.getY(), masterPos.getZ());
Vec3d rtOff1 = nodeLink.getRaytraceOffset(nodeHere).addVector(linkPos.getX(), linkPos.getY(), linkPos.getZ());
Set<BlockPos> ignore = new HashSet<>();
ignore.addAll(nodeHere.getIgnored(nodeLink));
ignore.addAll(nodeLink.getIgnored(nodeHere));
boolean canSee = Utils.rayTraceForFirst(rtOff0, rtOff1, world, ignore) == null;
if (canSee) {
int lengthOnStack = getLength(stack);
int length = (int) Math.sqrt(distanceSq);
if (length <= lengthOnStack) {
TargetingInfo targetLink = TargetingInfo.readFromNBT(stack.getTagCompound());
ImmersiveNetHandler.INSTANCE.addConnection(world, Utils.toCC(nodeHere), Utils.toCC(nodeLink), length, type);
nodeHere.connectCable(type, target, nodeLink);
nodeLink.connectCable(type, targetLink, nodeHere);
IESaveData.setDirty(world.provider.getDimension());
player.addStat(IEAchievements.connectWire);
if (!player.capabilities.isCreativeMode) {
if (length < lengthOnStack) {
setLength(stack, lengthOnStack - length);
} else {
player.setHeldItem(hand, ItemStack.EMPTY);
}
}
((TileEntity) nodeHere).markDirty();
world.addBlockEvent(masterPos, ((TileEntity) nodeHere).getBlockType(), -1, 0);
IBlockState state = world.getBlockState(masterPos);
world.notifyBlockUpdate(masterPos, state, state, 3);
((TileEntity) nodeLink).markDirty();
world.addBlockEvent(linkPos, ((TileEntity) nodeLink).getBlockType(), -1, 0);
state = world.getBlockState(linkPos);
world.notifyBlockUpdate(linkPos, state, state, 3);
} else {
player.sendMessage(new TextComponentTranslation(IndustrialWires.MODID + ".chat.tooLong"));
}
} else {
player.sendMessage(new TextComponentTranslation(Lib.CHAT_WARN + "cantSee"));
}
}
}
ItemNBTHelper.remove(stack, "linkingPos");
ItemNBTHelper.remove(stack, "side");
ItemNBTHelper.remove(stack, "hitX");
ItemNBTHelper.remove(stack, "hitY");
ItemNBTHelper.remove(stack, "hitZ");
}
return EnumActionResult.SUCCESS;
}
}
return EnumActionResult.PASS;
}
public static void setLength(ItemStack i, int blocks) {
i.setTagInfo(lengthKey, new NBTTagInt(blocks));
}
public static int getLength(ItemStack i) {
if (i.getTagCompound() == null) {
setLength(i, 4);
}
return i.getTagCompound().getInteger(lengthKey);
}
public static int getMaxWireLength(ItemStack i) {
return IWConfig.maxLengthOnCoil[i.getItemDamage()];
}
public static ItemStack getUninsulatedCable(ItemStack i) {
switch (i.getMetadata()) {
case 0:
return IC2Items.getItem("cable", "type:tin,insulation:0");
case 1:
return IC2Items.getItem("cable", "type:copper,insulation:0");
case 2:
return IC2Items.getItem("cable", "type:gold,insulation:0");
case 3:
return IC2Items.getItem("cable", "type:iron,insulation:0");
case 4:
return IC2Items.getItem("cable", "type:glass,insulation:0");
}
return null;
}
}

View file

@ -1,120 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.util;
import net.minecraft.nbt.NBTTagCompound;
public class DualEnergyStorage {
private double storedEU;
private double maxEU;
private double maxOutEU;
private double maxInEU;
public DualEnergyStorage(double maxEU, double maxInEU, double maxOutEU) {
this(0, maxEU, maxInEU, maxOutEU);
}
public DualEnergyStorage(double storedEU, double maxEU, double maxInEU, double maxOutEU) {
this.maxEU = maxEU;
this.maxInEU = maxInEU;
this.maxOutEU = maxOutEU;
this.storedEU = storedEU;
}
public DualEnergyStorage(double maxEU, double maxIoEU) {
this(maxEU, maxIoEU, maxIoEU);
}
public DualEnergyStorage(double maxEU) {
this(maxEU, maxEU, maxEU);
}
public DualEnergyStorage(int maxIF, int maxInIF, int maxOutIF) {
this(ConversionUtil.euPerIfIdeal() * maxIF, ConversionUtil.euPerIfIdeal() * maxInIF, ConversionUtil.euPerIfIdeal() * maxOutIF);
}
public DualEnergyStorage(int maxIF, int maxIoIF) {
this(maxIF, maxIoIF, maxIoIF);
}
public DualEnergyStorage(int maxIF) {
this(maxIF, maxIF, maxIF);
}
public double extractEU(double extractMax, boolean doExtract) {
double extr = Math.min(storedEU, extractMax);
if (doExtract) {
storedEU -= extr;
}
return extr;
}
public double extractIF(int extractMax, boolean doExtract) {
double eu = extractMax * ConversionUtil.euPerIfIdeal();
return ConversionUtil.ifPerEuIdeal() * extractEU(eu, doExtract);
}
public double insertEU(double insertMax, boolean doInsert) {
double ins = Math.min(insertMax, maxEU - storedEU);
if (doInsert) {
storedEU += ins;
}
return ins;
}
public double insertIF(int insertMax, boolean doInsert) {
double eu = insertMax * ConversionUtil.euPerIfIdeal();
return ConversionUtil.ifPerEuIdeal() * insertEU(eu, doInsert);
}
public double getEnergyStoredEU() {
return storedEU;
}
public double getMaxStoredEU() {
return maxEU;
}
public double getEnergyStoredIF() {
return storedEU * ConversionUtil.ifPerEuIdeal();
}
public double getMaxStoredIF() {
return maxEU * ConversionUtil.ifPerEuIdeal();
}
public double getEURequested() {
return Math.min(maxInEU, maxEU - storedEU);
}
public void writeToNbt(NBTTagCompound nbtOuter, String key) {
NBTTagCompound nbt = key == null ? nbtOuter : new NBTTagCompound();
nbt.setDouble("stored", storedEU);
nbt.setDouble("maxStored", maxEU);
nbt.setDouble("maxIn", maxInEU);
nbt.setDouble("maxOut", maxOutEU);
if (key != null) {
nbtOuter.setTag(key, nbt);
}
}
public static DualEnergyStorage readFromNBT(NBTTagCompound nbt) {
return new DualEnergyStorage(nbt.getDouble("stored"), nbt.getDouble("maxStored"), nbt.getDouble("maxIn"), nbt.getDouble("maxOut"));
}
}

View file

@ -1,87 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.util;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import com.google.common.collect.ImmutableSet;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiPredicate;
public final class MiscUtils {
private MiscUtils() {
}
public static Set<ImmersiveNetHandler.Connection> genConnBlockstate(Set<ImmersiveNetHandler.Connection> conns, World world) {
if (conns == null)
return ImmutableSet.of();
Set<ImmersiveNetHandler.Connection> ret = new HashSet<ImmersiveNetHandler.Connection>() {
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof HashSet))
return false;
HashSet<ImmersiveNetHandler.Connection> other = (HashSet<ImmersiveNetHandler.Connection>) o;
if (other.size() != this.size())
return false;
for (ImmersiveNetHandler.Connection c : this)
if (!other.contains(c))
return false;
return true;
}
};
for (ImmersiveNetHandler.Connection c : conns) {
IImmersiveConnectable end = ApiUtils.toIIC(c.end, world, false);
if (end == null)
continue;
// generate subvertices
c.getSubVertices(world);
ret.add(c);
}
return ret;
}
public static List<BlockPos> discoverLocal(World w, BlockPos here, BiPredicate<BlockPos, Integer> isValid) {
List<BlockPos> ret = new ArrayList<>();
List<BlockPos> open = new ArrayList<>();
open.add(here);
while (!open.isEmpty()) {
BlockPos curr = open.get(0);
ret.add(curr);
open.remove(0);
for (EnumFacing f : EnumFacing.VALUES) {
BlockPos next = curr.offset(f);
if (!open.contains(next) && !ret.contains(next) && isValid.test(next, ret.size())) {
open.add(next);
}
}
}
return ret;
}
}

View file

@ -1,105 +0,0 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.wires;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.Connection;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import malte0811.industrialWires.IWConfig;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.items.ItemIC2Coil;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class IC2Wiretype extends WireType {
final int type;
final int[] ic2Rates = {32 * 8, 128 * 8, 512 * 8, 2048 * 8, 8192 * 8};
final int[] ic2Colors = {0xa5bcc7, 0xbc7945, 0xfeff73, 0xb9d6d9, 0xf1f1f1};
final String[] ic2Names = {"ic2Tin", "ic2Copper", "ic2Gold", "ic2Hv", "ic2Glass"};
final double[] lossPerBlock = {.2, .2, .4, .8, .025};
final double[] ic2RenderDiameter = {.03125, .03125, .046875, .0625, .75 * .03125};
public static final IC2Wiretype[] IC2_TYPES = {new IC2Wiretype(0), new IC2Wiretype(1), new IC2Wiretype(2), new IC2Wiretype(3), new IC2Wiretype(4)};
public IC2Wiretype(int ordinal) {
super();
this.type = ordinal;
}
/**
* In this case, this does not return the loss RATIO but the loss PER BLOCK
*/
@Override
public double getLossRatio() {
return lossPerBlock[type];
}
@Override
public int getTransferRate() {
return ic2Rates[type];
}
@Override
public int getColour(Connection connection) {
return ic2Colors[type];
}
@Override
public double getSlack() {
return type == 2 ? 1.03 : 1.005;
}
@Override
@SideOnly(Side.CLIENT)
public TextureAtlasSprite getIcon(Connection connection) {
return iconDefaultWire;
}
@Override
public int getMaxLength() {
return IWConfig.maxLengthPerConn[type];
}
@Override
public ItemStack getWireCoil(ImmersiveNetHandler.Connection con) {
ItemStack ret = getWireCoil();
ItemIC2Coil.setLength(ret, con.length);
return ret;
}
@Override
public ItemStack getWireCoil() {
return new ItemStack(IndustrialWires.coil, 1, type);
}
@Override
public String getUniqueName() {
return ic2Names[type];
}
@Override
public double getRenderDiameter() {
return ic2RenderDiameter[type];
}
@Override
public boolean isEnergyWire() {
return true;
}
}

View file

@ -1,31 +1,32 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires;
package malte0811.industrialwires;
import malte0811.industrialWires.blocks.TileEntityJacobsLadder;
import malte0811.industrialWires.blocks.controlpanel.TileEntityPanelCreator;
import malte0811.industrialWires.blocks.controlpanel.TileEntityRSPanelConn;
import malte0811.industrialWires.containers.ContainerPanelComponent;
import malte0811.industrialWires.containers.ContainerPanelCreator;
import malte0811.industrialWires.containers.ContainerRSPanelConn;
import malte0811.industrialWires.containers.ContainerRenameKey;
import malte0811.industrialwires.blocks.controlpanel.TileEntityPanelCreator;
import malte0811.industrialwires.blocks.controlpanel.TileEntityRSPanel;
import malte0811.industrialwires.blocks.converter.TileEntityMechMB;
import malte0811.industrialwires.blocks.hv.TileEntityJacobsLadder;
import malte0811.industrialwires.blocks.hv.TileEntityMarx;
import malte0811.industrialwires.containers.ContainerPanelComponent;
import malte0811.industrialwires.containers.ContainerPanelCreator;
import malte0811.industrialwires.containers.ContainerRSPanelConn;
import malte0811.industrialwires.containers.ContainerRenameKey;
import malte0811.industrialwires.mech_mb.MechEnergy;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
@ -34,6 +35,8 @@ import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import java.util.Set;
public class CommonProxy implements IGuiHandler {
public void preInit() {
}
@ -47,6 +50,8 @@ public class CommonProxy implements IGuiHandler {
public void playJacobsLadderSound(TileEntityJacobsLadder te, int phase, Vec3d soundPos) {
}
public void startTinnitus() {
}
@Override
public Container getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
@ -55,8 +60,8 @@ public class CommonProxy implements IGuiHandler {
if (te instanceof TileEntityPanelCreator) {
return new ContainerPanelCreator(player.inventory, (TileEntityPanelCreator) te);
}
if (te instanceof TileEntityRSPanelConn) {
return new ContainerRSPanelConn((TileEntityRSPanelConn) te);
if (te instanceof TileEntityRSPanel) {
return new ContainerRSPanelConn((TileEntityRSPanel) te);
}
} else if (ID == 1) {//ITEM GUI
EnumHand h = z == 1 ? EnumHand.MAIN_HAND : EnumHand.OFF_HAND;
@ -76,4 +81,18 @@ public class CommonProxy implements IGuiHandler {
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return null;
}
public void playMarxBang(TileEntityMarx tileEntityMarx, Vec3d vec3d, float energy) {}
public void updateMechMBTurningSound(TileEntityMechMB te, MechEnergy energy) {}
public void stopAllSoundsExcept(BlockPos pos, Set<?> excluded) {}
public boolean isSingleplayer() {
return false;
}
public boolean isValidTextureSource(ItemStack stack) {
return stack.getItem() instanceof ItemBlock;
}
}

View file

@ -0,0 +1,68 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires;
import malte0811.industrialwires.items.ItemIC2Coil;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@Mod.EventBusSubscriber
public class EventHandler {
@SubscribeEvent
public static void onItemPickup(EntityItemPickupEvent ev) {
if (ev.getItem().getItem().getItem()==IndustrialWires.coil) {
ItemStack stack = ev.getItem().getItem();
InventoryPlayer playerInv = ev.getEntityPlayer().inventory;
boolean changed = false;
int lengthOnEntity = ItemIC2Coil.getLength(stack);
final int lengthPerCoilOrig = lengthOnEntity/stack.getCount();
for (int i = 0;i<playerInv.getSizeInventory();i++) {
ItemStack inInv = playerInv.getStackInSlot(i);
if (ItemStack.areItemsEqual(stack, inInv)) {
int oldLength = ItemIC2Coil.getLength(inInv);
int newLength = Math.min(oldLength+lengthOnEntity, ItemIC2Coil.getMaxWireLength(inInv));
ItemIC2Coil.setLength(inInv, newLength);
lengthOnEntity -= newLength-oldLength;
changed = true;
}
}
if (changed) {
ev.getEntityPlayer().onItemPickup(ev.getItem(), 1);
}
if (lengthOnEntity==0) {
ev.getItem().setDead();
ev.setCanceled(true);
} else if (stack.getCount()>1) {
int coilsRemaining = lengthOnEntity/lengthPerCoilOrig;
stack.setCount(coilsRemaining);
int leftover = lengthOnEntity-lengthPerCoilOrig*coilsRemaining;
if (leftover>0) {
EntityItem old = ev.getItem();
ItemStack leftoverItem = new ItemStack(stack.getItem(), 1, stack.getMetadata());
ItemIC2Coil.setLength(leftoverItem, leftover);
EntityItem newCoil = new EntityItem(old.world, old.posX, old.posY, old.posZ, leftoverItem);
old.world.spawnEntity(newCoil);
}
} else if (stack.getCount()==1) {
ItemIC2Coil.setLength(stack, lengthOnEntity);
}
}
}
}

View file

@ -0,0 +1,55 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires;
import blusunrize.immersiveengineering.ImmersiveEngineering;
import blusunrize.immersiveengineering.common.blocks.BlockIEBase;
import blusunrize.immersiveengineering.common.blocks.BlockTypes_MetalsIE;
import blusunrize.immersiveengineering.common.blocks.metal.*;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class IEObjects {
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":metal_decoration0")
public static BlockIEBase<BlockTypes_MetalDecoration0> blockMetalDecoration0 = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":metal_decoration1")
public static BlockIEBase<BlockTypes_MetalDecoration1> blockMetalDecoration1 = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":metal_decoration2")
public static BlockIEBase<BlockTypes_MetalDecoration2> blockMetalDecoration2 = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":metal_device0")
public static BlockIEBase<BlockTypes_MetalDevice0> blockMetalDevice0 = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":connector")
public static BlockIEBase<BlockTypes_Connector> blockConnectors = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":storage")
public static BlockIEBase<BlockTypes_MetalsIE> blockStorage = nullNotNull();
//ITEMS
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":earmuffs")
public static Item itemEarmuffs = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":material")
public static Item itemMaterial = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":wirecoil")
public static Item itemWireCoil = nullNotNull();
@GameRegistry.ObjectHolder(ImmersiveEngineering.MODID+":tool")
public static Item itemTool = nullNotNull();
// Ugly hack to prevent null warnings
private static <T> T nullNotNull() {
//noinspection ConstantConditions
return null;
}
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import malte0811.industrialwires.util.ConversionUtil;
import net.minecraft.entity.Entity;
public interface IMixedConnector extends IImmersiveConnectable {
/**
* @return leftover energy.
*/
double insertEnergy(double joules, boolean simulate);
@Override
default float getDamageAmount(Entity e, ImmersiveNetHandler.Connection c)
{
return (float) Math.ceil(IImmersiveConnectable.super.getDamageAmount(e, c) * ConversionUtil.euPerJoule());//Same as IC2 uses
}
}

View file

@ -1,33 +1,45 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires;
package malte0811.industrialwires;
import blusunrize.immersiveengineering.common.Config.IEConfig;
import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.Config.Comment;
import net.minecraftforge.common.config.Config.RequiresMcRestart;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@Config(modid = IndustrialWires.MODID)
@Mod.EventBusSubscriber
public class IWConfig {
@Comment({"The maximum length of a single connection.", "Order: Tin, Copper, Gold, HV, Glass Fiber"})
public static int[] maxLengthPerConn = {16, 16, 16, 32, 32};
@Comment({"The maximum length of wire a coil item.", "Order: Tin, Copper, Gold, HV, Glass Fiber (as above)"})
public static int[] maxLengthOnCoil = {1024, 1024, 1024, 2048, 2048};
@Comment({"The factor between the IF transfer rate of the wires and the IF transfer rate corresponding to the EU transfer rate.",
"The default value results in the same transfer rates as the standard IE wires"})
public static double wireRatio = .5;
@Comment({"The EU IO rates of the wires. Order is Tin, Copper, Gold, HV, Glass Fiber"})
public static double[] ioRatesEU = {32, 128, 512, 2048, 8192};
@Comment({"The EU loss rates of the wires (EU per block). Order is Tin, Copper, Gold, HV, Glass Fiber"})
public static double[] euLossPerBlock = {.2, .2, .4, .8, .025};
@Comment({"Set this to false to completely disable any conversion between IF and EU (default: true)"})
@RequiresMcRestart
public static boolean enableConversion = true;
public static MechConversion mech;
@ -41,27 +53,57 @@ public class IWConfig {
public static double kinPerEu = 4;
@Comment({"The maximum amount of IF that can be converted to rotational energy", "by one motor in one tick (default: 100)"})
@Config.RequiresWorldRestart
public static int maxIfToMech = 100;
@Comment({"The efficiency of the IF motor. The default value of 0.9 means that 10% of the energy are lost in the conversion."})
public static double ifMotorEfficiency = .9;
@Comment({"The maximum amount of IE rotational energy that can be converted into IC2 kinetic energy", "by one converter in one tick"})
public static double maxRotToKin = 50;
@Config.RequiresWorldRestart
public static double maxRotToKin = 200;
@Comment({"The efficiency of the conversion from IE rotational energy to IC2 kinetic energy"})
public static double rotToKinEfficiency = .7;
@Comment({"The maximum amount of IC2 kinetic energy that can be converted into IE rotational energy", "by one converter in one tick"})
public static int maxKinToRot = 2400;
@Config.RequiresWorldRestart
public static int maxKinToRot = 600;
@Comment({"The efficiency of the conversion from IC2 kinetic energy to IE rotational energy"})
public static double kinToRotEfficiency = .8;
@Comment({"The conversion factor between Joules (the SI unit) and RF. Used for the Marx generator and the rotary converters",
"With the default value the IE diesel generator produces 200kW"})
public static double joulesPerRF = 200e3 / (20 * IEConfig.Machines.dieselGen_output);
@Comment({"What energy types can be used with the mechanical multiblock. 0: None (Probably useless),",
"1: EU (Currently useless), 2: FE, 3:EU and FE (allows conversion, default)"})
public static int multiblockEnergyType = 3;
public static boolean allowMBFE() {
return (multiblockEnergyType & 2) != 0;
}
public static boolean allowMBEU() {
return (multiblockEnergyType & 1) != 0 && IndustrialWires.hasIC2;
}
}
public static HVStuff hv;
public static class HVStuff {
@Comment({"The amount of EU a Jacobs Ladder uses per tick, sorted by size of the ladder"})
public static double[] jacobsUsageEU = {20, 50, 100};
public static double[] jacobsUsageWatt = {40, 300, 2000};
@Comment({"The damage dealt by a small Jacobs Ladder. Normal Ladders deal twice this damage, huge ones 3 times as much"})
public static float jacobsBaseDmg = 5;
@Comment({"The effect of standing somewhat close to a Marx generator discharge.",
"0: Tinnitus, 1: Nausea, 2: normal damage"})
public static int marxSoundDamage = 0;
@Comment({"Set to false to disable shaders. They are used for rendering the Marx generator and the Jacob's ladder."})
public static boolean enableShaders = true;
}
}
@SubscribeEvent
public static void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent ev) {
if (ev.getModID().equals(IndustrialWires.MODID)) {
ConfigManager.sync(IndustrialWires.MODID, Config.Type.INSTANCE);
}
}
}

View file

@ -0,0 +1,29 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires;
import net.minecraft.util.DamageSource;
public class IWDamageSources {
public static class MarxDamage extends DamageSource {
public MarxDamage() {
super("industrialwires.marx");
setDamageBypassesArmor();
}
}
public static final MarxDamage dmg_marx = new MarxDamage();
public static final DamageSource dmg_jacobs = new DamageSource("industrialwires.jacobs_ladder");
}

View file

@ -0,0 +1,66 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
public class IWPotions {
public static PotionTinnitus tinnitus;
public static void init() {
tinnitus = new PotionTinnitus();
}
static class PotionTinnitus extends Potion {
ResourceLocation tex = new ResourceLocation(IndustrialWires.MODID,"textures/gui/tinnitus.png");
protected PotionTinnitus() {
super(true, 0xffff0000);
setIconIndex(0, 0);
this.setRegistryName(new ResourceLocation(IndustrialWires.MODID, "tinnitus"));
ForgeRegistries.POTIONS.register(this);
this.setPotionName("potion." + IndustrialWires.MODID + "." + getRegistryName().getPath());
}
@Override
public boolean isReady(int duration, int amplifier) {
return true;
}
@Override
public void performEffect(@Nonnull EntityLivingBase affected, int amp) {
if (affected.getEntityWorld().isRemote) {
Minecraft mc = Minecraft.getMinecraft();
if (mc.player==affected) {
IndustrialWires.proxy.startTinnitus();
}
}
}
@Override
@SideOnly(Side.CLIENT)
public int getStatusIconIndex()
{
Minecraft.getMinecraft().getTextureManager().bindTexture(tex);
return super.getStatusIconIndex();
}
}
}

View file

@ -0,0 +1,70 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires;
import malte0811.industrialwires.hv.MarxOreHandler;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.storage.WorldSavedData;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import javax.annotation.Nonnull;
@Mod.EventBusSubscriber
public class IWSaveData extends WorldSavedData {
private final static String MARX_MOD = "marxOreModifier";
public static IWSaveData INSTANCE = new IWSaveData();
public IWSaveData() {
super(IndustrialWires.MODID);
}
public IWSaveData(String name) {
super(name);
}
@Override
public void readFromNBT(@Nonnull NBTTagCompound nbt) {
if (nbt.hasKey(MARX_MOD)) {
MarxOreHandler.modifier = nbt.getDouble(MARX_MOD);
} else {
MarxOreHandler.resetModifier();
}
}
@Nonnull
@Override
public NBTTagCompound writeToNBT(@Nonnull NBTTagCompound compound) {
compound.setDouble(MARX_MOD, MarxOreHandler.modifier);
return compound;
}
@SubscribeEvent
public static void onWorldLoad(WorldEvent.Load event) {
World w = event.getWorld();
if (!w.isRemote) {
INSTANCE = (IWSaveData) w.loadData(IWSaveData.class, IndustrialWires.MODID);
if (INSTANCE==null) {
INSTANCE = new IWSaveData();
MarxOreHandler.resetModifier();
w.setData(IndustrialWires.MODID, INSTANCE);
INSTANCE.setDirty(true);
}
}
}
}

View file

@ -0,0 +1,322 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires;
import blusunrize.immersiveengineering.ImmersiveEngineering;
import blusunrize.immersiveengineering.api.MultiblockHandler;
import blusunrize.immersiveengineering.api.energy.wires.WireApi;
import com.google.common.collect.ImmutableMap;
import malte0811.industrialwires.blocks.BlockIWBase;
import malte0811.industrialwires.blocks.TEDataFixer;
import malte0811.industrialwires.blocks.controlpanel.*;
import malte0811.industrialwires.blocks.converter.*;
import malte0811.industrialwires.blocks.hv.*;
import malte0811.industrialwires.blocks.wire.*;
import malte0811.industrialwires.compat.Compat;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.controlpanel.PanelUtils;
import malte0811.industrialwires.crafting.Recipes;
import malte0811.industrialwires.entities.EntityBrokenPart;
import malte0811.industrialwires.hv.MarxOreHandler;
import malte0811.industrialwires.hv.MultiblockMarx;
import malte0811.industrialwires.items.ItemIC2Coil;
import malte0811.industrialwires.items.ItemKey;
import malte0811.industrialwires.items.ItemPanelComponent;
import malte0811.industrialwires.mech_mb.EUCapability;
import malte0811.industrialwires.mech_mb.MechMBPart;
import malte0811.industrialwires.mech_mb.MultiblockMechMB;
import malte0811.industrialwires.network.MessageGUIInteract;
import malte0811.industrialwires.network.MessageItemSync;
import malte0811.industrialwires.network.MessagePanelInteract;
import malte0811.industrialwires.network.MessageTileSyncIW;
import malte0811.industrialwires.util.CommandIW;
import malte0811.industrialwires.util.MultiblockTemplateManual;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.datafix.FixTypes;
import net.minecraftforge.common.util.ModFixs;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import static malte0811.industrialwires.blocks.wire.BlockTypes_IC2_Connector.*;
import static malte0811.industrialwires.entities.EntityBrokenPart.MARKER_TEXTURE;
import static malte0811.industrialwires.entities.EntityBrokenPart.RES_LOC_SERIALIZER;
import static malte0811.industrialwires.mech_mb.MechMBPart.EXAMPLE_MECHMB_LOC;
import static malte0811.industrialwires.wires.MixedWireType.*;
@Mod(modid = IndustrialWires.MODID, version = IndustrialWires.VERSION, dependencies = "required-after:immersiveengineering@[0.12-86,);after:ic2;required-after:forge@[14.23.3.2694,)",
certificateFingerprint = "7e11c175d1e24007afec7498a1616bef0000027d",
updateJSON = "https://raw.githubusercontent.com/malte0811/IndustrialWires/MC1.12/changelog.json")
@Mod.EventBusSubscriber
public class IndustrialWires {
public static final String MODID = "industrialwires";
public static final String VERSION = "${version}";
public static final String MODNAME = "Industrial Wires";
public static final int DATAFIXER_VER = 1;
public static final SoundEvent TINNITUS = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "tinnitus"));
public static final SoundEvent LADDER_START = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "jacobs_ladder_start"));//~470 ms ~=9 ticks
public static final SoundEvent LADDER_MIDDLE = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "jacobs_ladder_middle"));
public static final SoundEvent LADDER_END = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "jacobs_ladder_end"));//~210 ms ~= 4 ticks
public static final SoundEvent MARX_BANG = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "marx_bang"));
public static final SoundEvent MARX_POP = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "marx_pop"));
public static final SoundEvent TURN_FAST = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "mech_mb_fast"));
public static final SoundEvent TURN_SLOW = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "mech_mb_slow"));
public static final SoundEvent MMB_BREAKING = createSoundEvent(new ResourceLocation(IndustrialWires.MODID, "mech_mb_breaking"));
private static final SoundEvent createSoundEvent(ResourceLocation loc) {
return new SoundEvent(loc).setRegistryName(loc);
}
public static final List<BlockIWBase> blocks = new ArrayList<>();
public static final List<Item> items = new ArrayList<>();
@GameRegistry.ObjectHolder(MODID+":"+BlockIC2Connector.NAME)
public static BlockIC2Connector ic2conn = null;
@GameRegistry.ObjectHolder(MODID+":"+BlockMechanicalConverter.NAME)
public static BlockMechanicalConverter mechConv = null;
@GameRegistry.ObjectHolder(MODID+":"+BlockJacobsLadder.NAME)
public static BlockJacobsLadder jacobsLadder = null;
@GameRegistry.ObjectHolder(MODID+":"+BlockPanel.NAME)
public static BlockPanel panel = null;
@GameRegistry.ObjectHolder(MODID+":"+BlockHVMultiblocks.NAME)
public static BlockHVMultiblocks hvMultiblocks = null;
@GameRegistry.ObjectHolder(MODID+":"+BlockMechanicalMB.NAME)
public static BlockMechanicalMB mechanicalMB = null;
@GameRegistry.ObjectHolder(MODID+":"+ BlockGeneralHV.NAME)
public static BlockGeneralHV generalHV = null;
@GameRegistry.ObjectHolder(MODID+":"+ItemIC2Coil.NAME)
public static ItemIC2Coil coil = null;
@GameRegistry.ObjectHolder(MODID+":"+ItemPanelComponent.NAME)
public static ItemPanelComponent panelComponent = null;
@GameRegistry.ObjectHolder(MODID+":"+ItemKey.ITEM_NAME)
public static ItemKey key = null;
@GameRegistry.ObjectHolder("ic2:te")
public static Block ic2TeBlock = null;
public static final SimpleNetworkWrapper packetHandler = NetworkRegistry.INSTANCE.newSimpleChannel(MODID);
public static Logger logger;
@Mod.Instance(MODID)
public static IndustrialWires instance = new IndustrialWires();
public static CreativeTabs creativeTab = new CreativeTabs(MODID) {
@Override
public ItemStack createIcon() {
if (coil!=null) {
return new ItemStack(coil, 1, 2);
} else {
return new ItemStack(panel, 1, 3);
}
}
};
@SidedProxy(clientSide = "malte0811.industrialwires.client.ClientProxy", serverSide = "malte0811.industrialwires.CommonProxy")
public static CommonProxy proxy;
public static boolean hasIC2;
public static boolean hasTechReborn;
public static boolean isOldIE;
@EventHandler
public void preInit(FMLPreInitializationEvent e) {
hasIC2 = Loader.isModLoaded("ic2");
hasTechReborn = Loader.isModLoaded("techreborn");
{
double ieThreshold = 12.74275;
String ieVer = Loader.instance().getIndexedModList().get(ImmersiveEngineering.MODID).getDisplayVersion();
int firstDash = ieVer.indexOf('-');
String end = ieVer.substring(firstDash + 1);
String start = ieVer.substring(0, firstDash);
end = end.replaceAll("[^0-9]", "");
start = start.replaceAll("[^0-9]", "");
double ieVerDouble = Double.parseDouble(start + "." + end);
isOldIE = ieVerDouble < ieThreshold;
}
logger = e.getModLog();
new IWConfig();
GameRegistry.registerTileEntity(TileEntityIC2ConnectorTin.class, new ResourceLocation(MODID, "ic2ConnectorTin"));
GameRegistry.registerTileEntity(TileEntityIC2ConnectorCopper.class, new ResourceLocation(MODID, "ic2ConnectorCopper"));
GameRegistry.registerTileEntity(TileEntityIC2ConnectorGold.class, new ResourceLocation(MODID, "ic2ConnectorGold"));
GameRegistry.registerTileEntity(TileEntityIC2ConnectorHV.class, new ResourceLocation(MODID, "ic2ConnectorHV"));
GameRegistry.registerTileEntity(TileEntityIC2ConnectorGlass.class, new ResourceLocation(MODID, "ic2ConnectorGlass"));
if (hasIC2 && IWConfig.enableConversion) {
GameRegistry.registerTileEntity(TileEntityIEMotor.class, new ResourceLocation(MODID, "ieMotor"));
GameRegistry.registerTileEntity(TileEntityMechICtoIE.class, new ResourceLocation(MODID, "mechIcToIe"));
GameRegistry.registerTileEntity(TileEntityMechIEtoIC.class, new ResourceLocation(MODID, "mechIeToIc"));
}
GameRegistry.registerTileEntity(TileEntityMechMB.class, new ResourceLocation(MODID, "mechMB"));
GameRegistry.registerTileEntity(TileEntityJacobsLadder.class, new ResourceLocation(MODID, "jacobsLadder"));
GameRegistry.registerTileEntity(TileEntityMarx.class, new ResourceLocation(MODID, "marx_generator"));
GameRegistry.registerTileEntity(TileEntityPanel.class, new ResourceLocation(MODID, "control_panel"));
GameRegistry.registerTileEntity(TileEntityGeneralCP.class, new ResourceLocation(MODID, "gcp"));
GameRegistry.registerTileEntity(TileEntityRSPanelIE.class, new ResourceLocation(MODID, "control_panel_rs"));
GameRegistry.registerTileEntity(TileEntityRSPanelOthers.class, new ResourceLocation(MODID, "control_panel_rs_compat"));
GameRegistry.registerTileEntity(TileEntityPanelCreator.class, new ResourceLocation(MODID, "panel_creator"));
GameRegistry.registerTileEntity(TileEntityUnfinishedPanel.class, new ResourceLocation(MODID, "unfinished_panel"));
GameRegistry.registerTileEntity(TileEntityComponentPanel.class, new ResourceLocation(MODID, "single_component_panel"));
GameRegistry.registerTileEntity(TileEntityDischargeMeter.class, new ResourceLocation(MODID, "discharge_meter"));
DataSerializers.registerSerializer(RES_LOC_SERIALIZER);
MARKER_TEXTURE = EntityDataManager.createKey(EntityBrokenPart.class, RES_LOC_SERIALIZER);
EntityRegistry.registerModEntity(new ResourceLocation(MODID, "broken_part"), EntityBrokenPart.class,
"broken_part", 0, this, 64, 5, true);
proxy.preInit();
Compat.preInit();
MarxOreHandler.preInit();
// This has to run before textures are stitched, i.e. in preInit
MechMBPart.preInit();
}
@SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event) {
if (IWConfig.enableConversion&&hasIC2) {
event.getRegistry().register(new BlockMechanicalConverter());
}
event.getRegistry().register(new BlockIC2Connector());
event.getRegistry().register(new BlockJacobsLadder());
event.getRegistry().register(new BlockPanel());
event.getRegistry().register(new BlockHVMultiblocks());
event.getRegistry().register(new BlockMechanicalMB());
event.getRegistry().register(new BlockGeneralHV());
}
@SubscribeEvent
public static void registerItems(RegistryEvent.Register<Item> event) {
for (BlockIWBase b:blocks) {
event.getRegistry().register(b.createItemBlock());
}
event.getRegistry().register(new ItemIC2Coil());
event.getRegistry().register(new ItemPanelComponent());
event.getRegistry().register(new ItemKey());
}
@SubscribeEvent
public static void registerSounds(RegistryEvent.Register<SoundEvent> event) {
event.getRegistry().register(TINNITUS);
event.getRegistry().register(LADDER_START);
event.getRegistry().register(LADDER_MIDDLE);
event.getRegistry().register(LADDER_END);
event.getRegistry().register(MARX_BANG);
event.getRegistry().register(MARX_POP);
event.getRegistry().register(TURN_FAST);
event.getRegistry().register(TURN_SLOW);
event.getRegistry().register(MMB_BREAKING);
}
@SubscribeEvent
public static void registerRecipes(RegistryEvent.Register<IRecipe> event) {
Recipes.addRecipes(event.getRegistry());
}
@EventHandler
public void init(FMLInitializationEvent e) {
MultiblockMarx.INSTANCE = new MultiblockMarx();
MultiblockHandler.registerMultiblock(MultiblockMarx.INSTANCE);
MultiblockMechMB.INSTANCE = new MultiblockMechMB();
MultiblockHandler.registerMultiblock(MultiblockMechMB.INSTANCE);
MultiblockHandler.registerMultiblock(new MultiblockTemplateManual(EXAMPLE_MECHMB_LOC));
packetHandler.registerMessage(MessageTileSyncIW.HandlerClient.class, MessageTileSyncIW.class, 0, Side.CLIENT);
packetHandler.registerMessage(MessagePanelInteract.HandlerServer.class, MessagePanelInteract.class, 1, Side.SERVER);
packetHandler.registerMessage(MessageGUIInteract.HandlerServer.class, MessageGUIInteract.class, 2, Side.SERVER);
packetHandler.registerMessage(MessageItemSync.HandlerServer.class, MessageItemSync.class, 3, Side.SERVER);
if (hasIC2) {
ResourceLocation tex = new ResourceLocation(MODID, "blocks/ic2_conn_tin");
float[] uvs = {3, 4, 11, 12};
WireApi.registerFeedthroughForWiretype(TIN, new ResourceLocation("immersiveengineering:block/connector/connector_lv.obj"),
ImmutableMap.of("#immersiveengineering:blocks/connector_connector_lv",
IndustrialWires.MODID + ":blocks/ic2_conn_tin"), tex, uvs, .5, .5,
ic2conn.getDefaultState().withProperty(BlockIC2Connector.TYPE, TIN_CONN),
1/64F, TIN.getTransferRate(), f->(float)Math.ceil(f));
WireApi.registerFeedthroughForWiretype(COPPER_IC2, new ResourceLocation("immersiveengineering:block/connector/connector_lv.obj"),
ImmutableMap.of("#immersiveengineering:blocks/connector_connector_lv",
IndustrialWires.MODID + ":blocks/ic2_conn_copper"), tex, uvs, .5, .5,
ic2conn.getDefaultState().withProperty(BlockIC2Connector.TYPE, COPPER_CONN),
1/64F, COPPER_IC2.getTransferRate(), f->(float)Math.ceil(f));
WireApi.registerFeedthroughForWiretype(GOLD, new ResourceLocation("immersiveengineering:block/connector/connector_mv.obj"),
ImmutableMap.of("#immersiveengineering:blocks/connector_connector_mv",
IndustrialWires.MODID + ":blocks/ic2_conn_gold"), tex, uvs, .5625, .5625,
ic2conn.getDefaultState().withProperty(BlockIC2Connector.TYPE, GOLD_CONN),
1/64F, GOLD.getTransferRate(), f->(float)Math.ceil(f));
WireApi.registerFeedthroughForWiretype(HV, new ResourceLocation("immersiveengineering:block/connector/connector_hv.obj"),
ImmutableMap.of("#immersiveengineering:blocks/connector_connector_hv",
IndustrialWires.MODID + ":blocks/ic2_conn_hv"), tex, uvs, .75, .75,
ic2conn.getDefaultState().withProperty(BlockIC2Connector.TYPE, HV_CONN),
1/64F, HV.getTransferRate(), f->(float)Math.ceil(f));
WireApi.registerFeedthroughForWiretype(GLASS, new ResourceLocation("immersiveengineering:block/connector/connector_hv.obj"),
ImmutableMap.of("#immersiveengineering:blocks/connector_connector_hv",
IndustrialWires.MODID + ":blocks/ic2_conn_glass"), tex, uvs, .75, .75,
ic2conn.getDefaultState().withProperty(BlockIC2Connector.TYPE, GLASS_CONN),
1/64F, GLASS.getTransferRate(), f->(float)Math.ceil(f));
}
NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
IWPotions.init();
Compat.init();
MarxOreHandler.init();
PanelComponent.init();
MechMBPart.init();
if (hasIC2) {
EUCapability.register();
}
ModFixs fixer = FMLCommonHandler.instance().getDataFixer().init(MODID, DATAFIXER_VER);
fixer.registerFix(FixTypes.BLOCK_ENTITY, new TEDataFixer());
}
@EventHandler
public void postInit(FMLPostInitializationEvent e) {
PanelUtils.PANEL_ITEM = Item.getItemFromBlock(panel);
proxy.postInit();
}
@Mod.EventHandler
public void serverStarting(FMLServerStartingEvent event) {
event.registerServerCommand(new CommandIW());
}
}

View file

@ -1,52 +1,51 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import blusunrize.immersiveengineering.api.IEProperties;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IPlayerInteraction;
import blusunrize.immersiveengineering.common.util.Utils;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.util.MiscUtils;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.util.MiscUtils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.fml.common.registry.GameRegistry;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public abstract class BlockIWBase extends Block {
@ -56,13 +55,13 @@ public abstract class BlockIWBase extends Block {
super(mat);
setHardness(3.0F);
setResistance(15.0F);
GameRegistry.register(this, new ResourceLocation(IndustrialWires.MODID, name));
GameRegistry.register(createItemBlock(), new ResourceLocation(IndustrialWires.MODID, name));
setUnlocalizedName(IndustrialWires.MODID + "." + name);
setTranslationKey(IndustrialWires.MODID + "." + name);
setRegistryName(IndustrialWires.MODID, name);
setCreativeTab(IndustrialWires.creativeTab);
IndustrialWires.blocks.add(this);
}
protected ItemBlock createItemBlock() {
public ItemBlock createItemBlock() {
return new ItemBlockIW(this);
}
@ -143,6 +142,15 @@ public abstract class BlockIWBase extends Block {
return super.getBoundingBox(state, source, pos);
}
@Override
public void addCollisionBoxToList(IBlockState state, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull AxisAlignedBB entityBox,
@Nonnull List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) {
AxisAlignedBB aabb = getBoundingBox(state, worldIn, pos).offset(pos);
if (entityBox.intersects(aabb)) {
collidingBoxes.add(aabb);
}
}
//mostly copied from IE
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player,
@ -171,8 +179,9 @@ public abstract class BlockIWBase extends Block {
}
return true;
}
} else if (te instanceof IEBlockInterfaces.IPlayerInteraction) {
if (((IEBlockInterfaces.IPlayerInteraction) te).interact(side, player, hand, heldItem, hitX, hitY, hitZ)) {
}
if (te instanceof IPlayerInteraction) {
if (((IPlayerInteraction) te).interact(side, player, hand, heldItem, hitX, hitY, hitZ)) {
return true;
}
}
@ -212,5 +221,34 @@ public abstract class BlockIWBase extends Block {
return getMetaFromState(state);
}
@Override
public int getStrongPower(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof IEBlockInterfaces.IRedstoneOutput) {
return ((IEBlockInterfaces.IRedstoneOutput) te).getStrongRSOutput(state, side);
}
return 0;
}
@Override
public int getWeakPower(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof IEBlockInterfaces.IRedstoneOutput) {
return ((IEBlockInterfaces.IRedstoneOutput) te).getWeakRSOutput(state, side);
}
return 0;
}
@Override
public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, @Nullable EnumFacing side) {
if (side!=null) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof IEBlockInterfaces.IRedstoneOutput) {
return ((IEBlockInterfaces.IRedstoneOutput) te).canConnectRedstone(state, side);
}
}
return false;
}
protected abstract IProperty[] getProperties();
}

View file

@ -0,0 +1,78 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
public abstract class BlockIWMultiblock extends BlockIWBase {
public BlockIWMultiblock(Material mat, String name) {
super(mat, name);
}
@Override
public void breakBlock(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState state) {
TileEntity te = world.getTileEntity(pos);
if(te instanceof TileEntityIWMultiblock) {
((TileEntityIWMultiblock)te).disassemble();
}
super.breakBlock(world, pos, state);
}
@Override
public void getDrops(@Nonnull NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, @Nonnull IBlockState state, int fortune) {
//NOP
}
@Override
public boolean isTopSolid(IBlockState state) {
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
@Override
public boolean isFullBlock(IBlockState state) {
return false;
}
@Override
public boolean isFullCube(IBlockState state) {
return false;
}
@Nonnull
@Override
public ItemStack getPickBlock(@Nonnull IBlockState state, RayTraceResult target, @Nonnull World world, @Nonnull BlockPos pos, EntityPlayer player) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof TileEntityIWMultiblock) {
return ((TileEntityIWMultiblock) te).getOriginalItem();
}
return ItemStack.EMPTY;
}
}

View file

@ -1,21 +1,18 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import blusunrize.immersiveengineering.api.energy.immersiveflux.IFluxConnection;
import blusunrize.immersiveengineering.api.energy.immersiveflux.IFluxProvider;

View file

@ -0,0 +1,41 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces;
import blusunrize.immersiveengineering.common.util.chickenbones.Matrix4;
import malte0811.industrialwires.util.MiscUtils;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
public interface IBlockBoundsIW {
AxisAlignedBB getBoundingBox();
interface IBlockBoundsDirectional extends IBlockBoundsIW, IEBlockInterfaces.IDirectionalTile {
@Override
default AxisAlignedBB getBoundingBox() {
EnumFacing dir = getFacing();
Matrix4 mat = new Matrix4();
mat.translate(.5, 0, .5);
mat.rotate((-dir.getHorizontalAngle()+180)*Math.PI/180, 0, 1, 0);
mat.translate(-.5, 0, -.5);
return MiscUtils.apply(mat, getBoundingBoxNoRot());
}
AxisAlignedBB getBoundingBoxNoRot();
}
}

View file

@ -1,29 +1,31 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IGeneralMultiblock;
import net.minecraft.block.state.IBlockState;
public interface IHasDummyBlocksIW {
public interface IHasDummyBlocksIW extends IGeneralMultiblock {
void placeDummies(IBlockState state);
void breakDummies();
boolean isDummy();
default boolean isLogicDummy() {
return isDummy();
}
}

View file

@ -1,21 +1,18 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
public interface IMetaEnum {
Object[] getValues();

View file

@ -1,22 +1,19 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;

View file

@ -1,22 +1,19 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;

View file

@ -1,25 +1,25 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public interface ISyncReceiver {
@SideOnly(Side.CLIENT)
void onSync(NBTTagCompound nbt);
}

View file

@ -0,0 +1,62 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks;
import malte0811.industrialwires.util.MBSideConfig;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.util.IStringSerializable;
import net.minecraftforge.common.property.IUnlistedProperty;
public final class IWProperties {
private IWProperties() {}
public static final PropertyEnum<MarxType> MARX_TYPE = PropertyEnum.create("marx_type", MarxType.class);
public static final IUnlistedProperty<MBSideConfig> MB_SIDES = new MBSideConfigProperty();
public enum MarxType implements IStringSerializable {
NO_MODEL,
BOTTOM,
STAGE,
TOP,
CONNECTOR;
@Override
public String getName() {
return name().toLowerCase();
}
}
public static class MBSideConfigProperty implements IUnlistedProperty<MBSideConfig> {
@Override
public String getName() {
return "mb_side";
}
@Override
public boolean isValid(MBSideConfig value) {
return value!=null;
}
@Override
public Class<MBSideConfig> getType() {
return MBSideConfig.class;
}
@Override
public String valueToString(MBSideConfig value) {
return value.toString();
}
}
}

View file

@ -1,23 +1,21 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces;
import malte0811.industrialwires.IndustrialWires;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
@ -41,16 +39,18 @@ public class ItemBlockIW extends ItemBlock {
values = null;
}
hasSubtypes = true;
setRegistryName(b.getRegistryName());
setCreativeTab(IndustrialWires.creativeTab);
}
@Nonnull
@Override
public String getUnlocalizedName(ItemStack stack) {
public String getTranslationKey(ItemStack stack) {
int meta = stack.getMetadata();
if (values != null) {
return block.getUnlocalizedName() + "." + values[meta].toString().toLowerCase();
return block.getTranslationKey() + "." + values[meta].toString().toLowerCase();
} else {
return block.getUnlocalizedName();
return block.getTranslationKey();
}
}

View file

@ -0,0 +1,41 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks;
import malte0811.industrialwires.IndustrialWires;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.datafix.IFixableData;
import javax.annotation.Nonnull;
public class TEDataFixer implements IFixableData {
private static final String PREFIX = "minecraft:"+IndustrialWires.MODID;
private static final int PREFIX_LEN = PREFIX.length();
@Nonnull
@Override
public NBTTagCompound fixTagCompound(@Nonnull NBTTagCompound compound) {
String id = compound.getString("id");
if (id.startsWith(PREFIX)) {
compound.setString("id", IndustrialWires.MODID+":"+id.substring(PREFIX_LEN));
}
return compound;
}
@Override
public int getFixVersion() {
return 0;
}
}

View file

@ -1,33 +1,32 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks;
import com.google.common.collect.ImmutableSet;
import malte0811.industrialwires.IndustrialWires;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
public abstract class TileEntityIWBase extends TileEntity {
protected static final String ENERGY_TAG = "energy";
protected static final String BUFFER_TAG = "buffer";
protected static final String DIR_TAG = "dir";
@Nonnull
@Override
@ -57,11 +56,36 @@ public abstract class TileEntityIWBase extends TileEntity {
}
@Override
@SideOnly(Side.CLIENT)
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
super.onDataPacket(net, pkt);
readNBT(pkt.getNbtCompound(), true);
}
public void triggerRenderUpdate() {
if (world!=null) {
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state, state, 3);
world.addBlockEvent(pos, state.getBlock(), 255, 0);
}
}
@Override
public void invalidate() {
super.invalidate();
if (world.isRemote) {
IndustrialWires.proxy.stopAllSoundsExcept(pos, ImmutableSet.of());
}
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
if (world.isRemote) {
IndustrialWires.proxy.stopAllSoundsExcept(pos, ImmutableSet.of());
}
}
public abstract void writeNBT(NBTTagCompound out, boolean updatePacket);
public abstract void readNBT(NBTTagCompound in, boolean updatePacket);

View file

@ -0,0 +1,176 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IGeneralMultiblock;
import malte0811.industrialwires.util.MiscUtils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.BiConsumer;
public abstract class TileEntityIWMultiblock extends TileEntityIWBase implements IGeneralMultiblock,
IDirectionalTile {
protected final static String OFFSET = "offset";
protected final static String FORMED = "formed";
protected final static String MIRRORED = "mirrored";
protected final static String FACING = "facing";
//HFR
protected Vec3i size;
public Vec3i offset = new Vec3i(0, 1, 0);
public boolean formed;
public boolean mirrored;
public long onlyLocalDissassembly;
public EnumFacing facing = EnumFacing.NORTH;
@Nonnull
protected abstract BlockPos getOrigin();
public abstract IBlockState getOriginalBlock();
public ItemStack getOriginalItem() {
IBlockState state = getOriginalBlock();
return new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state));
}
public BiConsumer<World, BlockPos> getOriginalBlockPlacer() {
return (w, p)->w.setBlockState(p, getOriginalBlock());
}
@Nullable
public <T extends TileEntityIWMultiblock> T master(T here) {
if (!isLogicDummy()) {
return here;
}
TileEntity m = world.getTileEntity(pos.subtract(offset));
if (m!=null&&m.getClass().equals(this.getClass())) {
return (T) m;
}
return null;
}
@Override
public boolean isLogicDummy() {
return offset.getX()!=0||offset.getY()!=0||offset.getZ()!=0;
}
@Nonnull
public <T extends TileEntityIWMultiblock> T masterOr(T here, @Nonnull T def) {
T master = master(here);
return master!=null?master:def;
}
public void disassemble() {
if (formed && !world.isRemote) {
BlockPos startPos = getOrigin();
BlockPos masterPos = getPos().subtract(offset);
long time = world.getTotalWorldTime();
Vec3i size = getSize();
for (int up = 0; up < size.getX(); up++) {
for (int forward = 0; forward < size.getY(); forward++) {
for (int right = 0; right < size.getZ(); right++) {
BlockPos pos = MiscUtils.offset(startPos, facing, mirrored, right, forward, up);
TileEntity te = world.getTileEntity(pos);
if (te instanceof TileEntityIWMultiblock) {
TileEntityIWMultiblock part = (TileEntityIWMultiblock) te;
Vec3i diff = pos.subtract(masterPos);
if (part.offset.equals(diff) && time != part.onlyLocalDissassembly) {
part.formed = false;
if (!pos.equals(this.pos)) {
part.getOriginalBlockPlacer().accept(world, pos);
} else if (part.getOriginalBlock()!=null) {
ItemStack drop = getOriginalItem();
world.spawnEntity(new EntityItem(world, pos.getX()+.5,pos.getY()+.5,pos.getZ()+.5, drop));
}
}
}
}
}
}
}
}
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
out.setInteger(FACING, facing.getHorizontalIndex());
out.setIntArray(OFFSET, new int[]{offset.getX(), offset.getY(), offset.getZ()});
out.setBoolean(MIRRORED, mirrored);
out.setBoolean(FORMED, formed);
}
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
formed = in.getBoolean(FORMED);
mirrored = in.getBoolean(MIRRORED);
int[] offset = in.getIntArray(OFFSET);
this.offset = new Vec3i(offset[0], offset[1], offset[2]);
facing = EnumFacing.byHorizontalIndex(in.getInteger(FACING));
}
public Vec3i getSize() {
return size;
}
public int getRight() {
return dot(offset, facing.rotateY().getDirectionVec())*(mirrored?-1:1);
}
public int getForward() {
return dot(offset, facing.getDirectionVec());
}
protected int dot(Vec3i a, Vec3i b) {
return a.getX()*b.getX()+a.getY()*b.getY()+a.getZ()*b.getZ();
}
@Nonnull
@Override
public EnumFacing getFacing() {
return facing;
}
@Override
public void setFacing(@Nonnull EnumFacing facing) {
this.facing = facing;
}
@Override
public int getFacingLimitation() {
return 2;
}
@Override
public boolean mirrorFacingOnPlacement(@Nonnull EntityLivingBase placer) {
return false;
}
@Override
public boolean canHammerRotate(@Nonnull EnumFacing side, float hitX, float hitY, float hitZ, @Nonnull EntityLivingBase entity) {
return false;
}
@Override
public boolean canRotate(@Nonnull EnumFacing axis) {
return false;
}
}

View file

@ -1,30 +1,28 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.controlpanel;
package malte0811.industrialwires.blocks.controlpanel;
import blusunrize.immersiveengineering.api.IEProperties;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.BlockIWBase;
import malte0811.industrialWires.blocks.IMetaEnum;
import malte0811.industrialWires.controlpanel.PanelComponent;
import malte0811.industrialWires.controlpanel.PanelUtils;
import malte0811.industrialWires.controlpanel.PropertyComponents;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.BlockIWBase;
import malte0811.industrialwires.blocks.IMetaEnum;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.controlpanel.PropertyComponents;
import malte0811.industrialwires.util.MiscUtils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
@ -32,7 +30,6 @@ import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
@ -49,18 +46,19 @@ import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import javax.annotation.Nonnull;
import java.util.List;
import javax.annotation.Nullable;
public class BlockPanel extends BlockIWBase implements IMetaEnum {
public static final PropertyEnum<BlockTypes_Panel> type = PropertyEnum.create("type", BlockTypes_Panel.class);
public static final String NAME = "control_panel";
public BlockPanel() {
super(Material.IRON, "control_panel");
super(Material.IRON, NAME);
lightOpacity = 0;
}
@Override
protected ItemBlock createItemBlock() {
public ItemBlock createItemBlock() {
return new ItemBlockPanel(this);
}
@ -68,6 +66,7 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) {
switch (state.getValue(type)) {
case TOP:
case SINGLE_COMP:
return layer == BlockRenderLayer.CUTOUT;
case RS_WIRE:
return layer == BlockRenderLayer.TRANSLUCENT || layer == BlockRenderLayer.SOLID;
@ -79,16 +78,22 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
@Override
public TileEntity createTileEntity(@Nonnull World world, @Nonnull IBlockState state) {
switch (state.getValue(type)) {
case TOP:
return new TileEntityPanel();
case RS_WIRE:
return new TileEntityRSPanelConn();
case CREATOR:
return new TileEntityPanelCreator();
case TOP:
return new TileEntityPanel();
case RS_WIRE:
return new TileEntityRSPanelIE();
case CREATOR:
return new TileEntityPanelCreator();
case UNFINISHED:
return new TileEntityUnfinishedPanel();
default:
return null;
case SINGLE_COMP:
return new TileEntityComponentPanel();
case DUMMY:
return new TileEntityGeneralCP();
case OTHER_RS_WIRES:
return new TileEntityRSPanelOthers();
default:
return null;
}
}
@ -116,10 +121,11 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
public IBlockState getActualState(@Nonnull IBlockState state, IBlockAccess worldIn, BlockPos pos) {
state = super.getActualState(state, worldIn, pos);
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof TileEntityPanel) {
if (te instanceof TileEntityComponentPanel) {
state.withProperty(type, BlockTypes_Panel.SINGLE_COMP);
} else if (te instanceof TileEntityPanel) {
state.withProperty(type, BlockTypes_Panel.TOP);
}
if (te instanceof TileEntityRSPanelConn) {
} else if (te instanceof TileEntityRSPanelIE) {
state.withProperty(type, BlockTypes_Panel.RS_WIRE);
}
return state;
@ -143,6 +149,7 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
return state.getValue(type).ordinal();
}
@Nonnull
@Override
public IBlockState getStateFromMeta(int meta) {
return super.getStateFromMeta(meta).withProperty(type, BlockTypes_Panel.values()[meta]);
@ -154,9 +161,12 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
}
@Override
public void getSubBlocks(@Nonnull Item itemIn, CreativeTabs tab, NonNullList<ItemStack> list) {
for (int i = 0; i < BlockTypes_Panel.values().length; i++) {
list.add(new ItemStack(itemIn, 1, i));
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
BlockTypes_Panel[] values = BlockTypes_Panel.values();
for (int i = 0; i < values.length; i++) {
if (values[i].showInCreative()) {
list.add(new ItemStack(this, 1, i));
}
}
}
@ -184,7 +194,7 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!super.onBlockActivated(world, pos, state, player, hand, side, hitX, hitY, hitZ) && hand == EnumHand.MAIN_HAND) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof TileEntityRSPanelConn) {
if (te instanceof TileEntityRSPanel) {
if (!world.isRemote) {
player.openGui(IndustrialWires.instance, 0, te.getWorld(), te.getPos().getX(), te.getPos().getY(), te.getPos().getZ());
}
@ -198,7 +208,7 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
}
return false;
}
return state.getValue(type) == BlockTypes_Panel.TOP;
return state.getValue(type) == BlockTypes_Panel.TOP||state.getValue(type) == BlockTypes_Panel.SINGLE_COMP;
}
@Override
@ -216,36 +226,53 @@ public class BlockPanel extends BlockIWBase implements IMetaEnum {
super.harvestBlock(worldIn, player, pos, state, te, stack);
if (te instanceof TileEntityPanel) {
for (PanelComponent pc:((TileEntityPanel) te).getComponents()) {
pc.dropItems((TileEntityPanel)te);
pc.dropItems();
}
}
}
@Override
public void breakBlock(@Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state) {
super.breakBlock(worldIn, pos, state);
//break connections
List<BlockPos> panels = PanelUtils.discoverPanelParts(worldIn, pos, 11 * 11 * 11);
for (BlockPos p : panels) {
if (!p.equals(pos)) {
TileEntity panelPart = worldIn.getTileEntity(p);
if (panelPart instanceof TileEntityPanel) {
((TileEntityPanel) panelPart).removeAllRSCons();
}
}
}
public boolean canProvidePower(IBlockState state) {
return state.getValue(type)==BlockTypes_Panel.SINGLE_COMP;
}
@Override
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) {
super.onBlockAdded(worldIn, pos, state);
List<BlockPos> panels = PanelUtils.discoverPanelParts(worldIn, pos, 11 * 11 * 11);
for (BlockPos p : panels) {
if (!p.equals(pos)) {
TileEntity panelPart = worldIn.getTileEntity(p);
if (panelPart instanceof TileEntityPanel) {
((TileEntityPanel) panelPart).firstTick = true;
}
public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, @Nullable EnumFacing side) {
return state.getValue(type)==BlockTypes_Panel.SINGLE_COMP;
}
@Override
public int getStrongPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) {
if (blockState.getValue(type)==BlockTypes_Panel.SINGLE_COMP) {
TileEntity te = blockAccess.getTileEntity(pos);
if (te instanceof TileEntityComponentPanel&&side==((TileEntityComponentPanel) te).getComponents().getTop()) {
return ((TileEntityComponentPanel)te).getRSOutput();
}
}
return 0;
}
@Override
public int getWeakPower(IBlockState state, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) {
if (state.getValue(type)==BlockTypes_Panel.SINGLE_COMP) {
TileEntity te = blockAccess.getTileEntity(pos);
if (te instanceof TileEntityComponentPanel) {
return ((TileEntityComponentPanel)te).getRSOutput();
}
}
return 0;
}
@Override
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) {
super.neighborChanged(state, worldIn, pos, blockIn, fromPos);
if (!worldIn.isRemote) {
TileEntityGeneralCP panel = MiscUtils.getLoadedTE(worldIn, pos, TileEntityGeneralCP.class);
if (panel instanceof TileEntityComponentPanel) {
((TileEntityComponentPanel) panel).updateRSInput();
} else if (panel instanceof TileEntityRSPanelOthers) {
((TileEntityRSPanelOthers)panel).updateInput();
}
}
}

View file

@ -1,23 +1,21 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.controlpanel;
package malte0811.industrialwires.blocks.controlpanel;
import malte0811.industrialwires.compat.Compat;
import net.minecraft.util.IStringSerializable;
import java.util.Locale;
@ -27,14 +25,19 @@ public enum BlockTypes_Panel implements IStringSerializable {
RS_WIRE,
DUMMY,
CREATOR,
UNFINISHED;
UNFINISHED,
SINGLE_COMP,
OTHER_RS_WIRES;
@Override
public String getName() {
return toString().toLowerCase(Locale.ENGLISH);
}
public boolean isPanelConnector() {
return this != CREATOR && this != UNFINISHED;
public boolean showInCreative() {
if (this==OTHER_RS_WIRES) {
return Compat.enableOtherRS;
}
return this != SINGLE_COMP;
}
}

View file

@ -1,34 +1,32 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.controlpanel;
package malte0811.industrialwires.blocks.controlpanel;
import blusunrize.immersiveengineering.api.tool.IConfigurableTool;
import malte0811.industrialWires.blocks.ItemBlockIW;
import malte0811.industrialwires.blocks.ItemBlockIW;
import net.minecraft.block.Block;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.MathHelper;
import static malte0811.industrialwires.util.NBTKeys.ANGLE;
import static malte0811.industrialwires.util.NBTKeys.HEIGHT;
public class ItemBlockPanel extends ItemBlockIW implements IConfigurableTool {
private static final String HEIGHT = "height";
private static final String ANGLE = "angle";
public ItemBlockPanel(Block b) {
super(b);

View file

@ -0,0 +1,128 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.controlpanel;
import malte0811.industrialwires.controlpanel.ControlPanelNetwork;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.controlpanel.PropertyComponents;
import malte0811.industrialwires.items.ItemPanelComponent;
import net.minecraft.block.BlockRedstoneWire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import javax.annotation.Nonnull;
import static malte0811.industrialwires.util.MiscUtils.apply;
public class TileEntityComponentPanel extends TileEntityPanel {
private byte rsOut = 0;
public TileEntityComponentPanel() {
components = new PropertyComponents.AABBPanelProperties();
panelNetwork = new SingleCompNetwork();
}
@Override
public void onLoad() {
super.onLoad();
if (!world.isRemote) {
updateRSInput();
}
}
public void updateRSInput() {
int value = world.getRedstonePowerFromNeighbors(pos);
if (value == 0) {
for (EnumFacing f : EnumFacing.HORIZONTALS) {
IBlockState state = world.getBlockState(pos.offset(f));
if (state.getBlock() == Blocks.REDSTONE_WIRE && state.getValue(BlockRedstoneWire.POWER) > value)
value = state.getValue(BlockRedstoneWire.POWER);
}
}
((SingleCompNetwork)panelNetwork).setGlobalInput((byte) value);
}
public void markBlockForUpdate(BlockPos pos)
{
if (world!=null) {
IBlockState state = world.getBlockState(getBlockPos());
world.notifyBlockUpdate(pos, state, state, 3);
world.notifyNeighborsOfStateChange(pos, state.getBlock(), true);
}
}
@Override
public AxisAlignedBB getBoundingBox() {
if (defAABB == null) {
AxisAlignedBB base = ((PropertyComponents.AABBPanelProperties)components).getPanelBoundingBox();
defAABB = apply(components.getPanelBaseTransform(), base.setMaxY(components.getMaxHeight()));
}
return defAABB;
}
public int getRSOutput() {
return rsOut;
}
@Nonnull
@Override
public ItemStack getTileDrop(EntityPlayer player, @Nonnull IBlockState state) {
if (components.size()<1) {
return ItemStack.EMPTY;
}
return ItemPanelComponent.stackFromComponent(components.get(0));
}
@Override
public boolean canJoinNetwork() {
return false;
}
public void setComponent(PanelComponent comp) {
components.clear();
components.add(comp);
comp.setPanel(this);
comp.setNetwork(panelNetwork);
}
private class SingleCompNetwork extends ControlPanelNetwork {
@Override
public void setOutputs(IOwner owner, RSChannelState... out) {
super.setOutputs(owner, out);
byte oldOut = rsOut;
rsOut = 0;
for (OutputValue s:activeOutputs.values()) {
rsOut = (byte) Math.max(rsOut, s.getTargetState().getStrength());
}
if (oldOut!=rsOut) {
markBlockForUpdate(pos);
}
}
public void setGlobalInput(byte value) {
for (RSChannel channel: listeners.keySet()) {
RSChannelState state = new RSChannelState(channel, value);
for (ChangeListener l:listeners.get(channel)) {
l.onChange(state);
}
}
}
}
}

View file

@ -0,0 +1,88 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.controlpanel;
import malte0811.industrialwires.blocks.TileEntityIWBase;
import malte0811.industrialwires.controlpanel.ControlPanelNetwork;
import malte0811.industrialwires.controlpanel.ControlPanelNetwork.IOwner;
import malte0811.industrialwires.util.MiscUtils;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import javax.annotation.Nonnull;
public class TileEntityGeneralCP extends TileEntityIWBase implements IOwner {
@Nonnull
protected ControlPanelNetwork panelNetwork = new ControlPanelNetwork();
public void setNetworkAndInit(ControlPanelNetwork newNet) {
panelNetwork = newNet;
}
@Override
public void onLoad() {
super.onLoad();
if (!world.isRemote) {
boolean isFinalNet = false;
if (canJoinNetwork()) {
for (EnumFacing side : EnumFacing.VALUES) {
BlockPos posSide = pos.offset(side);
TileEntityGeneralCP neighbour = MiscUtils.getLoadedTE(world, posSide, TileEntityGeneralCP.class);
if (neighbour != null && neighbour.canJoinNetwork()) {
if (!isFinalNet) {
panelNetwork = neighbour.panelNetwork;
panelNetwork.addMember(this);
isFinalNet = true;
} else {
neighbour.panelNetwork.replaceWith(panelNetwork, world);
}
}
}
}
if (!isFinalNet) {
panelNetwork.addMember(this);
}
}
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
panelNetwork.removeMember(pos, world);
}
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {}
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {}
@Override
public void invalidate() {
super.invalidate();
panelNetwork.removeMember(pos, world);
}
@Override
public BlockPos getBlockPos() {
return pos;
}
public boolean canJoinNetwork() {
return true;
}
}

View file

@ -1,41 +1,36 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.controlpanel;
package malte0811.industrialwires.blocks.controlpanel;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IPlayerInteraction;
import blusunrize.immersiveengineering.common.util.chickenbones.Matrix4;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.IBlockBoundsIW;
import malte0811.industrialWires.blocks.TileEntityIWBase;
import malte0811.industrialWires.controlpanel.*;
import malte0811.industrialWires.network.MessagePanelInteract;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IBlockBoundsIW;
import malte0811.industrialwires.controlpanel.*;
import malte0811.industrialwires.controlpanel.ControlPanelNetwork.RSChannel;
import malte0811.industrialwires.network.MessagePanelInteract;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ITickable;
@ -43,26 +38,29 @@ import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.common.util.Constants;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTile, IBlockBoundsIW, IPlayerInteraction, ITickable, IEBlockInterfaces.ITileDrop {
private PropertyComponents.PanelRenderProperties components = new PropertyComponents.PanelRenderProperties();
public boolean firstTick = true;
// non-rendered properties
private Set<TileEntityRSPanelConn> rsPorts = new HashSet<>();
import static malte0811.industrialwires.util.MiscUtils.apply;
public class TileEntityPanel extends TileEntityGeneralCP implements IDirectionalTile, IBlockBoundsIW, IPlayerInteraction,
ITickable, IEBlockInterfaces.ITileDrop {
protected PropertyComponents.PanelRenderProperties components = new PropertyComponents.PanelRenderProperties();
{
int[] colors = {
16383998, 16351261, 13061821, 3847130, 16701501, 8439583, 15961002,
4673362, 10329495, 1481884, 8991416, 3949738, 8606770, 6192150
};
for (int i = 2; i < 14; i++) {
int color = EnumDyeColor.byMetadata(i - 2).getMapColor().colorValue;
IndicatorLight ind = new IndicatorLight(0, (byte) (i - 2), color);
LightedButton btn = new LightedButton(color, false, true, 1, i - 2);
int color = colors[i-2];
IndicatorLight ind = new IndicatorLight(new RSChannel(0, (byte) (i - 2)), color);
LightedButton btn = new LightedButton(color, false, true,
new RSChannel(0, (byte)(i-2)));
Label lbl = new Label("->", color);
ind.setX(0);
ind.setY(i / 16F);
@ -77,27 +75,28 @@ public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTil
components.add(lbl);
components.add(btn);
}
for (PanelComponent pc:components) {
pc.setPanel(this);
}
}
@Override
public void update() {
for (PanelComponent pc : components) {
pc.update(this);
}
if (!world.isRemote) {
if (firstTick) {
List<BlockPos> parts = PanelUtils.discoverPanelParts(world, pos, 100);
for (BlockPos bp : parts) {
TileEntity te = world.getTileEntity(bp);
if (te instanceof TileEntityRSPanelConn && !rsPorts.contains(te)) {
((TileEntityRSPanelConn) te).registerPanel(this);
}
}
firstTick = false;
for (PanelComponent pc : components) {
pc.update();
}
}
}
@Override
public void setNetworkAndInit(ControlPanelNetwork newNet) {
super.setNetworkAndInit(newNet);
for (PanelComponent pc : components) {
pc.setNetwork(newNet);
}
}
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
writeToItemNBT(out, false);
@ -108,13 +107,13 @@ public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTil
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
readFromItemNBT(in);
components.setFacing(EnumFacing.getHorizontal(in.getInteger("facing")));
components.setTop(EnumFacing.getFront(in.getInteger("top")));
components.setFacing(EnumFacing.byHorizontalIndex(in.getInteger("facing")));
components.setTop(EnumFacing.byIndex(in.getInteger("top")));
}
@Override
@Nonnull
public ItemStack getTileDrop(@Nonnull EntityPlayer player, @Nonnull IBlockState state) {
public ItemStack getTileDrop(@Nullable EntityPlayer player, @Nonnull IBlockState state) {
NBTTagCompound ret = new NBTTagCompound();
writeToItemNBT(ret, true);
ItemStack retStack = new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.TOP.ordinal());
@ -133,7 +132,17 @@ public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTil
if (nbt != null) {
NBTTagList l = nbt.getTagList("components", 10);
PanelUtils.readListFromNBT(l, components);
panelNetwork.removeIOFor(this);
for (PanelComponent pc : components) {
pc.setPanel(this);
if (world == null || !world.isRemote) {
pc.setNetwork(panelNetwork);
}
}
components.setHeight(nbt.getFloat("height"));
if (nbt.hasKey("texture", Constants.NBT.TAG_COMPOUND)) {
components.setTextureSource(new ItemStack(nbt.getCompoundTag("texture")));
}
components.setAngle(nbt.getFloat("angle"));
}
defAABB = null;
@ -149,6 +158,7 @@ public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTil
nbt.setTag("components", comps);
nbt.setFloat("height", components.getHeight());
nbt.setFloat("angle", components.getAngle());
nbt.setTag("texture", components.getTextureSource().serializeNBT());
}
@Nonnull
@ -202,7 +212,7 @@ public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTil
return false;
}
private AxisAlignedBB defAABB;
protected AxisAlignedBB defAABB;
@Override
public AxisAlignedBB getBoundingBox() {
@ -216,46 +226,50 @@ public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTil
return components;
}
public AxisAlignedBB apply(Matrix4 mat, AxisAlignedBB in) {
Vec3d min = new Vec3d(in.minX, in.minY, in.minZ);
Vec3d max = new Vec3d(in.maxX, in.maxY, in.maxZ);
min = mat.apply(min);
max = mat.apply(max);
return new AxisAlignedBB(min.x, min.y, min.z, max.x, max.y, max.z);
}
@Nullable
public Pair<PanelComponent, RayTraceResult> getSelectedComponent(EntityPlayer player, Vec3d hit, boolean hitAbs) {
//TODO prevent clicking through the back of the panel
public Pair<PanelComponent, RayTraceResult> getSelectedComponent(EntityPlayer player, Vec3d hitVec, boolean hitAbs) {
Matrix4 mat = components.getPanelTopTransformInverse();
PanelComponent retPc = null;
RayTraceResult retRay = null;
Vec3d playerPosRelative = player.getPositionVector().addVector(-pos.getX(), player.getEyeHeight() - pos.getY(), -pos.getZ());
Vec3d playerPosRelative = player.getPositionVector().add(-pos.getX(), player.getEyeHeight() - pos.getY(), -pos.getZ());
Vec3d playerPosTransformed = mat.apply(playerPosRelative);
Vec3d hitRel = hitAbs ? hitVec.add(-pos.getX(), -pos.getY(), -pos.getZ()) : hitVec;
RayTraceResult r = getBoundingBox().calculateIntercept(playerPosRelative, playerPosRelative.add(player.getLookVec().scale(200)));
if (r != null && r.hitVec != null) {
hitRel = r.hitVec;
}
Vec3d ray = hitRel.subtract(playerPosRelative.subtract(hitRel).scale(10));
Vec3d rayTransformed = mat.apply(ray);
{
//Check whether the player is clicking on the back of the panel
Vec3d hitTransformed = mat.apply(new Vec3d(hitRel.x, hitRel.y, hitRel.z));
if (hitTransformed.y < 0) {
return null;
}
}
for (PanelComponent pc : components) {
AxisAlignedBB box = pc.getBlockRelativeAABB();
if (box.maxY > box.minY) {
box = box.grow(.002);
Vec3d hitVec = hitAbs ? hit.addVector(-pos.getX(), -pos.getY(), -pos.getZ()) : hit;
hitVec = hitVec.subtract(playerPosRelative.subtract(hitVec).scale(10));
RayTraceResult ray = box.calculateIntercept(playerPosTransformed, mat.apply(hitVec));
if (ray != null) {
RayTraceResult hit = box.calculateIntercept(playerPosTransformed, rayTransformed);
if (hit != null) {
if (retPc == null) {
ray.hitVec = ray.hitVec.subtract(pc.getX(), 0, pc.getY());
retPc = pc;
retRay = ray;
retRay = hit;
} else {
double oldDist = retRay.hitVec.subtract(playerPosRelative).lengthSquared();
double newDist = ray.hitVec.subtract(playerPosRelative).lengthSquared();
double newDist = hit.hitVec.subtract(playerPosRelative).lengthSquared();
if (newDist < oldDist) {
ray.hitVec = ray.hitVec.subtract(pc.getX(), 0, pc.getY());
retPc = pc;
retRay = ray;
retRay = hit;
}
}
}
}
}
if (retRay != null) {
retRay.hitVec = retRay.hitVec.subtract(retPc.getX(), 0, retPc.getY());
}
return retPc != null ? new ImmutablePair<>(retPc, retRay) : null;
}
@ -272,49 +286,7 @@ public class TileEntityPanel extends TileEntityIWBase implements IDirectionalTil
public void interactServer(Vec3d hitRelative, int pcId, EntityPlayerMP player) {
if (pcId >= 0 && pcId < components.size()) {
components.get(pcId).interactWith(hitRelative, this, player);
components.get(pcId).interactWith(hitRelative, player);
}
}
public void triggerRenderUpdate() {
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state, state, 3);
world.addBlockEvent(pos, state.getBlock(), 255, 0);
}
public void registerRS(TileEntityRSPanelConn te) {
rsPorts.add(te);
}
public void unregisterRS(TileEntityRSPanelConn te) {
if (!tileEntityInvalid) {
rsPorts.remove(te);
}
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
for (PanelComponent pc : components) {
pc.invalidate(this);
}
removeAllRSCons();
}
public void removeAllRSCons() {
for (TileEntityRSPanelConn rs : rsPorts) {
rs.unregisterPanel(this, true);
}
rsPorts.clear();
firstTick = true;
}
@Override
public void invalidate() {
super.invalidate();
for (PanelComponent pc : components) {
pc.invalidate(this);
}
removeAllRSCons();
}
}

View file

@ -1,32 +1,28 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.controlpanel;
package malte0811.industrialwires.blocks.controlpanel;
import blusunrize.immersiveengineering.common.util.IELogger;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.IBlockBoundsIW;
import malte0811.industrialWires.blocks.INetGUI;
import malte0811.industrialWires.blocks.TileEntityIWBase;
import malte0811.industrialWires.controlpanel.MessageType;
import malte0811.industrialWires.controlpanel.PanelComponent;
import malte0811.industrialWires.controlpanel.PanelUtils;
import malte0811.industrialWires.items.ItemPanelComponent;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IBlockBoundsIW;
import malte0811.industrialwires.blocks.INetGUI;
import malte0811.industrialwires.blocks.TileEntityIWBase;
import malte0811.industrialwires.controlpanel.MessageType;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.controlpanel.PanelUtils;
import malte0811.industrialwires.items.ItemPanelComponent;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
@ -94,7 +90,7 @@ public class TileEntityPanelCreator extends TileEntityIWBase implements INetGUI,
p.inventory.markDirty();
}
} else {
IELogger.info("(IndustrialWires) Failed to load panel component send by " + p.getDisplayNameString());
IndustrialWires.logger.info("(IndustrialWires) Failed to load panel component send by " + p.getDisplayNameString());
}
break;
case REMOVE:
@ -119,7 +115,12 @@ public class TileEntityPanelCreator extends TileEntityIWBase implements INetGUI,
}
}
if (valid) {
NBTTagCompound panelNBT = new NBTTagCompound();
NBTTagCompound panelNBT;
if (inv.hasTagCompound()) {
panelNBT = inv.getTagCompound().copy();
} else {
panelNBT = new NBTTagCompound();
}
writeToItemNBT(panelNBT, true);
ItemStack panel = new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.TOP.ordinal());
panel.setTagCompound(panelNBT);

View file

@ -0,0 +1,145 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.controlpanel;
import malte0811.industrialwires.blocks.INetGUI;
import malte0811.industrialwires.controlpanel.ControlPanelNetwork;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ITickable;
import java.util.Arrays;
import java.util.function.Consumer;
public abstract class TileEntityRSPanel extends TileEntityGeneralCP implements INetGUI, ITickable {
protected byte[] out = new byte[16];
private boolean dirty = true;
private byte[] currInput = new byte[16];
private final ControlPanelNetwork.RSChannel[] channels = new ControlPanelNetwork.RSChannel[16];
private int controller = 0;
{
for (int i = 0; i < 16; i++) {
currInput[i] = -1;
}
updateChannelsArray();
}
private void updateChannelsArray() {
if (world == null || !world.isRemote) {
panelNetwork.removeIOFor(this);
for (byte i = 0; i < 16; i++) {
channels[i] = new ControlPanelNetwork.RSChannel(controller, i);
}
setNetworkAndInit(panelNetwork);
}
}
@Override
public void update() {
if (dirty) {
updateOutput();
dirty = false;
}
}
@Override
public void writeNBT(NBTTagCompound nbt, boolean updatePacket) {
nbt.setByteArray("out", this.out);
nbt.setByteArray("in", this.currInput);
nbt.setInteger("rsId", controller);
}
@Override
public void readNBT(NBTTagCompound nbt, boolean updatePacket) {
if (nbt.hasKey("out") && nbt.getByteArray("out").length == 16) {
out = nbt.getByteArray("out");
}
if (nbt.hasKey("in") && nbt.getByteArray("in").length == 16) {
currInput = nbt.getByteArray("in");
}
controller = nbt.getInteger("rsId");
updateChannelsArray();
}
protected void markRSDirty() {
dirty = true;
}
protected void onInputChanged(byte[] newIn) {
if (!Arrays.equals(currInput, newIn)) {
ControlPanelNetwork.RSChannelState[] newStates = new ControlPanelNetwork.RSChannelState[16];
for (byte i = 0; i < 16; i++) {
if (newIn[i]>out[i]) {
newStates[i] = new ControlPanelNetwork.RSChannelState(channels[i], newIn[i]);
} else {
newStates[i] = new ControlPanelNetwork.RSChannelState(channels[i], (byte) 0);
}
}
panelNetwork.setOutputs(this, newStates);
currInput = Arrays.copyOf(newIn, 16);
}
}
@Override
public void setNetworkAndInit(ControlPanelNetwork newNet) {
super.setNetworkAndInit(newNet);
Consumer<ControlPanelNetwork.RSChannelState> listener = state -> {
if (out[state.getColor()] != state.getStrength()) {
out[state.getColor()] = state.getStrength();
dirty = true;
}
};
panelNetwork.addListener(this, listener, channels);
byte[] oldIn = currInput;
currInput = new byte[16];
onInputChanged(oldIn);
}
@Override
public void onChange(NBTTagCompound nbt, EntityPlayer p) {
if (nbt.hasKey("rsId")) {
controller = nbt.getInteger("rsId");
markDirty();
panelNetwork.removeIOFor(this);
setNetworkAndInit(panelNetwork);
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state, state, 3);
updateChannelsArray();
}
}
public int getRsId() {
return controller;
}
protected abstract void updateOutput();
protected abstract void updateInput();
@Override
public void onLoad() {
super.onLoad();
if (!world.isRemote) {
updateInput();
updateOutput();
}
}
}

View file

@ -0,0 +1,267 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.controlpanel;
import blusunrize.immersiveengineering.api.TargetingInfo;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import blusunrize.immersiveengineering.api.energy.wires.redstone.IRedstoneConnector;
import blusunrize.immersiveengineering.api.energy.wires.redstone.RedstoneWireNetwork;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces;
import blusunrize.immersiveengineering.common.util.Utils;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IBlockBoundsIW;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Set;
import static blusunrize.immersiveengineering.api.energy.wires.WireType.REDSTONE_CATEGORY;
public class TileEntityRSPanelIE extends TileEntityRSPanel
implements IRedstoneConnector, IEBlockInterfaces.IDirectionalTile, IBlockBoundsIW {
private EnumFacing facing = EnumFacing.NORTH;
@Nonnull
private RedstoneWireNetwork wireNetwork = new RedstoneWireNetwork().add(this);
private boolean hasConn = false;
@Override
public void writeNBT(NBTTagCompound nbt, boolean updatePacket) {
super.writeNBT(nbt, updatePacket);
nbt.setBoolean("hasConn", hasConn);
nbt.setInteger("facing", facing.getIndex());
if (updatePacket) {
writeConnsToNBT(nbt);
}
}
@Override
public void readNBT(NBTTagCompound nbt, boolean updatePacket) {
super.readNBT(nbt, updatePacket);
if (nbt.hasKey("connectionList", Constants.NBT.TAG_LIST)) {
loadConnsFromNBT(nbt);
}
hasConn = nbt.getBoolean("hasConn");
facing = EnumFacing.VALUES[nbt.getInteger("facing")];
aabb = null;
}
//Copied from IE (TileEntityImmersiveConnectable)
private void loadConnsFromNBT(NBTTagCompound nbt) {
if (world != null && world.isRemote && !Minecraft.getMinecraft().isSingleplayer() && nbt != null) {
NBTTagList connectionList = nbt.getTagList("connectionList", Constants.NBT.TAG_COMPOUND);
ImmersiveNetHandler.INSTANCE.clearConnectionsOriginatingFrom(Utils.toCC(this), world);
for (int i = 0; i < connectionList.tagCount(); i++) {
NBTTagCompound conTag = connectionList.getCompoundTagAt(i);
ImmersiveNetHandler.Connection con = ImmersiveNetHandler.Connection.readFromNBT(conTag);
if (con != null) {
ImmersiveNetHandler.INSTANCE.addConnection(world, Utils.toCC(this), con);
} else
IndustrialWires.logger.error("CLIENT read connection as null from {}", nbt);
}
}
}
private void writeConnsToNBT(NBTTagCompound nbt) {
if (world != null && !world.isRemote && nbt != null) {
NBTTagList connectionList = new NBTTagList();
Set<ImmersiveNetHandler.Connection> conL = ImmersiveNetHandler.INSTANCE.getConnections(world, Utils.toCC(this));
if (conL != null)
for (ImmersiveNetHandler.Connection con : conL)
connectionList.appendTag(con.writeToNBT());
nbt.setTag("connectionList", connectionList);
}
}
@Override
protected void updateOutput() {
wireNetwork.updateValues();
}
@Override
protected void updateInput() {
updateInput(wireNetwork.channelValues);
}
@Override
public void setNetwork(@Nonnull RedstoneWireNetwork net) {
wireNetwork = net;
}
@Nonnull
@Override
public RedstoneWireNetwork getNetwork() {
return wireNetwork;
}
@Override
public void onChange() {
onInputChanged(wireNetwork.channelValues);
}
@Override
public void updateInput(byte[] currIn) {
for (int i = 0; i < 16; i++) {
currIn[i] = (byte) Math.max(currIn[i], out[i]);
}
}
@Override
public boolean canConnect() {
return true;
}
@Override
public boolean isEnergyOutput() {
return false;
}
@Override
public int outputEnergy(int amount, boolean simulate, int energyType) {
return 0;
}
@Override
public BlockPos getConnectionMaster(@Nullable WireType wire, TargetingInfo target) {
return pos;
}
@Override
public boolean canConnectCable(WireType wire, TargetingInfo targetingInfo, Vec3i offset) {
return REDSTONE_CATEGORY.equals(wire.getCategory()) && !hasConn;
}
@Override
public void connectCable(WireType wireType, TargetingInfo targetingInfo, IImmersiveConnectable other) {
hasConn = true;
RedstoneWireNetwork.updateConnectors(pos, world, wireNetwork);
}
@Override
public WireType getCableLimiter(TargetingInfo targetingInfo) {
return WireType.REDSTONE;
}
@Override
public boolean allowEnergyToPass(ImmersiveNetHandler.Connection connection) {
return true;
}
@Override
public void removeCable(ImmersiveNetHandler.Connection connection) {
hasConn = false;
wireNetwork.removeFromNetwork(this);
this.markDirty();
if (world != null) {
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state, state, 3);
}
}
@Override
public Vec3d getConnectionOffset(ImmersiveNetHandler.Connection connection) {
EnumFacing side = facing.getOpposite();
double conRadius = connection.cableType.getRenderDiameter() / 2;
return new Vec3d(.5 - conRadius * side.getXOffset(), .5 - conRadius * side.getYOffset(), .5 - conRadius * side.getZOffset());
}
@Override
public World getConnectorWorld() {
return world;
}
@Nonnull
@Override
public EnumFacing getFacing() {
return facing;
}
@Override
public void setFacing(@Nonnull EnumFacing facing) {
this.facing = facing;
}
@Override
public int getFacingLimitation() {
return 0;
}
@Override
public boolean mirrorFacingOnPlacement(@Nonnull EntityLivingBase placer) {
return true;
}
@Override
public boolean canHammerRotate(@Nonnull EnumFacing side, float hitX, float hitY, float hitZ, @Nonnull EntityLivingBase entity) {
return false;
}
@Override
public boolean canRotate(@Nonnull EnumFacing axis) {
return false;
}
private AxisAlignedBB aabb;
@Override
public AxisAlignedBB getBoundingBox() {
if (aabb == null) {
double h = 9 / 16D;
switch (facing) {
case DOWN:
aabb = new AxisAlignedBB(0, 0, 0, 1, h, 1);
break;
case UP:
aabb = new AxisAlignedBB(0, 1 - h, 0, 1, 1, 1);
break;
case NORTH:
aabb = new AxisAlignedBB(0, 0, 0, 1, 1, h);
break;
case SOUTH:
aabb = new AxisAlignedBB(0, 0, 1 - h, 1, 1, 1);
break;
case WEST:
aabb = new AxisAlignedBB(0, 0, 0, h, 1, 1);
break;
case EAST:
aabb = new AxisAlignedBB(1 - h, 0, 0, 1, 1, 1);
break;
}
}
return aabb;
}
@Override
public void invalidate() {
super.invalidate();
if (world.isRemote && !Minecraft.getMinecraft().isSingleplayer()) {
ImmersiveNetHandler.INSTANCE.clearAllConnectionsFor(pos, world, this, false);
}
}
}

View file

@ -0,0 +1,83 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.controlpanel;
import malte0811.industrialwires.compat.Compat;
import malte0811.industrialwires.compat.CompatCapabilities.Charset;
import mrtjp.projectred.api.IBundledTile;
import mrtjp.projectred.api.ProjectRedAPI;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.common.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
@Optional.Interface(iface = "mrtjp.projectred.api.IBundledTile", modid = ProjectRedAPI.modIDCore)
public class TileEntityRSPanelOthers extends TileEntityRSPanel implements IBundledTile {
@Override
public boolean canConnectBundled(int i) {
return true;
}
@Override
public byte[] getBundledSignal(int side) {
byte[] ret = new byte[16];
for (int i = 0;i<16;i++) {
ret[i] = (byte) (17*out[i]);
}
return ret;
}
@Override
public void updateInput() {
byte[] data = new byte[16];
for (EnumFacing f:EnumFacing.VALUES) {
byte[] tmp = Compat.getBundledRS.run(world, pos, f);
if (tmp!=null) {
for (int i = 0; i<16; i++) {
if (tmp[i]>data[i]) {
data[i] = tmp[i];
}
}
}
}
onInputChanged(data);
}
@Override
protected void updateOutput() {
Compat.updateBundledRS.run(world, pos, null);
}
@Nullable
@Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability==Charset.EMITTER_CAP) {
return Charset.EMITTER_CAP.cast(()->Arrays.copyOf(out, 16));
} else if (capability==Charset.RECEIVER_CAP) {
return Charset.RECEIVER_CAP.cast(this::updateInput);
}
return null;
}
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
return capability==Charset.EMITTER_CAP||capability==Charset.RECEIVER_CAP;
}
}

View file

@ -1,22 +1,19 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.controlpanel;
package malte0811.industrialwires.blocks.controlpanel;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;

View file

@ -1,25 +1,22 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.converter;
package malte0811.industrialwires.blocks.converter;
import blusunrize.immersiveengineering.api.IEProperties;
import malte0811.industrialWires.blocks.BlockIWBase;
import malte0811.industrialWires.blocks.IMetaEnum;
import malte0811.industrialwires.blocks.BlockIWBase;
import malte0811.industrialwires.blocks.IMetaEnum;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
@ -27,7 +24,6 @@ import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
@ -40,16 +36,17 @@ import net.minecraft.world.World;
import javax.annotation.Nonnull;
public class BlockMechanicalConverter extends BlockIWBase implements IMetaEnum {
public static final String NAME = "mechanical_converter";
private static PropertyEnum<MechanicalBlockType> type = PropertyEnum.create("type", MechanicalBlockType.class);
public BlockMechanicalConverter() {
super(Material.IRON, "mechanical_converter");
super(Material.IRON, NAME);
}
@Override
public void getSubBlocks(@Nonnull Item itemIn, CreativeTabs tab, NonNullList<ItemStack> list) {
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
for (int i = 0; i < 3; i++) {
list.add(new ItemStack(itemIn, 1, i));
list.add(new ItemStack(this, 1, i));
}
}

View file

@ -0,0 +1,124 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.converter;
import blusunrize.immersiveengineering.api.IEProperties;
import malte0811.industrialwires.blocks.BlockIWMultiblock;
import malte0811.industrialwires.blocks.IMetaEnum;
import malte0811.industrialwires.blocks.IWProperties;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class BlockMechanicalMB extends BlockIWMultiblock implements IMetaEnum {
public static final PropertyEnum<MechanicalMBBlockType> TYPE = PropertyEnum.create("type", MechanicalMBBlockType.class);
public static final String NAME = "mech_mb";
public BlockMechanicalMB() {
super(Material.IRON, NAME);
}
@Override
public void getSubBlocks(CreativeTabs itemIn, NonNullList<ItemStack> items) {
//NOP
}
@Override
protected IProperty[] getProperties() {
return new IProperty[] {
IEProperties.FACING_HORIZONTAL, TYPE
};
}
@Nonnull
@Override
protected BlockStateContainer createBlockState() {
BlockStateContainer base = super.createBlockState();
return new ExtendedBlockState(this, base.getProperties().toArray(new IProperty[0]), new IUnlistedProperty[]{
IWProperties.MB_SIDES
});
}
@Nonnull
@Override
public IBlockState getExtendedState(@Nonnull IBlockState state, IBlockAccess world, BlockPos pos) {
TileEntity te = world.getTileEntity(pos);
state = super.getExtendedState(state, world, pos);
if (te instanceof TileEntityMechMB)
state = ((TileEntityMechMB) te).getExtState(state);
return state;
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Nullable
@Override
public TileEntity createTileEntity(@Nonnull World world, @Nonnull IBlockState state) {
return new TileEntityMechMB();
}
@Override
public int getMetaFromState(IBlockState state) {
return state.getValue(TYPE).ordinal();
}
@Nonnull
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty(TYPE, MechanicalMBBlockType.VALUES[meta]);
}
@Override
public Object[] getValues() {
return TYPE.getAllowedValues().toArray();
}
@Override
public boolean eventReceived(IBlockState state, World worldIn, BlockPos pos, int id, int param) {
if ((id&255)==255) {
IBlockState s = worldIn.getBlockState(pos);
worldIn.notifyBlockUpdate(pos, s, s, 3);
if (param>=0) {
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof TileEntityMechMB && !((TileEntityMechMB) te).isLogicDummy()) {
int[] offsets = ((TileEntityMechMB) te).offsets;
if (offsets!=null && param<offsets.length) {
BlockPos otherPos = pos.offset(((TileEntityMechMB) te).getFacing(), -offsets[param]);
s = worldIn.getBlockState(otherPos);
worldIn.notifyBlockUpdate(otherPos, s, s, 3);
}
}
}
}
return super.eventReceived(state, worldIn, pos, id, param);
}
}

View file

@ -1,21 +1,18 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.converter;
package malte0811.industrialwires.blocks.converter;
import net.minecraft.util.IStringSerializable;

View file

@ -0,0 +1,39 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.converter;
import net.minecraft.util.IStringSerializable;
public enum MechanicalMBBlockType implements IStringSerializable {
NO_MODEL,
END,
OTHER_END,
COIL_4_PHASE,
COIL_1_PHASE,
SHAFT_BASIC,
SHAFT_4_PHASE,
SHAFT_1_PHASE,
SHAFT_COMMUTATOR,
FLYWHEEL,
SPEEDOMETER,
SHAFT_COMMUTATOR_4;
public static final MechanicalMBBlockType[] VALUES = values();
@Override
public String getName() {
return name().toLowerCase();
}
}

View file

@ -1,30 +1,27 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.converter;
package malte0811.industrialwires.blocks.converter;
import blusunrize.immersiveengineering.api.energy.IRotationAcceptor;
import blusunrize.immersiveengineering.api.energy.immersiveflux.FluxStorage;
import blusunrize.immersiveengineering.api.energy.immersiveflux.IFluxReceiver;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import malte0811.industrialWires.IWConfig.MechConversion;
import malte0811.industrialWires.blocks.EnergyAdapter;
import malte0811.industrialWires.blocks.TileEntityIWBase;
import malte0811.industrialWires.util.ConversionUtil;
import malte0811.industrialwires.IWConfig.MechConversion;
import malte0811.industrialwires.blocks.EnergyAdapter;
import malte0811.industrialwires.blocks.TileEntityIWBase;
import malte0811.industrialwires.util.ConversionUtil;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
@ -33,12 +30,15 @@ import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import static malte0811.industrialwires.util.NBTKeys.*;
public class TileEntityIEMotor extends TileEntityIWBase implements ITickable, IFluxReceiver, IDirectionalTile {
public final double bufferMax = 2 * MechConversion.maxIfToMech * ConversionUtil.rotPerIf();
private double rotBuffer = 0;
private FluxStorage energy = new FluxStorage(20 * MechConversion.maxIfToMech, 2 * MechConversion.maxIfToMech);
private EnumFacing dir = EnumFacing.DOWN;
@ -52,7 +52,8 @@ public class TileEntityIEMotor extends TileEntityIWBase implements ITickable, IF
}
int max = MechConversion.maxIfToMech;
boolean dirty = false;
if (rotBuffer < bufferMax && energy.extractEnergy(max, true) > 0) {
if (rotBuffer < 2 * MechConversion.maxIfToMech * ConversionUtil.rotPerIf()
&& energy.extractEnergy(max, true) > 0) {
int extracted = energy.extractEnergy(max, false);
rotBuffer += extracted * ConversionUtil.rotPerIf() * MechConversion.ifMotorEfficiency;
dirty = true;
@ -71,19 +72,19 @@ public class TileEntityIEMotor extends TileEntityIWBase implements ITickable, IF
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
dir = EnumFacing.VALUES[in.getByte(DIR_TAG)];
energy.readFromNBT(in.getCompoundTag(ENERGY_TAG));
dir = EnumFacing.VALUES[in.getByte(DIRECTION)];
energy.readFromNBT(in.getCompoundTag(ENERGY));
receiver = null;
rotBuffer = in.getDouble(BUFFER_TAG);
rotBuffer = in.getDouble(BUFFER);
}
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
out.setByte(DIR_TAG, (byte) dir.getIndex());
out.setByte(DIRECTION, (byte) dir.getIndex());
NBTTagCompound nbt = new NBTTagCompound();
energy.writeToNBT(nbt);
out.setTag(ENERGY_TAG, nbt);
out.setDouble(BUFFER_TAG, rotBuffer);
out.setTag(ENERGY, nbt);
out.setDouble(BUFFER, rotBuffer);
}
// Flux energy
@ -150,11 +151,14 @@ public class TileEntityIEMotor extends TileEntityIWBase implements ITickable, IF
return super.hasCapability(capability, facing);
}
private Map<EnumFacing, IEnergyStorage> energies = new HashMap<>();
@Override
@SuppressWarnings("unchecked")
public <T> T getCapability(@Nonnull Capability<T> capability, EnumFacing facing) {
if (capability == CapabilityEnergy.ENERGY && canConnectEnergy(facing)) {
return (T) new EnergyAdapter(this, facing);
if (!energies.containsKey(facing))
energies.put(facing, new EnergyAdapter(this, facing));
return CapabilityEnergy.ENERGY.cast(energies.get(facing));
}
return super.getCapability(capability, facing);
}

View file

@ -1,28 +1,25 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.converter;
package malte0811.industrialwires.blocks.converter;
import blusunrize.immersiveengineering.api.energy.IRotationAcceptor;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import ic2.api.energy.tile.IKineticSource;
import malte0811.industrialWires.IWConfig.MechConversion;
import malte0811.industrialWires.blocks.TileEntityIWBase;
import malte0811.industrialWires.util.ConversionUtil;
import malte0811.industrialwires.IWConfig.MechConversion;
import malte0811.industrialwires.blocks.TileEntityIWBase;
import malte0811.industrialwires.util.ConversionUtil;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
@ -32,13 +29,14 @@ import net.minecraft.util.math.BlockPos;
import javax.annotation.Nonnull;
import static malte0811.industrialwires.util.NBTKeys.BUFFER;
import static malte0811.industrialwires.util.NBTKeys.DIRECTION;
public class TileEntityMechICtoIE extends TileEntityIWBase implements IDirectionalTile, ITickable {
EnumFacing dir = EnumFacing.DOWN;
int kinBuffer = 0;
private final int kinBufMax = 2 * MechConversion.maxKinToRot;
private final double maxInsert = ConversionUtil.rotPerKin() * MechConversion.maxKinToRot;
BlockPos to;
BlockPos from;
private EnumFacing dir = EnumFacing.DOWN;
private int kinBuffer = 0;
private BlockPos to;
private BlockPos from;
@Override
public void update() {
@ -52,14 +50,15 @@ public class TileEntityMechICtoIE extends TileEntityIWBase implements IDirection
TileEntity teFrom = world.getTileEntity(from);
if (teFrom instanceof IKineticSource) {
int sourceMax = ((IKineticSource) teFrom).maxrequestkineticenergyTick(dir);
int draw = Math.min(kinBufMax - kinBuffer, sourceMax);
int draw = Math.min(2 * MechConversion.maxKinToRot - kinBuffer, sourceMax);
if (draw > 0) {
kinBuffer += ((IKineticSource) teFrom).requestkineticenergy(dir, draw) * MechConversion.kinToRotEfficiency;
}
}
TileEntity teTo = world.getTileEntity(to);
if (kinBuffer > 0 && teTo instanceof IRotationAcceptor) {
double out = Math.min(maxInsert, ConversionUtil.rotPerKin() * kinBuffer);
double out = Math.min(ConversionUtil.rotPerKin() * MechConversion.maxKinToRot,
ConversionUtil.rotPerKin() * kinBuffer);
((IRotationAcceptor) teTo).inputRotation(out, dir);
kinBuffer -= out * ConversionUtil.kinPerRot();
}
@ -68,14 +67,14 @@ public class TileEntityMechICtoIE extends TileEntityIWBase implements IDirection
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
out.setByte(DIR_TAG, (byte) dir.getIndex());
out.setInteger(BUFFER_TAG, kinBuffer);
out.setByte(DIRECTION, (byte) dir.getIndex());
out.setInteger(BUFFER, kinBuffer);
}
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
dir = EnumFacing.VALUES[in.getByte(DIR_TAG)];
kinBuffer = in.getInteger(BUFFER_TAG);
dir = EnumFacing.VALUES[in.getByte(DIRECTION)];
kinBuffer = in.getInteger(BUFFER);
to = null;
from = null;
}

View file

@ -1,50 +1,49 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.converter;
package malte0811.industrialwires.blocks.converter;
import blusunrize.immersiveengineering.api.energy.IRotationAcceptor;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import ic2.api.energy.tile.IKineticSource;
import malte0811.industrialWires.IWConfig.MechConversion;
import malte0811.industrialWires.blocks.TileEntityIWBase;
import malte0811.industrialWires.util.ConversionUtil;
import malte0811.industrialwires.IWConfig.MechConversion;
import malte0811.industrialwires.blocks.TileEntityIWBase;
import malte0811.industrialwires.util.ConversionUtil;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
import static malte0811.industrialwires.IWConfig.MechConversion.maxRotToKin;
import static malte0811.industrialwires.util.NBTKeys.BUFFER;
import static malte0811.industrialwires.util.NBTKeys.DIRECTION;
public class TileEntityMechIEtoIC extends TileEntityIWBase implements IDirectionalTile, IRotationAcceptor, IKineticSource {
EnumFacing dir = EnumFacing.DOWN;
double rotBuffer = 0;
private final double rotBufMax = 2 * MechConversion.maxRotToKin;
private final int maxOutput = (int) (ConversionUtil.kinPerRot() * MechConversion.maxRotToKin);
private EnumFacing dir = EnumFacing.DOWN;
private double rotBuffer = 0;
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
out.setByte(DIR_TAG, (byte) dir.getIndex());
out.setDouble(BUFFER_TAG, rotBuffer);
out.setByte(DIRECTION, (byte) dir.getIndex());
out.setDouble(BUFFER, rotBuffer);
}
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
dir = EnumFacing.VALUES[in.getByte(DIR_TAG)];
rotBuffer = in.getDouble(BUFFER_TAG);
dir = EnumFacing.VALUES[in.getByte(DIRECTION)];
rotBuffer = in.getDouble(BUFFER);
}
// Directional
@ -75,23 +74,36 @@ public class TileEntityMechIEtoIC extends TileEntityIWBase implements IDirection
return true;
}
@Override
@Deprecated
public int maxrequestkineticenergyTick(EnumFacing enumFacing) {
return 0;
}
//IC2 kinetic
@Override
public int maxrequestkineticenergyTick(EnumFacing f) {
public int getConnectionBandwidth(EnumFacing f) {
if (f == dir) {
return maxOutput;
return (int) (ConversionUtil.kinPerRot() * rotBuffer);
} else {
return 0;
}
}
@Override
public int requestkineticenergy(EnumFacing f, int requested) {
@Deprecated
public int requestkineticenergy(EnumFacing enumFacing, int i) {
return 0;
}
@Override
public int drawKineticEnergy(EnumFacing f, int requested, boolean simulate) {
if (f == dir) {
int stored = (int) (ConversionUtil.kinPerRot() * rotBuffer);
int out = Math.min(maxOutput, stored);
out = Math.min(requested, out);
rotBuffer -= out * ConversionUtil.rotPerKin();
int out = Math.min(requested, stored);
if (!simulate) {
rotBuffer -= out * ConversionUtil.rotPerKin();
}
return (int) (out * MechConversion.rotToKinEfficiency);
} else {
return 0;
@ -102,7 +114,7 @@ public class TileEntityMechIEtoIC extends TileEntityIWBase implements IDirection
@Override
public void inputRotation(double rotation, @Nonnull EnumFacing side) {
if (side == dir) {
rotBuffer = Math.min(rotBufMax, rotBuffer + rotation);
rotBuffer = Math.min(Math.max(rotBuffer, rotation), maxRotToKin);
}
}

View file

@ -0,0 +1,704 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.converter;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IPlayerInteraction;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IRedstoneOutput;
import blusunrize.immersiveengineering.common.blocks.metal.BlockTypes_MetalDecoration0;
import blusunrize.immersiveengineering.common.util.Utils;
import com.google.common.collect.MapMaker;
import ic2.api.energy.tile.IEnergyAcceptor;
import ic2.api.energy.tile.IEnergyEmitter;
import ic2.api.energy.tile.IEnergySink;
import ic2.api.energy.tile.IEnergySource;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IBlockBoundsIW.IBlockBoundsDirectional;
import malte0811.industrialwires.blocks.ISyncReceiver;
import malte0811.industrialwires.blocks.TileEntityIWMultiblock;
import malte0811.industrialwires.compat.Compat;
import malte0811.industrialwires.mech_mb.*;
import malte0811.industrialwires.network.MessageTileSyncIW;
import malte0811.industrialwires.util.LocalSidedWorld;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import static blusunrize.immersiveengineering.common.blocks.metal.BlockTypes_MetalDecoration0.HEAVY_ENGINEERING;
import static malte0811.industrialwires.IEObjects.blockMetalDecoration0;
import static malte0811.industrialwires.IndustrialWires.MMB_BREAKING;
import static malte0811.industrialwires.mech_mb.EUCapability.ENERGY_IC2;
import static malte0811.industrialwires.util.MiscUtils.getOffset;
import static malte0811.industrialwires.util.MiscUtils.offset;
import static malte0811.industrialwires.util.NBTKeys.*;
@net.minecraftforge.fml.common.Optional.InterfaceList({
@net.minecraftforge.fml.common.Optional.Interface(iface = "ic2.api.energy.tile.IEnergySource", modid = "ic2"),
@Optional.Interface(iface = "ic2.api.energy.tile.IEnergySink", modid = "ic2")
})
public class TileEntityMechMB extends TileEntityIWMultiblock implements ITickable, ISyncReceiver,
IEnergySource, IEnergySink, IPlayerInteraction, IRedstoneOutput, IBlockBoundsDirectional {
private static final double DECAY_BASE = Math.exp(Math.log(.95) / (60 * 60 * 20));
public static final double TICK_ANGLE_PER_SPEED = 180 / 20 / Math.PI;
private static final double SYNC_THRESHOLD = .95;
private static final Map<BlockPos, TileEntityMechMB> CLIENT_MASTER_BY_POS = new MapMaker().weakValues().makeMap();
public MechMBPart[] mechanical = null;
int[] offsets = null;
private int[][] electricalStartEnd = null;
public MechEnergy energyState;
private double lastSyncedSpeed = 0;
private double decay;
public double angle;
@SideOnly(Side.CLIENT)
public List<BakedQuad> rotatingModel;
private boolean firstTick = true;
// To allow changing the MB structure later on without resulting in dupes/conversion
private int structureVersion = 0;
@Override
public void update() {
ApiUtils.checkForNeedlessTicking(this);
if (firstTick && !world.isRemote) {
Compat.loadIC2Tile.accept(this);
firstTick = false;
}
if (isLogicDummy() || mechanical == null || mechanical.length==0) {
return;
}
if (world.isRemote) {
angle += energyState.getSpeed() * TICK_ANGLE_PER_SPEED;
angle %= 360;
if (firstTick) {
CLIENT_MASTER_BY_POS.put(pos, this);
}
if (energyState.clientUpdate()||firstTick) {
IndustrialWires.proxy.updateMechMBTurningSound(this, energyState);
TileEntity otherEnd = Utils.getExistingTileEntity(world, pos.offset(facing, -offsets[mechanical.length]));
if (otherEnd instanceof TileEntityMechMB) {
IndustrialWires.proxy.updateMechMBTurningSound((TileEntityMechMB) otherEnd, energyState);
}
}
return;
}
// Mechanical
for (MechMBPart part : mechanical) {
part.createMEnergy(energyState);
}
double requestSum = 0;
IdentityHashMap<MechMBPart, Double> individualRequests = new IdentityHashMap<>();
for (MechMBPart part : mechanical) {
double eForPart = part.requestMEnergy(energyState);
requestSum += eForPart;
individualRequests.put(part, eForPart);
}
double availableEnergy = energyState.getEnergy() / 5;//prevent energy transmission without movement
double factor = Math.min(availableEnergy / requestSum, 1);
energyState.extractEnergy(Math.min(requestSum, availableEnergy));
for (MechMBPart part : mechanical) {
part.insertMEnergy(factor * individualRequests.get(part));
}
Set<MechMBPart> failed = new HashSet<>();
for (MechMBPart part : mechanical) {
if (energyState.getSpeed() > part.getMaxSpeed()) {
failed.add(part);
}
}
if (!failed.isEmpty()) {
disassemble(failed);
return;
}
//Electrical
for (int[] section : electricalStartEnd) {
final int sectionLength = section[1] - section[0];
double[] available = new double[sectionLength];
Waveform[] availableWf = new Waveform[sectionLength];
boolean hasEnergy = false;
Set<Waveform> availableWaveforms = new HashSet<>();
for (int i = section[0]; i < section[1]; i++) {
IMBPartElectric electricalComp = ((IMBPartElectric) mechanical[i]);
Waveform localWf = electricalComp.getProduced(energyState).getForSpeed(energyState.getSpeed());
availableWf[i - section[0]] = localWf;
if (!localWf.isEnergyWaveform()) {
continue;
}
double availableLocal = electricalComp.getAvailableEEnergy(energyState);
available[i - section[0]] = availableLocal;
availableWaveforms.add(localWf);
if (availableLocal > 0) {
hasEnergy = true;
}
}
if (hasEnergy) {
List<Waveform> availableWfList = new ArrayList<>(availableWaveforms);
double[][] requested = new double[availableWfList.size()][sectionLength];
for (int i = 0; i < requested.length; i++) {
Waveform wf = availableWfList.get(i);
if (wf.isEnergyWaveform()) {
for (int j = 0; j < sectionLength; j++) {
requested[i][j] = ((IMBPartElectric) mechanical[j + section[0]]).requestEEnergy(wf, energyState);
}
}
}
int maxId = -1;
double maxTransferred = 0;
for (int i = 0; i < requested.length; i++) {
Waveform wf = availableWfList.get(i);
double transferred = transferElectric(section, Arrays.copyOf(available, sectionLength), availableWf, wf,
Arrays.copyOf(requested[i], sectionLength), true);
if (transferred > maxTransferred) {
maxTransferred = transferred;
maxId = i;
}
}
if (maxId < 0) {
double[] availablePerWf = new double[availableWaveforms.size()];
for (int i = 0; i < availableWf.length; i++) {
if (availableWf[i].isEnergyWaveform()) {
availablePerWf[availableWfList.indexOf(availableWf[i])] += available[i];
}
}
for (int i = 0; i < availablePerWf.length; i++) {
if (availablePerWf[i] > 0 && (maxId < 0 || availablePerWf[maxId] < availablePerWf[i])) {
maxId = i;
}
}
}
if (maxId >= 0) {
transferElectric(section, available, availableWf, availableWfList.get(maxId), requested[maxId], false);
}
}
}
//General
energyState.decaySpeed(decay);
markDirty();
if (lastSyncedSpeed < energyState.getSpeed() * SYNC_THRESHOLD || lastSyncedSpeed > energyState.getSpeed() / SYNC_THRESHOLD) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setDouble(SPEED, energyState.getSpeed());
IndustrialWires.packetHandler.sendToDimension(new MessageTileSyncIW(this, nbt), world.provider.getDimension());
lastSyncedSpeed = energyState.getSpeed();
}
}
@Override
public void setWorld(@Nonnull World worldIn) {
super.setWorld(worldIn);
if (!isLogicDummy()) {
int offset = 1;
for (MechMBPart part : mechanical) {
part.world.setWorld(world);
part.world.setOrigin(offset(pos, facing, mirrored, 0, -offset, 0));
offset += part.getLength();
}
}
}
public IBlockState getExtState(IBlockState in) {
TileEntityMechMB master = CLIENT_MASTER_BY_POS.get(pos.subtract(offset));
if (master==null)
return in;
Vec3i offsetDirectional = getOffsetDir();
int id = getPart(offsetDirectional.getZ(), master);
if (id < 0) {
return in;
}
MechMBPart part = master.mechanical[id];
return part.getExtState(in);
}
//return value is maximized to choose the waveform to use
private double transferElectric(int[] section, double[] available, Waveform[] availableWf, Waveform waveform,
double[] requested, boolean simulate) {
double totalAvailable = 0;
double totalRequested = 0;
for (int i = 0; i < available.length; i++) {
if (!availableWf[i].equals(waveform)) {
available[i] = 0;
}
totalRequested += requested[i];
}
for (int i = 0; i < available.length; i++) {
if (available[i]>0) {
available[i] = Math.min(available[i], totalRequested-requested[i]);
totalAvailable += available[i];
}
}
double[] ins = new double[section[1]-section[0]];
double[] extracted = new double[section[1]-section[0]];
if (totalAvailable>0) {
for (int i = section[0]; i < section[1]; i++) {
int i0 = i - section[0];
double otherRequests = totalRequested - requested[i0];
double extractFactor = Math.min(1, otherRequests / totalAvailable);
double extr = available[i0] * extractFactor;
if (extr == 0) {
continue;
}
for (int j = 0; j < section[1] - section[0]; j++) {
if (j != i0) {
ins[j] += extr * (requested[j] / otherRequests);
}
}
extracted[i0] = extr;
if (!simulate) {
IMBPartElectric electric = (IMBPartElectric) mechanical[i];
electric.extractEEnergy(extr, energyState);
}
}
}
if (!simulate) {
for (int i = section[0]; i < section[1]; i++) {
int i0 = i - section[0];
IMBPartElectric electric = (IMBPartElectric) mechanical[i];
electric.insertEEnergy(ins[i0], waveform, energyState);
}
}
double totalTransf = 0;
for (int i = 0; i < section[1] - section[0]; i++) {
totalTransf += Math.abs(ins[i]-extracted[i]);
}
return totalTransf;
}
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
super.writeNBT(out, updatePacket);
if (mechanical != null) {
NBTTagList mechParts = new NBTTagList();
for (MechMBPart part : mechanical) {
mechParts.appendTag(MechMBPart.toNBT(part));
}
out.setTag(PARTS, mechParts);
out.setDouble(SPEED, energyState.getSpeed());
}
out.setInteger(VERSION, structureVersion);
}
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
super.readNBT(in, updatePacket);
if (in.hasKey(PARTS, Constants.NBT.TAG_LIST)) {
NBTTagList mechParts = in.getTagList(PARTS, Constants.NBT.TAG_COMPOUND);
MechMBPart[] mech = new MechMBPart[mechParts.tagCount()];
int offset = 1;
for (int i = 0; i < mechParts.tagCount(); i++) {
mech[i] = MechMBPart.fromNBT(mechParts.getCompoundTagAt(i),
new LocalSidedWorld(world, offset(pos, facing, mirrored, 0, -offset, 0), facing.getOpposite(), mirrored));
offset += mech[i].getLength();
}
setMechanical(mech, in.getDouble(SPEED));
}
structureVersion = in.getInteger(VERSION);
rBB = null;
aabb = null;
}
public void setMechanical(MechMBPart[] mech, double speed) {
mechanical = mech;
offsets = new int[mechanical.length+1];
double weight = 0;
int offset = 1;
List<int[]> electrical = new ArrayList<>();
int lastEStart = -1;
for (int i = 0; i < mech.length; i++) {
offsets[i] = offset;
weight += mechanical[i].getInertia();
offset += mechanical[i].getLength();
if (lastEStart < 0 && mechanical[i] instanceof IMBPartElectric) {
lastEStart = i;
} else if (lastEStart >= 0 && !(mechanical[i] instanceof IMBPartElectric)) {
electrical.add(new int[]{lastEStart, i});
lastEStart = -1;
}
}
offsets[mechanical.length] = offset;
if (lastEStart >= 0) {
electrical.add(new int[]{lastEStart, mechanical.length});
}
electricalStartEnd = electrical.toArray(new int[electrical.size()][]);
decay = Math.pow(DECAY_BASE, mechanical.length);
if (energyState!=null) {
energyState.invalid = true;
}
energyState = new MechEnergy(weight, speed);
}
private int getPart(int offset, TileEntityMechMB master) {
if (offset == 0) {
return -1;
}
int pos = 1;
MechMBPart[] mechMaster = master.mechanical;
if (mechMaster != null) {
for (int i = 0, mechanical1Length = mechMaster.length; i < mechanical1Length; i++) {
MechMBPart part = mechMaster[i];
if (pos >= offset) {
return i;
}
pos += part.getLength();
}
}
return -1;
}
@Nonnull
@Override
protected BlockPos getOrigin() {
return pos;//Irrelevant, since this uses a custom disassembly method
}
@Override
public IBlockState getOriginalBlock() {
return Blocks.AIR.getDefaultState();//Irrelevant, the method below is used for pick block
}
@Override
public ItemStack getOriginalItem() {
Vec3i offsetDirectional = getOffsetDir();
TileEntityMechMB master = masterOr(this, this);
int id = getPart(offsetDirectional.getZ(), master);
if (id < 0) {
return new ItemStack(blockMetalDecoration0, 1,
BlockTypes_MetalDecoration0.HEAVY_ENGINEERING.ordinal());
}
MechMBPart part = master.mechanical[id];
BlockPos offsetPart = new BlockPos(offsetDirectional.getX(), offsetDirectional.getY(), offsetDirectional.getZ() - master.offsets[id]);
return part.getOriginalItem(offsetPart);
}
@Override
@SideOnly(Side.CLIENT)
public void onSync(NBTTagCompound nbt) {
energyState.setTargetSpeed(nbt.getDouble(SPEED));
}
private AxisAlignedBB rBB;
@Nonnull
@Override
public AxisAlignedBB getRenderBoundingBox() {
if (rBB == null) {
if (isLogicDummy()) {
rBB = new AxisAlignedBB(pos, pos);
} else {
rBB = new AxisAlignedBB(offset(pos, facing, mirrored, -2, 0, -2),
offset(pos, facing, mirrored, 2, -mechanical.length, 2));
}
}
return rBB;
}
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
Vec3i offsetDirectional = getOffsetDir();
TileEntityMechMB master = masterOr(this, this);
int id = getPart(offsetDirectional.getZ(), master);
if (id < 0) {
return false;
}
MechMBPart part = master.mechanical[id];
BlockPos offsetPart = new BlockPos(offsetDirectional.getX(), offsetDirectional.getY(), offsetDirectional.getZ() - master.offsets[id]);
return part.hasCapability(capability, part.world.realToTransformed(facing), offsetPart);
}
@Nullable
@Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
Vec3i offsetDirectional = getOffsetDir();
TileEntityMechMB master = masterOr(this, this);
int id = getPart(offsetDirectional.getZ(), master);
if (id < 0) {
return null;
}
MechMBPart part = master.mechanical[id];
BlockPos offsetPart = new BlockPos(offsetDirectional.getX(), offsetDirectional.getY(), offsetDirectional.getZ() - master.offsets[id]);
return part.getCapability(capability, part.world.realToTransformed(facing), offsetPart);
}
@Override
public void disassemble() {
final double MIN_BREAK = .1;
final double MIN_BREAK_BROKEN = .5;
if (formed) {
TileEntityMechMB master = master(this);
if (master != null) {
int partId = master.getPart(offset.getX(), master);
MechMBPart broken = null;
if (partId >= 0) {
broken = master.mechanical[partId];
}
Set<MechMBPart> failed = new HashSet<>();
for (MechMBPart part : master.mechanical) {
if (master.energyState.getSpeed() > (part == broken ? MIN_BREAK_BROKEN : MIN_BREAK) * part.getMaxSpeed()) {
failed.add(part);
}
}
master.disassemble(failed);
try {
IBlockState state = world.getBlockState(pos);
NonNullList<ItemStack> drops = NonNullList.create();
state.getBlock().getDrops(drops, world, pos, state, 0);
world.setBlockToAir(pos);
for (ItemStack s:drops) {
Block.spawnAsEntity(world, pos, s);
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
}
private void disassemble(Set<MechMBPart> failed) {
if (!world.isRemote && formed) {
formed = false;
world.setBlockState(pos,
blockMetalDecoration0.getDefaultState().withProperty(blockMetalDecoration0.property, HEAVY_ENGINEERING));
world.setBlockState(pos.down(),
blockMetalDecoration0.getDefaultState().withProperty(blockMetalDecoration0.property, HEAVY_ENGINEERING));
for (MechMBPart mech : mechanical) {
if (failed.contains(mech)) {
world.playSound(null, mech.world.getOrigin(), MMB_BREAKING, SoundCategory.BLOCKS, 1, 1);
mech.breakOnFailure(energyState);
} else {
mech.disassemble();
}
for (int l = 0;l<mech.getLength();l++) {
short pattern = mech.getFormPattern(l);
for (int i = 0; i < 9; i++) {
if (((pattern >> i) & 1) != 0) {
BlockPos pos = new BlockPos(i % 3 - 1, i / 3 - 1, -l);
if (mech.world.getBlockState(pos).getBlock() == IndustrialWires.mechanicalMB) {
mech.world.setBlockState(pos, Blocks.AIR.getDefaultState());
}
}
}
}
}
BlockPos otherEnd = offset(pos, facing.getOpposite(), mirrored, 0,
offsets[mechanical.length], 0);
world.setBlockState(otherEnd,
blockMetalDecoration0.getDefaultState().withProperty(blockMetalDecoration0.property, HEAVY_ENGINEERING));
world.setBlockState(otherEnd.down(),
blockMetalDecoration0.getDefaultState().withProperty(blockMetalDecoration0.property, HEAVY_ENGINEERING));
}
}
private EUCapability.IC2EnergyHandler getIC2Cap() {
return ENERGY_IC2 != null ? getCapability(ENERGY_IC2, null) : null;
}
@Override
public boolean emitsEnergyTo(IEnergyAcceptor output, EnumFacing side) {
if (ENERGY_IC2 == null)
return false;
Vec3i offsetDirectional = getOffsetDir();
TileEntityMechMB master = masterOr(this, this);
int id = getPart(offsetDirectional.getZ(), master);
if (id < 0) {
return false;
}
MechMBPart part = master.mechanical[id];
BlockPos offsetPart = new BlockPos(offsetDirectional.getX(), offsetDirectional.getY(), offsetDirectional.getZ() - master.offsets[id]);
EUCapability.IC2EnergyHandler cap = part.getCapability(ENERGY_IC2, part.world.realToTransformed(side), offsetPart);
return cap != null;
}
@Override
public double getDemandedEnergy() {
EUCapability.IC2EnergyHandler cap = getIC2Cap();
return cap != null ? cap.getDemandedEnergy() : 0;
}
@Override
public int getSinkTier() {
EUCapability.IC2EnergyHandler cap = getIC2Cap();
return cap != null ? cap.getEnergyTier() : 0;
}
@Override
public double injectEnergy(EnumFacing enumFacing, double amount, double voltage) {
EUCapability.IC2EnergyHandler cap = getIC2Cap();
return cap != null ? cap.injectEnergy(enumFacing, amount, voltage) : 0;
}
@Override
public boolean acceptsEnergyFrom(IEnergyEmitter input, EnumFacing side) {
if (ENERGY_IC2 == null)
return false;
Vec3i offsetDirectional = getOffsetDir();
TileEntityMechMB master = masterOr(this, this);
int id = getPart(offsetDirectional.getZ(), master);
if (id < 0) {
return false;
}
MechMBPart part = master.mechanical[id];
BlockPos offsetPart = new BlockPos(offsetDirectional.getX(), offsetDirectional.getY(), offsetDirectional.getZ() - master.offsets[id]);
EUCapability.IC2EnergyHandler cap = part.getCapability(ENERGY_IC2, part.world.realToTransformed(side), offsetPart);
return cap != null;
}
@Override
public double getOfferedEnergy() {
EUCapability.IC2EnergyHandler cap = getIC2Cap();
return cap != null ? cap.getOfferedEnergy() : 0;
}
@Override
public void drawEnergy(double amount) {
EUCapability.IC2EnergyHandler cap = getIC2Cap();
if (cap != null) {
cap.drawEnergy(amount);
}
}
@Override
public int getSourceTier() {
EUCapability.IC2EnergyHandler cap = getIC2Cap();
return cap != null ? cap.getEnergyTier() : 0;
}
@Override
public void invalidate() {
if (!world.isRemote && !firstTick)
Compat.unloadIC2Tile.accept(this);
else if (world.isRemote)
CLIENT_MASTER_BY_POS.remove(pos);
firstTick = true;
if (energyState!=null)
energyState.invalid = true;
super.invalidate();
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
if (!world.isRemote && !firstTick)
Compat.unloadIC2Tile.accept(this);
else if (world.isRemote)
CLIENT_MASTER_BY_POS.remove(pos);
if (energyState!=null)
energyState.invalid = true;
firstTick = true;
}
@Override
public boolean interact(@Nonnull EnumFacing side, @Nonnull EntityPlayer player, @Nonnull EnumHand hand,
@Nonnull ItemStack heldItem, float hitX, float hitY, float hitZ) {
TileEntityMechMB master = masterOr(this, this);
int id = getPart(getOffsetDir().getZ(), master);
if (id >= 0) {
MechMBPart part = master.mechanical[id];
side = part.world.realToTransformed(side);
int ret = part.interact(side, getOffsetDir().add(0, 0, - master.offsets[id]),
player, hand, heldItem);
if (ret>=0) {
if ((ret&1)!=0) {
IBlockState state = world.getBlockState(master.pos);
world.notifyBlockUpdate(master.pos, state, state, 3);
world.addBlockEvent(master.pos, state.getBlock(), 255, id);
}
return true;
}
}
return false;
}
private BlockPos getOffsetDir() {
BlockPos offset = getOffset(BlockPos.NULL_VECTOR, facing, mirrored, this.offset);
return new BlockPos(offset.getX(), offset.getZ(), offset.getY());
}
@Override
public int getStrongRSOutput(@Nonnull IBlockState state, @Nonnull EnumFacing side) {
TileEntityMechMB master = masterOr(this, this);
int id = getPart(getOffsetDir().getZ(), master);
if (id >= 0 && master.mechanical[id] instanceof IRedstoneOutput) {
MechMBPart part = master.mechanical[id];
return ((IRedstoneOutput) part).getStrongRSOutput(state,
part.world.realToTransformed(side));
}
return 0;
}
@Override
public boolean canConnectRedstone(@Nonnull IBlockState state, @Nonnull EnumFacing side) {
TileEntityMechMB master = masterOr(this, this);
int id = getPart(getOffsetDir().getZ(), master);
if (id >= 0 && master.mechanical[id] instanceof IRedstoneOutput) {
MechMBPart part = master.mechanical[id];
return ((IRedstoneOutput) part).canConnectRedstone(state,
part.world.realToTransformed(side));
}
return false;
}
@Override
public AxisAlignedBB getBoundingBoxNoRot() {
Vec3i offset = getOffsetDir();
TileEntityMechMB master = masterOr(this, this);
if (master==this&&!offset.equals(Vec3i.NULL_VECTOR))
return new AxisAlignedBB(0, 0, 0, 0, 0, 0);
int comp = getPart(offset.getZ(), master);
if (comp < 0) {
if (offset.getZ() == 0) {
return new AxisAlignedBB(0, 0, .25, 1, 1, 1 + offset.getY() * .25);
} else {
return new AxisAlignedBB(0, 0, -offset.getY() * .25, 1, 1, .75);
}
}
MechMBPart part = master.mechanical[comp];
BlockPos offsetPart = new BlockPos(offset.getX(), offset.getY(), offset.getZ() - master.offsets[comp]);
return part.getBoundingBox(offsetPart);
}
public AxisAlignedBB aabb = null;
@Override
public AxisAlignedBB getBoundingBox() {
if (aabb == null || aabb.minX==aabb.maxX)
{
aabb = IBlockBoundsDirectional.super.getBoundingBox();
}
return aabb;
}
}

View file

@ -0,0 +1,108 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.hv;
import blusunrize.immersiveengineering.api.IEProperties;
import malte0811.industrialwires.blocks.BlockIWBase;
import malte0811.industrialwires.blocks.IMetaEnum;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class BlockGeneralHV extends BlockIWBase implements IMetaEnum {
public static final PropertyEnum<BlockTypes_GeneralHV> PROPERTY = PropertyEnum.create("type",
BlockTypes_GeneralHV.class);
public static final String NAME = "general_hv";
public BlockGeneralHV() {
super(Material.IRON, NAME);
}
@Override
protected IProperty[] getProperties() {
return new IProperty[] {
IEProperties.BOOLEANS[0], PROPERTY, IEProperties.FACING_HORIZONTAL
};
}
@Override
public boolean isTopSolid(IBlockState state) {
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
@Override
public boolean isFullBlock(IBlockState state) {
return false;
}
@Override
public boolean isFullCube(IBlockState state) {
return false;
}
@Nonnull
@Override
public IBlockState getActualState(@Nonnull IBlockState state, IBlockAccess worldIn, BlockPos pos) {
state = super.getActualState(state, worldIn, pos);
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof TileEntityDischargeMeter)
state = state.withProperty(IEProperties.BOOLEANS[0], ((TileEntityDischargeMeter) te).hasWire);
return state;
}
@Nullable
@Override
public TileEntity createTileEntity(@Nonnull World world, @Nonnull IBlockState state) {
switch (state.getValue(PROPERTY)) {
case DISCHARGE_METER:
return new TileEntityDischargeMeter();
}
return null;
}
@Override
public BlockTypes_GeneralHV[] getValues() {
return BlockTypes_GeneralHV.values();
}
@Override
public int getMetaFromState(IBlockState state) {
return state.getValue(PROPERTY).ordinal();
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty(PROPERTY, getValues()[meta]);
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
}

View file

@ -0,0 +1,111 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.hv;
import blusunrize.immersiveengineering.api.IEProperties;
import malte0811.industrialwires.blocks.BlockIWMultiblock;
import malte0811.industrialwires.blocks.IMetaEnum;
import malte0811.industrialwires.blocks.IWProperties;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class BlockHVMultiblocks extends BlockIWMultiblock implements IMetaEnum {
public static final PropertyEnum<BlockTypes_HVMultiblocks> type = PropertyEnum.create("type", BlockTypes_HVMultiblocks.class);
public static final String NAME = "hv_multiblock";
public BlockHVMultiblocks() {
super(Material.IRON, NAME);
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
// No MB's in the creative inventory!
}
@Override
public boolean canRenderInLayer(IBlockState state, BlockRenderLayer layer) {
if (state.getValue(IWProperties.MARX_TYPE)!= IWProperties.MarxType.CONNECTOR)
return super.canRenderInLayer(state, layer);
else
return layer==BlockRenderLayer.TRANSLUCENT||layer==BlockRenderLayer.SOLID;
}
@Override
protected IProperty[] getProperties() {
return new IProperty[]{type, IWProperties.MARX_TYPE, IEProperties.FACING_HORIZONTAL, IEProperties.BOOLEANS[0]};
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Nullable
@Override
public TileEntity createTileEntity(@Nonnull World world, @Nonnull IBlockState state) {
switch (state.getValue(type)) {
case MARX:
return new TileEntityMarx(state.getValue(IEProperties.FACING_HORIZONTAL), state.getValue(IWProperties.MARX_TYPE), state.getValue(IEProperties.BOOLEANS[0]));
}
return null;
}
@Override
public int getMetaFromState(IBlockState state) {
return state.getValue(type).getMeta();
}
@Nonnull
@Override
public IBlockState getActualState(@Nonnull IBlockState state, IBlockAccess worldIn, BlockPos pos) {
IBlockState ret = super.getActualState(state, worldIn, pos);
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof TileEntityMarx) {
ret = ret.withProperty(IWProperties.MARX_TYPE, ((TileEntityMarx) te).type);
ret = ret.withProperty(IEProperties.BOOLEANS[0], ((TileEntityMarx)te).mirrored);
}
return ret;
}
@Nonnull
@Override
protected BlockStateContainer createBlockState() {
BlockStateContainer base = super.createBlockState();
return new ExtendedBlockState(this, base.getProperties().toArray(new IProperty[0]), new IUnlistedProperty[]{
IEProperties.CONNECTIONS
});
}
@Override
public Object[] getValues() {
return BlockTypes_HVMultiblocks.values();
}
}

View file

@ -1,25 +1,25 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks.hv;
import blusunrize.immersiveengineering.api.IEProperties;
import malte0811.industrialWires.blocks.TileEntityJacobsLadder.LadderSize;
import malte0811.industrialwires.blocks.BlockIWBase;
import malte0811.industrialwires.blocks.IMetaEnum;
import malte0811.industrialwires.blocks.IPlacementCheck;
import malte0811.industrialwires.blocks.hv.TileEntityJacobsLadder.LadderSize;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
@ -28,7 +28,6 @@ import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
@ -43,10 +42,11 @@ import net.minecraft.world.World;
import javax.annotation.Nonnull;
public class BlockJacobsLadder extends BlockIWBase implements IMetaEnum, IPlacementCheck {
public static final String NAME = "jacobs_ladder";
private static PropertyEnum<LadderSize> size_property = PropertyEnum.create("size", LadderSize.class);
public BlockJacobsLadder() {
super(Material.IRON, "jacobs_ladder");
super(Material.IRON, NAME);
}
@Nonnull
@ -75,11 +75,11 @@ public class BlockJacobsLadder extends BlockIWBase implements IMetaEnum, IPlacem
@Nonnull
@Override
public IBlockState getStateFromMeta(int meta) {
return super.getStateFromMeta(meta).withProperty(size_property, LadderSize.values()[meta]);
return super.getStateFromMeta(meta).withProperty(size_property, TileEntityJacobsLadder.LadderSize.values()[meta]);
}
@Override
public void getSubBlocks(@Nonnull Item itemIn, CreativeTabs tab, NonNullList<ItemStack> list) {
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
for (int i = 0; i < LadderSize.values().length; i++) {
list.add(new ItemStack(this, 1, i));
}
@ -143,24 +143,16 @@ public class BlockJacobsLadder extends BlockIWBase implements IMetaEnum, IPlacem
return new ItemStack(this, 1, getMetaFromState(state));
}
@Override
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) {
super.onEntityCollidedWithBlock(worldIn, pos, state, entityIn);
public void onEntityCollision(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) {
super.onEntityCollision(worldIn, pos, state, entityIn);
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof TileEntityJacobsLadder) {
((TileEntityJacobsLadder) te).onEntityTouch(entityIn);
}
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof TileEntityJacobsLadder) {
return ((TileEntityJacobsLadder) te).onActivated(playerIn, hand);
}
return super.onBlockActivated(worldIn, pos, state, playerIn, hand, side, hitX, hitY, hitZ);
}
@Override
public boolean canPlaceBlockAt(World w, BlockPos pos, ItemStack stack) {
int dummyCount = LadderSize.values()[stack.getMetadata()].dummyCount;
@ -175,6 +167,6 @@ public class BlockJacobsLadder extends BlockIWBase implements IMetaEnum, IPlacem
@Override
public boolean rotateBlock(World world, @Nonnull BlockPos pos, @Nonnull EnumFacing axis) {
TileEntity te = world.getTileEntity(pos);
return te instanceof TileEntityJacobsLadder && ((TileEntityJacobsLadder) te).rotate(world, pos, axis);
return te instanceof TileEntityJacobsLadder && ((TileEntityJacobsLadder) te).rotate(world, pos);
}
}

View file

@ -1,23 +1,27 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.util;
package malte0811.industrialwires.blocks.hv;
public interface TriConsumer<A, B, C> {
void accept(A a, B b, C c);
import net.minecraft.util.IStringSerializable;
public enum BlockTypes_GeneralHV implements IStringSerializable{
DISCHARGE_METER;
@Override
public String getName() {
return name().toLowerCase();
}
}

View file

@ -0,0 +1,38 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.hv;
import blusunrize.immersiveengineering.common.blocks.BlockIEBase;
public enum BlockTypes_HVMultiblocks implements BlockIEBase.IBlockEnum {
MARX;
@Override
public int getMeta() {
return ordinal();
}
@Override
public boolean listForCreative() {
return false;
}
@Override
public String getName() {
return name().toLowerCase();
}
}

View file

@ -0,0 +1,137 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.hv;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IPlayerInteraction;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IBlockBoundsIW.IBlockBoundsDirectional;
import malte0811.industrialwires.blocks.TileEntityIWBase;
import malte0811.industrialwires.hv.IMarxTarget;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.text.TextComponentTranslation;
import javax.annotation.Nonnull;
public class TileEntityDischargeMeter extends TileEntityIWBase implements IPlayerInteraction, IMarxTarget,
IBlockBoundsDirectional, IDirectionalTile {
private static final String HAS_WIRE = "hasWire";
private static final String FACING = "facing";
private static final String LAST_DISCHARGE = "last";
boolean hasWire;
EnumFacing facing = EnumFacing.NORTH;
double lastDischarge = -1;
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
out.setByte(FACING, (byte) facing.getHorizontalIndex());
out.setBoolean(HAS_WIRE, hasWire);
out.setDouble(LAST_DISCHARGE, lastDischarge);
}
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
hasWire = in.getBoolean(HAS_WIRE);
facing = EnumFacing.byHorizontalIndex(in.getByte(FACING));
lastDischarge = in.getDouble(LAST_DISCHARGE);
aabb = null;
}
@Override
public boolean interact(@Nonnull EnumFacing side, @Nonnull EntityPlayer player, @Nonnull EnumHand hand,
@Nonnull ItemStack heldItem, float hitX, float hitY, float hitZ) {
if (!world.isRemote) {
if (hasWire)
return false;
if (ApiUtils.compareToOreName(heldItem, "wireAluminum")) {
hasWire = true;
heldItem.shrink(1);
triggerRenderUpdate();
} else if (lastDischarge > 0) {
player.sendMessage(new TextComponentTranslation(IndustrialWires.MODID + ".chat.marxEnergy",
String.format("%.1f", lastDischarge/1e3)));
lastDischarge = -1;
}
markDirty();
}
return true;
}
@Override
public boolean onHit(double energy, TileEntityMarx master) {
if (hasWire) {
hasWire = false;
lastDischarge = energy;
triggerRenderUpdate();
markDirty();
return true;
}
return false;
}
AxisAlignedBB aabb = null;
@Override
public AxisAlignedBB getBoundingBoxNoRot() {
return new AxisAlignedBB(1F/16, 0, 5F/16,
10F/16, (hasWire?15F:14F)/16, 11F/16);
}
@Override
public AxisAlignedBB getBoundingBox() {
if (aabb==null) {
aabb = IBlockBoundsDirectional.super.getBoundingBox();
}
return aabb;
}
@Nonnull
@Override
public EnumFacing getFacing() {
return facing;
}
@Override
public void setFacing(@Nonnull EnumFacing facing) {
this.facing = facing;
}
@Override
public int getFacingLimitation() {
return 2;
}
@Override
public boolean mirrorFacingOnPlacement(@Nonnull EntityLivingBase placer) {
return false;
}
@Override
public boolean canHammerRotate(@Nonnull EnumFacing side, float hitX, float hitY, float hitZ, @Nonnull EntityLivingBase entity) {
return false;
}
@Override
public boolean canRotate(@Nonnull EnumFacing axis) {
return false;
}
}

View file

@ -1,35 +1,39 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks;
package malte0811.industrialwires.blocks.hv;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import blusunrize.immersiveengineering.common.blocks.TileEntityIEBase;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.event.EnergyTileUnloadEvent;
import com.elytradev.mirage.lighting.IColoredLight;
import com.elytradev.mirage.lighting.Light;
import ic2.api.energy.tile.IEnergyEmitter;
import ic2.api.energy.tile.IEnergySink;
import malte0811.industrialWires.IWConfig;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.network.MessageTileSyncIW;
import malte0811.industrialWires.util.Beziers;
import malte0811.industrialWires.util.DualEnergyStorage;
import malte0811.industrialwires.IWConfig;
import malte0811.industrialwires.IWDamageSources;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IBlockBoundsIW;
import malte0811.industrialwires.blocks.IHasDummyBlocksIW;
import malte0811.industrialwires.blocks.ISyncReceiver;
import malte0811.industrialwires.compat.Compat;
import malte0811.industrialwires.network.MessageTileSyncIW;
import malte0811.industrialwires.util.Beziers;
import malte0811.industrialwires.util.ConversionUtil;
import malte0811.industrialwires.util.JouleEnergyStorage;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
@ -40,40 +44,51 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickable, IHasDummyBlocksIW, ISyncReceiver, IEnergySink, IBlockBoundsIW, IDirectionalTile {
import static malte0811.industrialwires.IndustrialWires.hasIC2;
import static malte0811.industrialwires.util.MiscUtils.interpolate;
@Optional.InterfaceList({
@Optional.Interface(modid = "ic2", iface = "ic2.api.energy.tile.IEnergySink"),
@Optional.Interface(modid = "mirage", iface = "com.elytradev.mirage.lighting.IColoredLight")
})
public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickable, IHasDummyBlocksIW, ISyncReceiver,
IEnergySink, IBlockBoundsIW, IDirectionalTile, IColoredLight, IEBlockInterfaces.IPlayerInteraction {
public EnumFacing facing = EnumFacing.NORTH;
private DualEnergyStorage energy;
private JouleEnergyStorage energy;
public LadderSize size;
public Vec3d[] controls;
//first and last move along the "rails", only the middle points move in bezier curves
public Vec3d[][] controlControls;
private Vec3d[][] controlControls;
// movement of the controls in blocks/tick
public Vec3d[] controlMovement;
private double t = 0;
public int dummy = 0;
private int dummy = 0;
public int timeTillActive = -1;
private double tStep = 0;
private double consumtionEU;
private boolean addedToIC2Net = false;
private double consumtionJoule;
private int soundPhase;
private Vec3d soundPos;
public double salt;
public TileEntityJacobsLadder(LadderSize s) {
TileEntityJacobsLadder(LadderSize s) {
size = s;
initControl();
}
@ -88,21 +103,26 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
controlControls = new Vec3d[size.arcPoints - 2][size.movementPoints];
controlMovement = new Vec3d[size.arcPoints];
int sizeId = size.ordinal();
consumtionEU = IWConfig.HVStuff.jacobsUsageEU[sizeId];
energy = new DualEnergyStorage(20 * consumtionEU, 2 * consumtionEU);
consumtionJoule = IWConfig.HVStuff.jacobsUsageWatt[sizeId];
energy = new JouleEnergyStorage(20 * consumtionJoule,
40 * consumtionJoule);
}
@Override
public void onLoad() {
super.onLoad();
Compat.loadIC2Tile.accept(this);
}
@Override
public void update() {
ApiUtils.checkForNeedlessTicking(this);
if (isDummy()) {
return;
}
if (!world.isRemote) {
if (!addedToIC2Net) {
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
addedToIC2Net = true;
}
if ((controlControls[0][0] == null || timeTillActive == -1 || t >= 1) && energy.getEnergyStoredEU() >= 2 * consumtionEU) {
if ((controlControls[0][0] == null || timeTillActive == -1 || t >= 1)
&& energy.getEnergyStoredJ() >= 2 * consumtionJoule) {
for (int j = 0; j < size.movementPoints; j++) {
double y = j * (size.height + size.extraHeight) / (double) (size.movementPoints - 1) + size.innerPointOffset;
double width = widthFromHeight(y);
@ -119,9 +139,9 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
tStep = 1D / (int) (.875 * size.tickToTop + world.rand.nextInt(size.tickToTop / 4));
IndustrialWires.packetHandler.sendToAll(new MessageTileSyncIW(this, writeArcStarter()));
} else if (timeTillActive == 0 && t < 1) {
double extracted = energy.extractEU(consumtionEU, false);
if (extracted >= consumtionEU) {
energy.extractEU(consumtionEU, true);
double extracted = energy.extract(consumtionJoule, 1, true);
if (extracted >= consumtionJoule) {
energy.extract(consumtionJoule, 1, false);
} else {
timeTillActive = -1 - size.delay;
NBTTagCompound nbt = new NBTTagCompound();
@ -200,7 +220,7 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
initControl();
}
dummy = nbt.getInteger("dummy");
energy = DualEnergyStorage.readFromNBT(nbt.getCompoundTag("energy"));
energy.readFromNBT(nbt.getCompoundTag("energy"));
facing = EnumFacing.HORIZONTALS[nbt.getInteger("facing")];
salt = nbt.getDouble("salt");
}
@ -224,6 +244,7 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
return nbt;
}
@SideOnly(Side.CLIENT)
private void readArcStarter(NBTTagCompound nbt) {
controlControls = read2DVecArray(nbt.getTagList("ctrlCtrl", 9));
tStep = nbt.getDouble("tStep");
@ -296,6 +317,7 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
}
@Override
@SideOnly(Side.CLIENT)
public void onSync(NBTTagCompound nbt) {
if (nbt.hasKey("salt")) {
salt = nbt.getDouble("salt");
@ -308,7 +330,7 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
}
}
public boolean isActive() {
private boolean isActive() {
if (isDummy()) {
TileEntity master = world.getTileEntity(pos.down(dummy));
return master instanceof TileEntityJacobsLadder && ((TileEntityJacobsLadder) master).isActive();
@ -326,11 +348,12 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
}
private void hurtEntity(Entity e) {
e.attackEntityFrom(new DamageSource("industrialwires.jacobs_ladder"), IWConfig.HVStuff.jacobsBaseDmg * (size.ordinal() + 1));
e.attackEntityFrom(IWDamageSources.dmg_jacobs, IWConfig.HVStuff.jacobsBaseDmg * (size.ordinal() + 1));
}
public boolean onActivated(EntityPlayer player, EnumHand hand) {
ItemStack heldItem = player.getHeldItem(hand);
@Override
public boolean interact(@Nonnull EnumFacing side, @Nonnull EntityPlayer player,@Nonnull EnumHand hand,
@Nonnull ItemStack heldItem, float hitX, float hitY, float hitZ) {
TileEntity masterTE = dummy == 0 ? this : world.getTileEntity(pos.down(dummy));
if (masterTE instanceof TileEntityJacobsLadder) {
TileEntityJacobsLadder master = (TileEntityJacobsLadder) masterTE;
@ -366,7 +389,7 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
return false;
}
public boolean rotate(World world, BlockPos pos, EnumFacing axis) {
public boolean rotate(World world, BlockPos pos) {
if (isActive()) {
return false;
}
@ -392,21 +415,25 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
//ENERGY
@Override
@Optional.Method(modid = "ic2")
public double getDemandedEnergy() {
return energy.getEURequested();
return energy.getRequested(ConversionUtil.euPerJoule());
}
@Override
@Optional.Method(modid = "ic2")
public int getSinkTier() {
return 4;
}
@Override
@Optional.Method(modid = "ic2")
public double injectEnergy(EnumFacing dir, double amount, double voltage) {
return amount - energy.insertEU(amount, true);
return amount - energy.insert(amount, ConversionUtil.joulesPerEu(), true);
}
@Override
@Optional.Method(modid = "ic2")
public boolean acceptsEnergyFrom(IEnergyEmitter iEnergyEmitter, EnumFacing enumFacing) {
return !isDummy() && enumFacing == facing;
}
@ -421,7 +448,7 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (hasCapability(capability, facing)) {
if (capability == CapabilityEnergy.ENERGY) {
return (T) new EnergyCap();
return CapabilityEnergy.ENERGY.cast(energy);
}
}
return null;
@ -429,24 +456,24 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
@Override
public void onChunkUnload() {
if (!world.isRemote && addedToIC2Net)
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
addedToIC2Net = false;
if (hasIC2) {
Compat.unloadIC2Tile.accept(this);
}
super.onChunkUnload();
}
@Override
public void invalidate() {
if (!world.isRemote && addedToIC2Net) {
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
} else if (world.isRemote) {
if (hasIC2)
Compat.unloadIC2Tile.accept(this);
if (world.isRemote) {
//stop sound
IndustrialWires.proxy.playJacobsLadderSound(this, -1, soundPos);
}
addedToIC2Net = false;
super.invalidate();
}
@Nonnull
@Override
public AxisAlignedBB getRenderBoundingBox() {
@ -506,6 +533,47 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
return false;
}
private static final float[] saltColor = {1, 190 / 255F, 50 / 255F};
private static final float[] airColor = {1, .85F, 1};
private static final int factor = 20;
private static final double smallMin = Math.exp(-.5);
private static final double normalMin = Math.exp(-.25 * factor);
private static final double hugeMin = Math.exp(-.75 * factor);
public static float[] getColor(double t, double salt, LadderSize size) {
salt = Math.min(salt, 1);
double saltyness = 0;
double t2 = t - .5;
switch (size) {
case SMALL:
saltyness = salt * (1 - .9 * (Math.exp(-Math.abs(t2)) - smallMin));
break;
case NORMAL:
saltyness = salt * (1 - .9 * (Math.exp(-factor * t2 * t2) - normalMin));
break;
case HUGE:
saltyness = salt * (1 - .9 * (Math.exp(-Math.abs(factor * t2 * t2 * t2)) - hugeMin));
break;
}
return interpolate(saltyness, saltColor, 1 - saltyness, airColor);
}
@Nullable
@Override
@SideOnly(Side.CLIENT)
@Optional.Method(modid = "mirage")
public Light getColoredLight() {
if (timeTillActive == 0) {
float[] color = getColor(0, salt, size);
return Light.builder().pos(pos.getX()+.5,
Beziers.getPoint(.5, controls).y+pos.getY()+size.bottomDistance+1,
pos.getZ()+.5)
.color(color[0], color[1], color[2], 1)
.radius(size.soundVolume/3)
.build();
}
return null;
}
public enum LadderSize implements IStringSerializable {
/*
@ -566,37 +634,4 @@ public class TileEntityJacobsLadder extends TileEntityIEBase implements ITickabl
return name().toLowerCase();
}
}
public class EnergyCap implements IEnergyStorage {
@Override
public int receiveEnergy(int maxReceive, boolean simulate) {
return (int) energy.insertIF(maxReceive, !simulate);
}
@Override
public int extractEnergy(int maxExtract, boolean simulate) {
return 0;
}
@Override
public int getEnergyStored() {
return (int) energy.getEnergyStoredIF();
}
@Override
public int getMaxEnergyStored() {
return (int) energy.getMaxStoredIF();
}
@Override
public boolean canExtract() {
return false;
}
@Override
public boolean canReceive() {
return true;
}
}
}

View file

@ -0,0 +1,823 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.hv;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.api.IEProperties;
import blusunrize.immersiveengineering.api.TargetingInfo;
import blusunrize.immersiveengineering.api.energy.wires.IImmersiveConnectable;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import blusunrize.immersiveengineering.api.energy.wires.redstone.IRedstoneConnector;
import blusunrize.immersiveengineering.api.energy.wires.redstone.RedstoneWireNetwork;
import blusunrize.immersiveengineering.common.IESaveData;
import blusunrize.immersiveengineering.common.blocks.BlockTypes_MetalsIE;
import blusunrize.immersiveengineering.common.blocks.metal.*;
import blusunrize.immersiveengineering.common.util.Utils;
import blusunrize.immersiveengineering.common.util.chickenbones.Matrix4;
import com.elytradev.mirage.event.GatherLightsEvent;
import com.elytradev.mirage.lighting.Light;
import malte0811.industrialwires.*;
import malte0811.industrialwires.blocks.IBlockBoundsIW;
import malte0811.industrialwires.blocks.ISyncReceiver;
import malte0811.industrialwires.blocks.IWProperties;
import malte0811.industrialwires.blocks.TileEntityIWMultiblock;
import malte0811.industrialwires.hv.IMarxTarget;
import malte0811.industrialwires.hv.MarxOreHandler;
import malte0811.industrialwires.network.MessageTileSyncIW;
import malte0811.industrialwires.util.ConversionUtil;
import malte0811.industrialwires.util.JouleEnergyStorage;
import malte0811.industrialwires.util.MiscUtils;
import malte0811.industrialwires.wires.MixedWireType;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import static blusunrize.immersiveengineering.api.energy.wires.WireType.REDSTONE_CATEGORY;
import static malte0811.industrialwires.blocks.hv.TileEntityMarx.FiringState.FIRE;
import static malte0811.industrialwires.util.MiscUtils.offset;
import static malte0811.industrialwires.util.NBTKeys.*;
import static malte0811.industrialwires.wires.MixedWireType.IC2_HV_CAT;
import static net.minecraft.item.EnumDyeColor.*;
/**
* Channel: Purpose
* White: Coarse Vcharge
* Orange: Coarse bottom cap voltage
* Magenta: Coarse top voltage
* LBlue: Firing trigger
* Yellow: Fine Vcharge
* Lime: Fine bottom cap voltage
* Pink: Fine top cap voltage
*/
@Mod.EventBusSubscriber
public class TileEntityMarx extends TileEntityIWMultiblock implements ITickable, ISyncReceiver, IBlockBoundsIW, IImmersiveConnectable, IMixedConnector,
IRedstoneConnector {
//Only relevant client-side.
private static final Set<TileEntityMarx> FIRING_GENERATORS = Collections.newSetFromMap(new WeakHashMap<>());
private double rcTimeConst;
private double timeFactor;
private double timeFactorBottom;
private final static double CAPACITANCE = 1.6e-6;
private final static double MAX_VOLTAGE = 250e3;
public IWProperties.MarxType type = IWProperties.MarxType.NO_MODEL;
private int stageCount = 0;
public FiringState state = FiringState.CHARGING;
public Discharge dischargeData;
// Voltage=10*storedJ
private JouleEnergyStorage storage = new JouleEnergyStorage(50_000, 20*32_000);
private boolean hasConnection;
private double[] capVoltages;
private int voltageControl = 0;
private boolean loaded = false;
private double leftover;
private long lastUpdate = -1;
TileEntityMarx(EnumFacing facing, IWProperties.MarxType type, boolean mirrored) {
this.facing = facing;
this.type = type;
this.mirrored = mirrored;
}
public TileEntityMarx() {}
@Override
public void writeNBT(NBTTagCompound out, boolean updatePacket) {
super.writeNBT(out, updatePacket);
MiscUtils.writeConnsToNBT(out, this);
out.setInteger(TYPE, type.ordinal());
out.setInteger(STAGES, stageCount);
out.setBoolean(HAS_CONN, hasConnection);
storage.writeToNbt(out, ENERGY);
NBTTagList voltages = new NBTTagList();
if (capVoltages != null) {
for (int i = 0; i < stageCount; i++) {
voltages.appendTag(new NBTTagDouble(capVoltages[i]));
}
}
out.setTag(CAP_VOLTAGES, voltages);
}
@Override
public void readNBT(NBTTagCompound in, boolean updatePacket) {
super.readNBT(in, updatePacket);
MiscUtils.loadConnsFromNBT(in, this);
type = IWProperties.MarxType.values()[in.getInteger(TYPE)];
setStageCount(in.getInteger(STAGES));
NBTTagList voltages = in.getTagList(CAP_VOLTAGES, 6);//DOUBLE
capVoltages = new double[stageCount];
for (int i = 0;i<stageCount;i++) {
capVoltages[i] = voltages.getDoubleAt(i);
}
storage.readFromNBT(in.getCompoundTag(ENERGY));
hasConnection = in.getBoolean(HAS_CONN);
collisionAabb = null;
renderAabb = null;
}
@Nonnull
@Override
protected BlockPos getOrigin() {
return getPos().subtract(offset).offset(facing.getOpposite(), 3);
}
@Override
public IBlockState getOriginalBlock() {
int forward = getForward();
int right = getRight();
int up = offset.getY();
if (forward==0) {
return IEObjects.blockMetalDevice0.getDefaultState().withProperty(IEObjects.blockMetalDevice0.property, BlockTypes_MetalDevice0.CAPACITOR_HV);
} else if (forward==-1) {
return IEObjects.blockConnectors.getDefaultState().withProperty(IEObjects.blockConnectors.property, BlockTypes_Connector.RELAY_HV)
.withProperty(IEProperties.FACING_ALL, facing);
} else if (forward==4&&up==0&&right==1) {
return IEObjects.blockStorage.getDefaultState().withProperty(IEObjects.blockStorage.property, BlockTypes_MetalsIE.STEEL);
} else if (forward>0) {
if ((right==0&&up==0)||(right==1&&up==stageCount-1)) {
return IEObjects.blockMetalDecoration1.getDefaultState().withProperty(IEObjects.blockMetalDecoration1.property, BlockTypes_MetalDecoration1.STEEL_FENCE);
} else {
return IEObjects.blockMetalDecoration2.getDefaultState().withProperty(IEObjects.blockMetalDecoration2.property, BlockTypes_MetalDecoration2.STEEL_WALLMOUNT)
.withProperty(IEProperties.INT_4, 1-right).withProperty(IEProperties.FACING_ALL, facing.getOpposite());
}
} else if (forward==-2) {
return IEObjects.blockMetalDecoration0.getDefaultState().withProperty(IEObjects.blockMetalDecoration0.property, BlockTypes_MetalDecoration0.HEAVY_ENGINEERING);
} else if (right==0) {
return IEObjects.blockConnectors.getDefaultState().withProperty(IEObjects.blockConnectors.property, BlockTypes_Connector.CONNECTOR_REDSTONE)
.withProperty(IEProperties.FACING_ALL, facing);
} else {
return IEObjects.blockConnectors.getDefaultState().withProperty(IEObjects.blockConnectors.property, BlockTypes_Connector.CONNECTOR_HV)
.withProperty(IEProperties.FACING_ALL, facing);
}
}
@Override
public void disassemble() {
boolean active = formed && !world.isRemote;
IndustrialWires.logger.info("Calling disassemble for {}, active {}", pos, active);
super.disassemble();
if (active) {
final int forward = -1;
BlockPos master = pos.subtract(offset);
ItemStack coil = new ItemStack(IEObjects.itemWireCoil, 1, 2);
WireType type = WireType.STEEL;
TargetingInfo dummy = new TargetingInfo(EnumFacing.DOWN, 0, 0, 0);
for (int up = 0; up < stageCount - 1; ++up) {
for (int right = 0; right < 2; ++right) {
BlockPos lowerPos = offset(master, facing, mirrored, right, forward, up);
BlockPos upperPos = lowerPos.up();
IndustrialWires.logger.info("Lower: {}, upper: {}, master: {}", lowerPos, upperPos, master);
TileEntity lowerTE = world.getTileEntity(lowerPos);
if (!(lowerTE instanceof IImmersiveConnectable)) {
world.spawnEntity(new EntityItem(world, lowerPos.getX() + .5, lowerPos.getY() + .5,
lowerPos.getZ() + .5, coil));
continue;
}
TileEntity upperTE = world.getTileEntity(upperPos);
if (!(upperTE instanceof IImmersiveConnectable)) {
world.spawnEntity(new EntityItem(world, lowerPos.getX() + .5, lowerPos.getY() + .5,
lowerPos.getZ() + .5, coil));
continue;
}
IImmersiveConnectable lowerIIC = (IImmersiveConnectable) lowerTE;
IImmersiveConnectable upperIIC = (IImmersiveConnectable) upperTE;
ImmersiveNetHandler.Connection conn = ImmersiveNetHandler.INSTANCE.addAndGetConnection(world,
lowerPos, upperPos, 1, type);
lowerIIC.connectCable(type, dummy, upperIIC);
upperIIC.connectCable(type, dummy, lowerIIC);
ImmersiveNetHandler.INSTANCE.addBlockData(world, conn);
IESaveData.setDirty(world.provider.getDimension());
lowerTE.markDirty();
IBlockState state = world.getBlockState(lowerPos);
world.notifyBlockUpdate(lowerPos, state, state, 3);
upperTE.markDirty();
state = world.getBlockState(upperPos);
world.notifyBlockUpdate(upperPos, state, state, 3);
}
}
}
}
@Override
public void update() {
ApiUtils.checkForNeedlessTicking(this);
FIRING_GENERATORS.remove(this);
switch (state) {
case NEXT_TICK:
if (world.isRemote) {
FIRING_GENERATORS.add(this);
IndustrialWires.proxy.playMarxBang(this, getMiddle(), (float) getNormedEnergy(dischargeData.energy));
} else {
fire();
}
state = FIRE;
break;
case FIRE:
state = FiringState.CHARGING;
break;
}
if (!world.isRemote&&type== IWProperties.MarxType.BOTTOM) {
if (capVoltages == null || capVoltages.length != stageCount) {
capVoltages = new double[stageCount];
}
final double oldTopVoltage = capVoltages[stageCount - 1];
final double oldBottomVoltage = capVoltages[0];
for (int i = stageCount - 1; i > 0; i--) {
double oldVoltage = capVoltages[i];
double u0 = capVoltages[i - 1];
capVoltages[i] = u0 - (u0 - oldVoltage) * timeFactor;
capVoltages[i - 1] -= capVoltages[i] - oldVoltage;
}
//charge bottom cap from storage
double setVoltage = MAX_VOLTAGE * voltageControl / 255F;
double u0 = Math.min(setVoltage, 10 * storage.getEnergyStoredJ());
if (u0 < 0) {
u0 = 0;
}
if (u0 < capVoltages[0] && setVoltage > capVoltages[0]) {
u0 = capVoltages[0];
}
double tmp = u0 - (u0 - oldBottomVoltage) * timeFactorBottom;
double energyUsed = .5 * (tmp * tmp - oldBottomVoltage * oldBottomVoltage) * CAPACITANCE;
if (energyUsed > 0 && storage.extract(energyUsed, 1, true) == energyUsed) {// energyUsed can be negative when discharging the caps
storage.extract(energyUsed, 1, false);
capVoltages[0] = tmp;
} else if (energyUsed <= 0) {
capVoltages[0] = tmp;
}
int delta = (int) (lastUpdate+15-world.getTotalWorldTime());
if (Math.abs(getRSSignalFromVoltage(oldBottomVoltage)-getRSSignalFromVoltage(capVoltages[0]))>delta) {
net.updateValues();
} else if (Math.abs(getRSSignalFromVoltage(oldTopVoltage)-getRSSignalFromVoltage(capVoltages[stageCount-1]))>delta) {
net.updateValues();
}
if (capVoltages[0] > MAX_VOLTAGE * 14.5 / 15) {
state = FiringState.NEXT_TICK;
}
}
leftover = storage.getMaxInPerTick();
}
private void fire() {
if (!world.isRemote) {
//calculate energy
double energyStored = 0;
boolean failed = capVoltages[0]<MAX_VOLTAGE*.5;
double totalVoltage = 0;
for (int i = 0;i<stageCount;i++) {
energyStored += .5*capVoltages[i]*capVoltages[i]*CAPACITANCE;
totalVoltage += capVoltages[i];
capVoltages[i] = 0;
}
if (totalVoltage<.1*MAX_VOLTAGE*stageCount) {
return;
}
failed |= totalVoltage<MAX_VOLTAGE*.3*stageCount;
net.updateValues();
NBTTagCompound data = new NBTTagCompound();
if (failed) {
energyStored = -energyStored;
} else {
int seed = Utils.RAND.nextInt();
genDischarge((float) energyStored, seed);
data.setInteger("randSeed", seed);
handleEntities(energyStored);
handleOreProcessing(energyStored);//After entities to prevent killing the newly dropped items
}
data.setDouble("energy", energyStored);
IndustrialWires.packetHandler.sendToDimension(new MessageTileSyncIW(this, data), world.provider.getDimension());
}
}
private void handleOreProcessing(double energyStored) {
BlockPos bottom = getBottomElectrode();
List<BlockPos> toBreak = new ArrayList<>(stageCount - 2);
int ores = 0;
for (int i = 1;i<stageCount-1;i++) {
BlockPos blockHere = bottom.up(i);
if (!world.isAirBlock(blockHere)) {
toBreak.add(blockHere);
ores++;
}
}
if (ores>0) {
double energyPerOre = energyStored / ores;
for (BlockPos here:toBreak) {
IBlockState state = world.getBlockState(here);
if (state.getBlockHardness(world, here) < 0) {
continue;
}
if (!world.isAirBlock(here)) {
TileEntity te = world.getTileEntity(here);
if (te instanceof IMarxTarget) {
if (((IMarxTarget) te).onHit(energyPerOre, this)) {
continue;
}
}
ItemStack[] out = MarxOreHandler.getYield(world, here, energyPerOre);
for (ItemStack stack : out) {
EntityItem item = new EntityItem(world, here.getX() + .5, here.getY() + .5, here.getZ() + .5, stack);
final double maxMotion = .3;
item.motionX = 2 * maxMotion * (Utils.RAND.nextDouble() - .5);
item.motionY = 2 * maxMotion * (Utils.RAND.nextDouble() - .5);
item.motionZ = 2 * maxMotion * (Utils.RAND.nextDouble() - .5);
world.spawnEntity(item);
}
world.setBlockToAir(here);
}
}
}
}
private void handleEntities(double energyStored) {
double damageDistSqu = Math.sqrt(energyStored/50e3);
double tinnitusDistSqu = Math.sqrt(energyStored)/50;
Vec3d v0 = getMiddle();
AxisAlignedBB aabb = new AxisAlignedBB(v0.x, v0.y, v0.z, v0.x, v0.y, v0.z);
aabb = aabb.grow(0, stageCount / 2. - 1, 0);
aabb = aabb.grow(tinnitusDistSqu);
List<Entity> fools = world.getEntitiesWithinAABB(Entity.class, aabb);
damageDistSqu *= damageDistSqu;
tinnitusDistSqu *= tinnitusDistSqu;
if (IWConfig.HVStuff.marxSoundDamage == 2) {
damageDistSqu = tinnitusDistSqu;
tinnitusDistSqu = -1;
}
for (Entity entity : fools) {
double y;
if (entity.posY<pos.getY()+1) {
y = pos.getY()+1;
} else if (entity.posY>pos.getY()+stageCount-2) {
y = pos.getY()+stageCount-2;
} else {
y = entity.posY;
}
double distSqu = entity.getDistanceSq(v0.x, y, v0.z);
if (distSqu<=damageDistSqu) {
float dmg = (float) (10*stageCount*(1-distSqu/damageDistSqu));
entity.attackEntityFrom(IWDamageSources.dmg_marx, dmg);
}
if (distSqu<=tinnitusDistSqu && entity instanceof EntityPlayer) {
ItemStack helmet = ((EntityPlayer) entity).inventory.armorInventory.get(3);
boolean earMuff = helmet.getItem()==IEObjects.itemEarmuffs;
if (!earMuff&&helmet.hasTagCompound()) {
earMuff = helmet.getTagCompound().hasKey("IE:Earmuffs");
}
if (!earMuff) {
double multipl = Math.min(5, Math.sqrt(stageCount));
int duration = (int) (20*20*(1+multipl*(1-distSqu/tinnitusDistSqu)));
if (IWConfig.HVStuff.marxSoundDamage == 0) {
((EntityPlayer) entity).addPotionEffect(new PotionEffect(IWPotions.tinnitus, duration));
} else {
((EntityPlayer) entity).addPotionEffect(new PotionEffect(Potion.getPotionFromResourceLocation("nausea"), duration));
}
}
}
}
}
private int getRSSignalFromVoltage(double voltage) {
return (int) (Math.round(255 * voltage / MAX_VOLTAGE)&0xff);
}
@Override
public Vec3i getSize() {
return new Vec3i(stageCount, 8, 2);
}
@Override
public void onSync(NBTTagCompound nbt) {
float energy = nbt.getFloat("energy");
if (energy>0) {
genDischarge(energy, nbt.getInteger("randSeed"));
} else {
if (dischargeData==null) {
dischargeData = new Discharge(stageCount);
}
dischargeData.energy = energy;
}
state = FiringState.NEXT_TICK;
}
private void genDischarge(float energy, int seed) {
if (dischargeData==null) {
dischargeData = new Discharge(stageCount);
}
dischargeData.energy = energy;
dischargeData.diameter = (float) getNormedEnergy(dischargeData.energy);
dischargeData.genMarxPoint(seed);
}
private double getNormedEnergy(double total) {
return total*2/(stageCount*MAX_VOLTAGE*MAX_VOLTAGE*CAPACITANCE);
}
private AxisAlignedBB renderAabb = null;
@Nonnull
@Override
public AxisAlignedBB getRenderBoundingBox() {
if (renderAabb ==null) {
if (type== IWProperties.MarxType.BOTTOM) {
renderAabb = new AxisAlignedBB(pos,
offset(pos, facing, mirrored, 2, 4, stageCount));
} else {
renderAabb = new AxisAlignedBB(pos, pos);
}
}
return renderAabb;
}
private AxisAlignedBB collisionAabb = null;
@Override
public AxisAlignedBB getBoundingBox() {
if (collisionAabb ==null) {
int forward = getForward();
int right = getRight();
int up = offset.getY();
AxisAlignedBB ret = Block.FULL_BLOCK_AABB;
switch (forward) {
case -3://IO
if (right == 1) {
ret = new AxisAlignedBB(5 / 16D, 5 / 16D, .25, 11 / 16D, 11 / 16D, 1);
} else {
ret = new AxisAlignedBB(5 / 16D, 5 / 16D, 7 / 16D, 11 / 16D, 11 / 16D, 1);
}
break;
case -1://charging resistors
if (up == 0) {
ret = new AxisAlignedBB(.375, 0, 0, .625, 1, 1);
} else if (up == stageCount - 1) {
ret = new AxisAlignedBB(.375, 0, 9 / 16D, .625, 5 / 16D, 1);
} else {
ret = new AxisAlignedBB(.375, 0, 9 / 16D, .625, 1, 1);
}
break;
case 1://spark gaps
if (right == 0) {
if (up!=0) {
ret = new AxisAlignedBB(0, 0, 0, 9 / 16D, up == stageCount - 1 ? .5 : 1, 7 / 16D);
} else {
ret = new AxisAlignedBB(7/16D, 0, 0, 9/16D, 5/16D, 1);
}
} else {
if (stageCount - 1 == up) {
ret = new AxisAlignedBB(7 / 16D, 3 / 16D, 0, 9 / 16D, 5 / 16D, 1);
} else {
ret = new AxisAlignedBB(7 / 16D, 0, 0, 1, 1, 7 / 16D);
}
}
break;
case -2://Controller
break;
case 0://Caps
if (up == stageCount - 1) {
ret = new AxisAlignedBB(0, 0, 0, 1, .5, 1);
}
break;
default:
if (right == 0) {
if (forward<4) {
ret = new AxisAlignedBB(7/16D, 0, 0, 9/16D, 5/16D, 1);
} else {
ret = new AxisAlignedBB(0, 0, 0, 9/16D, 5/16D, 9/16D);
}
} else {
if (up==0) {
ret = Block.FULL_BLOCK_AABB;
} else if (forward < 4) {
ret = new AxisAlignedBB(7 / 16D, 3 / 16D, 0, 9 / 16D, 5 / 16D, 1);
} else {
ret = new AxisAlignedBB(6 / 16D, 1 / 16D, 0, 10 / 16D, 5 / 16D, 10 / 16D);
}
}
}
collisionAabb = MiscUtils.apply(getBaseTransform(), ret);
}
return collisionAabb;
}
private Matrix4 getBaseTransform() {
Matrix4 transform = new Matrix4();
transform.translate(.5, 0, .5);
transform.rotate(-facing.getHorizontalAngle() * Math.PI / 180, 0, 1, 0);
if (mirrored) {
transform.scale(-1, 1, 1);
}
transform.translate(-.5, 0, -.5);
return transform;
}
//WIRE STUFF
@Override
public boolean canConnect() {
return getForward()==-3;
}
@Override
public boolean isEnergyOutput() {
return getForward()==-3&&getRight()==1;
}
@Override
public int outputEnergy(int amount, boolean simulate, int energyType) {
TileEntityMarx master = master(this);
if (master!=null && amount>0) {
double ret = master.storage.insert(amount, ConversionUtil.joulesPerIf(), simulate, master.leftover);
master.leftover -= ret;
return (int) ret;
} else {
return 0;
}
}
@Override
public double insertEnergy(double joules, boolean simulate) {
TileEntityMarx master = master(this);
if (master!=null) {
double ret = master.storage.insert(joules, 1, simulate, master.leftover);
if (!simulate) {
master.leftover -= ret;
}
return joules -ret;
} else {
return 0;
}
}
@Override
public BlockPos getConnectionMaster(@Nullable WireType cableType, TargetingInfo target) {
return pos;
}
@Override
public boolean canConnectCable(WireType cableType, TargetingInfo target, Vec3i offset) {
if (hasConnection) {
return false;
}
if (getRight()==0) {
return REDSTONE_CATEGORY.equals(cableType.getCategory());
} else {
return WireType.HV_CATEGORY.equals(cableType.getCategory())|| IC2_HV_CAT.equals(cableType.getCategory());
}
}
@Override
public void connectCable(WireType cableType, TargetingInfo target, IImmersiveConnectable other) {
hasConnection = true;
if (WireType.REDSTONE_CATEGORY.equals(cableType.getCategory()))
RedstoneWireNetwork.updateConnectors(pos, world, getNetwork());
}
@Override
public WireType getCableLimiter(TargetingInfo target) {
return getRight()==0?WireType.REDSTONE:MixedWireType.HV;
}
@Override
public boolean allowEnergyToPass(ImmersiveNetHandler.Connection con) {
return true;
}
@Override
public void onEnergyPassthrough(int amount) {
}
@Override
public void removeCable(ImmersiveNetHandler.Connection connection) {
hasConnection = false;
if(world != null)
{
IBlockState state = world.getBlockState(pos);
world.notifyBlockUpdate(pos, state,state, 3);
}
}
@Override
public Vec3d getConnectionOffset(ImmersiveNetHandler.Connection con) {
Matrix4 transf = getBaseTransform();
if (getRight()==0) {
return transf.apply(new Vec3d(.5, .5, 7/16D));
} else {
return transf.apply(new Vec3d(.5, .5, 4/16D));
}
}
@Override
public void validate()
{
super.validate();
if (!world.isRemote)
ApiUtils.addFutureServerTask(world, () -> ImmersiveNetHandler.INSTANCE.onTEValidated(this));
}
@Override
public void invalidate()
{
super.invalidate();
if (world.isRemote && !IndustrialWires.proxy.isSingleplayer())
ImmersiveNetHandler.INSTANCE.clearConnectionsOriginatingFrom(pos, world);
}
@Override
public boolean receiveClientEvent(int id, int type) {
return MiscUtils.handleUpdate(id, pos, world)||super.receiveClientEvent(id, type);
}
// Redstone wire stuff
private RedstoneWireNetwork net = new RedstoneWireNetwork();
@Override
public void setNetwork(RedstoneWireNetwork net) {
masterOr(this, this).net = net;
}
@Override
public RedstoneWireNetwork getNetwork() {
TileEntityMarx master = masterOr(this, this);
if (!loaded) {
master.net.add(this);
loaded = true;
}
return master.net;
}
@Override
public void onChange() {
TileEntityMarx master = masterOr(this, this);
master.voltageControl = (master.net.channelValues[WHITE.getMetadata()]<<4)|master.net.channelValues[YELLOW.getMetadata()];
if (master.net.channelValues[LIGHT_BLUE.getMetadata()]!=0) {
master.tryTriggeredDischarge();
}
master.lastUpdate = world.getTotalWorldTime();
}
private void tryTriggeredDischarge() {
state = FiringState.NEXT_TICK;
}
@Override
public World getConnectorWorld() {
return world;
}
@Override
public void updateInput(byte[] signals) {
TileEntityMarx master = masterOr(this, this);
if (master.capVoltages!=null&&master.capVoltages.length==stageCount) {
int signalTop = getRSSignalFromVoltage(master.capVoltages[stageCount-1]);
int signalBottom = getRSSignalFromVoltage(master.capVoltages[0]);
setSignal(ORANGE, (signalBottom>>4)&0xf, signals);
setSignal(MAGENTA, (signalTop>>4)&0xf, signals);
setSignal(LIME, signalBottom&0xf, signals);
setSignal(PINK, signalTop&0xf, signals);
}
}
private void setSignal(EnumDyeColor channel, int value, byte[] signals) {
signals[channel.getMetadata()] = (byte) Math.max(value, signals[channel.getMetadata()]);
}
public void setStageCount(int stageCount) {
this.stageCount = stageCount;
rcTimeConst = 5D/stageCount;
timeFactor = Math.exp(-1/(20*rcTimeConst));
timeFactorBottom = Math.exp(-1 / (20 * rcTimeConst * 2 / 3));
collisionAabb = null;
renderAabb = null;
}
public int getStageCount() {
return stageCount;
}
private Vec3d getMiddle() {
double middleY = pos.getY()+(stageCount)/2D;
Vec3i electrodXZ = getBottomElectrode();
return new Vec3d(electrodXZ.getX()+.5, middleY, electrodXZ.getZ()+.5);
}
private BlockPos getBottomElectrode() {
return offset(pos, facing, mirrored, 1, 4, 0);
}
@Optional.Method(modid="mirage")
@SubscribeEvent
public static void gatherLights(GatherLightsEvent event) {
for (TileEntityMarx te:FIRING_GENERATORS) {
Vec3d origin = te.getMiddle().subtract(0, .5*te.stageCount-1,0);
Light.Builder builder = Light.builder()
.color(1, 1, 1)
.radius(5);
List<Light> toAdd = new ArrayList<>(te.stageCount*2-3);
if (te.dischargeData!=null&&te.dischargeData.energy>0) {
toAdd.add(builder.pos(origin.add(0, 0, 0)).build());
toAdd.add(builder.pos(origin.add(0, te.stageCount / 2, 0)).build());
toAdd.add(builder.pos(origin.add(0, te.stageCount - 2, 0)).build());
}
origin = new Vec3d(offset(te.pos, te.facing, te.mirrored, 1, 0, 0))
.add(0, .75, 0)
.add(new Vec3d(te.facing.getDirectionVec()).scale(.25));
builder.radius(.5F);
for (int i = 0;i<te.stageCount-1;i+=te.stageCount/5) {
toAdd.add(builder.pos(origin.add(0, i, 0)).build());
}
event.getLightList().addAll(toAdd);
}
}
public enum FiringState {
CHARGING,
NEXT_TICK,
FIRE
}
public static final class Discharge {
public float energy;
public Vec3d[] vertices;
public float diameter = .25F;
final int stageCount;
Discharge(int stages) {
stageCount = stages;
int count = stages/5+1;
vertices = new Vec3d[2*count];
vertices[0] = new Vec3d(0, -.5F, 0);
for (int i = 1;i<vertices.length;i++) {
vertices[i] = new Vec3d(0, 0, 0);
}
vertices[vertices.length-1] = new Vec3d(0, stageCount-1.9375F, 0);
}
// Meant to be const
private final Vec3d side = new Vec3d(0, 0, 1);
private Matrix4 transform = new Matrix4();
void genMarxPoint(int randSeed) {
genMarxPoint(0, vertices.length-1, new Random(randSeed));
}
/**
* @param min The first point of the discharge section to be generated. has to be pre-populated
* @param max The last point of the discharge section to be generated. has to be pre-populated
*/
void genMarxPoint(int min, int max, Random rand) {
int toGenerate = (min+max)/2;
Vec3d diff = vertices[max].subtract(vertices[min]);
Vec3d v0 = diff.crossProduct(side);
transform.setIdentity();
double diffLength = diff.length();
double noise = Math.sqrt(diffLength)*rand.nextDouble()*1/(1+Math.abs(stageCount/2.0-toGenerate))*.75;
if ((max-min)%2==1) {
noise *= (toGenerate-min)/(double)(max-min);
}
v0 = v0.scale((float) (noise / v0.length()));
diff = diff.scale(1/diffLength);
transform.rotate(Math.PI*2*rand.nextDouble(), diff.x, diff.y, diff.z);
Vec3d center = vertices[max].add(vertices[min]).scale(.5);
vertices[toGenerate] = transform.apply(v0);
vertices[toGenerate] = center.add(vertices[toGenerate]);
if (toGenerate-min>1) {
genMarxPoint(min, toGenerate, rand);
}
if (max-toGenerate>1) {
genMarxPoint(toGenerate, max, rand);
}
}
}
}

View file

@ -1,36 +1,35 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.wire;
package malte0811.industrialwires.blocks.wire;
import blusunrize.immersiveengineering.api.IEProperties;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.BlockIWBase;
import malte0811.industrialWires.blocks.IMetaEnum;
import malte0811.industrialWires.wires.IC2Wiretype;
import malte0811.industrialwires.IWConfig;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.BlockIWBase;
import malte0811.industrialwires.blocks.IMetaEnum;
import malte0811.industrialwires.util.ConversionUtil;
import malte0811.industrialwires.wires.MixedWireType;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
@ -41,28 +40,31 @@ import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
public class BlockIC2Connector extends BlockIWBase implements IMetaEnum {
private static PropertyEnum<BlockTypes_IC2_Connector> type = PropertyEnum.create("type", BlockTypes_IC2_Connector.class);
public static final PropertyEnum<BlockTypes_IC2_Connector> TYPE = PropertyEnum.create("type", BlockTypes_IC2_Connector.class);
public static final String NAME = "ic2_connector";
public BlockIC2Connector() {
super(Material.IRON, "ic2_connector");
super(Material.IRON, NAME);
setHardness(3.0F);
setResistance(15.0F);
lightOpacity = 0;
this.setCreativeTab(IndustrialWires.creativeTab);
}
@Override
public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos posNeighbor) {
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof TileEntityIC2ConnectorTin) {
TileEntityIC2ConnectorTin connector = (TileEntityIC2ConnectorTin) te;
if (world.isAirBlock(pos.offset(connector.f))) {
if (world.isAirBlock(pos.offset(connector.getFacing()))) {
this.dropBlockAsItem(connector.getWorld(), pos, world.getBlockState(pos), 0);
connector.getWorld().setBlockToAir(pos);
}
@ -70,9 +72,9 @@ public class BlockIC2Connector extends BlockIWBase implements IMetaEnum {
}
@Override
public void getSubBlocks(@Nonnull Item itemIn, CreativeTabs tab, NonNullList<ItemStack> list) {
for (int i = 0; i < type.getAllowedValues().size(); i++) {
list.add(new ItemStack(itemIn, 1, i));
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
for (int i = 0; i < TYPE.getAllowedValues().size(); i++) {
list.add(new ItemStack(this, 1, i));
}
}
@ -88,7 +90,7 @@ public class BlockIC2Connector extends BlockIWBase implements IMetaEnum {
@Override
protected IProperty<?>[] getProperties() {
return new IProperty[]{type, IEProperties.FACING_ALL};
return new IProperty[]{TYPE, IEProperties.FACING_ALL};
}
@Nonnull
@ -105,7 +107,7 @@ public class BlockIC2Connector extends BlockIWBase implements IMetaEnum {
@Nonnull
@Override
public IBlockState getStateFromMeta(int meta) {
return super.getStateFromMeta(meta).withProperty(type, BlockTypes_IC2_Connector.values()[meta]);
return super.getStateFromMeta(meta).withProperty(TYPE, BlockTypes_IC2_Connector.values()[meta]);
}
@Override
@ -120,7 +122,15 @@ public class BlockIC2Connector extends BlockIWBase implements IMetaEnum {
@Override
public TileEntity createTileEntity(@Nonnull World world, @Nonnull IBlockState state) {
switch (state.getValue(type)) {
TileEntityIC2ConnectorTin base = getBaseTE(state.getValue(TYPE));
if (base!=null) {
base.setFacing(state.getValue(IEProperties.FACING_ALL));
}
return base;
}
private TileEntityIC2ConnectorTin getBaseTE(BlockTypes_IC2_Connector type) {
switch (type) {
case TIN_CONN:
return new TileEntityIC2ConnectorTin(false);
case TIN_RELAY:
@ -146,12 +156,16 @@ public class BlockIC2Connector extends BlockIWBase implements IMetaEnum {
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean advanced) {
super.addInformation(stack, player, tooltip, advanced);
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, @Nullable World world, List<String> tooltip, ITooltipFlag advanced) {
super.addInformation(stack, world, tooltip, advanced);
if (!stack.isEmpty() && stack.getMetadata() % 2 == 0) {
int type = stack.getMetadata() / 2;
tooltip.add(I18n.format(IndustrialWires.MODID + ".tooltip.power_tier", type + 1));
tooltip.add(I18n.format(IndustrialWires.MODID + ".tooltip.eu_per_tick", IC2Wiretype.IC2_TYPES[type].getTransferRate() / 8));
tooltip.add(I18n.format(IndustrialWires.MODID + ".tooltip.power_tier", (type%5) + 1));
MixedWireType wire = MixedWireType.ALL[type];
tooltip.add(I18n.format(IndustrialWires.MODID + ".tooltip.energy_per_tick",
wire.getIORate()*ConversionUtil.euPerJoule(),
wire.getIORate()*ConversionUtil.ifPerJoule()*IWConfig.wireRatio));
}
}
@ -191,6 +205,6 @@ public class BlockIC2Connector extends BlockIWBase implements IMetaEnum {
@Override
public int getMetaFromState(IBlockState state) {
return state.getValue(type).ordinal();
return state.getValue(TYPE).ordinal();
}
}

View file

@ -1,21 +1,18 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.wire;
package malte0811.industrialwires.blocks.wire;
import blusunrize.immersiveengineering.common.blocks.BlockIEBase.IBlockEnum;

View file

@ -1,42 +1,28 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.wire;
package malte0811.industrialwires.blocks.wire;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import malte0811.industrialWires.wires.IC2Wiretype;
import static malte0811.industrialwires.wires.MixedWireType.COPPER_IC2;
public class TileEntityIC2ConnectorCopper extends TileEntityIC2ConnectorTin {
public TileEntityIC2ConnectorCopper(boolean rel) {
super(rel);
super(rel, COPPER_IC2, 2, .5, .5);
}
public TileEntityIC2ConnectorCopper() {
this(false);
}
{
tier = 2;
maxStored = IC2Wiretype.IC2_TYPES[1].getTransferRate() / 8;
}
@Override
public boolean canConnect(WireType t) {
return t == IC2Wiretype.IC2_TYPES[1];
}
}

View file

@ -1,40 +1,27 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.blocks.wire;
package malte0811.industrialwires.blocks.wire;
import blusunrize.immersiveengineering.api.energy.wires.WireType;
import malte0811.industrialWires.wires.IC2Wiretype;
import static malte0811.industrialwires.wires.MixedWireType.GLASS;
public class TileEntityIC2ConnectorGlass extends TileEntityIC2ConnectorHV {
public class TileEntityIC2ConnectorGlass extends TileEntityIC2ConnectorTin {
public TileEntityIC2ConnectorGlass(boolean rel) {
super(rel);
super(rel, GLASS, 5, .875, .75);
}
public TileEntityIC2ConnectorGlass() {
}
{
tier = 5;
maxStored = IC2Wiretype.IC2_TYPES[4].getTransferRate() / 8;
}
@Override
public boolean canConnect(WireType t) {
return t == IC2Wiretype.IC2_TYPES[4];
this(false);
}
}

View file

@ -0,0 +1,28 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.wire;
import static malte0811.industrialwires.wires.MixedWireType.GOLD;
public class TileEntityIC2ConnectorGold extends TileEntityIC2ConnectorTin {
public TileEntityIC2ConnectorGold(boolean rel) {
super(rel, GOLD, 3, .5625, .5625);
}
public TileEntityIC2ConnectorGold() {
this(false);
}
}

View file

@ -0,0 +1,28 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.wire;
import static malte0811.industrialwires.wires.MixedWireType.HV;
public class TileEntityIC2ConnectorHV extends TileEntityIC2ConnectorTin {
public TileEntityIC2ConnectorHV(boolean rel) {
super(rel, HV, 4, .875, .75);
}
public TileEntityIC2ConnectorHV() {
this(false);
}
}

View file

@ -0,0 +1,648 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.blocks.wire;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.api.TargetingInfo;
import blusunrize.immersiveengineering.api.energy.wires.*;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.AbstractConnection;
import blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.Connection;
import blusunrize.immersiveengineering.common.blocks.IEBlockInterfaces.IDirectionalTile;
import com.cout970.magneticraft.api.core.INode;
import com.cout970.magneticraft.api.energy.IElectricNode;
import com.cout970.magneticraft.api.energy.IElectricNodeHandler;
import com.cout970.magneticraft.registry.CapabilitiesKt;
import com.cout970.magneticraft.systems.config.Config;
import gregtech.api.capability.GregtechCapabilities;
import gregtech.api.capability.IEnergyContainer;
import ic2.api.energy.tile.IEnergyAcceptor;
import ic2.api.energy.tile.IEnergyEmitter;
import ic2.api.energy.tile.IEnergySink;
import ic2.api.energy.tile.IEnergySource;
import malte0811.industrialwires.IMixedConnector;
import malte0811.industrialwires.IWConfig;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IBlockBoundsIW;
import malte0811.industrialwires.compat.Compat;
import malte0811.industrialwires.util.ConversionUtil;
import malte0811.industrialwires.util.MiscUtils;
import malte0811.industrialwires.wires.MixedWireType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.*;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Optional;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import java.util.function.Consumer;
import static malte0811.industrialwires.wires.MixedWireType.TIN;
@Optional.InterfaceList({
@Optional.Interface(iface = "ic2.api.energy.tile.IEnergySource", modid = "ic2"),
@Optional.Interface(iface = "ic2.api.energy.tile.IEnergySink", modid = "ic2")
})
public class TileEntityIC2ConnectorTin extends TileEntityImmersiveConnectable implements IEnergySource, IEnergySink, IDirectionalTile,
ITickable, IMixedConnector, IBlockBoundsIW {
private static final double EPS = .1;
private EnumFacing facing = EnumFacing.NORTH;
private boolean relay;
// external net to IE net buffer
private double bufferToNet = 0;
private double potentialIEInputInTick = 0;
private double actualIEInputInTick = 0;
private double maxToNet = 0;
//IE net to external net buffer
private double bufferToMachine = 0;
private double externalInputInTick = 0;
private double maxToMachine = 0;
//private EnergyType energyType = NONE;
private boolean shouldBreak = false;
private final double maxIO;
private final MixedWireType wireType;
private final int tier;
private final double relayOffset;
private final double connOffset;
protected TileEntityIC2ConnectorTin(boolean relay, MixedWireType type, int tier, double relayLength, double connLength) {
this.relay = relay;
wireType = type;
maxIO = type.getIORate();
this.tier = tier;
this.relayOffset = relayLength-.5;
this.connOffset = connLength-.5;
}
public TileEntityIC2ConnectorTin(boolean relay) {
this(relay, TIN, 1, .5, .5);
}
public TileEntityIC2ConnectorTin() {
this(false);
}
@Override
public void onLoad() {
super.onLoad();
if (!world.isRemote&& IndustrialWires.hasIC2)
Compat.loadIC2Tile.accept(this);
ImmersiveNetHandler.INSTANCE.onTEValidated(this);
}
@Override
public void update() {
if (!world.isRemote) {
if (shouldBreak) {
Deque<BlockPos> open = new ArrayDeque<>();
open.push(pos);
Set<BlockPos> closed = new HashSet<>();
closed.add(pos);
while (!open.isEmpty()) {
BlockPos next = open.pop();
Set<Connection> conns = ImmersiveNetHandler.INSTANCE.getConnections(world, next);
if (conns!=null) {
for (Connection c:conns) {
ImmersiveNetHandler.INSTANCE.getTransferedRates(world.provider.getDimension())
.put(c, 2*c.cableType.getTransferRate());
if (closed.add(c.end)) {
open.push(c.end);
}
}
}
}
for (BlockPos p:closed) {
TileEntity tile = world.getTileEntity(p);
if (tile instanceof IImmersiveConnectable && ((IImmersiveConnectable) tile).isEnergyOutput()) {
world.createExplosion(null, p.getX()+.5, p.getY()+.5, p.getZ()+.5,
3, true);
}
}
return;
}
if (bufferToNet < maxToNet) {
maxToNet = bufferToNet;
}
if (externalInputInTick > maxToNet) {
maxToNet = externalInputInTick;
}
externalInputInTick = 0;
if (bufferToMachine < maxToMachine) {
maxToMachine = bufferToMachine;
}
potentialIEInputInTick = Math.min(Math.max(potentialIEInputInTick, actualIEInputInTick), getMaxIO());
if (potentialIEInputInTick > maxToMachine) {
maxToMachine = potentialIEInputInTick;
}
potentialIEInputInTick = 0;
actualIEInputInTick = 0;
if (bufferToNet > EPS) {
transferPowerToNet();
}
if (bufferToNet >EPS) {
notifyAvailableEnergy(bufferToNet);
}
if (bufferToMachine > EPS) {
transferPowerToFEMachine();
if (Loader.isModLoaded("gregtech"))
transferPowerToGTMachine();
if (Loader.isModLoaded("magneticraft"))
transferPowerToMagn();
}
}
}
private void transferPowerToNet() {
Set<AbstractConnection> conns = ImmersiveNetHandler.INSTANCE.getIndirectEnergyConnections(pos, world, true);
Map<AbstractConnection, Pair<IMixedConnector, Double>> maxOutputs = new HashMap<>();
double outputMax = Math.min(bufferToNet, maxToNet);
double sum = 0;
for (AbstractConnection c : conns) {
if (c.isEnergyOutput) {
IImmersiveConnectable iic = ApiUtils.toIIC(c.end, world);
if (iic instanceof IMixedConnector) {
double extract =
outputMax - ((IMixedConnector) iic).insertEnergy(outputMax, true);
if (extract > EPS) {
maxOutputs.put(c, new ImmutablePair<>((IMixedConnector) iic, extract));
sum += extract;
}
}
}
}
if (sum > EPS) {
HashMap<Connection, Integer> transferedPerConn = ImmersiveNetHandler.INSTANCE.getTransferedRates(world.provider.getDimension());
for (Map.Entry<AbstractConnection, Pair<IMixedConnector, Double>> entry : maxOutputs.entrySet()) {
Pair<IMixedConnector, Double> p = entry.getValue();
AbstractConnection c = entry.getKey();
double out = outputMax * p.getRight() / sum;
double loss = Math.min(getAverageLossRate(c), 1)*out;
out = Math.min(out, bufferToNet -loss);
if (out<=0)
continue;
double inserted = out - p.getLeft().insertEnergy(out, false);
double energyAtConn = inserted + loss;
bufferToNet -= energyAtConn;
float intermediaryLoss = 0;
HashSet<IImmersiveConnectable> passedConnectors = new HashSet<>();
for (Connection sub : c.subConnections) {
int transferredPerCon = transferedPerConn.getOrDefault(sub, 0);
energyAtConn -= sub.cableType.getLossRatio() * sub.length;
double wireLoad = energyAtConn;
transferedPerConn.put(sub, (int) (transferredPerCon + wireLoad));
IImmersiveConnectable subStart = ApiUtils.toIIC(sub.start, world);
IImmersiveConnectable subEnd = ApiUtils.toIIC(sub.end, world);
if (subStart != null && passedConnectors.add(subStart))
subStart.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
if (subEnd != null && passedConnectors.add(subEnd))
subEnd.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
}
}
}
}
private void transferPowerToFEMachine() {
BlockPos outPos = pos.offset(facing);
TileEntity te = MiscUtils.getLoadedTE(world, outPos, TileEntity.class);
if (te!=null && te.hasCapability(CapabilityEnergy.ENERGY, facing.getOpposite())) {
IEnergyStorage handler = te.getCapability(CapabilityEnergy.ENERGY, facing.getOpposite());
assert handler!=null;
double outJoules = Math.min(bufferToMachine, maxToMachine*IWConfig.wireRatio);
int outFE = MathHelper.floor(outJoules*ConversionUtil.ifPerJoule());
int received = handler.receiveEnergy(outFE, false);
bufferToMachine -= received*ConversionUtil.joulesPerIf();
}
}
private void transferPowerToGTMachine() {
BlockPos outPos = pos.offset(facing);
TileEntity te = MiscUtils.getLoadedTE(world, outPos, TileEntity.class);
if (te!=null && te.hasCapability(GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER, facing.getOpposite())) {
IEnergyContainer container = te.getCapability(GregtechCapabilities.CAPABILITY_ENERGY_CONTAINER, facing.getOpposite());
assert container!=null;
double outJoules = Math.min(bufferToMachine, maxToMachine*IWConfig.wireRatio);
long outEU = Math.min(MathHelper.floor(outJoules*ConversionUtil.euPerJoule()), container.getInputVoltage());
long received = container.addEnergy(outEU);
bufferToMachine -= received*ConversionUtil.joulesPerEu();
}
}
private void transferPowerToMagn() {
BlockPos outPos = pos.offset(facing);
TileEntity te = MiscUtils.getLoadedTE(world, outPos, TileEntity.class);
if (te!=null && te.hasCapability(CapabilitiesKt.getELECTRIC_NODE_HANDLER(), facing.getOpposite())) {
IElectricNodeHandler handler = te.getCapability(CapabilitiesKt.getELECTRIC_NODE_HANDLER(), facing.getOpposite());
assert handler!=null;
double outJoules = Math.min(bufferToMachine, maxToMachine*IWConfig.wireRatio);
int outRF = MathHelper.floor(outJoules*ConversionUtil.ifPerJoule());
IElectricNode node = null;
for (INode n : handler.getNodes()) {
if (n instanceof IElectricNode) {
node = (IElectricNode) n;
break;
}
}
if (node != null) {
double insertet = node.applyPower(outRF * Config.INSTANCE.getWattsToFE(), false);
bufferToMachine -= insertet/Config.INSTANCE.getWattsToFE();
}
}
}
private void notifyAvailableEnergy(double storedNew)
{
Set<AbstractConnection> outputs = ImmersiveNetHandler.INSTANCE.getIndirectEnergyConnections(pos, world, true);
for(AbstractConnection con : outputs)
{
IImmersiveConnectable end = ApiUtils.toIIC(con.end, world);
if(con.cableType!=null && end!=null && end.allowEnergyToPass(null))
{
Pair<Float, Consumer<Float>> e = getEnergyForConnection(con, storedNew);
end.addAvailableEnergy(e.getKey(), e.getValue());
}
}
addAvailableEnergy(-1, null);
}
private Pair<Float, Consumer<Float>> getEnergyForConnection(@Nullable AbstractConnection c, double storedNew)
{
float loss = c!=null?c.getAverageLossRate():0;
float max = (float) (storedNew-loss);
Consumer<Float> extract = (energy)-> bufferToNet -= energy+loss;
return new ImmutablePair<>(max, extract);
}
private double getAverageLossRate(AbstractConnection conn) {
double f = 0;
for (Connection c : conn.subConnections) {
WireType type = c.cableType;
if (type instanceof MixedWireType) {
f += c.length * ((MixedWireType)type).getLoss();
} else {
f = Double.POSITIVE_INFINITY;
}
}
return f;
}
//Input through the net
@Override
public double insertEnergy(double joules, boolean simulate) {
double insert = Math.min(getMaxIO() - bufferToMachine, joules);
insert = Math.min(getMaxIO()-actualIEInputInTick, insert);
if (!simulate) {
bufferToMachine += insert;
actualIEInputInTick += insert;
} else {
//Yes, this is weird. But it works, otherwise the system can get stuck at a lower output rate with a full buffer
potentialIEInputInTick += Math.min(joules, getMaxIO());
}
return joules - insert;
}
private double getMaxIO() {
return maxIO;
}
@Override
public void invalidate() {
if (!world.isRemote)
Compat.unloadIC2Tile.accept(this);
super.invalidate();
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
if (!world.isRemote)
Compat.unloadIC2Tile.accept(this);
}
@Override
public Vec3d getConnectionOffset(Connection con) {
EnumFacing side = facing.getOpposite();
double conRadius = con.cableType.getRenderDiameter() / 2;
double length = relay?relayOffset:connOffset;
return new Vec3d(.5 + (length - conRadius) * side.getXOffset(),
.5 + (length - conRadius) * side.getYOffset(),
.5 + (length - conRadius) * side.getZOffset());
}
@Override
public boolean canConnect() {
return true;
}
@Override
public boolean isEnergyOutput() {
return !relay;
}
@Override
public boolean canConnectCable(WireType cableType, TargetingInfo target, Vec3i offset) {
return (limitType == null || this.isRelay()) && WireApi.canMix(cableType, wireType);
}
@Override
protected boolean isRelay() {
return relay;
}
@Override
@Optional.Method(modid="ic2")
public boolean emitsEnergyTo(IEnergyAcceptor receiver, EnumFacing side) {
return !relay && side == facing;
}
@Override
@Optional.Method(modid="ic2")
public boolean acceptsEnergyFrom(IEnergyEmitter emitter, EnumFacing side) {
return !relay && side == facing;
}
@Override
@Optional.Method(modid="ic2")
public double getDemandedEnergy() {
double ret = (getMaxIO() - bufferToNet) * ConversionUtil.euPerJoule() + .05;
if (ret < .1)
ret = 0;
return ret;
}
@Override
@Optional.Method(modid="ic2")
public int getSinkTier() {
return tier;
}
@Override
@Optional.Method(modid="ic2")
public double injectEnergy(EnumFacing directionFrom, double amount, double voltage) {
return amount-ConversionUtil.euPerJoule()*addToIn(ConversionUtil.joulesPerEu()*amount, false);
}
@Override
@Optional.Method(modid="ic2")
public double getOfferedEnergy() {
return Math.min(maxToMachine, bufferToMachine) * ConversionUtil.euPerJoule();
}
@Override
@Optional.Method(modid="ic2")
public void drawEnergy(double amount) {
bufferToMachine -= amount*ConversionUtil.joulesPerEu();
markDirty();
}
@Nullable
protected Pair<Float,Consumer<Float>> getOwnEnergy()
{
if (isRelay())
return null;
return new ImmutablePair<>((float) bufferToNet, (d)-> bufferToNet -= d);
}
@Override
protected float getBaseDamage(ImmersiveNetHandler.Connection c) {
return 1/64F;
}
@Override
@Optional.Method(modid="ic2")
public int getSourceTier() {
return tier;
}
// Returns amount of energy consumed
private double addToIn(double joules, boolean simulate) {
joules = Math.min(getMaxIO() - externalInputInTick + .5, joules);
if (bufferToNet < getMaxIO()) {
if (!simulate) {
bufferToNet += joules;
externalInputInTick += joules;
notifyAvailableEnergy(joules);
}
markDirty();
return joules;
}
return 0;
}
@Override
public void readCustomNBT(@Nonnull NBTTagCompound nbt, boolean descPacket) {
super.readCustomNBT(nbt, descPacket);
facing = EnumFacing.byIndex(nbt.getInteger("facing"));
relay = nbt.getBoolean("relay");
int version = nbt.getInteger("version");
bufferToNet = nbt.getDouble("inBuffer");
bufferToMachine = nbt.getDouble("outBuffer");
if (nbt.hasKey("maxToNet")) {
maxToNet = nbt.getDouble("maxToNet");
} else {
maxToNet = bufferToNet;
}
if (nbt.hasKey("maxToMachine")) {
maxToMachine = nbt.getDouble("maxToMachine");
} else {
maxToMachine = bufferToMachine;
}
if (version==0) {
bufferToNet *= ConversionUtil.joulesPerEu();
bufferToMachine *= ConversionUtil.joulesPerEu();
maxToNet *= ConversionUtil.joulesPerEu();
maxToMachine *= ConversionUtil.joulesPerEu();
}
}
@Override
public void writeCustomNBT(@Nonnull NBTTagCompound nbt, boolean descPacket) {
super.writeCustomNBT(nbt, descPacket);
nbt.setInteger("facing", facing.getIndex());
nbt.setBoolean("relay", relay);
nbt.setDouble("inBuffer", bufferToNet);
nbt.setDouble("outBuffer", bufferToMachine);
nbt.setDouble("maxToNet", maxToNet);
nbt.setDouble("maxToMachine", maxToMachine);
nbt.setInteger("version", 1);
}
@Nonnull
@Override
public EnumFacing getFacing() {
return facing;
}
@Override
public void setFacing(@Nonnull EnumFacing facing) {
this.facing = facing;
}
@Override
public int getFacingLimitation() {
return 0;
}
@Override
public boolean mirrorFacingOnPlacement(@Nonnull EntityLivingBase placer) {
return true;
}
@Override
public boolean canHammerRotate(@Nonnull EnumFacing side, float hitX, float hitY, float hitZ, @Nonnull EntityLivingBase entity) {
return false;
}
@Override
public AxisAlignedBB getBoundingBox() {
double length = .5+(relay?relayOffset:connOffset);
double wMin = .3125;
double wMax = .6875;
switch (facing.getOpposite()) {
case UP:
return new AxisAlignedBB(wMin, 0, wMin, wMax, length, wMax);
case DOWN:
return new AxisAlignedBB(wMin, 1 - length, wMin, wMax, 1, wMax);
case SOUTH:
return new AxisAlignedBB(wMin, wMin, 0, wMax, wMax, length);
case NORTH:
return new AxisAlignedBB(wMin, wMin, 1 - length, wMax, wMax, 1);
case EAST:
return new AxisAlignedBB(0, wMin, wMin, length, wMax, wMax);
case WEST:
return new AxisAlignedBB(1 - length, wMin, wMin, 1, wMax, wMax);
}
return new AxisAlignedBB(0, 0, 0, 1, 1, 1);
}
@Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
if (capability==CapabilityEnergy.ENERGY) {
return !isRelay() && facing == this.facing;
}
return super.hasCapability(capability, facing);
}
@Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability==CapabilityEnergy.ENERGY) {
if (!isRelay() && facing == this.facing) {
return CapabilityEnergy.ENERGY.cast(energyHandler);
}
return null;
}
return super.getCapability(capability, facing);
}
/*
* regarding equals+hashCode
* TE's are considered equal if they have the same pos+dimension id
* This is necessary to work around a weird bug causing a lot of log spam (100GB and above are well possible).
* For further information see #1 (https://github.com/malte0811/IndustrialWires/issues/1)
*/
@Override
public int hashCode() {
if (world==null)
return 0;
int ret = world.provider.getDimension();
ret = 31 * ret + pos.hashCode();
return ret;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TileEntityIC2ConnectorTin)) {
return false;
}
if (obj.getClass() != getClass()) {
return false;
}
TileEntityIC2ConnectorTin te = (TileEntityIC2ConnectorTin) obj;
if (!te.pos.equals(pos)) {
return false;
}
if (te.world.provider.getDimension() != world.provider.getDimension()) {
return false;
}
return true;
}
@Override
public boolean canRotate(@Nonnull EnumFacing axis) {
return false;
}
private EnergyHandler energyHandler = new EnergyHandler();
private class EnergyHandler implements IEnergyStorage {
@Override
public int receiveEnergy(int maxReceive, boolean simulate) {
if (bufferToNet>=getMaxIO()) {
return 0;
}
double joules = maxReceive*ConversionUtil.joulesPerIf();
double accepted = addToIn(joules, simulate);
return MathHelper.ceil(accepted*ConversionUtil.ifPerJoule());
}
@Override
public int extractEnergy(int maxExtract, boolean simulate) {
double joules = maxExtract*ConversionUtil.joulesPerIf();
if (joules>maxToMachine) {
joules = maxToMachine;
}
if (joules>bufferToMachine) {
joules = bufferToMachine;
}
if (!simulate) {
bufferToMachine -= joules;
}
return MathHelper.floor(ConversionUtil.ifPerJoule()*joules);
}
@Override
public int getEnergyStored() {
return (int)((bufferToMachine+bufferToNet)*ConversionUtil.ifPerJoule());
}
@Override
public int getMaxEnergyStored() {
return (int) (2* getMaxIO() *ConversionUtil.ifPerJoule());
}
@Override
public boolean canExtract() {
return true;
}
@Override
public boolean canReceive() {
return true;
}
}
}

View file

@ -0,0 +1,219 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client;
import blusunrize.immersiveengineering.api.IEProperties;
import blusunrize.immersiveengineering.api.Lib;
import blusunrize.immersiveengineering.client.ClientUtils;
import blusunrize.immersiveengineering.common.util.ItemNBTHelper;
import com.google.common.collect.ImmutableMap;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.BlockIWBase;
import malte0811.industrialwires.blocks.IMetaEnum;
import malte0811.industrialwires.blocks.controlpanel.TileEntityPanel;
import malte0811.industrialwires.blocks.hv.BlockHVMultiblocks;
import malte0811.industrialwires.client.panelmodel.PanelModel;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.items.ItemIC2Coil;
import malte0811.industrialwires.items.ItemKey;
import malte0811.industrialwires.items.ItemPanelComponent;
import malte0811.industrialwires.mech_mb.MechMBPart;
import malte0811.industrialwires.wires.MixedWireType;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.ScreenShotHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.*;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.obj.OBJModel;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import java.util.Locale;
import java.util.Map;
import static malte0811.industrialwires.client.render.TileRenderMechMB.BASE_MODELS;
@Mod.EventBusSubscriber(modid = IndustrialWires.MODID, value = Side.CLIENT)
@SideOnly(Side.CLIENT)
public class ClientEventHandler {
public static boolean shouldScreenshot = false;
@SubscribeEvent(priority = EventPriority.LOW)
public static void renderOverlayPost(RenderGameOverlayEvent.Post e) {
if (ClientUtils.mc().player != null && e.getType() == RenderGameOverlayEvent.ElementType.TEXT) {
EntityPlayer player = ClientUtils.mc().player;
for (EnumHand hand : EnumHand.values()) {
if (!player.getHeldItem(hand).isEmpty()) {
ItemStack equipped = player.getHeldItem(hand);
if (OreDictionary.itemMatches(new ItemStack(IndustrialWires.coil, 1, OreDictionary.WILDCARD_VALUE), equipped, false)) {
MixedWireType type = MixedWireType.ALL[equipped.getItemDamage()];
int color = type.getColour(null);
final int threshold = 0x40-1;
for (int i = 0;i<3;i++) {
if (((color>>(8*i))&255)<threshold) {
color |= threshold<<(8*i);
}
}
String s = I18n.format(IndustrialWires.MODID + ".desc.wireLength", ItemIC2Coil.getLength(equipped));
ClientUtils.font().drawString(s, e.getResolution().getScaledWidth() / 2 - ClientUtils.font().getStringWidth(s) / 2,
e.getResolution().getScaledHeight() - GuiIngameForge.left_height - 40, color, true);
if (ItemNBTHelper.hasKey(equipped, "linkingPos")) {
int[] link = ItemNBTHelper.getIntArray(equipped, "linkingPos");
if (link != null && link.length > 3) {
s = I18n.format(Lib.DESC_INFO + "attachedTo", link[1], link[2], link[3]);
RayTraceResult focussedBlock = ClientUtils.mc().objectMouseOver;
double distSquared;
if (focussedBlock != null && focussedBlock.typeOfHit == RayTraceResult.Type.BLOCK) {
distSquared = focussedBlock.getBlockPos().distanceSq(link[1], link[2], link[3]);
} else {
distSquared = player.getDistanceSq(link[1], link[2], link[3]);
}
int length = Math.min(ItemIC2Coil.getLength(equipped), type.getMaxLength());
if (length * length < distSquared) {
color = 0xdd3333;
}
ClientUtils.font().drawString(s, e.getResolution().getScaledWidth() / 2 - ClientUtils.font().getStringWidth(s) / 2,
e.getResolution().getScaledHeight() - GuiIngameForge.left_height - 20, color, true);
}
}
}
}
}
}
}
@SubscribeEvent
public static void renderBoundingBoxes(DrawBlockHighlightEvent event) {
if (!event.isCanceled() && event.getSubID() == 0 && event.getTarget().typeOfHit == RayTraceResult.Type.BLOCK) {
TileEntity tile = event.getPlayer().world.getTileEntity(event.getTarget().getBlockPos());
if (tile instanceof TileEntityPanel) {
TileEntityPanel panel = (TileEntityPanel) tile;
Pair<PanelComponent, RayTraceResult> pc = panel.getSelectedComponent(Minecraft.getMinecraft().player, event.getTarget().hitVec, true);
if (pc != null) {
pc.getLeft().renderBox();
event.setCanceled(true);
}
}
}
}
@SubscribeEvent
public static void bakeModel(ModelBakeEvent event) {
event.getModelRegistry().putObject(new ModelResourceLocation(IndustrialWires.MODID + ":control_panel", "inventory,type=top"), new PanelModel());
event.getModelRegistry().putObject(new ModelResourceLocation(IndustrialWires.MODID + ":control_panel", "inventory,type=unfinished"), new PanelModel());
}
@SubscribeEvent
public static void registerModels(ModelRegistryEvent evt) {
if (IndustrialWires.coil!=null) {
for (int meta = 0; meta < ItemIC2Coil.subNames.length; meta++) {
ResourceLocation loc = new ResourceLocation(IndustrialWires.MODID, "ic2_wire_coil/" + ItemIC2Coil.subNames[meta]);
ModelBakery.registerItemVariants(IndustrialWires.coil, loc);
ModelLoader.setCustomModelResourceLocation(IndustrialWires.coil, meta, new ModelResourceLocation(loc, "inventory"));
}
}
for (int meta = 0; meta < ItemPanelComponent.types.length; meta++) {
ResourceLocation loc = new ResourceLocation(IndustrialWires.MODID, "panel_component/" + ItemPanelComponent.types[meta]);
ModelBakery.registerItemVariants(IndustrialWires.panelComponent, loc);
ModelLoader.setCustomModelResourceLocation(IndustrialWires.panelComponent, meta, new ModelResourceLocation(loc, "inventory"));
}
for (int meta = 0; meta < ItemKey.types.length; meta++) {
ResourceLocation loc = new ResourceLocation(IndustrialWires.MODID, "key/" + ItemKey.types[meta]);
ModelBakery.registerItemVariants(IndustrialWires.key, loc);
ModelLoader.setCustomModelResourceLocation(IndustrialWires.key, meta, new ModelResourceLocation(loc, "inventory"));
}
for (BlockIWBase b : IndustrialWires.blocks) {
Item blockItem = Item.getItemFromBlock(b);
final ResourceLocation loc = b.getRegistryName();
assert loc != null;
ModelLoader.setCustomMeshDefinition(blockItem, stack -> new ModelResourceLocation(loc, "inventory"));
Object[] v = ((IMetaEnum) b).getValues();
for (int meta = 0; meta < v.length; meta++) {
String location = loc.toString();
String prop = "inventory,type=" + v[meta].toString().toLowerCase(Locale.US);
try {
ModelLoader.setCustomModelResourceLocation(blockItem, meta, new ModelResourceLocation(location, prop));
} catch (NullPointerException npe) {
throw new RuntimeException(b + " lacks an item!", npe);
}
}
}
ModelLoader.setCustomStateMapper(IndustrialWires.hvMultiblocks, new StateMapperBase()
{
@Nonnull
@Override
protected ModelResourceLocation getModelResourceLocation(@Nonnull IBlockState state)
{
Map<IProperty<?>, Comparable<?>> properties = state.getProperties();
boolean mirror = (Boolean) properties.get(IEProperties.BOOLEANS[0]);
return new ModelResourceLocation(
new ResourceLocation(IndustrialWires.MODID,
BlockHVMultiblocks.NAME+(mirror?"_mirrored":"")),
getPropertyString(properties));
}
});
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public static void renderWorldLastLow(RenderWorldLastEvent ev) {
if (shouldScreenshot) {
Minecraft mc = Minecraft.getMinecraft();
ITextComponent comp = ScreenShotHelper.saveScreenshot(mc.gameDir, mc.displayWidth, mc.displayHeight, mc.getFramebuffer());//TODO
mc.player.sendMessage(comp);
shouldScreenshot = false;
}
}
@SubscribeEvent
public static void onTextureStitch(TextureStitchEvent event) {
for (MechMBPart type:MechMBPart.INSTANCES.values()) {
ResourceLocation loc = type.getRotatingBaseModel();
try {
IModel model = ModelLoaderRegistry.getModel(loc);
if (model instanceof OBJModel) {
model = model.process(ImmutableMap.of("flip-v", "true"));
}
model.getTextures().forEach((rl)->event.getMap().registerSprite(rl));
IBakedModel b = model.bake(model.getDefaultState(), DefaultVertexFormats.BLOCK, (rl)->Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(rl.toString()));
BASE_MODELS.put(loc, b);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}

View file

@ -0,0 +1,512 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client;
import blusunrize.immersiveengineering.api.ManualHelper;
import blusunrize.immersiveengineering.api.ManualPageMultiblock;
import blusunrize.immersiveengineering.client.ClientUtils;
import blusunrize.immersiveengineering.common.Config;
import blusunrize.immersiveengineering.common.util.Utils;
import blusunrize.lib.manual.IManualPage;
import blusunrize.lib.manual.ManualInstance;
import blusunrize.lib.manual.ManualPages;
import blusunrize.lib.manual.ManualPages.PositionedItemStack;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import malte0811.industrialwires.*;
import malte0811.industrialwires.blocks.controlpanel.BlockTypes_Panel;
import malte0811.industrialwires.blocks.controlpanel.TileEntityPanelCreator;
import malte0811.industrialwires.blocks.controlpanel.TileEntityRSPanel;
import malte0811.industrialwires.blocks.converter.TileEntityMechMB;
import malte0811.industrialwires.blocks.hv.TileEntityJacobsLadder;
import malte0811.industrialwires.blocks.hv.TileEntityMarx;
import malte0811.industrialwires.client.gui.GuiPanelComponent;
import malte0811.industrialwires.client.gui.GuiPanelCreator;
import malte0811.industrialwires.client.gui.GuiRSPanelConn;
import malte0811.industrialwires.client.gui.GuiRenameKey;
import malte0811.industrialwires.client.manual.TextSplitter;
import malte0811.industrialwires.client.multiblock_io_model.MBIOModelLoader;
import malte0811.industrialwires.client.panelmodel.PanelModelLoader;
import malte0811.industrialwires.client.render.*;
import malte0811.industrialwires.compat.Compat;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.crafting.IC2TRHelper;
import malte0811.industrialwires.entities.EntityBrokenPart;
import malte0811.industrialwires.hv.MarxOreHandler;
import malte0811.industrialwires.hv.MultiblockMarx;
import malte0811.industrialwires.items.ItemIC2Coil;
import malte0811.industrialwires.items.ItemPanelComponent;
import malte0811.industrialwires.mech_mb.*;
import malte0811.industrialwires.util.CommandIWClient;
import malte0811.industrialwires.util.ConversionUtil;
import malte0811.industrialwires.util.MiscUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.ISound;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.audio.SoundHandler;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.obj.OBJLoader;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.*;
import static malte0811.industrialwires.IndustrialWires.*;
@SideOnly(Side.CLIENT)
public class ClientProxy extends CommonProxy {
@Override
public void preInit() {
super.preInit();
OBJLoader.INSTANCE.addDomain(IndustrialWires.MODID);
ModelLoaderRegistry.registerLoader(new PanelModelLoader());
ModelLoaderRegistry.registerLoader(new MBIOModelLoader());
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityJacobsLadder.class, new TileRenderJacobsLadder());
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityMarx.class, new TileRenderMarx());
TileRenderMechMB tesr = new TileRenderMechMB();
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityMechMB.class, tesr);
((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(tesr);
RenderingRegistry.registerEntityRenderingHandler(EntityBrokenPart.class, EntityRenderBrokenPart::new);
Shaders.initShaders(true);
}
@Override
public void postInit() {
super.postInit();
ManualInstance m = ManualHelper.getManual();
boolean uni = m.fontRenderer.getUnicodeFlag();
m.fontRenderer.setUnicodeFlag(true);
m.entryRenderPre();
TextSplitter splitter;
{
PositionedItemStack[][] wireRecipes = new PositionedItemStack[3][10];
int xBase = 15;
Ingredient copperCable = IC2TRHelper.getStack("cable", "type:copper,insulation:0");
Object2IntMap<ItemStack> copperCables = new Object2IntLinkedOpenHashMap<>();
for (ItemStack itemStack : copperCable.getMatchingStacks()) {
copperCables.put(itemStack, 1);
}
copperCables.put(new ItemStack(IEObjects.itemWireCoil, 1, 0), 8);
List<ItemStack> copperCableList = new ArrayList<>(copperCables.keySet());
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
wireRecipes[0][3 * i + j] = new PositionedItemStack(copperCableList, 18 * i + xBase, 18 * j);
}
}
ItemStack copperCoil = new ItemStack(IndustrialWires.coil, 1, 1);
ItemIC2Coil.setLength(copperCoil, 9);
wireRecipes[0][9] = new PositionedItemStack(copperCoil, 18 * 4 + xBase, 18);
Random r = new Random();
for (int i = 1; i < 3; i++) {
int lengthSum = 0;
for (int j1 = 0; j1 < 3; j1++) {
for (int j2 = 0; j2 < 3; j2++) {
if (r.nextDouble() > 1 / (1. + copperCables.size())) {
// cable
ItemStack chosen = copperCableList.get(r.nextInt(copperCables.size()));
lengthSum += copperCables.getInt(chosen);
wireRecipes[i][3 * j1 + j2] = new PositionedItemStack(chosen, 18 * j1 + xBase, 18 * j2);
} else {
// wire coil
int length = r.nextInt(99) + 1;
copperCoil = new ItemStack(IndustrialWires.coil, 1, 1);
ItemIC2Coil.setLength(copperCoil, length);
wireRecipes[i][3 * j1 + j2] = new PositionedItemStack(copperCoil, 18 * j1 + xBase, 18 * j2);
lengthSum += length;
}
}
}
copperCoil = new ItemStack(IndustrialWires.coil);
ItemIC2Coil.setLength(copperCoil, lengthSum);
wireRecipes[i][9] = new PositionedItemStack(copperCoil, 18 * 4 + xBase, 18);
}
splitter = new TextSplitter(m);
splitter.addSpecialPage(0, 0, 10,
s->new ManualPages.CraftingMulti(m, s, (Object[]) wireRecipes));
String text = I18n.format("ie.manual.entry.industrialwires.wires");
splitter.split(text);
List<IManualPage> entry = splitter.toManualEntry();
m.addEntry("industrialwires.wires", IndustrialWires.MODID, entry.toArray(new IManualPage[0]));
}
if (hasIC2 && IndustrialWires.mechConv != null) {
m.addEntry("industrialwires.mechConv", "industrialwires",
new ManualPages.Crafting(m, "industrialwires.mechConv0", new ItemStack(IndustrialWires.mechConv, 1, 1)),
new ManualPages.Crafting(m, "industrialwires.mechConv1", new ItemStack(IndustrialWires.mechConv, 1, 2)),
new ManualPages.Crafting(m, "industrialwires.mechConv2", new ItemStack(IndustrialWires.mechConv, 1, 0))
);
}
addUnblockableSounds(TINNITUS, TURN_FAST, TURN_SLOW);
ClientUtils.mc().getItemColors().registerItemColorHandler((stack, pass) -> {
if (pass == 1) {
PanelComponent pc = ItemPanelComponent.componentFromStack(stack);
if (pc != null) {
return 0xff000000 | pc.getColor();
}
}
return ~0;
}, IndustrialWires.panelComponent);
Config.manual_doubleA.put("iwJacobsUsage", IWConfig.HVStuff.jacobsUsageWatt);
Config.manual_double.put("iwFluxPerJoule", ConversionUtil.ifPerJoule());
Config.manual_int.put("iwKeysOnRing", IWConfig.maxKeysOnRing);
m.addEntry("industrialwires.jacobs", IndustrialWires.MODID,
new ManualPages.CraftingMulti(m, "industrialwires.jacobs0", new ItemStack(IndustrialWires.jacobsLadder, 1, 0), new ItemStack(IndustrialWires.jacobsLadder, 1, 1), new ItemStack(IndustrialWires.jacobsLadder, 1, 2)),
new ManualPages.Text(m, "industrialwires.jacobs1"));
String text = I18n.format("ie.manual.entry.industrialwires.intro");
splitter = new TextSplitter(m);
splitter.addSpecialPage(0, 0, 9, s -> new ManualPages.Crafting(m, s,
new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.DUMMY.ordinal())));
splitter.addSpecialPage(1, 0, 9, s -> new ManualPages.Crafting(m, s,
new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.UNFINISHED.ordinal())));
splitter.split(text);
m.addEntry("industrialwires.intro", "control_panels",
splitter.toManualEntry().toArray(new IManualPage[0])
);
m.addEntry("industrialwires.panel_creator", "control_panels",
new ManualPages.Crafting(m, "industrialwires.panel_creator0", new ItemStack(IndustrialWires.panel, 1, BlockTypes_Panel.CREATOR.ordinal())),
new ManualPages.Text(m, "industrialwires.panel_creator1"),
new ManualPages.Text(m, "industrialwires.panel_creator2")
);
text = I18n.format("ie.manual.entry.industrialwires.redstone");
splitter = new TextSplitter(m);
splitter.addSpecialPage(-1, 0, Compat.enableOtherRS ? 9 : 12, s -> new ManualPages.CraftingMulti(m, s,
new ResourceLocation(IndustrialWires.MODID, "control_panel_rs_other"),
new ResourceLocation(IndustrialWires.MODID, "control_panel_rs_wire")));
splitter.split(text);
m.addEntry("industrialwires.redstone", "control_panels",
splitter.toManualEntry().toArray(new IManualPage[0])
);
m.addEntry("industrialwires.components", "control_panels",
new ManualPages.Text(m, "industrialwires.components.general"),
new ManualPages.Crafting(m, "industrialwires.button", new ItemStack(IndustrialWires.panelComponent, 1, 0)),
new ManualPages.Crafting(m, "industrialwires.label", new ItemStack(IndustrialWires.panelComponent, 1, 1)),
new ManualPages.Crafting(m, "industrialwires.indicator_light", new ItemStack(IndustrialWires.panelComponent, 1, 2)),
new ManualPages.Crafting(m, "industrialwires.slider", new ItemStack(IndustrialWires.panelComponent, 1, 3)),
new ManualPages.CraftingMulti(m, "industrialwires.toggle_switch", new ItemStack(IndustrialWires.panelComponent, 1, 5), new ItemStack(IndustrialWires.panelComponent, 1, 6)),
new ManualPages.Text(m, "industrialwires.toggle_switch1"),
new ManualPages.Crafting(m, "industrialwires.variac", new ItemStack(IndustrialWires.panelComponent, 1, 4)),
new ManualPages.CraftingMulti(m, "industrialwires.lock", new ItemStack(IndustrialWires.panelComponent, 1, 7), new ItemStack(IndustrialWires.key)),
new ManualPages.Crafting(m, "industrialwires.lock1", new ItemStack(IndustrialWires.key, 1, 2)),
new ManualPages.Crafting(m, "industrialwires.panel_meter", new ItemStack(IndustrialWires.panelComponent, 1, 8)),
new ManualPages.Crafting(m, "industrialwires.7seg", new ItemStack(IndustrialWires.panelComponent, 1, 9)),
new ManualPages.Crafting(m, "industrialwires.rgb_led", new ItemStack(IndustrialWires.panelComponent, 1, 10))
);
List<MarxOreHandler.OreInfo> ores = MarxOreHandler.getRecipes();
text = I18n.format("ie.manual.entry.industrialwires.marx");
for (int i = 0; i < ores.size(); i++) {
MarxOreHandler.OreInfo curr = ores.get(i);
if (!curr.exampleInput.isEmpty()) {
text += I18n.format(IndustrialWires.MODID + ".desc.input") + ": §l" + curr.exampleInput.get(0).getDisplayName() + "§r<br>";
text += I18n.format(IndustrialWires.MODID + ".desc.output") + ": " + Utils.formatDouble(curr.maxYield, "0.#") + "x" + curr.output.get().getDisplayName() + "<br>";
if (curr.outputSmall != null && !curr.outputSmall.get().isEmpty()) {
text += I18n.format(IndustrialWires.MODID + ".desc.alt") + ": " + curr.smallMax + "x" + curr.outputSmall.get().getDisplayName() + "<br>";
}
text += I18n.format(IndustrialWires.MODID + ".desc.ideal_e") + ": " + Utils.formatDouble(curr.avgEnergy * MarxOreHandler.defaultEnergy / 1000, "0.#") + " kJ<br><br>";
}
}
splitter = new TextSplitter(m);
splitter.addSpecialPage(0, 0, 6,
(s) -> new ManualPageMultiblock(m, s,
MultiblockMarx.INSTANCE));
splitter.split(text);
List<IManualPage> marxEntry = splitter.toManualEntry();
m.addEntry("industrialwires.marx", IndustrialWires.MODID, marxEntry.toArray(new IManualPage[0]));
text = I18n.format("ie.manual.entry.industrialwires.mech_mb");
splitter = new TextSplitter(m);
splitter.addSpecialPage(0, 0, 8, (s) -> new ManualPageMultiblock(m, s,
MiscUtils.getMBFromName(MechMBPart.EXAMPLE_MECHMB_LOC.toString())));
splitter.split(text);
List<IManualPage> mechMBEntry = splitter.toManualEntry();
m.addEntry("industrialwires.mech_mb", IndustrialWires.MODID, mechMBEntry.toArray(new IManualPage[0]));
String[][] flywheelTable;
{
List<String[]> flywheelTableList = new ArrayList<>(1 + Material.values().length);
flywheelTableList.add(new String[]{"industrialwires.desc.material", "industrialwires.desc.inertia", "industrialwires.desc.max_speed"});
for (Material mat : Material.values()) {
MechPartFlywheel f = new MechPartFlywheel(mat);
flywheelTableList.add(new String[]{mat.oreName(), Utils.formatDouble(f.getInertia(), "0.#"),
Utils.formatDouble(f.getMaxSpeed(), "0.#")});
}
flywheelTable = flywheelTableList.toArray(new String[0][]);
}
text = I18n.format("ie.manual.entry.industrialwires.mech_mb_parts");
splitter = new TextSplitter(m);
splitter.addSpecialPage(0, 0, 10, (s) -> new ManualPageMultiblock(m, s,
MechMBPart.getManualMBForPart(MechPartFlywheel.class)));
splitter.addSpecialPage(1, 0, 1, s -> new ManualPages.Table(m, "", flywheelTable, true));
splitter.addSpecialPage(2, 0, 10, (s) -> new ManualPageMultiblock(m, s,
MechMBPart.getManualMBForPart(MechPartSingleCoil.class)));
splitter.addSpecialPage(3, 0, 10, (s) -> new ManualPageMultiblock(m, s,
MechMBPart.getManualMBForPart(MechPartFourElectrodes.class)));
if (IWConfig.MechConversion.allowMBEU()) {
text += I18n.format("ie.manual.entry.industrialwires.mech_mb_parts.commutator");
splitter.addSpecialPage(4, 0, 10, (s) -> new ManualPageMultiblock(m, s,
MechMBPart.getManualMBForPart(MechPartCommutator4Phase.class)));
}
splitter.split(text);
List<IManualPage> partsEntry = splitter.toManualEntry();
m.addEntry("industrialwires.mech_mb_parts", IndustrialWires.MODID, partsEntry.toArray(new IManualPage[0]));
m.entryRenderPost();
m.fontRenderer.setUnicodeFlag(uni);
ClientCommandHandler.instance.registerCommand(new CommandIWClient());
}
private static ISound playingTinnitus = null;
private void addUnblockableSounds(SoundEvent... sounds) {
int oldLength = Config.IEConfig.Tools.earDefenders_SoundBlacklist.length;
Config.IEConfig.Tools.earDefenders_SoundBlacklist =
Arrays.copyOf(Config.IEConfig.Tools.earDefenders_SoundBlacklist, oldLength + sounds.length);
for (int i = 0;i<sounds.length;i++) {
Config.IEConfig.Tools.earDefenders_SoundBlacklist[oldLength+i] = sounds[i].getSoundName().toString();
}
}
@Override
public void startTinnitus() {
final Minecraft mc = Minecraft.getMinecraft();
if (playingTinnitus==null||!mc.getSoundHandler().isSoundPlaying(playingTinnitus)) {
playingTinnitus = getTinnitus();
mc.getSoundHandler().playSound(playingTinnitus);
}
}
private ISound getTinnitus() {
final Minecraft mc = Minecraft.getMinecraft();
return new MovingSound(TINNITUS, SoundCategory.PLAYERS) {
@Override
public void update() {
if (mc.player.getActivePotionEffect(IWPotions.tinnitus)==null) {
donePlaying = true;
playingTinnitus = null;
}
}
@Override
public float getVolume() {
return .5F;
}
@Override
public float getXPosF() {
return (float) mc.player.posX;
}
@Override
public float getYPosF() {
return (float) mc.player.posY;
}
@Override
public float getZPosF() {
return (float) mc.player.posZ;
}
@Override
public boolean canRepeat() {
return true;
}
};
}
@Override
public World getClientWorld() {
return Minecraft.getMinecraft().world;
}
private Map<BlockPos, List<ISound>> playingSounds = new HashMap<>();
@Override
public void playJacobsLadderSound(TileEntityJacobsLadder te, int phase, Vec3d soundPos) {
stopAllSoundsExcept(te.getPos(), ImmutableSet.of());
SoundEvent event;
switch (phase) {
case 0:
event = LADDER_START;
break;
case 1:
event = LADDER_MIDDLE;
break;
case 2:
event = LADDER_END;
break;
default:
return;
}
PositionedSoundRecord sound = new PositionedSoundRecord(event.getSoundName(), SoundCategory.BLOCKS, te.size.soundVolume, 1,
false, 0, ISound.AttenuationType.LINEAR, (float) soundPos.x, (float) soundPos.y, (float) soundPos.z);
ClientUtils.mc().getSoundHandler().playSound(sound);
addSound(te.getPos(), sound);
}
@Override
public void updateMechMBTurningSound(TileEntityMechMB te, MechEnergy energy) {
SoundHandler sndHandler = ClientUtils.mc().getSoundHandler();
List<ISound> soundsAtPos;
if (playingSounds.containsKey(te.getPos())) {
soundsAtPos = playingSounds.get(te.getPos());
soundsAtPos.removeIf(s -> !sndHandler.isSoundPlaying(s));
if (soundsAtPos.isEmpty()) {
playingSounds.remove(te.getPos());
}
} else {
soundsAtPos = ImmutableList.of();
}
boolean hasSlow = false, hasFast = false;
for (ISound s:soundsAtPos) {
if (s.getSoundLocation().equals(TURN_FAST.getSoundName())) {
hasFast = true;
} else if (s.getSoundLocation().equals(TURN_SLOW.getSoundName())) {
hasSlow = true;
}
}
if (!hasSlow && energy.getVolumeSlow() > 0) {
ISound snd = new IWTickableSound(TURN_SLOW, SoundCategory.BLOCKS, energy::getVolumeSlow, energy::getPitch,
te.getPos().getX(), te.getPos().getY(), te.getPos().getZ());
sndHandler.playSound(snd);
addSound(te.getPos(), snd);
}
if (!hasFast && energy.getVolumeFast() > 0) {
ISound snd = new IWTickableSound(TURN_FAST, SoundCategory.BLOCKS, energy::getVolumeFast, energy::getPitch,
te.getPos().getX(), te.getPos().getY(), te.getPos().getZ());
sndHandler.playSound(snd);
addSound(te.getPos(), snd);
}
}
@Override
public void playMarxBang(TileEntityMarx te, Vec3d pos, float energy) {
SoundEvent soundLoc = MARX_BANG;
if (energy<0) {
energy = -energy;
soundLoc = MARX_POP;
}
PositionedSoundRecord sound = new PositionedSoundRecord(soundLoc.getSoundName(), SoundCategory.BLOCKS, 5*energy, 1,
false, 0, ISound.AttenuationType.LINEAR, (float) pos.x, (float) pos.y, (float) pos.z);
ClientUtils.mc().getSoundHandler().playSound(sound);
addSound(te.getPos(), sound);
}
private void addSound(BlockPos pos, ISound sound) {
List<ISound> allForPos = playingSounds.get(pos);
if (allForPos==null) {
allForPos = new ArrayList<>();
}
allForPos.add(sound);
if (allForPos.size()==1) {
playingSounds.put(pos, allForPos);
}
}
@Override
public void stopAllSoundsExcept(BlockPos pos, Set<?> excluded) {
if (playingSounds.containsKey(pos)) {
SoundHandler manager = Minecraft.getMinecraft().getSoundHandler();
List<ISound> sounds = playingSounds.get(pos);
List<ISound> toRemove = new ArrayList<>(sounds.size()-excluded.size());
for (ISound sound:sounds) {
if (!excluded.contains(sound)) {
manager.stopSound(sound);
toRemove.add(sound);
}
}
sounds.removeAll(toRemove);
if (sounds.isEmpty()) {
playingSounds.remove(pos);
}
}
}
@Override
public boolean isSingleplayer() {
return Minecraft.getMinecraft().isSingleplayer();
}
@Override
public boolean isValidTextureSource(ItemStack stack) {
if (!super.isValidTextureSource(stack)) {
return false;
}
IBakedModel texModel = Minecraft.getMinecraft().getRenderItem().getItemModelWithOverrides(stack,
null, null);
TextureAtlasSprite sprite = texModel.getParticleTexture();
//noinspection ConstantConditions
if (sprite == null || sprite.hasAnimationMetadata()) {
return false;
}
int[][] data = sprite.getFrameTextureData(0);
for (int x = 0; x < data.length; x++) {
for (int y = 0; y < data[x].length; y++) {
if ((data[x][y] >>> 24) != 255) {
return false;
}
}
}
return true;
}
@Override
public Gui getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
if (ID == 0) {
TileEntity te = world.getTileEntity(new BlockPos(x, y, z));
if (te instanceof TileEntityRSPanel) {
return new GuiRSPanelConn((TileEntityRSPanel) te);
}
if (te instanceof TileEntityPanelCreator) {
return new GuiPanelCreator(player.inventory, (TileEntityPanelCreator) te);
}
} else if (ID == 1) {
EnumHand h = z == 1 ? EnumHand.MAIN_HAND : EnumHand.OFF_HAND;
ItemStack held = player.getHeldItem(h);
if (!held.isEmpty()) {
if (held.getItem() == IndustrialWires.panelComponent) {
return new GuiPanelComponent(h, ItemPanelComponent.componentFromStack(held));
} else if (held.getItem() == IndustrialWires.key) {
return new GuiRenameKey(h);
}
}
}
return null;
}
}

View file

@ -0,0 +1,84 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client;
import blusunrize.immersiveengineering.common.util.chickenbones.Matrix4;
import malte0811.industrialwires.client.panelmodel.SmartLightingQuadIW;
import malte0811.industrialwires.controlpanel.PanelUtils;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.client.model.obj.OBJModel;
import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.util.vector.Vector3f;
import java.util.List;
@SideOnly(Side.CLIENT)
public class ClientUtilsIW {
/**
* Base on {@link blusunrize.immersiveengineering.client.ClientUtils#renderModelTESRFast(List, BufferBuilder, World, BlockPos)}
* (which I wrote)
*/
public static void renderModelTESRFast(List<BakedQuad> quads, BufferBuilder renderer) {
int brightness = 15 << 20 | 15 << 4;
int l1 = (brightness >> 0x10) & 0xFFFF;
int l2 = brightness & 0xFFFF;
for (BakedQuad quad : quads) {
int[] vData = quad.getVertexData();
VertexFormat format = quad.getFormat();
int size = format.getIntegerSize();
int uv = format.getUvOffsetById(0) / 4;
for (int i = 0; i < 4; ++i) {
renderer
.pos(Float.intBitsToFloat(vData[size * i]),
Float.intBitsToFloat(vData[size * i + 1]),
Float.intBitsToFloat(vData[size * i + 2]))
.color(255, 255, 255, 255)
.tex(Float.intBitsToFloat(vData[size * i + uv]), Float.intBitsToFloat(vData[size * i + uv + 1]))
.lightmap(l1, l2)
.endVertex();
}
}
}
@SideOnly(Side.CLIENT)
public static BakedQuad bakeQuad(RawQuad raw, Matrix4 transform, Matrix4 transfNormal) {
VertexFormat format = DefaultVertexFormats.ITEM;
UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(format);
builder.setQuadOrientation(raw.facing);
builder.setTexture(raw.tex);
Vector3f[] vertices = raw.vertices;
float[][] uvs = raw.uvs;
Vector3f normal = transfNormal.apply(raw.normal);
OBJModel.Normal faceNormal = new OBJModel.Normal(normal.x, normal.y, normal.z);
for (int i = 0; i < 4; i++) {
PanelUtils.putVertexData(format, builder, transform.apply(vertices[i]), faceNormal, uvs[i][0], uvs[i][1], raw.tex,
raw.colorA);
}
BakedQuad ret = builder.build();
if (raw.light>0) {
ret = new SmartLightingQuadIW(ret, raw.light);
}
return ret;
}
}

View file

@ -0,0 +1,87 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client;
import blusunrize.immersiveengineering.api.Lib;
import blusunrize.immersiveengineering.common.items.ItemEarmuffs;
import blusunrize.immersiveengineering.common.util.ItemNBTHelper;
import malte0811.industrialwires.IEObjects;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.ITickableSound;
import net.minecraft.client.audio.PositionedSound;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import java.util.function.Supplier;
public class IWTickableSound extends PositionedSound implements ITickableSound {
private Supplier<Float> getVolume;
private Supplier<Float> getPitch;
protected IWTickableSound(SoundEvent sound, SoundCategory category,
Supplier<Float> getVolume, Supplier<Float> getPitch,
float xPosF, float yPosF, float zPosF) {
super(sound, category);
this.getVolume = getVolume;
this.getPitch = getPitch;
this.repeat = true;
this.repeatDelay = 0;
this.xPosF = xPosF;
this.yPosF = yPosF;
this.zPosF = zPosF;
}
@Override
public boolean isDonePlaying() {
return getVolume.get()<=0;
}
@Override
public void update() {
//NOP
}
//This can be static as it's the same for all sounds
private static float mod = 1;
private static long lastCheck = Long.MIN_VALUE;
private static final int UPDATE_FREQU = 5;
@Override
public float getVolume() {
Minecraft mc = Minecraft.getMinecraft();
long time = mc.world.getTotalWorldTime();
// Earmuffs don't work well for long sounds
// so I adjust the volume manually and blacklist the sounds from the "normal" muffling
if (time>lastCheck+UPDATE_FREQU) {
mod = 1;
lastCheck = time;
ItemStack earmuffs = mc.player.getItemStackFromSlot(EntityEquipmentSlot.HEAD);
if (ItemNBTHelper.hasKey(earmuffs, Lib.NBT_Earmuffs))
earmuffs = ItemNBTHelper.getItemStack(earmuffs, Lib.NBT_Earmuffs);
if (!earmuffs.isEmpty() && IEObjects.itemEarmuffs.equals(earmuffs.getItem()) &&
!ItemNBTHelper.getBoolean(earmuffs, "IE:Earmuffs:Cat_" + category.getName())) {
mod = ItemEarmuffs.getVolumeMod(earmuffs);
}
}
return mod*getVolume.get();
}
@Override
public float getPitch() {
return getPitch.get();
}
}

View file

@ -1,26 +1,28 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client;
package malte0811.industrialwires.client;
import blusunrize.immersiveengineering.common.util.chickenbones.Matrix4;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.renderer.vertex.VertexFormatElement;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.util.vector.Vector3f;
import javax.annotation.Nullable;
@ -29,6 +31,7 @@ import java.util.Arrays;
import static org.lwjgl.util.vector.Vector3f.cross;
import static org.lwjgl.util.vector.Vector3f.sub;
@SideOnly(Side.CLIENT)
public class RawQuad {
public final Vector3f[] vertices = new Vector3f[4];
public final EnumFacing facing;
@ -78,10 +81,56 @@ public class RawQuad {
this.light = light;
}
public static RawQuad unbake(BakedQuad q) {
Vector3f[] vertices = new Vector3f[4];
float[] color = new float[4];
Vector3f normal = new Vector3f();
float[][] uvs = new float[4][2];
TextureAtlasSprite sprite = q.getSprite();
VertexFormat format = q.getFormat();
int pos = 0;
for (int v = 0; v < 4; v++) {
for (int e = 0; e < format.getElementCount(); e++) {
switch (format.getElement(e).getUsage()) {
case POSITION:
int x = q.getVertexData()[pos];
int y = q.getVertexData()[pos + 1];
int z = q.getVertexData()[pos + 2];
vertices[v] = new Vector3f(Float.intBitsToFloat(x),
Float.intBitsToFloat(y),
Float.intBitsToFloat(z));
break;
case COLOR:
for (int i = 0; i < 4; i++) {
color[i] = Float.intBitsToFloat(q.getVertexData()[pos + i]);
}
break;
case UV:
if (format.getElement(e).getType() == VertexFormatElement.EnumType.FLOAT) {
uvs[v][0] = sprite.getUnInterpolatedU(Float.intBitsToFloat(q.getVertexData()[pos]));
uvs[v][1] = sprite.getUnInterpolatedV(Float.intBitsToFloat(q.getVertexData()[pos + 1]));
}
break;
case NORMAL:
x = q.getVertexData()[pos];
y = q.getVertexData()[pos + 1];
z = q.getVertexData()[pos + 2];
normal.set(Float.intBitsToFloat(x),
Float.intBitsToFloat(y),
Float.intBitsToFloat(z));
break;
}
pos += format.getElement(e).getSize() / 4;
}
}
return new RawQuad(vertices[0], vertices[1], vertices[2], vertices[3],
q.getFace(), sprite, color, normal, uvs, -1);
}
public RawQuad apply(Matrix4 mat) {
Matrix4 matNormal = mat.copy().transpose();
matNormal.invert();
return new RawQuad(mat.apply(vertices[0]), mat.apply(vertices[1]), mat.apply(vertices[2]), mat.apply(vertices[3]),
facing, tex, colorA, matNormal.apply(normal), uvs, light);
}
}
}

View file

@ -1,18 +1,33 @@
package malte0811.industrialWires.client.gui;
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.gui;
import blusunrize.immersiveengineering.client.ClientUtils;
import blusunrize.immersiveengineering.client.gui.elements.GuiButtonCheckbox;
import blusunrize.immersiveengineering.client.gui.elements.GuiSliderIE;
import com.google.common.collect.ImmutableList;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.client.gui.elements.GuiChannelPicker;
import malte0811.industrialWires.client.gui.elements.GuiChannelPickerSmall;
import malte0811.industrialWires.client.gui.elements.GuiIntChooser;
import malte0811.industrialWires.containers.ContainerPanelComponent;
import malte0811.industrialWires.controlpanel.IConfigurableComponent;
import malte0811.industrialWires.controlpanel.PanelComponent;
import malte0811.industrialWires.items.ItemPanelComponent;
import malte0811.industrialWires.network.MessageItemSync;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.client.gui.elements.GuiChannelPicker;
import malte0811.industrialwires.client.gui.elements.GuiChannelPickerSmall;
import malte0811.industrialwires.client.gui.elements.GuiIntChooser;
import malte0811.industrialwires.containers.ContainerPanelComponent;
import malte0811.industrialwires.controlpanel.IConfigurableComponent;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.network.MessageItemSync;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
@ -28,6 +43,8 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static malte0811.industrialwires.util.NBTKeys.*;
public class GuiPanelComponent extends GuiContainer {
private PanelComponent component;
private IConfigurableComponent confComp;
@ -67,9 +84,9 @@ public class GuiPanelComponent extends GuiContainer {
toAdd.setText(sc.value);
stringTexts.add(toAdd);
}
IConfigurableComponent.RSChannelConfig[] rs = confComp.getRSChannelOptions();
IConfigurableComponent.RSColorConfig[] rs = confComp.getRSChannelOptions();
rsChannelChoosers.clear();
for (IConfigurableComponent.RSChannelConfig rc : rs) {
for (IConfigurableComponent.RSColorConfig rc : rs) {
if (rc.small) {
rsChannelChoosers.add(new GuiChannelPickerSmall(0, componentLeft + rc.x, componentTop + rc.y, 10, 40, rc.value));
} else {
@ -135,6 +152,11 @@ public class GuiPanelComponent extends GuiContainer {
sync(i, picker.getSelected());
}
if (stopNow) {
for (GuiChannelPicker picker2:rsChannelChoosers) {
if (picker!=picker2&&picker2 instanceof GuiChannelPickerSmall) {
((GuiChannelPickerSmall) picker2).close();
}
}
return;
}
}
@ -187,14 +209,13 @@ public class GuiPanelComponent extends GuiContainer {
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
GlStateManager.color(1, 1, 1, 1);
RenderHelper.disableStandardItemLighting();
for (GuiChannelPicker pick : rsChannelChoosers) {
pick.drawButton(mc, mouseX, mouseY);
}
for (GuiButtonCheckbox box : boolButtons) {
box.drawButton(mc, mouseX, mouseY);
box.drawButton(mc, mouseX, mouseY, partialTicks);
}
for (GuiTextField field : stringTexts) {
field.drawTextBox();
@ -202,8 +223,24 @@ public class GuiPanelComponent extends GuiContainer {
for (GuiIntChooser choose : intChoosers) {
choose.drawChooser();
}
for (GuiSliderIE choose : floatSliders) {
choose.drawButton(mc, mouseX, mouseY);
for (int i = 0; i < floatSliders.size(); i++) {
GuiSliderIE slider = floatSliders.get(i);
double oldV = slider.getValue();
slider.drawButton(mc, mouseX, mouseY, partialTicks);
if (oldV != slider.getValue()) {
sync(i, (float) slider.getValue());
}
}
GuiChannelPickerSmall openPicker = null;
for (GuiChannelPicker pick : rsChannelChoosers) {
if (pick instanceof GuiChannelPickerSmall&&((GuiChannelPickerSmall) pick).open) {
openPicker = (GuiChannelPickerSmall) pick;
} else {
pick.drawButton(mc, mouseX, mouseY, partialTicks);
}
}
if (openPicker != null) {
openPicker.drawButton(mc, mouseX, mouseY, partialTicks);
}
//TOOLTIPS
for (int i = 0; i < rsChannelChoosers.size(); i++) {
@ -211,6 +248,7 @@ public class GuiPanelComponent extends GuiContainer {
String tooltip = confComp.fomatConfigDescription(IConfigurableComponent.ConfigType.RS_CHANNEL, i);
if (tooltip != null && pick.isHovered(mouseX, mouseY)) {
ClientUtils.drawHoveringText(ImmutableList.of(tooltip), mouseX, mouseY, mc.fontRenderer);
return;
}
}
for (int i = 0; i < boolButtons.size(); i++) {
@ -218,6 +256,7 @@ public class GuiPanelComponent extends GuiContainer {
String tooltip = confComp.fomatConfigDescription(IConfigurableComponent.ConfigType.BOOL, i);
if (tooltip != null && box.isMouseOver()) {
ClientUtils.drawHoveringText(ImmutableList.of(tooltip), mouseX, mouseY, mc.fontRenderer);
return;
}
}
for (int i = 0; i < stringTexts.size(); i++) {
@ -226,6 +265,7 @@ public class GuiPanelComponent extends GuiContainer {
if (tooltip != null && mouseX >= field.x && mouseX < field.x + field.width &&
mouseY >= field.y && mouseY < field.y + field.height) {
ClientUtils.drawHoveringText(ImmutableList.of(tooltip), mouseX, mouseY, mc.fontRenderer);
return;
}
}
for (int i = 0; i < intChoosers.size(); i++) {
@ -233,6 +273,7 @@ public class GuiPanelComponent extends GuiContainer {
String tooltip = confComp.fomatConfigDescription(IConfigurableComponent.ConfigType.INT, i);
if (tooltip != null && choose.isMouseOver(mouseX, mouseY)) {
ClientUtils.drawHoveringText(ImmutableList.of(tooltip), mouseX, mouseY, mc.fontRenderer);
return;
}
}
for (int i = 0; i < floatSliders.size(); i++) {
@ -240,47 +281,48 @@ public class GuiPanelComponent extends GuiContainer {
String tooltip = confComp.fomatConfigDescription(IConfigurableComponent.ConfigType.FLOAT, i);
if (tooltip != null && choose.isMouseOver()) {
ClientUtils.drawHoveringText(ImmutableList.of(tooltip), mouseX, mouseY, mc.fontRenderer);
return;
}
}
}
private void sync(int id, String value) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.STRING.ordinal());
update.setInteger(ItemPanelComponent.ID, id);
update.setString(ItemPanelComponent.VALUE, value);
update.setInteger(TYPE, IConfigurableComponent.ConfigType.STRING.ordinal());
update.setInteger(ID, id);
update.setString(VALUE, value);
syncSingle(update);
}
private void sync(int id, boolean value) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.BOOL.ordinal());
update.setInteger(ItemPanelComponent.ID, id);
update.setBoolean(ItemPanelComponent.VALUE, value);
update.setInteger(TYPE, IConfigurableComponent.ConfigType.BOOL.ordinal());
update.setInteger(ID, id);
update.setBoolean(VALUE, value);
syncSingle(update);
}
private void sync(int id, byte value) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.RS_CHANNEL.ordinal());
update.setInteger(ItemPanelComponent.ID, id);
update.setByte(ItemPanelComponent.VALUE, value);
update.setInteger(TYPE, IConfigurableComponent.ConfigType.RS_CHANNEL.ordinal());
update.setInteger(ID, id);
update.setByte(VALUE, value);
syncSingle(update);
}
private void sync(int id, int value) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.INT.ordinal());
update.setInteger(ItemPanelComponent.ID, id);
update.setInteger(ItemPanelComponent.VALUE, value);
update.setInteger(TYPE, IConfigurableComponent.ConfigType.INT.ordinal());
update.setInteger(ID, id);
update.setInteger(VALUE, value);
syncSingle(update);
}
private void sync(int id, float value) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.FLOAT.ordinal());
update.setInteger(ItemPanelComponent.ID, id);
update.setFloat(ItemPanelComponent.VALUE, value);
update.setInteger(TYPE, IConfigurableComponent.ConfigType.FLOAT.ordinal());
update.setInteger(ID, id);
update.setFloat(VALUE, value);
syncSingle(update);
}
@ -288,37 +330,37 @@ public class GuiPanelComponent extends GuiContainer {
NBTTagList list = new NBTTagList();
for (int i = 0; i < stringTexts.size(); i++) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.STRING.ordinal());
update.setInteger(ItemPanelComponent.ID, i);
update.setString(ItemPanelComponent.VALUE, stringTexts.get(i).getText());
update.setInteger(TYPE, IConfigurableComponent.ConfigType.STRING.ordinal());
update.setInteger(ID, i);
update.setString(VALUE, stringTexts.get(i).getText());
list.appendTag(update);
}
for (int i = 0; i < boolButtons.size(); i++) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.BOOL.ordinal());
update.setInteger(ItemPanelComponent.ID, i);
update.setBoolean(ItemPanelComponent.VALUE, boolButtons.get(i).state);
update.setInteger(TYPE, IConfigurableComponent.ConfigType.BOOL.ordinal());
update.setInteger(ID, i);
update.setBoolean(VALUE, boolButtons.get(i).state);
list.appendTag(update);
}
for (int i = 0; i < rsChannelChoosers.size(); i++) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.RS_CHANNEL.ordinal());
update.setInteger(ItemPanelComponent.ID, i);
update.setByte(ItemPanelComponent.VALUE, rsChannelChoosers.get(i).getSelected());
update.setInteger(TYPE, IConfigurableComponent.ConfigType.RS_CHANNEL.ordinal());
update.setInteger(ID, i);
update.setByte(VALUE, rsChannelChoosers.get(i).getSelected());
list.appendTag(update);
}
for (int i = 0; i < intChoosers.size(); i++) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.INT.ordinal());
update.setInteger(ItemPanelComponent.ID, i);
update.setInteger(ItemPanelComponent.VALUE, intChoosers.get(i).getValue());
update.setInteger(TYPE, IConfigurableComponent.ConfigType.INT.ordinal());
update.setInteger(ID, i);
update.setInteger(VALUE, intChoosers.get(i).getValue());
list.appendTag(update);
}
for (int i = 0; i < floatSliders.size(); i++) {
NBTTagCompound update = new NBTTagCompound();
update.setInteger(ItemPanelComponent.TYPE, IConfigurableComponent.ConfigType.FLOAT.ordinal());
update.setInteger(ItemPanelComponent.ID, i);
update.setFloat(ItemPanelComponent.VALUE, (float) floatSliders.get(i).getValue());
update.setInteger(TYPE, IConfigurableComponent.ConfigType.FLOAT.ordinal());
update.setInteger(ID, i);
update.setFloat(VALUE, (float) floatSliders.get(i).getValue());
list.appendTag(update);
}
sync(list);
@ -334,5 +376,6 @@ public class GuiPanelComponent extends GuiContainer {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setTag("data", list);
IndustrialWires.packetHandler.sendToServer(new MessageItemSync(container.hand, nbt));
IndustrialWires.panelComponent.onChange(nbt, Minecraft.getMinecraft().player, container.hand);
}
}

View file

@ -1,33 +1,30 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.gui;
package malte0811.industrialwires.client.gui;
import blusunrize.immersiveengineering.client.ClientUtils;
import com.google.common.collect.ImmutableList;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.controlpanel.TileEntityPanelCreator;
import malte0811.industrialWires.containers.ContainerPanelCreator;
import malte0811.industrialWires.controlpanel.MessageType;
import malte0811.industrialWires.controlpanel.PanelComponent;
import malte0811.industrialWires.controlpanel.PanelUtils;
import malte0811.industrialWires.items.ItemPanelComponent;
import malte0811.industrialWires.network.MessageGUIInteract;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.controlpanel.TileEntityPanelCreator;
import malte0811.industrialwires.containers.ContainerPanelCreator;
import malte0811.industrialwires.controlpanel.MessageType;
import malte0811.industrialwires.controlpanel.PanelComponent;
import malte0811.industrialwires.controlpanel.PanelUtils;
import malte0811.industrialwires.items.ItemPanelComponent;
import malte0811.industrialwires.network.MessageGUIInteract;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
@ -39,14 +36,23 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
public class GuiPanelCreator extends GuiContainer {
public int panelSize = 128;
private ContainerPanelCreator container;
private boolean snapToGrid = false;
private int snapToGrid = 0;
private ResourceLocation textureLoc = new ResourceLocation(IndustrialWires.MODID, "textures/gui/panel_creator.png");
public GuiPanelCreator(InventoryPlayer ip, TileEntityPanelCreator te) {
@ -60,26 +66,128 @@ public class GuiPanelCreator extends GuiContainer {
GlStateManager.color(1, 1, 1, 1);
mc.getTextureManager().bindTexture(textureLoc);
this.drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
for (PanelComponent pc : container.tile.components) {
drawPanelComponent(pc, -1, -1);
}
int x0 = getX0();
int y0 = getY0();
int xRel = mouseX - x0;
int yRel = mouseY - y0;
if (snapToGrid) {
xRel = (int) Math.floor(xRel * 16 / panelSize) * panelSize / 16;
yRel = (int) Math.floor(yRel * 16 / panelSize) * panelSize / 16;
}
for (PanelComponent pc : container.tile.components) {
drawPanelComponent(pc, -1, -1);
}
PanelComponent curr = getFloatingPC();
if (curr != null && 0 <= xRel && xRel <= panelSize && 0 <= yRel && yRel <= panelSize) {
Runnable after = ()->{};
if (snapToGrid != 0) {
curr.setX(xRel/(float)panelSize);
curr.setY(yRel/(float)panelSize);
BiFunction<Integer, Integer, Integer> right = (a, b)->b;
BiFunction<Integer, Integer, Integer> left = (a, b)->a;
Function<PanelComponent, Double> xSize = (pc)->{
AxisAlignedBB aabb = pc.getBlockRelativeAABB();
return aabb.maxX-aabb.minX;
};
Function<PanelComponent, Double> ySize = (pc)->{
AxisAlignedBB aabb = pc.getBlockRelativeAABB();
return aabb.maxZ-aabb.minZ;
};
Pair<Integer, Runnable> xSnap = snapToGrid(xRel, curr, PanelComponent::getX, PanelComponent::getY,
xSize, ySize, left, right);
xRel = xSnap.getLeft();
Pair<Integer, Runnable> ySnap = snapToGrid(yRel, curr, PanelComponent::getY, PanelComponent::getX,
ySize, xSize, right, left);
yRel = ySnap.getLeft();
after = ()->{
xSnap.getRight().run();
ySnap.getRight().run();
};
}
drawPanelComponent(curr, xRel, yRel);
after.run();
}
}
private Pair<Integer, Runnable> snapToGrid(int mouse, PanelComponent toPlace, Function<PanelComponent, Float> pos, Function<PanelComponent, Float> pos2,
Function<PanelComponent, Double> size,Function<PanelComponent, Double> size2,
BiFunction<Integer, Integer, Integer> getY, BiFunction<Integer, Integer, Integer> getX) {
List<PanelComponent> components = container.tile.components;
if (snapToGrid==2&&!components.isEmpty()) {
List<Pair<PanelComponent, Double>> compLefts = new ArrayList<>(components.size());
List<Pair<PanelComponent, Double>> compCenters = new ArrayList<>(components.size());
List<Pair<PanelComponent, Double>> compRights = new ArrayList<>(components.size());
for (PanelComponent pc : components) {
double compLeft = pos.apply(pc);
double compSize = size.apply(pc);
compLefts.add(new ImmutablePair<>(pc, compLeft));
compRights.add(new ImmutablePair<>(pc, compLeft + compSize));
compCenters.add(new ImmutablePair<>(pc, compLeft + compSize / 2));
}
double mainLeft = pos.apply(toPlace);
double mainSize = size.apply(toPlace);
double mainRight = mainLeft + mainSize;
double mainCenter = (mainRight + mainLeft) / 2;
Triple<PanelComponent, ComponentSnapType, Double> min = getMinDist(compLefts, mainLeft, mainCenter, mainRight);
{
Triple<PanelComponent, ComponentSnapType, Double> tmpMin = getMinDist(compCenters, mainLeft, mainCenter, mainRight);
if (Math.abs(tmpMin.getRight()) < Math.abs(min.getRight())) {
min = tmpMin;
}
tmpMin = getMinDist(compRights, mainLeft, mainCenter, mainRight);
if (Math.abs(tmpMin.getRight()) < Math.abs(min.getRight())) {
min = tmpMin;
}
}
if (Math.abs(min.getRight())<.5/16) {
int ret = (int)(mouse+min.getRight()*panelSize);
PanelComponent snappedTo = min.getLeft();
ComponentSnapType type = min.getMiddle();
return new ImmutablePair<>(ret,()->{
int hor1, hor2;
float posOther = pos2.apply(toPlace);
hor1 = Math.round(Math.min(posOther, pos2.apply(snappedTo))*panelSize);
hor2 = (int) Math.round(Math.max(posOther+size2.apply(toPlace), pos2.apply(snappedTo)+size2.apply(snappedTo))*panelSize);
int vert1 = (int) (ret+(.5*type.ordinal())*mainSize*panelSize);
int vert2 = vert1+1;
int x0 = getX0(), y0 = getY0();
drawRect(x0+getX.apply(hor1, vert1), y0+getY.apply(hor1, vert1), x0+getX.apply(hor2, vert2),
y0+getY.apply(hor2, vert2), 0xff666666);
});
}
}
if (snapToGrid!=0) {
mouse = Math.round(mouse * 16 / panelSize) * panelSize / 16;
}
return new ImmutablePair<>(mouse, ()->{});
}
private Triple<PanelComponent, ComponentSnapType, Double> getMinDist(List<Pair<PanelComponent, Double>> comps,
double left, double center, double right) {
Pair<PanelComponent, Double> tmpMin = Collections.min(comps, Comparator.comparingDouble(a -> Math.abs(a.getRight() - left)));
Triple<PanelComponent, ComponentSnapType, Double> totalMin = new ImmutableTriple<>(tmpMin.getLeft(), ComponentSnapType.LEFT,
tmpMin.getRight()-left);
tmpMin = Collections.min(comps, Comparator.comparingDouble(a -> Math.abs(a.getRight() - center)));
if (Math.abs(tmpMin.getRight() - center)<Math.abs(totalMin.getRight())) {
totalMin = new ImmutableTriple<>(tmpMin.getLeft(), ComponentSnapType.CENTER,
tmpMin.getRight()-center);
}
tmpMin = Collections.min(comps, Comparator.comparingDouble(a -> Math.abs(a.getRight() - right)));
if (Math.abs(tmpMin.getRight() - right)<Math.abs(totalMin.getRight())) {
totalMin = new ImmutableTriple<>(tmpMin.getLeft(), ComponentSnapType.RIGHT,
tmpMin.getRight()-right);
}
return totalMin;
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
String tooltip = null;
if (buttonList.get(0).isMouseOver()) {
tooltip = I18n.format(IndustrialWires.MODID + ".desc.create_panel");
@ -87,11 +195,7 @@ public class GuiPanelCreator extends GuiContainer {
} else if (buttonList.get(1).isMouseOver()) {
tooltip = I18n.format(IndustrialWires.MODID + ".desc.remove_all");
} else if (buttonList.get(2).isMouseOver()) {
if (snapToGrid) {
tooltip = I18n.format(IndustrialWires.MODID + ".desc.disable_snap");
} else {
tooltip = I18n.format(IndustrialWires.MODID + ".desc.enable_snap");
}
tooltip = I18n.format(IndustrialWires.MODID + ".desc.snap"+snapToGrid);
} else if (buttonList.get(3).isMouseOver()) {
tooltip = I18n.format(IndustrialWires.MODID + ".desc.disassemble");
}
@ -199,13 +303,13 @@ public class GuiPanelCreator extends GuiContainer {
nbt.setInteger("type", MessageType.REMOVE_ALL.ordinal());
break;
case 2:
snapToGrid = !snapToGrid;
snapToGrid = (snapToGrid+1)%3;
break;
case 3:
nbt.setInteger("type", MessageType.DISASSEMBLE.ordinal());
break;
}
if (!nbt.hasNoTags()) {
if (!nbt.isEmpty()) {
IndustrialWires.packetHandler.sendToServer(new MessageGUIInteract(container.tile, nbt));
}
}
@ -225,4 +329,10 @@ public class GuiPanelCreator extends GuiContainer {
lastFloatingPC = ItemPanelComponent.componentFromStack(floating);
return lastFloatingPC;
}
private enum ComponentSnapType {
LEFT,
CENTER,
RIGHT;
}
}

View file

@ -1,28 +1,25 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.gui;
package malte0811.industrialwires.client.gui;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.blocks.controlpanel.TileEntityRSPanelConn;
import malte0811.industrialWires.client.gui.elements.GuiIntChooser;
import malte0811.industrialWires.containers.ContainerRSPanelConn;
import malte0811.industrialWires.network.MessageGUIInteract;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.controlpanel.TileEntityRSPanel;
import malte0811.industrialwires.client.gui.elements.GuiIntChooser;
import malte0811.industrialwires.containers.ContainerRSPanelConn;
import malte0811.industrialwires.network.MessageGUIInteract;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
@ -33,10 +30,10 @@ import net.minecraft.util.ResourceLocation;
import java.io.IOException;
public class GuiRSPanelConn extends GuiContainer {
private TileEntityRSPanelConn te;
private TileEntityRSPanel te;
private GuiIntChooser chooser;
public GuiRSPanelConn(TileEntityRSPanelConn tile) {
public GuiRSPanelConn(TileEntityRSPanel tile) {
super(new ContainerRSPanelConn(tile));
te = tile;
}
@ -59,7 +56,9 @@ public class GuiRSPanelConn extends GuiContainer {
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
GlStateManager.color(1, 1, 1, 1);
RenderHelper.disableStandardItemLighting();
chooser.drawChooser();

View file

@ -1,26 +1,23 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.gui;
package malte0811.industrialwires.client.gui;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.containers.ContainerRenameKey;
import malte0811.industrialWires.network.MessageItemSync;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.containers.ContainerRenameKey;
import malte0811.industrialwires.network.MessageItemSync;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
@ -59,7 +56,9 @@ public class GuiRenameKey extends GuiContainer {
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
GlStateManager.color(1, 1, 1, 1);
RenderHelper.disableStandardItemLighting();
field.drawTextBox();

View file

@ -1,4 +1,19 @@
package malte0811.industrialWires.client.gui.elements;
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.gui.elements;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
@ -17,7 +32,7 @@ public class GuiChannelPicker extends GuiButton {
}
@Override
public void drawButton(@Nonnull Minecraft mc, int mouseX, int mouseY) {
public void drawButton(@Nonnull Minecraft mc, int mouseX, int mouseY, float patrtialTicks) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
@ -31,7 +46,7 @@ public class GuiChannelPicker extends GuiButton {
int xMax = xMin + width / 4;
int yMax = yMin + height / 4;
EnumDyeColor color = EnumDyeColor.byMetadata(i);
int colorVal = color.getMapColor().colorValue | 0xff000000;
int colorVal = color.getColorValue() | 0xff000000;
if (mouseX >= xMin && mouseX < xMax && mouseY >= yMin && mouseY < yMax) {
currHovered = i;
}

View file

@ -1,22 +1,19 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.gui.elements;
package malte0811.industrialwires.client.gui.elements;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
@ -25,7 +22,7 @@ import net.minecraft.item.EnumDyeColor;
import javax.annotation.Nonnull;
public class GuiChannelPickerSmall extends GuiChannelPicker {
private boolean open = false;
public boolean open = false;
private int offSize, onSize;
public GuiChannelPickerSmall(int id, int x, int y, int offSize, int onSize, byte selectedChannel) {
@ -36,16 +33,17 @@ public class GuiChannelPickerSmall extends GuiChannelPicker {
}
@Override
public void drawButton(@Nonnull Minecraft mc, int mouseX, int mouseY) {
public void drawButton(@Nonnull Minecraft mc, int mouseX, int mouseY, float partialTicks) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
if (open) {
super.drawButton(mc, mouseX, mouseY);
drawRect(x, y, x + width, y + height, 0xff99ff99);
super.drawButton(mc, mouseX, mouseY, partialTicks);
} else {
EnumDyeColor color = EnumDyeColor.byMetadata(selected);
int colorVal = color.getMapColor().colorValue | 0xff000000;
int colorVal = color.getColorValue() | 0xff000000;
drawRect(x, y, x + width, y + height, colorVal);
}
}
@ -66,10 +64,14 @@ public class GuiChannelPickerSmall extends GuiChannelPicker {
select();
ret = true;
}
open = false;
width = offSize;
height = offSize;
close();
return ret;
}
}
public void close() {
open = false;
width = offSize;
height = offSize;
}
}

View file

@ -1,4 +1,19 @@
package malte0811.industrialWires.client.gui.elements;
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.gui.elements;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
@ -24,13 +39,23 @@ public class GuiIntChooser extends Gui {
public void drawChooser() {
int color = 0xE0E0E0;
String val = String.format(format, Integer.toString(value)).replace(' ', '0');
if (value >= 0 && allowNegative) {
val = "+" + val;
String val = String.format(format, Integer.toString(Math.abs(value))).replace(' ', '0');
if (allowNegative) {
if (value > 0) {
val = "+" + val;
} else if (value < 0) {
val = "-" + val;
} else {
val = "0" + val;
}
}
mc.fontRenderer.drawStringWithShadow(val, xPos + mc.fontRenderer.getCharWidth('-') + 1, yPos, color);
mc.fontRenderer.drawStringWithShadow("-", xPos, yPos, color);
mc.fontRenderer.drawStringWithShadow("+", xPlus, yPos, color);
color = 0x9999ff;
if (allowNegative&&value!=0) {
color = value<0?0xff9999:0x99ff99;
}
mc.fontRenderer.drawStringWithShadow(val, xPos + mc.fontRenderer.getCharWidth('-') + 1, yPos, color);
}
public void click(int x, int y) {
@ -41,7 +66,7 @@ public class GuiIntChooser extends Gui {
value++;
}
} else if (x >= xPos && x <= xPos + mc.fontRenderer.getCharWidth('-')) {
if (value > (allowNegative ? -value : 0)) {
if (value > (allowNegative ? -1 : 0)) {
value--;
}
}

View file

@ -0,0 +1,252 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.manual;
import blusunrize.lib.manual.IManualPage;
import blusunrize.lib.manual.ManualInstance;
import blusunrize.lib.manual.ManualPages;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class TextSplitter {
private final Function<String, Integer> width;
private final TIntObjectMap<Map<Integer, Page>> specialByAnchor = new TIntObjectHashMap<>();
private final TIntObjectMap<Page> specialByPage = new TIntObjectHashMap<>();
private final List<List<String>> entry = new ArrayList<>();
private final Function<String, String> tokenTransform;
private final int lineWidth;
private final int linesPerPage;
private TIntIntMap pageByAnchor = new TIntIntHashMap();
private final Function<String, IManualPage> defaultPage;
public TextSplitter(Function<String, Integer> w, int lineWidthPixel, int linesPerPage,
Function<String, IManualPage> defPage, Function<String, String> tokenTransform) {
width = w;
this.lineWidth = lineWidthPixel;
this.linesPerPage = linesPerPage;
this.tokenTransform = tokenTransform;
this.defaultPage = defPage;
}
public TextSplitter(ManualInstance m) {
this(m.fontRenderer::getStringWidth, 120, 16, s-> new ManualPages.Text(m, s), (s) -> s);
}
public TextSplitter(ManualInstance m, Function<String, String> tokenTransform) {
this(m.fontRenderer::getStringWidth, 120, 16,s-> new ManualPages.Text(m, s), tokenTransform);
}
public void clearSpecialByPage() {
specialByPage.clear();
}
public void clearSpecialByAnchor() {
specialByAnchor.clear();
}
public void addSpecialPage(int ref, int offset, int lines, Function<String, IManualPage> factory) {
if (offset < 0 || (ref != -1 && ref < 0)) {
throw new IllegalArgumentException();
}
if (!specialByAnchor.containsKey(ref)) {
specialByAnchor.put(ref, new HashMap<>());
}
specialByAnchor.get(ref).put(offset, new Page(lines, factory));
}
// I added labels to all break statements to make it more readable
@SuppressWarnings({"UnnecessaryLabelOnBreakStatement", "UnusedLabel"})
public void split(String in) {
clearSpecialByPage();
entry.clear();
String[] wordsAndSpaces = splitWhitespace(in);
int pos = 0;
List<String> overflow = new ArrayList<>();
updateSpecials(-1, 0, 0, -1);
entry:
while (pos < wordsAndSpaces.length) {
List<String> page = new ArrayList<>(overflow);
overflow.clear();
page:
while (page.size() < getLinesOnPage(entry.size()) && pos < wordsAndSpaces.length) {
String line = "";
int currWidth = 0;
line:
while (pos < wordsAndSpaces.length && currWidth < lineWidth) {
String token = tokenTransform.apply(wordsAndSpaces[pos]);
int textWidth = getWidth(token);
if (currWidth + textWidth < lineWidth || line.length() == 0) {
pos++;
if (token.equals("<np>")) {
page.add(line);
break page;
} else if (token.equals("<br>")) {
break line;
} else if (token.startsWith("<&") && token.endsWith(">")) {
int id = Integer.parseInt(token.substring(2, token.length() - 1));
int pageForId = entry.size();
Map<Integer, Page> specialForId = specialByAnchor.get(id);
if (specialForId != null && specialForId.containsKey(0)) {
if (page.size() >= specialForId.get(0).lines) {
pageForId++;
}
}
//New page if there is already a special element on this page
if (updateSpecials(id, pageForId, page.size(), entry.size())) {
page.add(line);
pos--;
break page;
}
} else if (!Character.isWhitespace(token.charAt(0)) || line.length() != 0) {//Don't add whitespace at the start of a line
line += token;
currWidth += textWidth;
}
} else {
break line;
}
}
line = line.trim();
if (!line.isEmpty())
page.add(line);
}
if (!(page.stream().allMatch(String::isEmpty) && pos == wordsAndSpaces.length)) {
int linesMax = getLinesOnPage(entry.size());
if (page.size() > linesMax) {
overflow.addAll(page.subList(linesMax, page.size()));
page = page.subList(0, linesMax);
}
entry.add(page);
}
}
}
public List<IManualPage> toManualEntry() {
List<IManualPage> ret = new ArrayList<>(entry.size());
for (int i = 0; i < entry.size(); i++) {
String s = entry.get(i).stream().collect(Collectors.joining("\n"));
if (specialByPage.containsKey(i)) {
ret.add(specialByPage.get(i).factory.apply(s));
} else {
ret.add(defaultPage.apply(s));
}
}
return ret;
}
private int getWidth(String text) {
switch (text) {
case "<br>":
case "<np>":
return 0;
default:
if (text.startsWith("<link;")) {
text = text.substring(text.indexOf(';') + 1);
text = text.substring(text.indexOf(';') + 1, text.lastIndexOf(';'));
}
return width.apply(text);
}
}
private int getLinesOnPage(int id) {
if (specialByPage.containsKey(id)) {
return specialByPage.get(id).lines;
}
return linesPerPage;
}
private boolean updateSpecials(int ref, int pageRef, int currLine, int currPage) {
if (specialByAnchor.containsKey(ref)) {
TIntObjectMap<Page> specialByPageTmp = new TIntObjectHashMap<>();
for (Map.Entry<Integer, Page> entry : specialByAnchor.get(ref).entrySet()) {
int specialPage = pageRef + entry.getKey();
if (specialByPage.containsKey(specialPage)) {
return true;
}
if (entry.getKey()==0 && currPage==pageRef&&entry.getValue().lines<=currLine) {
return true;
}
specialByPageTmp.put(specialPage, entry.getValue());
}
specialByPage.putAll(specialByPageTmp);
} else if (ref != -1) {//Default reference for page 0
System.out.println("WARNING: Reference " + ref + " was found, but no special pages were registered for it");
}
pageByAnchor.put(ref, pageRef);
return false;
}
private String[] splitWhitespace(String in) {
List<String> parts = new ArrayList<>();
for (int i = 0; i < in.length(); ) {
StringBuilder here = new StringBuilder();
char first = in.charAt(i);
here.append(first);
i++;
for (; i < in.length(); ) {
char hereC = in.charAt(i);
byte action = shouldSplit(first, hereC);
if ((action & 1) != 0) {
here.append(in.charAt(i));
i++;
}
if ((action & 2) != 0 || (action & 1) == 0) {
break;
}
}
parts.add(here.toString());
}
return parts.toArray(new String[0]);
}
/**
* @return &1: add
* &2: end here
*/
private byte shouldSplit(char start, char here) {
byte ret = 0b01;
if (Character.isWhitespace(start) ^ Character.isWhitespace(here)) {
ret = 0b10;
}
if (here == '<') {
ret = 0b10;
}
if (start == '<') {
ret = 0b01;
if (here == '>') {
ret |= 0b10;
}
}
return ret;
}
private class Page {
final int lines;
final Function<String, IManualPage> factory;
public Page(int l, Function<String, IManualPage> f) {
factory = f;
lines = l;
}
}
}

View file

@ -0,0 +1,183 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.multiblock_io_model;
import blusunrize.immersiveengineering.api.IEEnums.SideConfig;
import blusunrize.immersiveengineering.common.util.chickenbones.Matrix4;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableList;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.blocks.IWProperties;
import malte0811.industrialwires.client.ClientUtilsIW;
import malte0811.industrialwires.client.RawQuad;
import malte0811.industrialwires.util.MBSideConfig;
import malte0811.industrialwires.util.MBSideConfig.BlockFace;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.common.model.IModelState;
import net.minecraftforge.common.model.TRSRTransformation;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.util.vector.Vector3f;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@SideOnly(Side.CLIENT)
public class BakedMBIOModel implements IBakedModel {
private static final MBSideConfig NULL_CONFIG = new MBSideConfig(ImmutableList.of(new BlockFace(new BlockPos(0, 2, 0), EnumFacing.DOWN)));
private static final Matrix4 ID = new Matrix4();
static final ResourceLocation IO_LOC = new ResourceLocation(IndustrialWires.MODID, "blocks/io");
static TextureAtlasSprite IO_TEX = null;
private final IBakedModel base;
private final TRSRTransformation transform;
private final Cache<MBSideConfig, List<BakedQuad>> cache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES)
.maximumSize(100).build();
BakedMBIOModel(IBakedModel base, IModelState transform) {
this.base = base;
this.transform = TRSRTransformation.blockCornerToCenter(transform.apply(Optional.empty()).orElse(TRSRTransformation.identity()));
}
@Nonnull
@Override
public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) {
if (side != null)
return ImmutableList.of();
MBSideConfig config = NULL_CONFIG;
if (state instanceof IExtendedBlockState) {
MBSideConfig tmpConfig = ((IExtendedBlockState) state).getValue(IWProperties.MB_SIDES);
if (tmpConfig!=null) {
config = tmpConfig;
}
}
List<BakedQuad> ret = cache.getIfPresent(config);
if (ret==null) {
if (IO_TEX==null) {
IO_TEX = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(IO_LOC.toString());
}
Matrix4 mat = new Matrix4(transform.getMatrix());
ret = new ArrayList<>(base.getQuads(state, side, rand));
for (Map.Entry<BlockFace, SideConfig> f:config.sides.entrySet()) {
if (f.getKey().face==null) {
continue;
}
Vec3d transformedPos = mat.apply(new Vec3d(f.getKey().offset));
EnumFacing transformedFace = transform.rotate(f.getKey().face);
Vector3f[] verts = getVerticesFromFace(transformedPos, transformedFace);
RawQuad q = new RawQuad(verts[0], verts[1], verts[2], verts[3], transformedFace,
IO_TEX, new float[]{1, 1, 1, 1}, getNormal(transformedFace),
getUVsForConfig(f.getValue()));
ret.add(ClientUtilsIW.bakeQuad(q, ID, ID));
}
ret = ImmutableList.copyOf(ret);
cache.put(config.copy(), ret);
}
return ret;
}
private static final Vector3f[] NORMALS = new Vector3f[6];
private static final Vector3f[][] VERTICES = new Vector3f[6][4];
static {
final float innerSize = .5F;
final float offsetInner = 1-innerSize/2;
float[] vec = new float[3];
for (int i = 0; i < EnumFacing.VALUES.length; i++) {
EnumFacing f = EnumFacing.VALUES[i];
NORMALS[i] = new Vector3f(f.getXOffset(), f.getYOffset(), f.getZOffset());
int axis = f.getAxis().ordinal();
vec[axis] = f.getAxisDirection()==EnumFacing.AxisDirection.POSITIVE?1.001F:-.001F;
float x1 = f.getAxisDirection()==EnumFacing.AxisDirection.POSITIVE?offsetInner:1-offsetInner;
for (int j = 0;j<4;j++) {
vec[(axis+1)%3] = 0<j&&j<3?x1:1-x1;
vec[(axis+2)%3] = j<2?1-offsetInner:offsetInner;
VERTICES[i][j] = vecFromArray(vec);
}
}
}
private static Vector3f vecFromArray(float[] in) {
return new Vector3f(in[0], in[1], in[2]);
}
private Vector3f[] getVerticesFromFace(Vec3d p, EnumFacing f) {
Vector3f[] orig = VERTICES[f.ordinal()];
Vector3f[] ret = new Vector3f[4];
Vector3f offset = new Vector3f((float) p.x, (float) p.y, (float) p.z);
for (int i = 0; i < 4; i++) {
ret[i] = Vector3f.add(orig[i], offset, null);
}
return ret;
}
private float[] getUVsForConfig(SideConfig sc) {
float u = (sc.ordinal()/2)*8, v = (sc.ordinal()%2)*8;
return new float[]{u, v, u+8, v+8};
}
private Vector3f getNormal(EnumFacing face) {
return NORMALS[face.ordinal()];
}
@Override
public boolean isAmbientOcclusion() {
return base.isAmbientOcclusion();
}
@Override
public boolean isGui3d() {
return base.isGui3d();
}
@Override
public boolean isBuiltInRenderer() {
return base.isBuiltInRenderer();
}
@Nonnull
@Override
public TextureAtlasSprite getParticleTexture() {
return base.getParticleTexture();
}
@Nonnull
@Override
public ItemOverrideList getOverrides() {
return base.getOverrides();
}
public void clearCache() {
cache.invalidateAll();
}
}

View file

@ -0,0 +1,117 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.multiblock_io_model;
import blusunrize.immersiveengineering.api.IEApi;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import malte0811.industrialwires.IndustrialWires;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.ICustomModelLoader;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.common.model.IModelState;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import static net.minecraftforge.fml.relauncher.Side.CLIENT;
@SideOnly(CLIENT)
public class MBIOModelLoader implements ICustomModelLoader {
private static final Set<BakedMBIOModel> activeModels = new HashSet<>();
static {
IEApi.renderCacheClearers.add(()-> {
for (BakedMBIOModel m:activeModels) {
m.clearCache();
}
});
}
@Override
public boolean accepts(@Nonnull ResourceLocation modelLocation) {
return IndustrialWires.MODID.equals(modelLocation.getNamespace())
&& "models/block/mbio".equals(modelLocation.getPath());
}
@Nonnull
@Override
public IModel loadModel(@Nonnull ResourceLocation modelLocation) throws Exception {
return new MBIOModel();
}
@Override
public void onResourceManagerReload(@Nonnull IResourceManager resourceManager) {
activeModels.clear();
BakedMBIOModel.IO_TEX = null;
}
@SideOnly(CLIENT)
private static class MBIOModel implements IModel {
private static final Collection<ResourceLocation> TEXTURES = ImmutableList.of(
BakedMBIOModel.IO_LOC
);
private ResourceLocation baseModel = new ResourceLocation(IndustrialWires.MODID, "missing");
private ImmutableMap<String, String> custom = ImmutableMap.of();
@Nonnull
@Override
public Collection<ResourceLocation> getDependencies() {
return ImmutableList.of(baseModel);
}
@Nonnull
@Override
public Collection<ResourceLocation> getTextures() {
return TEXTURES;
}
@Nonnull
@Override
@SideOnly(CLIENT)
public IBakedModel bake(@Nonnull IModelState state, @Nonnull VertexFormat format,
@Nonnull Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) {
try {
IModel baseBaked = ModelLoaderRegistry.getModel(baseModel);
baseBaked = baseBaked.process(custom);
IBakedModel baked = baseBaked.bake(state, format, bakedTextureGetter);
BakedMBIOModel ret = new BakedMBIOModel(baked, state);
activeModels.add(ret);
return ret;
} catch (Exception e) {
e.printStackTrace();
}
return ModelLoaderRegistry.getMissingModel().bake(state, format, bakedTextureGetter);
}
@Nonnull
@Override
public IModel process(ImmutableMap<String, String> customData) {
MBIOModel ret = new MBIOModel();
String bm = customData.get("base_model");
ret.baseModel = new ResourceLocation(bm.substring(1, bm.length()-1));
ret.custom = customData;
return ret;
}
}
}

View file

@ -1,33 +1,30 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.panelmodel;
package malte0811.industrialwires.client.panelmodel;
import blusunrize.immersiveengineering.api.IEApi;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableList;
import malte0811.industrialWires.blocks.controlpanel.BlockTypes_Panel;
import malte0811.industrialWires.blocks.controlpanel.TileEntityPanel;
import malte0811.industrialWires.blocks.controlpanel.TileEntityUnfinishedPanel;
import malte0811.industrialWires.controlpanel.PanelUtils;
import malte0811.industrialWires.controlpanel.PropertyComponents;
import malte0811.industrialWires.controlpanel.PropertyComponents.PanelRenderProperties;
import malte0811.industrialwires.blocks.controlpanel.BlockTypes_Panel;
import malte0811.industrialwires.blocks.controlpanel.TileEntityPanel;
import malte0811.industrialwires.blocks.controlpanel.TileEntityUnfinishedPanel;
import malte0811.industrialwires.controlpanel.PanelUtils;
import malte0811.industrialwires.controlpanel.PropertyComponents;
import malte0811.industrialwires.controlpanel.PropertyComponents.PanelRenderProperties;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.*;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@ -36,6 +33,8 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.util.vector.Vector3f;
import javax.annotation.Nonnull;
@ -45,6 +44,7 @@ import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@SideOnly(Side.CLIENT)
public class PanelModel implements IBakedModel {
public final static Cache<PanelRenderProperties, AssembledBakedModel> modelCache = CacheBuilder.newBuilder()
.maximumSize(100)

View file

@ -1,27 +1,23 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.panelmodel;
package malte0811.industrialwires.client.panelmodel;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import malte0811.industrialWires.IndustrialWires;
import malte0811.industrialWires.controlpanel.PanelUtils;
import malte0811.industrialwires.IndustrialWires;
import malte0811.industrialwires.controlpanel.PanelUtils;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.VertexFormat;
@ -37,6 +33,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
public class PanelModelLoader implements ICustomModelLoader {
public static final String RESOURCE_BASE = "models/block/";
@ -49,13 +46,14 @@ public class PanelModelLoader implements ICustomModelLoader {
}
@Override
public boolean accepts(ResourceLocation modelLocation) {
return modelLocation.getResourcePath().contains(RESOURCE_BASE + RESOURCE_LOCATION);
public boolean accepts(@Nonnull ResourceLocation modelLocation) {
return modelLocation.getPath().contains(RESOURCE_BASE + RESOURCE_LOCATION);
}
@Nonnull
@Override
public IModel loadModel(ResourceLocation modelLocation) throws IOException {
String resourcePath = modelLocation.getResourcePath();
public IModel loadModel(@Nonnull ResourceLocation modelLocation) throws IOException {
String resourcePath = modelLocation.getPath();
int pos = resourcePath.indexOf(RESOURCE_LOCATION);
if (pos >= 0) {
return new PanelModelBase();
@ -65,11 +63,13 @@ public class PanelModelLoader implements ICustomModelLoader {
private class PanelModelBase implements IModel {
@Nonnull
@Override
public Collection<ResourceLocation> getDependencies() {
return ImmutableList.of();
}
@Nonnull
@Override
public Collection<ResourceLocation> getTextures() {
try {
@ -82,8 +82,9 @@ public class PanelModelLoader implements ICustomModelLoader {
}
}
@Nonnull
@Override
public IBakedModel bake(IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) {
public IBakedModel bake(@Nonnull IModelState state, @Nonnull VertexFormat format, @Nonnull Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) {
try {
return new PanelModel();
} catch (Exception e) {
@ -91,10 +92,5 @@ public class PanelModelLoader implements ICustomModelLoader {
}
}
@Override
public IModelState getDefaultState() {
return null;
}
}
}

View file

@ -1,26 +1,23 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.panelmodel;
package malte0811.industrialwires.client.panelmodel;
import blusunrize.immersiveengineering.common.util.chickenbones.Matrix4;
import com.google.common.collect.ImmutableList;
import malte0811.industrialWires.client.RawQuad;
import malte0811.industrialwires.client.RawQuad;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@ -32,22 +29,38 @@ import net.minecraft.util.ResourceLocation;
import org.lwjgl.util.vector.Vector3f;
import javax.annotation.Nonnull;
import java.util.Map;
import java.util.WeakHashMap;
public class RawModelFontRenderer extends FontRenderer {
public static final ResourceLocation FONT = new ResourceLocation("minecraft", "textures/font/ascii.png");
private static final Map<Thread, RawModelFontRenderer> instances = new WeakHashMap<>();
float[] colorA = new float[4];
private ImmutableList.Builder<RawQuad> builder = ImmutableList.builder();
private final Vector3f normal = new Vector3f(0, 1, 0);
public final float scale;
private float scale;
public Matrix4 transform = null;
private TextureAtlasSprite sprite;
private static TextureAtlasSprite sprite = null;
public RawModelFontRenderer(GameSettings settings, ResourceLocation font, TextureManager manager, boolean isUnicode, float scale) {
public static RawModelFontRenderer get() {
Thread current = Thread.currentThread();
if (!instances.containsKey(current)) {
instances.put(current, new RawModelFontRenderer(Minecraft.getMinecraft().gameSettings, FONT, Minecraft.getMinecraft().getTextureManager(),
false, 1));
}
return instances.get(current);
}
private RawModelFontRenderer(GameSettings settings, ResourceLocation font, TextureManager manager, boolean isUnicode, float scale) {
super(settings, font, manager, isUnicode);
this.scale = scale / (9 * 16);
onResourceManagerReload(null);
}
public void setScale(float scale) {
this.scale = scale / (9 * 16);
}
@Override
protected float renderDefaultChar(int pos, boolean italic) {
float x = (pos % 16);
@ -78,10 +91,10 @@ public class RawModelFontRenderer extends FontRenderer {
@Override
public void onResourceManagerReload(IResourceManager resourceManager) {
super.onResourceManagerReload(resourceManager);
String p = locationFontTexture.getResourcePath();
String p = locationFontTexture.getPath();
if (p.startsWith("textures/")) p = p.substring("textures/".length(), p.length());
if (p.endsWith(".png")) p = p.substring(0, p.length() - ".png".length());
String f = locationFontTexture.getResourceDomain() + ":" + p;
String f = locationFontTexture.getNamespace() + ":" + p;
sprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(f);
}
@ -112,4 +125,8 @@ public class RawModelFontRenderer extends FontRenderer {
protected void bindTexture(@Nonnull ResourceLocation location) {
//NO-OP
}
}
public float getScale() {
return scale;
}
}

View file

@ -1,4 +1,19 @@
package malte0811.industrialWires.client.panelmodel;
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.panelmodel;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;

View file

@ -0,0 +1,64 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.render;
import blusunrize.immersiveengineering.client.ClientUtils;
import malte0811.industrialwires.entities.EntityBrokenPart;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class EntityRenderBrokenPart extends Render<EntityBrokenPart> {
public EntityRenderBrokenPart(RenderManager renderManager) {
super(renderManager);
}
@Override
public void doRender(@Nonnull EntityBrokenPart entity, double x, double y, double z, float entityYaw, float partialTicks) {
GlStateManager.pushMatrix();
AxisAlignedBB aabb = entity.getEntityBoundingBox();
ClientUtils.bindAtlas();
Tessellator tes = Tessellator.getInstance();
BufferBuilder bb = tes.getBuffer();
bb.setTranslation(x - entity.lastTickPosX, y - entity.lastTickPosY, z - entity.lastTickPosZ);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
bb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
TextureAtlasSprite tex = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(entity.texture.toString());
ClientUtils.renderTexturedBox(bb, aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ,
tex.getMinU(), tex.getMinV(), tex.getInterpolatedU(8), tex.getInterpolatedV(8));
tes.draw();
bb.setTranslation(0, 0, 0);
GlStateManager.popMatrix();
super.doRender(entity, x, y, z, entityYaw, partialTicks);
}
@Nullable
@Override
protected ResourceLocation getEntityTexture(@Nonnull EntityBrokenPart entity) {
return entity.texture;
}
}

View file

@ -0,0 +1,176 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Industrial Wires 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialwires.client.render;
import blusunrize.immersiveengineering.api.IEApi;
import malte0811.industrialwires.IWConfig;
import malte0811.industrialwires.IndustrialWires;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import org.lwjgl.opengl.ARBFragmentShader;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.ARBVertexShader;
import org.lwjgl.opengl.GL11;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Shaders
{
public static int JACOBS_ARC;
public static int MARX;
private static String PREFIX = "/assets/"+ IndustrialWires.MODID+"/shaders/";
public static void initShaders(boolean setupReload) {
if (areShadersEnabled()) {
JACOBS_ARC = createProgram(null, PREFIX + "jacobs.frag");
MARX = createProgram(null, PREFIX + "marx.frag");
if (setupReload) {
IEApi.renderCacheClearers.add(() -> {
if (JACOBS_ARC != 0) {
deleteShader(JACOBS_ARC);
JACOBS_ARC = 0;
}
if (MARX != 0) {
deleteShader(MARX);
MARX = 0;
}
initShaders(false);
});
}
}
}
//All stolen from Botania...
private static final int VERT = ARBVertexShader.GL_VERTEX_SHADER_ARB;
private static final int FRAG = ARBFragmentShader.GL_FRAGMENT_SHADER_ARB;
private static void deleteShader(int id) {
if (id != 0) {
ARBShaderObjects.glDeleteObjectARB(id);
}
}
public static void useShader(int shader) {
if (areShadersEnabled()) {
ARBShaderObjects.glUseProgramObjectARB(shader);
if (shader != 0) {
int time = ARBShaderObjects.glGetUniformLocationARB(shader, "time");
ARBShaderObjects.glUniform1fARB(time, Minecraft.getMinecraft().world.getTotalWorldTime() + Minecraft.getMinecraft().getRenderPartialTicks());
}
}
}
public static void stopUsingShaders() {
useShader(0);
}
private static int createProgram(String vert, String frag) {
int vertId = 0, fragId = 0, program;
if(vert != null)
vertId = createShader(vert, VERT);
if(frag != null)
fragId = createShader(frag, FRAG);
program = ARBShaderObjects.glCreateProgramObjectARB();
if(program == 0)
return 0;
if(vert != null)
ARBShaderObjects.glAttachObjectARB(program, vertId);
if(frag != null)
ARBShaderObjects.glAttachObjectARB(program, fragId);
ARBShaderObjects.glLinkProgramARB(program);
if(ARBShaderObjects.glGetObjectParameteriARB(program, ARBShaderObjects.GL_OBJECT_LINK_STATUS_ARB) == GL11.GL_FALSE) {
IndustrialWires.logger.error(getLogInfo(program));
return 0;
}
ARBShaderObjects.glValidateProgramARB(program);
if (ARBShaderObjects.glGetObjectParameteriARB(program, ARBShaderObjects.GL_OBJECT_VALIDATE_STATUS_ARB) == GL11.GL_FALSE) {
IndustrialWires.logger.error(getLogInfo(program));
return 0;
}
return program;
}
private static int createShader(String filename, int shaderType){
int shader = 0;
try {
shader = ARBShaderObjects.glCreateShaderObjectARB(shaderType);
if(shader == 0)
return 0;
ARBShaderObjects.glShaderSourceARB(shader, readFileAsString(filename));
ARBShaderObjects.glCompileShaderARB(shader);
if (ARBShaderObjects.glGetObjectParameteriARB(shader, ARBShaderObjects.GL_OBJECT_COMPILE_STATUS_ARB) == GL11.GL_FALSE)
throw new RuntimeException("Error creating shader: " + getLogInfo(shader));
return shader;
}
catch(Exception e) {
ARBShaderObjects.glDeleteObjectARB(shader);
e.printStackTrace();
return -1;
}
}
private static String getLogInfo(int obj) {
return ARBShaderObjects.glGetInfoLogARB(obj, ARBShaderObjects.glGetObjectParameteriARB(obj, ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB));
}
private static String readFileAsString(String filename) throws Exception {
InputStream in = Shaders.class.getResourceAsStream(filename);
if(in == null)
return "";
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
return preProcess(reader.lines());
}
}
public static boolean areShadersEnabled() {
return IWConfig.HVStuff.enableShaders && OpenGlHelper.shadersSupported;
}
/*
* Custom PreProcessor, I need random a lot and wanted #include
*/
private static String preProcess(Stream<String> lines) {
lines = lines.map((s)->{
if (s.startsWith("#include ")) {
s = s.substring("#include ".length());
String fileName = PREFIX +s;
try {
return readFileAsString(fileName);
} catch (Exception e) {
throw new RuntimeException(fileName+" not readable", e);
}
}
return s;
});
return lines.collect(Collectors.joining("\n"));
}
}

View file

@ -1,58 +1,57 @@
/*
* This file is part of Industrial Wires.
* Copyright (C) 2016-2017 malte0811
*
* Copyright (C) 2016-2018 malte0811
* Industrial Wires is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Industrial Wires 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Industrial Wires. If not, see <http://www.gnu.org/licenses/>.
*/
package malte0811.industrialWires.client.render;
package malte0811.industrialwires.client.render;
import malte0811.industrialWires.blocks.TileEntityJacobsLadder;
import malte0811.industrialWires.blocks.TileEntityJacobsLadder.LadderSize;
import malte0811.industrialWires.util.Beziers;
import malte0811.industrialwires.blocks.hv.TileEntityJacobsLadder;
import malte0811.industrialwires.blocks.hv.TileEntityJacobsLadder.LadderSize;
import malte0811.industrialwires.util.Beziers;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.Vec3d;
import org.lwjgl.opengl.GL11;
import static malte0811.industrialwires.blocks.hv.TileEntityJacobsLadder.getColor;
public class TileRenderJacobsLadder extends TileEntitySpecialRenderer<TileEntityJacobsLadder> {
@Override
public void renderTileEntityAt(TileEntityJacobsLadder tile, double x, double y, double z, float partialTicks, int destroyStage) {
super.renderTileEntityAt(tile, x, y, z, partialTicks, destroyStage);
public void render(TileEntityJacobsLadder tile, double x, double y, double z, float partialTicks, int destroyStage, float alpha) {
super.render(tile, x, y, z, partialTicks, destroyStage, alpha);
if (!tile.isDummy() && tile.timeTillActive == 0 && tile.controls[0] != null) {
GlStateManager.pushMatrix();
GlStateManager.translate(x + .5, y + tile.size.heightOffset, z + .5);
GlStateManager.rotate(tile.facing.getHorizontalAngle(), 0, 1, 0);
GlStateManager.translate(-tile.size.bottomDistance / 2, 0, 0);
GlStateManager.disableTexture2D();
GlStateManager.disableLighting();
GlStateManager.shadeModel(GL11.GL_SMOOTH);
if (Shaders.areShadersEnabled()) {
GlStateManager.enableBlend();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
}
float oldBX = OpenGlHelper.lastBrightnessX;
float oldBY = OpenGlHelper.lastBrightnessY;
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 238, 238);
setLightmapDisabled(true);
GlStateManager.color(1, .85F, 1, 1);
Vec3d[] controls = new Vec3d[tile.size.arcPoints];
for (int i = 0; i < tile.size.arcPoints; i++) {
Vec3d speed = tile.controlMovement[i];
controls[i] = tile.controls[i].addVector(speed.x * partialTicks, speed.y * partialTicks, speed.z * partialTicks);
Vec3d speed = tile.controlMovement[i].scale(partialTicks);
controls[i] = tile.controls[i].add(speed);
}
drawBezier(controls, tile.salt, tile.size);
//DEBUG CODE
@ -70,85 +69,64 @@ public class TileRenderJacobsLadder extends TileEntitySpecialRenderer<TileEntity
tes.draw();*/
//END OF DEBUG CODE
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, oldBX, oldBY);
setLightmapDisabled(false);
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.shadeModel(GL11.GL_FLAT);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
}
private void drawBezier(Vec3d[] controls, double salt, LadderSize size) {
Shaders.useShader(Shaders.JACOBS_ARC);
int steps = size.renderPoints;
double diameter = size.renderDiameter;
Vec3d radY = new Vec3d(0, diameter / 2, 0);
Vec3d radZ = new Vec3d(0, 0, diameter / 2);
Tessellator tes = Tessellator.getInstance();
VertexBuffer vertBuffer = tes.getBuffer();
BufferBuilder vertBuffer = tes.getBuffer();
float[][] colors = new float[steps + 1][];
vertBuffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
Vec3d last = Beziers.getPoint(0, controls);
colors[0] = getColor(0, salt, size);
if (Shaders.areShadersEnabled()) {
colors[0][0] = 0;
}
for (int i = 1; i <= steps; i++) {
double d = i / (double) steps;
colors[i] = getColor(d, salt, size);
Vec3d pos = Beziers.getPoint(d, controls);
drawQuad(last, pos, radY, colors[i - 1], colors[i], vertBuffer);
drawQuad(last, pos, radZ, colors[i - 1], colors[i], vertBuffer);
if (Shaders.areShadersEnabled()) {
colors[i][0] = (float) d;
}
drawQuad(last, pos, radY, colors[i - 1], colors[i], vertBuffer, false);
drawQuad(last, pos, radZ, colors[i - 1], colors[i], vertBuffer, false);
last = pos;
}
tes.draw();
Shaders.stopUsingShaders();
}
private final float[] saltColor = {1, 190 / 255F, 50 / 255F};
private final float[] airColor = {1, .85F, 1};
private void drawQuad(Vec3d v0, Vec3d v1, Vec3d rad, float[] color0, float[] color1, BufferBuilder vertexBuffer,
boolean horizontal) {
float alpha0 = horizontal?.5F:0;
float alpha1 = horizontal?.5F:1;
color(color1, alpha0, vertexBuffer.pos(v1.x - rad.x, v1.y - rad.y, v1.z - rad.z)).endVertex();
color(color0, alpha0, vertexBuffer.pos(v0.x - rad.x, v0.y - rad.y, v0.z - rad.z)).endVertex();
color(color0, alpha1, vertexBuffer.pos(v0.x + rad.x, v0.y + rad.y, v0.z + rad.z)).endVertex();
color(color1, alpha1, vertexBuffer.pos(v1.x + rad.x, v1.y + rad.y, v1.z + rad.z)).endVertex();
private float[] getColor(double t, double salt, LadderSize size) {
salt = Math.min(salt, 1);
int factor = 20;
double smallMin = Math.exp(-.5);
double normalMin = Math.exp(-.25 * factor);
double hugeMin = Math.exp(-.75 * factor);
double saltyness = 0;
double t2 = t - .5;
switch (size) {
case SMALL:
saltyness = salt * (1 - .9 * (Math.exp(-Math.abs(t2)) - smallMin));
break;
case NORMAL:
saltyness = salt * (1 - .9 * (Math.exp(-factor * t2 * t2) - normalMin));
break;
case HUGE:
saltyness = salt * (1 - .9 * (Math.exp(-Math.abs(factor * t2 * t2 * t2)) - hugeMin));
break;
}
return interpolate(saltyness, saltColor, 1 - saltyness, airColor);
color(color1, alpha1, vertexBuffer.pos(v1.x + rad.x, v1.y + rad.y, v1.z + rad.z)).endVertex();
color(color0, alpha1, vertexBuffer.pos(v0.x + rad.x, v0.y + rad.y, v0.z + rad.z)).endVertex();
color(color0, alpha0, vertexBuffer.pos(v0.x - rad.x, v0.y - rad.y, v0.z - rad.z)).endVertex();
color(color1, alpha0, vertexBuffer.pos(v1.x - rad.x, v1.y - rad.y, v1.z - rad.z)).endVertex();
}
private float[] interpolate(double a, float[] cA, double b, float[] cB) {
float[] ret = new float[cA.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = (float) (a * cA[i] + b * cB[i]);
}
return ret;
}
private void drawQuad(Vec3d v0, Vec3d v1, Vec3d rad, float[] color0, float[] color1, VertexBuffer vertexBuffer) {
color(color1, vertexBuffer.pos(v1.x - rad.x, v1.y - rad.y, v1.z - rad.z)).endVertex();
color(color0, vertexBuffer.pos(v0.x - rad.x, v0.y - rad.y, v0.z - rad.z)).endVertex();
color(color0, vertexBuffer.pos(v0.x + rad.x, v0.y + rad.y, v0.z + rad.z)).endVertex();
color(color1, vertexBuffer.pos(v1.x + rad.x, v1.y + rad.y, v1.z + rad.z)).endVertex();
color(color1, vertexBuffer.pos(v1.x + rad.x, v1.y + rad.y, v1.z + rad.z)).endVertex();
color(color0, vertexBuffer.pos(v0.x + rad.x, v0.y + rad.y, v0.z + rad.z)).endVertex();
color(color0, vertexBuffer.pos(v0.x - rad.x, v0.y - rad.y, v0.z - rad.z)).endVertex();
color(color1, vertexBuffer.pos(v1.x - rad.x, v1.y - rad.y, v1.z - rad.z)).endVertex();
}
private VertexBuffer color(float[] color, VertexBuffer vb) {
vb.color(color[0], color[1], color[2], 1);
private BufferBuilder color(float[] color, float alpha, BufferBuilder vb) {
vb.color(color[0], color[1], color[2], alpha);
return vb;
}
}

Some files were not shown because too many files have changed in this diff Show more