commit 6e8f973b60439602ead4d50b618accc27d4a51df Author: p455w0rd Date: Wed Apr 27 11:14:05 2016 -0400 Initial commit diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..645d6c4 --- /dev/null +++ b/.classpath @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..2020904 --- /dev/null +++ b/.project @@ -0,0 +1,19 @@ + + + WirelessCraftingTerminal + + + Minecraft + RemoteSystemsTempFiles + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..d17b672 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program 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. + + This program 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 this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1491a36 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# WirelessCraftingTerminal \ No newline at end of file diff --git a/src/java/cofh/api/CoFHAPIProps.java b/src/java/cofh/api/CoFHAPIProps.java new file mode 100644 index 0000000..9b52830 --- /dev/null +++ b/src/java/cofh/api/CoFHAPIProps.java @@ -0,0 +1,11 @@ +package cofh.api; + +public class CoFHAPIProps { + + private CoFHAPIProps() { + + } + + public static final String VERSION = "1.7.10R1.0.2"; + +} diff --git a/src/java/cofh/api/energy/EnergyStorage.java b/src/java/cofh/api/energy/EnergyStorage.java new file mode 100644 index 0000000..1674c18 --- /dev/null +++ b/src/java/cofh/api/energy/EnergyStorage.java @@ -0,0 +1,158 @@ +package cofh.api.energy; + +import net.minecraft.nbt.NBTTagCompound; + +/** + * Reference implementation of {@link IEnergyStorage}. Use/extend this or implement your own. + * + * @author King Lemming + * + */ +public class EnergyStorage implements IEnergyStorage { + + protected int energy; + protected int capacity; + protected int maxReceive; + protected int maxExtract; + + public EnergyStorage(int capacity) { + + this(capacity, capacity, capacity); + } + + public EnergyStorage(int capacity, int maxTransfer) { + + this(capacity, maxTransfer, maxTransfer); + } + + public EnergyStorage(int capacity, int maxReceive, int maxExtract) { + + this.capacity = capacity; + this.maxReceive = maxReceive; + this.maxExtract = maxExtract; + } + + public EnergyStorage readFromNBT(NBTTagCompound nbt) { + + this.energy = nbt.getInteger("Energy"); + + if (energy > capacity) { + energy = capacity; + } + return this; + } + + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + + if (energy < 0) { + energy = 0; + } + nbt.setInteger("Energy", energy); + return nbt; + } + + public void setCapacity(int capacity) { + + this.capacity = capacity; + + if (energy > capacity) { + energy = capacity; + } + } + + public void setMaxTransfer(int maxTransfer) { + + setMaxReceive(maxTransfer); + setMaxExtract(maxTransfer); + } + + public void setMaxReceive(int maxReceive) { + + this.maxReceive = maxReceive; + } + + public void setMaxExtract(int maxExtract) { + + this.maxExtract = maxExtract; + } + + public int getMaxReceive() { + + return maxReceive; + } + + public int getMaxExtract() { + + return maxExtract; + } + + /** + * This function is included to allow for server -> client sync. Do not call this externally to the containing Tile Entity, as not all IEnergyHandlers + * are guaranteed to have it. + * + * @param energy + */ + public void setEnergyStored(int energy) { + + this.energy = energy; + + if (this.energy > capacity) { + this.energy = capacity; + } else if (this.energy < 0) { + this.energy = 0; + } + } + + /** + * This function is included to allow the containing tile to directly and efficiently modify the energy contained in the EnergyStorage. Do not rely on this + * externally, as not all IEnergyHandlers are guaranteed to have it. + * + * @param energy + */ + public void modifyEnergyStored(int energy) { + + this.energy += energy; + + if (this.energy > capacity) { + this.energy = capacity; + } else if (this.energy < 0) { + this.energy = 0; + } + } + + /* IEnergyStorage */ + @Override + public int receiveEnergy(int maxReceive, boolean simulate) { + + int energyReceived = Math.min(capacity - energy, Math.min(this.maxReceive, maxReceive)); + + if (!simulate) { + energy += energyReceived; + } + return energyReceived; + } + + @Override + public int extractEnergy(int maxExtract, boolean simulate) { + + int energyExtracted = Math.min(energy, Math.min(this.maxExtract, maxExtract)); + + if (!simulate) { + energy -= energyExtracted; + } + return energyExtracted; + } + + @Override + public int getEnergyStored() { + + return energy; + } + + @Override + public int getMaxEnergyStored() { + + return capacity; + } + +} diff --git a/src/java/cofh/api/energy/IEnergyConnection.java b/src/java/cofh/api/energy/IEnergyConnection.java new file mode 100644 index 0000000..79bdf77 --- /dev/null +++ b/src/java/cofh/api/energy/IEnergyConnection.java @@ -0,0 +1,21 @@ +package cofh.api.energy; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this interface on TileEntities which should connect to energy transportation blocks. This is intended for blocks which generate energy but do not + * accept it; otherwise just use IEnergyHandler. + *

+ * Note that {@link IEnergyHandler} is an extension of this. + * + * @author King Lemming + * + */ +public interface IEnergyConnection { + + /** + * Returns TRUE if the TileEntity can connect on a given side. + */ + boolean canConnectEnergy(ForgeDirection from); + +} diff --git a/src/java/cofh/api/energy/IEnergyContainerItem.java b/src/java/cofh/api/energy/IEnergyContainerItem.java new file mode 100644 index 0000000..317f26b --- /dev/null +++ b/src/java/cofh/api/energy/IEnergyContainerItem.java @@ -0,0 +1,55 @@ +package cofh.api.energy; + +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +/** + * Implement this interface on Item classes that support external manipulation of their internal energy storages. + *

+ * A reference implementation is provided {@link ItemEnergyContainer}. + * + * @author King Lemming + * + */ +public interface IEnergyContainerItem { + + /** + * Adds energy to a container item. Returns the quantity of energy that was accepted. This should always return 0 if the item cannot be externally charged. + * + * @param container + * ItemStack to be charged. + * @param maxReceive + * Maximum amount of energy to be sent into the item. + * @param simulate + * If TRUE, the charge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) received by the item. + */ + int receiveEnergy(ItemStack container, int maxReceive, boolean simulate); + + /** + * Removes energy from a container item. Returns the quantity of energy that was removed. This should always return 0 if the item cannot be externally + * discharged. + * + * @param container + * ItemStack to be discharged. + * @param maxExtract + * Maximum amount of energy to be extracted from the item. + * @param simulate + * If TRUE, the discharge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) extracted from the item. + */ + int extractEnergy(ItemStack container, int maxExtract, boolean simulate); + + /** + * Get the amount of energy currently stored in the container item. + */ + int getEnergyStored(ItemStack container); + + /** + * Get the max amount of energy that can be stored in the container item. + */ + int getMaxEnergyStored(ItemStack container); + +} diff --git a/src/java/cofh/api/energy/IEnergyHandler.java b/src/java/cofh/api/energy/IEnergyHandler.java new file mode 100644 index 0000000..22f2dbc --- /dev/null +++ b/src/java/cofh/api/energy/IEnergyHandler.java @@ -0,0 +1,58 @@ +package cofh.api.energy; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this interface on Tile Entities which should handle energy, generally storing it in one or more internal {@link IEnergyStorage} objects. + *

+ * A reference implementation is provided {@link TileEnergyHandler}. + * + * @author King Lemming + * + */ +public interface IEnergyHandler extends IEnergyProvider, IEnergyReceiver { + + // merely a convenience interface (remove these methods in 1.8; provided here for back-compat via compiler doing things) + + /** + * Add energy to an IEnergyReceiver, internal distribution is left entirely to the IEnergyReceiver. + * + * @param from + * Orientation the energy is received from. + * @param maxReceive + * Maximum amount of energy to receive. + * @param simulate + * If TRUE, the charge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) received. + */ + @Override + int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate); + + /** + * Remove energy from an IEnergyProvider, internal distribution is left entirely to the IEnergyProvider. + * + * @param from + * Orientation the energy is extracted from. + * @param maxExtract + * Maximum amount of energy to extract. + * @param simulate + * If TRUE, the extraction will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) extracted. + */ + @Override + int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate); + + + /** + * Returns the amount of energy currently stored. + */ + @Override + int getEnergyStored(ForgeDirection from); + + /** + * Returns the maximum amount of energy that can be stored. + */ + @Override + int getMaxEnergyStored(ForgeDirection from); + +} diff --git a/src/java/cofh/api/energy/IEnergyProvider.java b/src/java/cofh/api/energy/IEnergyProvider.java new file mode 100644 index 0000000..05287b3 --- /dev/null +++ b/src/java/cofh/api/energy/IEnergyProvider.java @@ -0,0 +1,38 @@ +package cofh.api.energy; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this interface on Tile Entities which should provide energy, generally storing it in one or more internal {@link IEnergyStorage} objects. + *

+ * A reference implementation is provided {@link TileEnergyHandler}. + * + * @author King Lemming + * + */ +public interface IEnergyProvider extends IEnergyConnection { + + /** + * Remove energy from an IEnergyProvider, internal distribution is left entirely to the IEnergyProvider. + * + * @param from + * Orientation the energy is extracted from. + * @param maxExtract + * Maximum amount of energy to extract. + * @param simulate + * If TRUE, the extraction will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) extracted. + */ + int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate); + + /** + * Returns the amount of energy currently stored. + */ + int getEnergyStored(ForgeDirection from); + + /** + * Returns the maximum amount of energy that can be stored. + */ + int getMaxEnergyStored(ForgeDirection from); + +} diff --git a/src/java/cofh/api/energy/IEnergyReceiver.java b/src/java/cofh/api/energy/IEnergyReceiver.java new file mode 100644 index 0000000..c726e09 --- /dev/null +++ b/src/java/cofh/api/energy/IEnergyReceiver.java @@ -0,0 +1,38 @@ +package cofh.api.energy; + +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Implement this interface on Tile Entities which should receive energy, generally storing it in one or more internal {@link IEnergyStorage} objects. + *

+ * A reference implementation is provided {@link TileEnergyHandler}. + * + * @author King Lemming + * + */ +public interface IEnergyReceiver extends IEnergyConnection { + + /** + * Add energy to an IEnergyReceiver, internal distribution is left entirely to the IEnergyReceiver. + * + * @param from + * Orientation the energy is received from. + * @param maxReceive + * Maximum amount of energy to receive. + * @param simulate + * If TRUE, the charge will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) received. + */ + int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate); + + /** + * Returns the amount of energy currently stored. + */ + int getEnergyStored(ForgeDirection from); + + /** + * Returns the maximum amount of energy that can be stored. + */ + int getMaxEnergyStored(ForgeDirection from); + +} diff --git a/src/java/cofh/api/energy/IEnergyStorage.java b/src/java/cofh/api/energy/IEnergyStorage.java new file mode 100644 index 0000000..bc20656 --- /dev/null +++ b/src/java/cofh/api/energy/IEnergyStorage.java @@ -0,0 +1,46 @@ +package cofh.api.energy; + +/** + * An energy storage is the unit of interaction with Energy inventories.
+ * This is not to be implemented on TileEntities. This is for internal use only. + *

+ * A reference implementation can be found at {@link EnergyStorage}. + * + * @author King Lemming + * + */ +public interface IEnergyStorage { + + /** + * Adds energy to the storage. Returns quantity of energy that was accepted. + * + * @param maxReceive + * Maximum amount of energy to be inserted. + * @param simulate + * If TRUE, the insertion will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) accepted by the storage. + */ + int receiveEnergy(int maxReceive, boolean simulate); + + /** + * Removes energy from the storage. Returns quantity of energy that was removed. + * + * @param maxExtract + * Maximum amount of energy to be extracted. + * @param simulate + * If TRUE, the extraction will only be simulated. + * @return Amount of energy that was (or would have been, if simulated) extracted from the storage. + */ + int extractEnergy(int maxExtract, boolean simulate); + + /** + * Returns the amount of energy currently stored. + */ + int getEnergyStored(); + + /** + * Returns the maximum amount of energy that can be stored. + */ + int getMaxEnergyStored(); + +} diff --git a/src/java/cofh/api/energy/ItemEnergyContainer.java b/src/java/cofh/api/energy/ItemEnergyContainer.java new file mode 100644 index 0000000..0555ba0 --- /dev/null +++ b/src/java/cofh/api/energy/ItemEnergyContainer.java @@ -0,0 +1,113 @@ +package cofh.api.energy; + +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Reference implementation of {@link IEnergyContainerItem}. Use/extend this or implement your own. + * + * @author King Lemming + * + */ +public class ItemEnergyContainer extends Item implements IEnergyContainerItem { + + protected int capacity; + protected int maxReceive; + protected int maxExtract; + + public ItemEnergyContainer() { + + } + + public ItemEnergyContainer(int capacity) { + + this(capacity, capacity, capacity); + } + + public ItemEnergyContainer(int capacity, int maxTransfer) { + + this(capacity, maxTransfer, maxTransfer); + } + + public ItemEnergyContainer(int capacity, int maxReceive, int maxExtract) { + + this.capacity = capacity; + this.maxReceive = maxReceive; + this.maxExtract = maxExtract; + } + + public ItemEnergyContainer setCapacity(int capacity) { + + this.capacity = capacity; + return this; + } + + public void setMaxTransfer(int maxTransfer) { + + setMaxReceive(maxTransfer); + setMaxExtract(maxTransfer); + } + + public void setMaxReceive(int maxReceive) { + + this.maxReceive = maxReceive; + } + + public void setMaxExtract(int maxExtract) { + + this.maxExtract = maxExtract; + } + + /* IEnergyContainerItem */ + @Override + public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) { + + if (container.stackTagCompound == null) { + container.stackTagCompound = new NBTTagCompound(); + } + int energy = container.stackTagCompound.getInteger("Energy"); + int energyReceived = Math.min(capacity - energy, Math.min(this.maxReceive, maxReceive)); + + if (!simulate) { + energy += energyReceived; + container.stackTagCompound.setInteger("Energy", energy); + } + return energyReceived; + } + + @Override + public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) { + + if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("Energy")) { + return 0; + } + int energy = container.stackTagCompound.getInteger("Energy"); + int energyExtracted = Math.min(energy, Math.min(this.maxExtract, maxExtract)); + + if (!simulate) { + energy -= energyExtracted; + container.stackTagCompound.setInteger("Energy", energy); + } + return energyExtracted; + } + + @Override + public int getEnergyStored(ItemStack container) { + + if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("Energy")) { + return 0; + } + return container.stackTagCompound.getInteger("Energy"); + } + + @Override + public int getMaxEnergyStored(ItemStack container) { + + return capacity; + } + +} diff --git a/src/java/cofh/api/energy/TileEnergyHandler.java b/src/java/cofh/api/energy/TileEnergyHandler.java new file mode 100644 index 0000000..7cc655e --- /dev/null +++ b/src/java/cofh/api/energy/TileEnergyHandler.java @@ -0,0 +1,65 @@ +package cofh.api.energy; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; + +/** + * Reference implementation of {@link IEnergyHandler}. Use/extend this or implement your own. + * + * @author King Lemming + * + */ +public class TileEnergyHandler extends TileEntity implements IEnergyHandler { + + protected EnergyStorage storage = new EnergyStorage(32000); + + @Override + public void readFromNBT(NBTTagCompound nbt) { + + super.readFromNBT(nbt); + storage.readFromNBT(nbt); + } + + @Override + public void writeToNBT(NBTTagCompound nbt) { + + super.writeToNBT(nbt); + storage.writeToNBT(nbt); + } + + /* IEnergyConnection */ + @Override + public boolean canConnectEnergy(ForgeDirection from) { + + return true; + } + + /* IEnergyReceiver */ + @Override + public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { + + return storage.receiveEnergy(maxReceive, simulate); + } + + /* IEnergyProvider */ + @Override + public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { + + return storage.extractEnergy(maxExtract, simulate); + } + + /* IEnergyReceiver and IEnergyProvider */ + @Override + public int getEnergyStored(ForgeDirection from) { + + return storage.getEnergyStored(); + } + + @Override + public int getMaxEnergyStored(ForgeDirection from) { + + return storage.getMaxEnergyStored(); + } + +} diff --git a/src/java/cofh/api/energy/package-info.java b/src/java/cofh/api/energy/package-info.java new file mode 100644 index 0000000..7379702 --- /dev/null +++ b/src/java/cofh/api/energy/package-info.java @@ -0,0 +1,10 @@ +/** + * (C) 2014 Team CoFH / CoFH / Cult of the Full Hub + * http://www.teamcofh.com + */ +@API(apiVersion = CoFHAPIProps.VERSION, owner = "CoFHAPI", provides = "CoFHAPI|energy") +package cofh.api.energy; + +import cofh.api.CoFHAPIProps; +import cpw.mods.fml.common.API; + diff --git a/src/java/cofh/api/package-info.java b/src/java/cofh/api/package-info.java new file mode 100644 index 0000000..08ff5fc --- /dev/null +++ b/src/java/cofh/api/package-info.java @@ -0,0 +1,9 @@ +/** + * (C) 2014 Team CoFH / CoFH / Cult of the Full Hub + * http://www.teamcofh.com + */ +@API(apiVersion = CoFHAPIProps.VERSION, owner = "CoFHLib", provides = "CoFHAPI") +package cofh.api; + +import cpw.mods.fml.common.API; + diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTInteractionHelper.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTInteractionHelper.java new file mode 100644 index 0000000..b399d7e --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTInteractionHelper.java @@ -0,0 +1,11 @@ +package net.p455w0rd.wirelesscraftingterminal.api; + +import javax.annotation.Nonnull; + +import net.minecraft.entity.player.EntityPlayer; + +public interface IWCTInteractionHelper { + + void openWirelessCraftingTerminalGui( @Nonnull EntityPlayer player ); + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTItemDescription.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTItemDescription.java new file mode 100644 index 0000000..9c5987f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTItemDescription.java @@ -0,0 +1,40 @@ +package net.p455w0rd.wirelesscraftingterminal.api; + +import javax.annotation.Nonnull; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public interface IWCTItemDescription { + /** + * Gets the damage, or meta, value of the item. + * + * @return + */ + int getDamage(); + + /** + * Gets the item. + * + * @return + */ + @Nonnull + Item getItem(); + + /** + * Gets a stack of size 1. + * + * @return + */ + @Nonnull + ItemStack getStack(); + + /** + * Gets a stack of the specified size. + * + * @param amount + * @return + */ + @Nonnull + ItemStack getStacks( int amount ); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTItems.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTItems.java new file mode 100644 index 0000000..0e2650d --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWCTItems.java @@ -0,0 +1,38 @@ +package net.p455w0rd.wirelesscraftingterminal.api; + +import javax.annotation.Nonnull; + +public abstract class IWCTItems { + /** + * WirelessCraftingTerminal + */ + @Nonnull + public IWCTItemDescription WirelessCraftingTerminal; + + /** + * Infinity Booster Card + */ + @Nonnull + public IWCTItemDescription InfinityBoosterCard; + + /** + * Used for the creat6ive tab + * TODO: remove unneeded item and just + * add the icon properly + */ + @Nonnull + public IWCTItemDescription WCTDummyIcon; + + /** + * Item used solely for infinity booster + * card slot background icon + */ + @Nonnull + public IWCTItemDescription WCTBoosterBGIcon; + + /** + * Magnet Card + */ + @Nonnull + public IWCTItemDescription MagnetCard; +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWirelessCraftingTermHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWirelessCraftingTermHandler.java new file mode 100644 index 0000000..0fd8bf2 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/IWirelessCraftingTermHandler.java @@ -0,0 +1,39 @@ +package net.p455w0rd.wirelesscraftingterminal.api; + +import javax.annotation.Nonnull; + +//import appeng.api.features.INetworkEncodable; +import appeng.api.features.IWirelessTermHandler; +import appeng.api.implementations.items.IAEItemPowerStorage; +import appeng.api.util.IConfigManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Provides the required functionality of a wireless terminal. + * Presumably this interface would be implemented on an Item, but that is + * not a requirement. + * + * @author Nividica + * + */ +public interface IWirelessCraftingTermHandler extends IWirelessTermHandler, IAEItemPowerStorage { +//public interface IWirelessCraftingTermHandler extends INetworkEncodable, IAEItemPowerStorage { + /** + * Gets the tag used to store the terminal data. + * + * @param terminalItemstack + * @return + */ + //@Nonnull + //NBTTagCompound getWTerminalTag( @Nonnull ItemStack terminalItemstack ); + + boolean canHandle( ItemStack is ); + + boolean usePower( EntityPlayer player, double amount, ItemStack is ); + + boolean hasPower( EntityPlayer player, double amount, ItemStack is ); + + IConfigManager getConfigManager( ItemStack is ); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/WCTApi.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/WCTApi.java new file mode 100644 index 0000000..708763e --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/WCTApi.java @@ -0,0 +1,45 @@ +package net.p455w0rd.wirelesscraftingterminal.api; + +import java.lang.reflect.Method; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public abstract class WCTApi { + + protected static WCTApi api = null; + + @Nullable + public static WCTApi instance() + { + // Have we already retrieved the api? + if( WCTApi.api == null ) + { + try + { + // Attempt to locate the API implementation + Class clazz = Class.forName( "net.p455w0rd.wirelesscraftingterminal.implementation.WCTAPIImplementation" ); + + // Get the instance method + Method instanceAccessor = clazz.getMethod( "instance" ); + + // Attempt to get the API instance + WCTApi.api = (WCTApi)instanceAccessor.invoke( null ); + } + catch( Throwable e ) + { + // Unable to locate the API, return null + return null; + } + } + + return WCTApi.api; + } + + @Nonnull + public abstract IWCTInteractionHelper interact(); + + @Nonnull + public abstract IWCTItems items(); + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/MissingIngredientError.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/MissingIngredientError.java new file mode 100644 index 0000000..01fb26e --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/MissingIngredientError.java @@ -0,0 +1,10 @@ +package net.p455w0rd.wirelesscraftingterminal.api.exceptions; + +public class MissingIngredientError extends Exception { + + private static final long serialVersionUID = -998858343831371697L; + + public MissingIngredientError(final String n) { + super(n); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/ModNotInstalled.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/ModNotInstalled.java new file mode 100644 index 0000000..28b4dcf --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/ModNotInstalled.java @@ -0,0 +1,12 @@ +package net.p455w0rd.wirelesscraftingterminal.api.exceptions; + +public class ModNotInstalled extends Exception +{ + + private static final long serialVersionUID = -9052435206368425494L; + + public ModNotInstalled( final String t ) + { + super( t ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/RegistrationError.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/RegistrationError.java new file mode 100644 index 0000000..695582a --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/exceptions/RegistrationError.java @@ -0,0 +1,10 @@ +package net.p455w0rd.wirelesscraftingterminal.api.exceptions; + +public class RegistrationError extends Exception { + + private static final long serialVersionUID = -6602870588617670263L; + + public RegistrationError(final String n) { + super(n); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/grid/ICraftingIssuerHost.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/grid/ICraftingIssuerHost.java new file mode 100644 index 0000000..fece46b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/grid/ICraftingIssuerHost.java @@ -0,0 +1,26 @@ +package net.p455w0rd.wirelesscraftingterminal.api.grid; + +import appeng.api.storage.ITerminalHost; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +/** + * Defines the requirements for a terminal that wishes to issue AE2 crafting jobs. + * + * @author Nividica + * + */ +public interface ICraftingIssuerHost extends ITerminalHost { + /** + * Gets the icon for this terminal. + * + * @return + */ + ItemStack getIcon(); + + /** + * Launches the terminal's GUI. + * Used to return to the gui after crafting is confirmed or canceled. + */ + void launchGUI( EntityPlayer player ); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/gui/ICraftingIssuerContainer.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/gui/ICraftingIssuerContainer.java new file mode 100644 index 0000000..d4af8d4 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/gui/ICraftingIssuerContainer.java @@ -0,0 +1,12 @@ +package net.p455w0rd.wirelesscraftingterminal.api.gui; + +import net.p455w0rd.wirelesscraftingterminal.api.grid.ICraftingIssuerHost; + +import javax.annotation.Nonnull; + +public interface ICraftingIssuerContainer { + + @Nonnull + ICraftingIssuerHost getCraftingHost(); + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/MachineSource.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/MachineSource.java new file mode 100644 index 0000000..0bbf2c2 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/MachineSource.java @@ -0,0 +1,20 @@ +package net.p455w0rd.wirelesscraftingterminal.api.networking.security; + +import appeng.api.networking.security.BaseActionSource; + +public class MachineSource extends BaseActionSource +{ + + public final WCTIActionHost via; + + public MachineSource( final WCTIActionHost v ) + { + this.via = v; + } + + @Override + public boolean isMachine() + { + return true; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/WCTIActionHost.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/WCTIActionHost.java new file mode 100644 index 0000000..de6a04e --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/WCTIActionHost.java @@ -0,0 +1,19 @@ +package net.p455w0rd.wirelesscraftingterminal.api.networking.security; + +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; + +public interface WCTIActionHost extends IGridHost +{ + + /** + * Used to for calculating security rules, you must supply a node from your + * IGridHost for the security test, this should be the primary node for the + * machine, unless the action is preformed by a non primary node. + * + * @return the the gridnode that actions from this IGridHost are preformed + * by. + */ + IGridNode getActionableNode(); + IGridNode getActionableNode(boolean ignoreRange); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/WCTPlayerSource.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/WCTPlayerSource.java new file mode 100644 index 0000000..048a43f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/networking/security/WCTPlayerSource.java @@ -0,0 +1,27 @@ +package net.p455w0rd.wirelesscraftingterminal.api.networking.security; + + +import appeng.api.networking.security.IActionHost; +import appeng.api.networking.security.PlayerSource; +import net.minecraft.entity.player.EntityPlayer; + + +public class WCTPlayerSource extends PlayerSource +{ + + public final EntityPlayer player; + public final WCTIActionHost via; + + public WCTPlayerSource( final EntityPlayer p, final WCTIActionHost v ) + { + super(p,(IActionHost) v); + this.player = p; + this.via = v; + } + + @Override + public boolean isPlayer() + { + return true; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/IIngredient.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/IIngredient.java new file mode 100644 index 0000000..fa7b79f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/IIngredient.java @@ -0,0 +1,70 @@ +package net.p455w0rd.wirelesscraftingterminal.api.recipes; + +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.MissingIngredientError; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.RegistrationError; + +public interface IIngredient { + + /** + * Acquire a single input stack for the current recipe, if more then one + * ItemStack is possible a RegistrationError exception will be thrown, + * ignore these and let the system handle the error. + * + * @return a single ItemStack for the recipe handler. + * + * @throws RegistrationError + * @throws MissingIngredientError + */ + ItemStack getItemStack() throws RegistrationError, MissingIngredientError; + + /** + * Acquire a list of all the input stacks for the current recipe, this is + * for handlers that support multiple inputs per slot. + * + * @return an array of ItemStacks for the recipe handler. + * + * @throws RegistrationError + * @throws MissingIngredientError + */ + ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError; + + /** + * If you wish to support air, you must test before getting the ItemStack, + * or ItemStackSet + * + * @return true if this slot contains no ItemStack, this is passed as "_" + */ + boolean isAir(); + + /** + * @return The Name Space of the item. Prefer getItemStack or + * getItemStackSet + */ + String getNameSpace(); + + /** + * @return The Name of the item. Prefer getItemStack or getItemStackSet + */ + String getItemName(); + + /** + * @return The Damage Value of the item. Prefer getItemStack or + * getItemStackSet + */ + int getDamageValue(); + + /** + * @return The Damage Value of the item. Prefer getItemStack or + * getItemStackSet + */ + int getQty(); + + /** + * Bakes the lists in for faster runtime look-ups. + * + * @throws MissingIngredientError + * @throws RegistrationError + */ + void bake() throws RegistrationError, MissingIngredientError; +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/IRecipeBakeable.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/IRecipeBakeable.java new file mode 100644 index 0000000..09b6365 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/IRecipeBakeable.java @@ -0,0 +1,8 @@ +package net.p455w0rd.wirelesscraftingterminal.api.recipes.game; + +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.RegistrationError; + +public interface IRecipeBakeable +{ + void bake() throws RegistrationError; +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/ShapedRecipe.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/ShapedRecipe.java new file mode 100644 index 0000000..df8fe61 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/ShapedRecipe.java @@ -0,0 +1,307 @@ +package net.p455w0rd.wirelesscraftingterminal.api.recipes.game; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.world.World; +import net.minecraftforge.oredict.OreDictionary; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.MissingIngredientError; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.RegistrationError; +import net.p455w0rd.wirelesscraftingterminal.api.recipes.IIngredient; + + +public class ShapedRecipe implements IRecipe, IRecipeBakeable +{ + // Added in for future ease of change, but hard coded for now. + private static final int MAX_CRAFT_GRID_WIDTH = 3; + private static final int MAX_CRAFT_GRID_HEIGHT = 3; + + private ItemStack output = null; + private Object[] input = null; + private int width = 0; + private int height = 0; + private boolean mirrored = true; + private boolean disable = false; + + public ShapedRecipe( final ItemStack result, Object... recipe ) + { + this.output = result.copy(); + + final StringBuilder shape = new StringBuilder(); + int idx = 0; + + if( recipe[idx] instanceof Boolean ) + { + this.mirrored = (Boolean) recipe[idx]; + if( recipe[idx + 1] instanceof Object[] ) + { + recipe = (Object[]) recipe[idx + 1]; + } + else + { + idx = 1; + } + } + + if( recipe[idx] instanceof String[] ) + { + final String[] parts = ( (String[]) recipe[idx] ); + idx++; + + for( final String s : parts ) + { + this.width = s.length(); + shape.append( s ); + } + + this.height = parts.length; + } + else + { + while( recipe[idx] instanceof String ) + { + final String s = (String) recipe[idx]; + idx++; + shape.append( s ); + this.width = s.length(); + this.height++; + } + } + + if( this.width * this.height != shape.length() ) + { + final StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); + for( final Object tmp : recipe ) + { + ret.append( tmp ).append( ", " ); + } + ret.append( this.output ); + throw new IllegalStateException( ret.toString() ); + } + + final Map itemMap = new HashMap(); + + for( ; idx < recipe.length; idx += 2 ) + { + final Character chr = (Character) recipe[idx]; + final Object in = recipe[idx + 1]; + + if( in instanceof IIngredient ) + { + itemMap.put( chr, (IIngredient) in ); + } + else + { + final StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); + for( final Object tmp : recipe ) + { + ret.append( tmp ).append( ", " ); + } + ret.append( this.output ); + throw new IllegalStateException( ret.toString() ); + } + } + + this.input = new Object[this.width * this.height]; + int x = 0; + for( final char chr : shape.toString().toCharArray() ) + { + this.input[x] = itemMap.get( chr ); + x++; + } + } + + public boolean isEnabled() + { + return !this.disable; + } + + @Override + public boolean matches( final InventoryCrafting inv, final World world ) + { + if( this.disable ) + { + return false; + } + + for( int x = 0; x <= MAX_CRAFT_GRID_WIDTH - this.width; x++ ) + { + for( int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - this.height; ++y ) + { + if( this.checkMatch( inv, x, y, false ) ) + { + return true; + } + + if( this.mirrored && this.checkMatch( inv, x, y, true ) ) + { + return true; + } + } + } + + return false; + } + + @Override + public ItemStack getCraftingResult( final InventoryCrafting var1 ) + { + return this.output.copy(); + } + + @Override + public int getRecipeSize() + { + return this.input.length; + } + + @Override + public ItemStack getRecipeOutput() + { + return this.output; + } + + @SuppressWarnings( "unchecked" ) + private boolean checkMatch( final InventoryCrafting inv, final int startX, final int startY, final boolean mirror ) + { + if( this.disable ) + { + return false; + } + + for( int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++ ) + { + for( int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++ ) + { + final int subX = x - startX; + final int subY = y - startY; + Object target = null; + + if( subX >= 0 && subY >= 0 && subX < this.width && subY < this.height ) + { + if( mirror ) + { + target = this.input[this.width - subX - 1 + subY * this.width]; + } + else + { + target = this.input[subX + subY * this.width]; + } + } + + final ItemStack slot = inv.getStackInRowAndColumn( x, y ); + + if( target instanceof IIngredient ) + { + boolean matched = false; + + try + { + for( final ItemStack item : ( (IIngredient) target ).getItemStackSet() ) + { + matched = matched || this.checkItemEquals( item, slot ); + } + } + catch( final RegistrationError e ) + { + // :P + } + catch( final MissingIngredientError e ) + { + // :P + } + + if( !matched ) + { + return false; + } + } + else if( target instanceof ArrayList ) + { + boolean matched = false; + + for( final ItemStack item : (Iterable) target ) + { + matched = matched || this.checkItemEquals( item, slot ); + } + + if( !matched ) + { + return false; + } + } + else if( target == null && slot != null ) + { + return false; + } + } + } + + return true; + } + + private boolean checkItemEquals( final ItemStack target, final ItemStack input ) + { + if( input == null && target != null || input != null && target == null ) + { + return false; + } + return( target.getItem() == input.getItem() && ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input.getItemDamage() ) ); + } + + public ShapedRecipe setMirrored( final boolean mirror ) + { + this.mirrored = mirror; + return this; + } + + /** + * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array + * as it will effect the recipe itself. + * + * @return The recipes input vales. + */ + public Object[] getInput() + { + return this.input; + } + + public int getWidth() + { + return this.width; + } + + public int getHeight() + { + return this.height; + } + + public Object[] getIngredients() + { + return this.input; + } + + @Override + public void bake() throws RegistrationError + { + try + { + this.disable = false; + for( final Object o : this.input ) + { + if( o instanceof IIngredient ) + { + ( (IIngredient) o ).bake(); + } + } + } + catch( final MissingIngredientError err ) + { + this.disable = true; + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/ShapelessRecipe.java b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/ShapelessRecipe.java new file mode 100644 index 0000000..e78d005 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/api/recipes/game/ShapelessRecipe.java @@ -0,0 +1,161 @@ +package net.p455w0rd.wirelesscraftingterminal.api.recipes.game; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.world.World; +import net.minecraftforge.oredict.OreDictionary; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.MissingIngredientError; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.RegistrationError; +import net.p455w0rd.wirelesscraftingterminal.api.recipes.IIngredient; + +import java.util.ArrayList; + +public class ShapelessRecipe implements IRecipe, IRecipeBakeable +{ + + private final ArrayList input = new ArrayList(); + private ItemStack output = null; + private boolean disable = false; + + public ShapelessRecipe( final ItemStack result, final Object... recipe ) + { + this.output = result.copy(); + for( final Object in : recipe ) + { + if( in instanceof IIngredient ) + { + this.input.add( in ); + } + else + { + final StringBuilder ret = new StringBuilder( "Invalid shapeless ore recipe: " ); + for( final Object tmp : recipe ) + { + ret.append( tmp ).append( ", " ); + } + ret.append( this.output ); + throw new IllegalArgumentException( ret.toString() ); + } + } + } + + public boolean isEnabled() + { + return !this.disable; + } + + @SuppressWarnings( "unchecked" ) + @Override + public boolean matches( final InventoryCrafting var1, final World world ) + { + if( this.disable ) + { + return false; + } + + final ArrayList required = new ArrayList( this.input ); + + for( int x = 0; x < var1.getSizeInventory(); x++ ) + { + final ItemStack slot = var1.getStackInSlot( x ); + + if( slot != null ) + { + boolean inRecipe = false; + + for( final Object next : required ) + { + boolean match = false; + + if( next instanceof IIngredient ) + { + try + { + for( final ItemStack item : ( (IIngredient) next ).getItemStackSet() ) + { + match = match || this.checkItemEquals( item, slot ); + } + } + catch( final RegistrationError e ) + { + // :P + } + catch( final MissingIngredientError e ) + { + // :P + } + } + + if( match ) + { + inRecipe = true; + required.remove( next ); + break; + } + } + + if( !inRecipe ) + { + return false; + } + } + } + + return required.isEmpty(); + } + + @Override + public ItemStack getCraftingResult( final InventoryCrafting var1 ) + { + return this.output.copy(); + } + + @Override + public int getRecipeSize() + { + return this.input.size(); + } + + @Override + public ItemStack getRecipeOutput() + { + return this.output; + } + + private boolean checkItemEquals( final ItemStack target, final ItemStack input ) + { + return( target.getItem() == input.getItem() && ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input.getItemDamage() ) ); + } + + /** + * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array + * as it will effect the recipe itself. + * + * @return The recipes input vales. + */ + public ArrayList getInput() + { + return this.input; + } + + @Override + public void bake() throws RegistrationError + { + try + { + this.disable = false; + for( final Object o : this.input ) + { + if( o instanceof IIngredient ) + { + ( (IIngredient) o ).bake(); + } + } + } + catch( final MissingIngredientError e ) + { + this.disable = true; + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/AEBaseGui.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/AEBaseGui.java new file mode 100644 index 0000000..694db1b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/AEBaseGui.java @@ -0,0 +1,918 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import com.google.common.base.Joiner; +import com.google.common.base.Stopwatch; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiScrollbar; +import net.p455w0rd.wirelesscraftingterminal.client.me.AppEngRenderItem; +import net.p455w0rd.wirelesscraftingterminal.client.me.InternalSlotME; +import net.p455w0rd.wirelesscraftingterminal.client.me.SlotDisconnected; +import net.p455w0rd.wirelesscraftingterminal.client.me.SlotME; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngCraftingSlot; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngSlot; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngSlot.hasCalculatedValidness; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.OptionalSlotFake; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotCraftingTerm; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotDisabled; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotFake; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotInaccessible; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotOutput; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketInventoryAction; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwapSlots; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationRegistry; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationType; +import net.p455w0rd.wirelesscraftingterminal.integration.abstraction.INEI; +import cpw.mods.fml.common.ObfuscationReflectionHelper; + +import appeng.api.storage.data.IAEItemStack; +import appeng.client.gui.widgets.ITooltip; +import appeng.container.slot.SlotRestrictedInput; +import appeng.helpers.InventoryAction; + + +public abstract class AEBaseGui extends GuiContainer +{ + private static boolean switchingGuis; + private final List meSlots = new LinkedList(); + // drag y + private final Set drag_click = new HashSet(); + private final AppEngRenderItem aeRenderItem = new AppEngRenderItem(); + private GuiScrollbar scrollBar = null; + private boolean disableShiftClick = false; + private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); + private ItemStack dbl_whichItem; + private Slot bl_clicked; + private boolean subGui; + + public AEBaseGui( final Container container ) + { + super( container ); + this.subGui = switchingGuis; + switchingGuis = false; + } + + protected static String join( final Collection toolTip, final String delimiter ) + { + final Joiner joiner = Joiner.on( delimiter ); + + return joiner.join( toolTip ); + } + + protected int getQty( final GuiButton btn ) + { + try + { + final DecimalFormat df = new DecimalFormat( "+#;-#" ); + return df.parse( btn.displayString ).intValue(); + } + catch( final ParseException e ) + { + return 0; + } + } + + public boolean isSubGui() + { + return this.subGui; + } + + @Override + public void initGui() + { + super.initGui(); + + final List slots = this.getInventorySlots(); + final Iterator i = slots.iterator(); + while( i.hasNext() ) + { + if( i.next() instanceof SlotME ) + { + i.remove(); + } + } + + for( final InternalSlotME me : this.meSlots ) + { + slots.add( new SlotME( me ) ); + } + } + + @SuppressWarnings( "unchecked" ) + private List getInventorySlots() + { + return this.inventorySlots.inventorySlots; + } + + @Override + public void drawScreen( final int mouseX, final int mouseY, final float btn ) + { + super.drawScreen( mouseX, mouseY, btn ); + + final boolean hasClicked = Mouse.isButtonDown( 0 ); + if( hasClicked && this.scrollBar != null ) + { + this.scrollBar.click( this, mouseX - this.guiLeft, mouseY - this.guiTop ); + } + + for( final Object c : this.buttonList ) + { + if( c instanceof ITooltip ) + { + final ITooltip tooltip = (ITooltip) c; + final int x = tooltip.xPos(); // ((GuiImgButton) c).xPosition; + int y = tooltip.yPos(); // ((GuiImgButton) c).yPosition; + + if( x < mouseX && x + tooltip.getWidth() > mouseX && tooltip.isVisible() ) + { + if( y < mouseY && y + tooltip.getHeight() > mouseY ) + { + if( y < 15 ) + { + y = 15; + } + + final String msg = tooltip.getMessage(); + if( msg != null ) + { + this.drawTooltip( x + 11, y + 4, 0, msg ); + } + } + } + } + } + } + + public void drawTooltip( final int par2, final int par3, final int forceWidth, final String message ) + { + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + GL11.glDisable( GL12.GL_RESCALE_NORMAL ); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable( GL11.GL_LIGHTING ); + GL11.glDisable( GL11.GL_DEPTH_TEST ); + final String[] var4 = message.split( "\n" ); + + if( var4.length > 0 ) + { + int var5 = 0; + int var6; + int var7; + + for( var6 = 0; var6 < var4.length; ++var6 ) + { + var7 = this.fontRendererObj.getStringWidth( var4[var6] ); + + if( var7 > var5 ) + { + var5 = var7; + } + } + + var6 = par2 + 12; + var7 = par3 - 12; + int var9 = 8; + + if( var4.length > 1 ) + { + var9 += 2 + ( var4.length - 1 ) * 10; + } + + if( this.guiTop + var7 + var9 + 6 > this.height ) + { + var7 = this.height - var9 - this.guiTop - 6; + } + + if( forceWidth > 0 ) + { + var5 = forceWidth; + } + + this.zLevel = 300.0F; + itemRender.zLevel = 300.0F; + final int var10 = -267386864; + this.drawGradientRect( var6 - 3, var7 - 4, var6 + var5 + 3, var7 - 3, var10, var10 ); + this.drawGradientRect( var6 - 3, var7 + var9 + 3, var6 + var5 + 3, var7 + var9 + 4, var10, var10 ); + this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 + var9 + 3, var10, var10 ); + this.drawGradientRect( var6 - 4, var7 - 3, var6 - 3, var7 + var9 + 3, var10, var10 ); + this.drawGradientRect( var6 + var5 + 3, var7 - 3, var6 + var5 + 4, var7 + var9 + 3, var10, var10 ); + final int var11 = 1347420415; + final int var12 = ( var11 & 16711422 ) >> 1 | var11 & -16777216; + this.drawGradientRect( var6 - 3, var7 - 3 + 1, var6 - 3 + 1, var7 + var9 + 3 - 1, var11, var12 ); + this.drawGradientRect( var6 + var5 + 2, var7 - 3 + 1, var6 + var5 + 3, var7 + var9 + 3 - 1, var11, var12 ); + this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 - 3 + 1, var11, var11 ); + this.drawGradientRect( var6 - 3, var7 + var9 + 2, var6 + var5 + 3, var7 + var9 + 3, var12, var12 ); + + for( int var13 = 0; var13 < var4.length; ++var13 ) + { + String var14 = var4[var13]; + + if( var13 == 0 ) + { + var14 = '\u00a7' + Integer.toHexString( 15 ) + var14; + } + else + { + var14 = "\u00a77" + var14; + } + + this.fontRendererObj.drawStringWithShadow( var14, var6, var7, -1 ); + + if( var13 == 0 ) + { + var7 += 2; + } + + var7 += 10; + } + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + GL11.glPopAttrib(); + } + + @Override + protected final void drawGuiContainerForegroundLayer( final int x, final int y ) + { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + + if( this.scrollBar != null ) + { + this.scrollBar.draw( this ); + } + + this.drawFG( ox, oy, x, y ); + } + + public abstract void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ); + + @Override + protected final void drawGuiContainerBackgroundLayer( final float f, final int x, final int y ) + { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + this.drawBG( ox, oy, x, y ); + + final List slots = this.getInventorySlots(); + for( final Slot slot : slots ) + { + if( slot instanceof OptionalSlotFake ) + { + final OptionalSlotFake fs = (OptionalSlotFake) slot; + if( fs.renderDisabled() ) + { + if( fs.isEnabled() ) + { + this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, 18 ); + } + else + { + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 0.4F ); + GL11.glEnable( GL11.GL_BLEND ); + this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, 18 ); + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + GL11.glPopAttrib(); + } + } + } + } + } + + @Override + protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) + { + this.drag_click.clear(); + + if( btn == 1 ) + { + for( final Object o : this.buttonList ) + { + final GuiButton guibutton = (GuiButton) o; + if( guibutton.mousePressed( this.mc, xCoord, yCoord ) ) + { + super.mouseClicked( xCoord, yCoord, 0 ); + return; + } + } + } + + super.mouseClicked( xCoord, yCoord, btn ); + } + + @Override + protected void mouseClickMove( final int x, final int y, final int c, final long d ) + { + final Slot slot = this.getSlot( x, y ); + final ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); + + if( slot instanceof SlotFake && itemstack != null ) + { + this.drag_click.add( slot ); + if( this.drag_click.size() > 1 ) + { + for( final Slot dr : this.drag_click ) + { + final PacketInventoryAction p = new PacketInventoryAction( c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN : InventoryAction.PLACE_SINGLE, dr.slotNumber, 0 ); + NetworkHandler.instance.sendToServer( p ); + } + } + } + else + { + super.mouseClickMove( x, y, c, d ); + } + } + + @Override + protected void handleMouseClick( final Slot slot, final int slotIdx, final int ctrlDown, final int key ) + { + final EntityPlayer player = Minecraft.getMinecraft().thePlayer; + + if( slot instanceof SlotFake ) + { + final InventoryAction action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + + if( this.drag_click.size() > 1 ) + { + return; + } + + final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); + NetworkHandler.instance.sendToServer( p ); + + return; + } + + if( slot instanceof SlotCraftingTerm ) + { + if( key == 6 ) + { + return; // prevent weird double clicks.. + } + + InventoryAction action = null; + if( key == 1 ) + { + action = InventoryAction.CRAFT_SHIFT; + } + else + { + action = ctrlDown == 1 ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM; + } + + final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); + NetworkHandler.instance.sendToServer( p ); + + return; + } + + if( Keyboard.isKeyDown( Keyboard.KEY_SPACE ) ) + { + if( this.enableSpaceClicking() ) + { + IAEItemStack stack = null; + if( slot instanceof SlotME ) + { + stack = ( (SlotME) slot ).getAEStack(); + } + + int slotNum = this.getInventorySlots().size(); + + if( !( slot instanceof SlotME ) && slot != null ) + { + slotNum = slot.slotNumber; + } + + ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); + final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, slotNum, 0 ); + NetworkHandler.instance.sendToServer( p ); + return; + } + } + + if( slot instanceof SlotDisconnected ) + { + InventoryAction action = null; + + switch( key ) + { + case 0: // pickup / set-down. + action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + break; + + case 3: // creative dupe: + + if( player.capabilities.isCreativeMode ) + { + action = InventoryAction.CREATIVE_DUPLICATE; + } + + break; + + default: + case 4: // drop item: + case 6: + } + + if( action != null ) + { + final PacketInventoryAction p = new PacketInventoryAction( action, slot.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); + NetworkHandler.instance.sendToServer( p ); + } + + return; + } + + if( slot instanceof SlotME ) + { + InventoryAction action = null; + IAEItemStack stack = null; + + switch( key ) + { + case 0: // pickup / set-down. + action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + stack = ( (SlotME) slot ).getAEStack(); + + if( stack != null && action == InventoryAction.PICKUP_OR_SET_DOWN && stack.getStackSize() == 0 && player.inventory.getItemStack() == null ) + { + action = InventoryAction.AUTO_CRAFT; + } + + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + stack = ( (SlotME) slot ).getAEStack(); + break; + + case 3: // creative dupe: + + stack = ( (SlotME) slot ).getAEStack(); + if( stack != null && stack.isCraftable() ) + { + action = InventoryAction.AUTO_CRAFT; + } + else if( player.capabilities.isCreativeMode ) + { + final IAEItemStack slotItem = ( (SlotME) slot ).getAEStack(); + if( slotItem != null ) + { + action = InventoryAction.CREATIVE_DUPLICATE; + } + } + break; + + default: + case 4: // drop item: + case 6: + } + + if( action != null ) + { + ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); + final PacketInventoryAction p = new PacketInventoryAction( action, this.getInventorySlots().size(), 0 ); + NetworkHandler.instance.sendToServer( p ); + } + + return; + } + + if( !this.disableShiftClick && isShiftKeyDown() ) + { + this.disableShiftClick = true; + + if( this.dbl_whichItem == null || this.bl_clicked != slot || this.dbl_clickTimer.elapsed( TimeUnit.MILLISECONDS ) > 150 ) + { + // some simple double click logic. + this.bl_clicked = slot; + this.dbl_clickTimer = Stopwatch.createStarted(); + if( slot != null ) + { + this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : null; + } + else + { + this.dbl_whichItem = null; + } + } + else if( this.dbl_whichItem != null ) + { + // a replica of the weird broken vanilla feature. + + final List slots = this.getInventorySlots(); + for( final Slot inventorySlot : slots ) + { + if( inventorySlot != null && inventorySlot.canTakeStack( this.mc.thePlayer ) && inventorySlot.getHasStack() && inventorySlot.inventory == slot.inventory && Container.func_94527_a( inventorySlot, this.dbl_whichItem, true ) ) + { + this.handleMouseClick( inventorySlot, inventorySlot.slotNumber, ctrlDown, 1 ); + } + } + } + + this.disableShiftClick = false; + } + + super.handleMouseClick( slot, slotIdx, ctrlDown, key ); + } + + @Override + protected boolean checkHotbarKeys( final int keyCode ) + { + final Slot theSlot; + + try + { + theSlot = ObfuscationReflectionHelper.getPrivateValue( GuiContainer.class, this, "theSlot", "field_147006_u", "f" ); + } + catch( final Throwable t ) + { + return false; + } + + if( this.mc.thePlayer.inventory.getItemStack() == null && theSlot != null ) + { + for( int j = 0; j < 9; ++j ) + { + if( keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode() ) + { + final List slots = this.getInventorySlots(); + for( final Slot s : slots ) + { + if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) + { + if( !s.canTakeStack( ( (AEBaseContainer) this.inventorySlots ).getPlayerInv().player ) ) + { + return false; + } + } + } + + if( theSlot.getSlotStackLimit() == 64 ) + { + this.handleMouseClick( theSlot, theSlot.slotNumber, j, 2 ); + return true; + } + else + { + for( final Slot s : slots ) + { + if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) + { + NetworkHandler.instance.sendToServer( new PacketSwapSlots( s.slotNumber, theSlot.slotNumber ) ); + return true; + } + } + } + } + } + } + + return false; + } + + @Override + public void onGuiClosed() + { + super.onGuiClosed(); + this.subGui = true; // in case the gui is reopened later ( i'm looking at you NEI ) + } + + protected Slot getSlot( final int mouseX, final int mouseY ) + { + final List slots = this.getInventorySlots(); + for( final Slot slot : slots ) + { + // isPointInRegion + if( this.func_146978_c( slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY ) ) + { + return slot; + } + } + + return null; + } + + public abstract void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ); + + @Override + public void handleMouseInput() + { + super.handleMouseInput(); + + final int i = Mouse.getEventDWheel(); + if( i != 0 && isShiftKeyDown() ) + { + final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + this.mouseWheelEvent( x, y, i / Math.abs( i ) ); + } + else if( i != 0 && this.scrollBar != null ) + { + this.scrollBar.wheel( i ); + } + } + + private void mouseWheelEvent( final int x, final int y, final int wheel ) + { + final Slot slot = this.getSlot( x, y ); + if( slot instanceof SlotME ) + { + final IAEItemStack item = ( (SlotME) slot ).getAEStack(); + if( item != null ) + { + ( (AEBaseContainer) this.inventorySlots ).setTargetStack( item ); + final InventoryAction direction = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; + final int times = Math.abs( wheel ); + final int inventorySize = this.getInventorySlots().size(); + for( int h = 0; h < times; h++ ) + { + final PacketInventoryAction p = new PacketInventoryAction( direction, inventorySize, 0 ); + NetworkHandler.instance.sendToServer( p ); + } + } + } + } + + protected boolean enableSpaceClicking() + { + return true; + } + + public void bindTexture( final String base, final String file ) + { + final ResourceLocation loc = new ResourceLocation( base, "textures/" + file ); + this.mc.getTextureManager().bindTexture( loc ); + } + + protected void drawItem( final int x, final int y, final ItemStack is ) + { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + GL11.glEnable( GL11.GL_LIGHTING ); + GL11.glEnable( GL12.GL_RESCALE_NORMAL ); + GL11.glEnable( GL11.GL_DEPTH_TEST ); + RenderHelper.enableGUIStandardItemLighting(); + itemRender.renderItemAndEffectIntoGUI( this.fontRendererObj, this.mc.renderEngine, is, x, y ); + GL11.glPopAttrib(); + + itemRender.zLevel = 0.0F; + this.zLevel = 0.0F; + } + + protected String getGuiDisplayName( final String in ) + { + return this.hasCustomInventoryName() ? this.getInventoryName() : in; + } + + private boolean hasCustomInventoryName() + { + if( this.inventorySlots instanceof AEBaseContainer ) + { + return ( (AEBaseContainer) this.inventorySlots ).getCustomName() != null; + } + return false; + } + + private String getInventoryName() + { + return ( (AEBaseContainer) this.inventorySlots ).getCustomName(); + } + + private void drawSlot( final Slot s ) + { + if( s instanceof SlotME ) + { + final RenderItem pIR = this.setItemRender( this.aeRenderItem ); + try + { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + if( !this.isPowered() ) + { + GL11.glDisable( GL11.GL_LIGHTING ); + drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, 0x66111111 ); + GL11.glEnable( GL11.GL_LIGHTING ); + } + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + + this.aeRenderItem.setAeStack( ( (SlotME) s ).getAEStack() ); + + this.safeDrawSlot( s ); + } + catch( final Exception err ) + { + WCTLog.warning( "WCT prevented crash while drawing slot: " + err.toString() ); + } + this.setItemRender( pIR ); + return; + } + else + { + try + { + final ItemStack is = s.getStack(); + if( s instanceof AppEngSlot && ( ( (AppEngSlot) s ).renderIconWithItem() || is == null ) && ( ( (AppEngSlot) s ).shouldDisplay() ) ) + { + final AppEngSlot aes = (AppEngSlot) s; + if( aes.getIcon() >= 0 ) + { + this.bindTexture( "guis/states.png" ); + + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + final Tessellator tessellator = Tessellator.instance; + try + { + final int uv_y = (int) Math.floor( aes.getIcon() / 16 ); + final int uv_x = aes.getIcon() - uv_y * 16; + + GL11.glEnable( GL11.GL_BLEND ); + GL11.glDisable( GL11.GL_LIGHTING ); + GL11.glEnable( GL11.GL_TEXTURE_2D ); + GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); + GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + final float par1 = aes.xDisplayPosition; + final float par2 = aes.yDisplayPosition; + final float par3 = uv_x * 16; + final float par4 = uv_y * 16; + + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ); + final float f1 = 0.00390625F; + final float f = 0.00390625F; + final float par6 = 16; + tessellator.addVertexWithUV( par1 + 0, par2 + par6, this.zLevel, ( par3 + 0 ) * f, ( par4 + par6 ) * f1 ); + final float par5 = 16; + tessellator.addVertexWithUV( par1 + par5, par2 + par6, this.zLevel, ( par3 + par5 ) * f, ( par4 + par6 ) * f1 ); + tessellator.addVertexWithUV( par1 + par5, par2 + 0, this.zLevel, ( par3 + par5 ) * f, ( par4 + 0 ) * f1 ); + tessellator.addVertexWithUV( par1 + 0, par2 + 0, this.zLevel, ( par3 + 0 ) * f, ( par4 + 0 ) * f1 ); + tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, 1.0f ); + tessellator.draw(); + } + catch( final Exception err ) + { + } + GL11.glPopAttrib(); + } + } + + if( is != null && s instanceof AppEngSlot ) + { + if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.NotAvailable ) + { + boolean isValid = s.isItemValid( is ) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected; + if( isValid && s instanceof SlotRestrictedInput ) + { + try + { + isValid = ( (SlotRestrictedInput) s ).isValid( is, this.mc.theWorld ); + } + catch( final Exception err ) + { + WCTLog.debug( err.getMessage() ); + } + } + ( (AppEngSlot) s ).setIsValid( isValid ? hasCalculatedValidness.Valid : hasCalculatedValidness.Invalid ); + } + + if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.Invalid ) + { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glDisable( GL11.GL_LIGHTING ); + drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, 0x66ff6666 ); + GL11.glEnable( GL11.GL_LIGHTING ); + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + } + + if( s instanceof AppEngSlot ) + { + ( (AppEngSlot) s ).setDisplay( true ); + this.safeDrawSlot( s ); + } + else + { + this.safeDrawSlot( s ); + } + + return; + } + catch( final Exception err ) + { + WCTLog.warning( "WCT prevented crash while drawing slot: " + err.toString() ); + } + } + // do the usual for non-ME Slots. + this.safeDrawSlot( s ); + } + + private RenderItem setItemRender( final RenderItem item ) + { + if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ) ) + { + return ( (INEI) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.NEI ) ).setItemRender( item ); + } + else + { + final RenderItem ri = itemRender; + itemRender = item; + return ri; + } + } + + protected boolean isPowered() + { + return true; + } + + private void safeDrawSlot( final Slot s ) + { + try + { + GuiContainer.class.getDeclaredMethod( "func_146977_a_original", Slot.class ).invoke( this, s ); + } + catch( final Exception err ) + { + } + } + + public void bindTexture( final String file ) + { + final ResourceLocation loc = new ResourceLocation( "appliedenergistics2", "textures/" + file ); + this.mc.getTextureManager().bindTexture( loc ); + } + + public void func_146977_a( final Slot s ) + { + this.drawSlot( s ); + } + + protected GuiScrollbar getScrollBar() + { + return this.scrollBar; + } + + protected void setScrollBar( final GuiScrollbar myScrollBar ) + { + this.scrollBar = myScrollBar; + } + + protected List getMeSlots() + { + return this.meSlots; + } + + public static final synchronized boolean isSwitchingGuis() + { + return switchingGuis; + } + + public static final synchronized void setSwitchingGuis( final boolean switchingGuis ) + { + AEBaseGui.switchingGuis = switchingGuis; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftAmount.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftAmount.java new file mode 100644 index 0000000..f113f76 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftAmount.java @@ -0,0 +1,263 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import appeng.api.AEApi; +import appeng.api.definitions.IDefinitions; +import appeng.api.definitions.IParts; +import appeng.api.storage.ITerminalHost; +import appeng.client.gui.widgets.GuiNumberBox; +import appeng.core.AEConfig; +import appeng.core.localization.GuiText; +import appeng.helpers.Reflected; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiTabButton; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftAmount; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketCraftRequest; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwitchGuis; +import net.p455w0rd.wirelesscraftingterminal.helpers.WirelessTerminalGuiObject; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + + +public class GuiCraftAmount extends AEBaseGui +{ + private GuiNumberBox amountToCraft; + private GuiTabButton originalGuiBtn; + + private GuiButton next; + + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; + + private ItemStack myIcon; + + private int originalGui; + + @Reflected + public GuiCraftAmount( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) + { + super( new ContainerCraftAmount( inventoryPlayer, te ) ); + myIcon = RandomUtils.getWirelessTerm(inventoryPlayer); + } + + @Override + public void initGui() + { + super.initGui(); + + final int a = AEConfig.instance.craftItemsByStackAmounts( 0 ); + final int b = AEConfig.instance.craftItemsByStackAmounts( 1 ); + final int c = AEConfig.instance.craftItemsByStackAmounts( 2 ); + final int d = AEConfig.instance.craftItemsByStackAmounts( 3 ); + + this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a ) ); + this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b ) ); + this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c ) ); + this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d ) ); + + this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a ) ); + this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b ) ); + this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c ) ); + this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d ) ); + + this.buttonList.add( this.next = new GuiButton( 0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal() ) ); + final Object target = ( (ContainerCraftAmount) this.inventorySlots ).getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); + + if( target instanceof WirelessTerminalGuiObject ) + { + /* + for( final ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) + { + myIcon = wirelessTerminalStack; + } + */ + this.originalGui = WirelessCraftingTerminal.GUI_WCT; + } + + if( this.originalGui > 0 && myIcon != null ) + { + this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop - 4, myIcon, myIcon.getDisplayName(), itemRender ) ); + } + + this.amountToCraft = new GuiNumberBox( this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT, Integer.class ); + this.amountToCraft.setEnableBackgroundDrawing( false ); + this.amountToCraft.setMaxStringLength( 16 ); + this.amountToCraft.setTextColor( 0xFFFFFF ); + this.amountToCraft.setVisible( true ); + this.amountToCraft.setFocused( true ); + this.amountToCraft.setText( "1" ); + } + + @Override + public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) + { + this.fontRendererObj.drawString( GuiText.SelectAmount.getLocal(), 8, 6, 4210752 ); + } + + @Override + public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) + { + this.next.displayString = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); + + this.bindTexture( "appliedenergistics2", "guis/craftAmt.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + + try + { + Long.parseLong( this.amountToCraft.getText() ); + this.next.enabled = this.amountToCraft.getText().length() > 0; + } + catch( final NumberFormatException e ) + { + this.next.enabled = false; + } + + this.amountToCraft.drawTextBox(); + } + + @Override + protected void keyTyped( final char character, final int key ) + { + if( !this.checkHotbarKeys( key ) ) + { + if( key == 28 ) + { + this.actionPerformed( this.next ); + } + if( ( key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character ) ) && this.amountToCraft.textboxKeyTyped( character, key ) ) + { + try + { + String out = this.amountToCraft.getText(); + + boolean fixed = false; + while( out.startsWith( "0" ) && out.length() > 1 ) + { + out = out.substring( 1 ); + fixed = true; + } + + if( fixed ) + { + this.amountToCraft.setText( out ); + } + + if( out.isEmpty() ) + { + out = "0"; + } + + final long result = Long.parseLong( out ); + if( result < 0 ) + { + this.amountToCraft.setText( "1" ); + } + } + catch( final NumberFormatException e ) + { + // :P + } + } + else + { + super.keyTyped( character, key ); + } + } + } + + @Override + protected void actionPerformed( final GuiButton btn ) + { + super.actionPerformed( btn ); + + try + { + + if( btn == this.originalGuiBtn ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); + } + + if( btn == this.next ) + { + NetworkHandler.instance.sendToServer( new PacketCraftRequest( Integer.parseInt( this.amountToCraft.getText() ), isShiftKeyDown() ) ); + } + } + catch( final NumberFormatException e ) + { + // nope.. + this.amountToCraft.setText( "1" ); + } + + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + + if( isPlus || isMinus ) + { + this.addQty( this.getQty( btn ) ); + } + } + + private void addQty( final int i ) + { + try + { + String out = this.amountToCraft.getText(); + + boolean fixed = false; + while( out.startsWith( "0" ) && out.length() > 1 ) + { + out = out.substring( 1 ); + fixed = true; + } + + if( fixed ) + { + this.amountToCraft.setText( out ); + } + + if( out.isEmpty() ) + { + out = "0"; + } + + long result = Integer.parseInt( out ); + + if( result == 1 && i > 1 ) + { + result = 0; + } + + result += i; + if( result < 1 ) + { + result = 1; + } + + out = Long.toString( result ); + Integer.parseInt( out ); + this.amountToCraft.setText( out ); + } + catch( final NumberFormatException e ) + { + // :P + } + } + + protected String getBackground() + { + return "guis/craftAmt.png"; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftConfirm.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftConfirm.java new file mode 100644 index 0000000..c5d5b45 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftConfirm.java @@ -0,0 +1,544 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import java.io.IOException; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import com.google.common.base.Joiner; + +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiScrollbar; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftConfirm; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwitchGuis; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; +import net.p455w0rd.wirelesscraftingterminal.helpers.WirelessTerminalGuiObject; +import appeng.api.AEApi; +import appeng.api.storage.ITerminalHost; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.core.localization.GuiText; +import appeng.util.Platform; + + +public class GuiCraftConfirm extends AEBaseGui +{ + + private final ContainerCraftConfirm ccc; + + private final int rows = 5; + + private final IItemList storage = AEApi.instance().storage().createItemList(); + private final IItemList pending = AEApi.instance().storage().createItemList(); + private final IItemList missing = AEApi.instance().storage().createItemList(); + + private final List visual = new ArrayList(); + + private int OriginalGui=0; + private GuiButton cancel; + private GuiButton start; + private GuiButton selectCPU; + private int tooltip = -1; + + public GuiCraftConfirm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) + { + super(new ContainerCraftConfirm( inventoryPlayer, te ) ); + this.xSize = 238; + this.ySize = 206; + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar( scrollbar ); + + this.ccc = (ContainerCraftConfirm) this.inventorySlots; + + + if( te instanceof WirelessTerminalGuiObject ) + { + this.OriginalGui = WirelessCraftingTerminal.GUI_WCT; + } + + } + + boolean isAutoStart() + { + return ( (ContainerCraftConfirm) this.inventorySlots ).isAutoStart(); + } + + @Override + public void initGui() + { + super.initGui(); + + this.start = new GuiButton( 0, this.guiLeft + 162, this.guiTop + this.ySize - 25, 50, 20, GuiText.Start.getLocal() ); + this.start.enabled = false; + this.buttonList.add( this.start ); + + this.selectCPU = new GuiButton( 0, this.guiLeft + ( 219 - 180 ) / 2, this.guiTop + this.ySize - 68, 180, 20, GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic ); + this.selectCPU.enabled = false; + this.buttonList.add( this.selectCPU ); + + if( this.OriginalGui > 0 ) + { + this.cancel = new GuiButton( 0, this.guiLeft + 6, this.guiTop + this.ySize - 25, 50, 20, GuiText.Cancel.getLocal() ); + } + + this.buttonList.add( this.cancel ); + } + + @Override + public void drawScreen( final int mouseX, final int mouseY, final float btn ) + { + this.updateCPUButtonText(); + + this.start.enabled = !( this.ccc.hasNoCPU() || this.isSimulation() ); + this.selectCPU.enabled = !this.isSimulation(); + + final int gx = ( this.width - this.xSize ) / 2; + final int gy = ( this.height - this.ySize ) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for( int z = 0; z <= 4 * 5; z++ ) + { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if( minX < mouseX && minX + 67 > mouseX ) + { + if( minY < mouseY && minY + offY - 2 > mouseY ) + { + this.tooltip = z; + break; + } + } + + x++; + + if( x > 2 ) + { + y++; + x = 0; + } + } + + super.drawScreen( mouseX, mouseY, btn ); + } + + private void updateCPUButtonText() + { + String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); + if( this.ccc.getSelectedCpu() >= 0 )// && status.selectedCpu < status.cpus.size() ) + { + if( this.ccc.getName().length() > 0 ) + { + final String name = this.ccc.getName().substring( 0, Math.min( 20, this.ccc.getName().length() ) ); + btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; + } + else + { + btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu(); + } + } + + if( this.ccc.hasNoCPU() ) + { + btnTextText = GuiText.NoCraftingCPUs.getLocal(); + } + + this.selectCPU.displayString = btnTextText; + } + + private boolean isSimulation() + { + return ( (ContainerCraftConfirm) this.inventorySlots ).isSimulation(); + } + + @Override + public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) + { + final long BytesUsed = this.ccc.getUsedBytes(); + //final long BytesUsed = ((ContainerCraftConfirm) this.inventorySlots).getUsedBytes(); + final String byteUsed = NumberFormat.getInstance().format( BytesUsed ); + final String Add = BytesUsed > 0 ? ( byteUsed + ' ' + GuiText.BytesUsed.getLocal() ) : GuiText.CalculatingWait.getLocal(); + this.fontRendererObj.drawString( GuiText.CraftingPlan.getLocal() + " -- " + Add, 8, 7, 4210752 ); + + String dsp = null; + + if( this.isSimulation() ) + { + dsp = GuiText.Simulation.getLocal(); + } + else + { + dsp = this.ccc.getCpuAvailableBytes() > 0 ? ( GuiText.Bytes.getLocal() + ": " + this.ccc.getCpuAvailableBytes() + " : " + GuiText.CoProcessors.getLocal() + ": " + this.ccc.getCpuCoProcessors() ) : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; + } + + final int offset = ( 219 - this.fontRendererObj.getStringWidth( dsp ) ) / 2; + this.fontRendererObj.drawString( dsp, offset, 165, 4210752 ); + + final int sectionLength = 67; + + int x = 0; + int y = 0; + final int xo = 9; + final int yo = 22; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * this.rows; + + String dspToolTip = ""; + final List lineList = new LinkedList(); + int toolPosX = 0; + int toolPosY = 0; + + final int offY = 23; + + for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) + { + final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); + if( refStack != null ) + { + GL11.glPushMatrix(); + GL11.glScaled( 0.5, 0.5, 0.5 ); + + final IAEItemStack stored = this.storage.findPrecise( refStack ); + final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); + final IAEItemStack missingStack = this.missing.findPrecise( refStack ); + + int lines = 0; + + if( stored != null && stored.getStackSize() > 0 ) + { + lines++; + } + if( pendingStack != null && pendingStack.getStackSize() > 0 ) + { + lines++; + } + if( pendingStack != null && pendingStack.getStackSize() > 0 ) + { + lines++; + } + + final int negY = ( ( lines - 1 ) * 5 ) / 2; + int downY = 0; + + if( stored != null && stored.getStackSize() > 0 ) + { + String str = Long.toString( stored.getStackSize() ); + if( stored.getStackSize() >= 10000 ) + { + str = Long.toString( stored.getStackSize() / 1000 ) + 'k'; + } + if( stored.getStackSize() >= 10000000 ) + { + str = Long.toString( stored.getStackSize() / 1000000 ) + 'm'; + } + + str = GuiText.FromStorage.getLocal() + ": " + str; + final int w = 4 + this.fontRendererObj.getStringWidth( str ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); + + if( this.tooltip == z - viewStart ) + { + lineList.add( GuiText.FromStorage.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); + } + + downY += 5; + } + + boolean red = false; + if( missingStack != null && missingStack.getStackSize() > 0 ) + { + String str = Long.toString( missingStack.getStackSize() ); + if( missingStack.getStackSize() >= 10000 ) + { + str = Long.toString( missingStack.getStackSize() / 1000 ) + 'k'; + } + if( missingStack.getStackSize() >= 10000000 ) + { + str = Long.toString( missingStack.getStackSize() / 1000000 ) + 'm'; + } + + str = GuiText.Missing.getLocal() + ": " + str; + final int w = 4 + this.fontRendererObj.getStringWidth( str ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); + + if( this.tooltip == z - viewStart ) + { + lineList.add( GuiText.Missing.getLocal() + ": " + Long.toString( missingStack.getStackSize() ) ); + } + + red = true; + downY += 5; + } + + if( pendingStack != null && pendingStack.getStackSize() > 0 ) + { + String str = Long.toString( pendingStack.getStackSize() ); + if( pendingStack.getStackSize() >= 10000 ) + { + str = Long.toString( pendingStack.getStackSize() / 1000 ) + 'k'; + } + if( pendingStack.getStackSize() >= 10000000 ) + { + str = Long.toString( pendingStack.getStackSize() / 1000000 ) + 'm'; + } + + str = GuiText.ToCraft.getLocal() + ": " + str; + final int w = 4 + this.fontRendererObj.getStringWidth( str ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, 4210752 ); + + if( this.tooltip == z - viewStart ) + { + lineList.add( GuiText.ToCraft.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); + } + } + + GL11.glPopMatrix(); + final int posX = x * ( 1 + sectionLength ) + xo + sectionLength - 19; + final int posY = y * offY + yo; + + final ItemStack is = refStack.copy().getItemStack(); + + if( this.tooltip == z - viewStart ) + { + dspToolTip = Platform.getItemDisplayName( is ); + + if( lineList.size() > 0 ) + { + dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); + } + + toolPosX = x * ( 1 + sectionLength ) + xo + sectionLength - 8; + toolPosY = y * offY + yo; + } + + this.drawItem( posX, posY, is ); + + if( red ) + { + final int startX = x * ( 1 + sectionLength ) + xo; + final int startY = posY - 4; + drawRect( startX, startY, startX + sectionLength, startY + offY, 0x1AFF0000 ); + } + + x++; + + if( x > 2 ) + { + y++; + x = 0; + } + } + } + + if( this.tooltip >= 0 && dspToolTip.length() > 0 ) + { + this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); + } + } + + @Override + public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) + { + this.setScrollBar(); + this.bindTexture( "appliedenergistics2", "guis/craftingreport.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } + + private void setScrollBar() + { + final int size = this.visual.size(); + + this.getScrollBar().setTop( 19 ).setLeft( 218 ).setHeight( 114 ); + this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - this.rows, 1 ); + } + + public void postUpdate( final List list, final byte ref ) + { + switch( ref ) + { + case 0: + for( final IAEItemStack l : list ) + { + this.handleInput( this.storage, l ); + } + break; + + case 1: + for( final IAEItemStack l : list ) + { + this.handleInput( this.pending, l ); + } + break; + + case 2: + for( final IAEItemStack l : list ) + { + this.handleInput( this.missing, l ); + } + break; + } + + for( final IAEItemStack l : list ) + { + final long amt = this.getTotal( l ); + + if( amt <= 0 ) + { + this.deleteVisualStack( l ); + } + else + { + final IAEItemStack is = this.findVisualStack( l ); + is.setStackSize( amt ); + } + } + + this.setScrollBar(); + } + + private void handleInput( final IItemList s, final IAEItemStack l ) + { + IAEItemStack a = s.findPrecise( l ); + + if( l.getStackSize() <= 0 ) + { + if( a != null ) + { + a.reset(); + } + } + else + { + if( a == null ) + { + s.add( l.copy() ); + a = s.findPrecise( l ); + } + + if( a != null ) + { + a.setStackSize( l.getStackSize() ); + } + } + } + + private long getTotal( final IAEItemStack is ) + { + final IAEItemStack a = this.storage.findPrecise( is ); + final IAEItemStack c = this.pending.findPrecise( is ); + final IAEItemStack m = this.missing.findPrecise( is ); + + long total = 0; + + if( a != null ) + { + total += a.getStackSize(); + } + + if( c != null ) + { + total += c.getStackSize(); + } + + if( m != null ) + { + total += m.getStackSize(); + } + + return total; + } + + private void deleteVisualStack( final IAEItemStack l ) + { + final Iterator i = this.visual.iterator(); + while( i.hasNext() ) + { + final IAEItemStack o = i.next(); + if( o.equals( l ) ) + { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack( final IAEItemStack l ) + { + for( final IAEItemStack o : this.visual ) + { + if( o.equals( l ) ) + { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add( stack ); + return stack; + } + + @Override + protected void keyTyped( final char character, final int key ) + { + if( !this.checkHotbarKeys( key ) ) + { + if( key == 28 ) + { + this.actionPerformed( this.start ); + } + super.keyTyped( character, key ); + } + } + + @Override + protected void actionPerformed( final GuiButton btn ) + { + super.actionPerformed( btn ); + + final boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.selectCPU ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + + if( btn == this.cancel ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); + } + + if( btn == this.start ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Start", "Start" ) ); + } + catch( final Throwable e ) + { + WCTLog.debug( e.getMessage() ); + } + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftingCPU.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftingCPU.java new file mode 100644 index 0000000..c84807f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftingCPU.java @@ -0,0 +1,471 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import com.google.common.base.Joiner; + +import org.apache.commons.lang3.time.DurationFormatUtils; +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiScrollbar; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftingCPU; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; +import appeng.api.AEApi; +import appeng.api.config.SortDir; +import appeng.api.config.SortOrder; +import appeng.api.config.ViewItems; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.api.util.AEColor; +import appeng.client.gui.widgets.ISortSource; +import appeng.core.AEConfig; +import appeng.core.localization.GuiText; +import appeng.util.Platform; +import appeng.util.ReadableNumberConverter; + + +public class GuiCraftingCPU extends AEBaseGui implements ISortSource +{ + private static final int GUI_HEIGHT = 184; + private static final int GUI_WIDTH = 238; + + private static final int DISPLAYED_ROWS = 6; + + private static final int TEXT_COLOR = 0x404040; + private static final int BACKGROUND_ALPHA = 0x5A000000; + + private static final int SECTION_LENGTH = 67; + + private static final int SCROLLBAR_TOP = 19; + private static final int SCROLLBAR_LEFT = 218; + private static final int SCROLLBAR_HEIGHT = 137; + + private static final int CANCEL_LEFT_OFFSET = 163; + private static final int CANCEL_TOP_OFFSET = 25; + private static final int CANCEL_HEIGHT = 20; + private static final int CANCEL_WIDTH = 50; + + private static final int TITLE_TOP_OFFSET = 7; + private static final int TITLE_LEFT_OFFSET = 8; + + private static final int ITEMSTACK_LEFT_OFFSET = 9; + private static final int ITEMSTACK_TOP_OFFSET = 22; + + private final ContainerCraftingCPU craftingCpu; + + private IItemList storage = AEApi.instance().storage().createItemList(); + private IItemList active = AEApi.instance().storage().createItemList(); + private IItemList pending = AEApi.instance().storage().createItemList(); + + private List visual = new ArrayList(); + private GuiButton cancel; + private int tooltip = -1; + + public GuiCraftingCPU( final InventoryPlayer inventoryPlayer, final Object te ) + { + this( new ContainerCraftingCPU( inventoryPlayer, te ) ); + } + + protected GuiCraftingCPU( final ContainerCraftingCPU container ) + { + super( container ); + this.craftingCpu = container; + this.ySize = GUI_HEIGHT; + this.xSize = GUI_WIDTH; + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar( scrollbar ); + } + + public void clearItems() + { + this.storage = AEApi.instance().storage().createItemList(); + this.active = AEApi.instance().storage().createItemList(); + this.pending = AEApi.instance().storage().createItemList(); + this.visual = new ArrayList(); + } + + @Override + protected void actionPerformed( final GuiButton btn ) + { + super.actionPerformed( btn ); + + if( this.cancel == btn ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileCrafting.Cancel", "Cancel" ) ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + } + + @Override + public void initGui() + { + super.initGui(); + this.setScrollBar(); + this.cancel = new GuiButton( 0, this.guiLeft + CANCEL_LEFT_OFFSET, this.guiTop + this.ySize - CANCEL_TOP_OFFSET, CANCEL_WIDTH, CANCEL_HEIGHT, GuiText.Cancel.getLocal() ); + this.buttonList.add( this.cancel ); + } + + private void setScrollBar() + { + final int size = this.visual.size(); + + this.getScrollBar().setTop( SCROLLBAR_TOP ).setLeft( SCROLLBAR_LEFT ).setHeight( SCROLLBAR_HEIGHT ); + this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - DISPLAYED_ROWS, 1 ); + } + + @Override + public void drawScreen( final int mouseX, final int mouseY, final float btn ) + { + this.cancel.enabled = !this.visual.isEmpty(); + + final int gx = ( this.width - this.xSize ) / 2; + final int gy = ( this.height - this.ySize ) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for( int z = 0; z <= 4 * 5; z++ ) + { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if( minX < mouseX && minX + 67 > mouseX ) + { + if( minY < mouseY && minY + offY - 2 > mouseY ) + { + this.tooltip = z; + break; + } + } + + x++; + + if( x > 2 ) + { + y++; + x = 0; + } + } + + super.drawScreen( mouseX, mouseY, btn ); + } + + @Override + public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) + { + String title = this.getGuiDisplayName( GuiText.CraftingStatus.getLocal() ); + + if( this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty() ) + { + final long etaInMilliseconds = TimeUnit.MILLISECONDS.convert( this.craftingCpu.getEstimatedTime(), TimeUnit.NANOSECONDS ); + final String etaTimeText = DurationFormatUtils.formatDuration( etaInMilliseconds, GuiText.ETAFormat.getLocal() ); + title += " - " + etaTimeText; + } + + this.fontRendererObj.drawString( title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, TEXT_COLOR ); + + int x = 0; + int y = 0; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * 6; + + String dspToolTip = ""; + final List lineList = new LinkedList(); + int toolPosX = 0; + int toolPosY = 0; + + final int offY = 23; + + final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) + { + final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); + if( refStack != null ) + { + GL11.glPushMatrix(); + GL11.glScaled( 0.5, 0.5, 0.5 ); + + final IAEItemStack stored = this.storage.findPrecise( refStack ); + final IAEItemStack activeStack = this.active.findPrecise( refStack ); + final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); + + int lines = 0; + + if( stored != null && stored.getStackSize() > 0 ) + { + lines++; + } + boolean active = false; + if( activeStack != null && activeStack.getStackSize() > 0 ) + { + lines++; + active = true; + } + boolean scheduled = false; + if( pendingStack != null && pendingStack.getStackSize() > 0 ) + { + lines++; + scheduled = true; + } + + if( AEConfig.instance.useColoredCraftingStatus && ( active || scheduled ) ) + { + final int bgColor = ( active ? AEColor.Green.blackVariant : AEColor.Yellow.blackVariant ) | BACKGROUND_ALPHA; + final int startX = ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET ) * 2; + final int startY = ( ( y * offY + ITEMSTACK_TOP_OFFSET ) - 3 ) * 2; + drawRect( startX, startY, startX + ( SECTION_LENGTH * 2 ), startY + ( offY * 2 ) - 2, bgColor ); + } + + final int negY = ( ( lines - 1 ) * 5 ) / 2; + int downY = 0; + + if( stored != null && stored.getStackSize() > 0 ) + { + final String str = GuiText.Stored.getLocal() + ": " + converter.toWideReadableForm( stored.getStackSize() ); + final int w = 4 + this.fontRendererObj.getStringWidth( str ); + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); + + if( this.tooltip == z - viewStart ) + { + lineList.add( GuiText.Stored.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); + } + + downY += 5; + } + + if( activeStack != null && activeStack.getStackSize() > 0 ) + { + final String str = GuiText.Crafting.getLocal() + ": " + converter.toWideReadableForm( activeStack.getStackSize() ); + final int w = 4 + this.fontRendererObj.getStringWidth( str ); + + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); + + if( this.tooltip == z - viewStart ) + { + lineList.add( GuiText.Crafting.getLocal() + ": " + Long.toString( activeStack.getStackSize() ) ); + } + + downY += 5; + } + + if( pendingStack != null && pendingStack.getStackSize() > 0 ) + { + final String str = GuiText.Scheduled.getLocal() + ": " + converter.toWideReadableForm( pendingStack.getStackSize() ); + final int w = 4 + this.fontRendererObj.getStringWidth( str ); + + this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); + + if( this.tooltip == z - viewStart ) + { + lineList.add( GuiText.Scheduled.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); + } + } + + GL11.glPopMatrix(); + final int posX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19; + final int posY = y * offY + ITEMSTACK_TOP_OFFSET; + + final ItemStack is = refStack.copy().getItemStack(); + + if( this.tooltip == z - viewStart ) + { + dspToolTip = Platform.getItemDisplayName( is ); + + if( lineList.size() > 0 ) + { + dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); + } + + toolPosX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 8; + toolPosY = y * offY + ITEMSTACK_TOP_OFFSET; + } + + this.drawItem( posX, posY, is ); + + x++; + + if( x > 2 ) + { + y++; + x = 0; + } + } + } + + if( this.tooltip >= 0 && dspToolTip.length() > 0 ) + { + this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); + } + } + + @Override + public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) + { + this.bindTexture( "appliedenergistics2", "guis/craftingcpu.png" ); + this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + } + + public void postUpdate( final List list, final byte ref ) + { + switch( ref ) + { + case 0: + for( final IAEItemStack l : list ) + { + this.handleInput( this.storage, l ); + } + break; + + case 1: + for( final IAEItemStack l : list ) + { + this.handleInput( this.active, l ); + } + break; + + case 2: + for( final IAEItemStack l : list ) + { + this.handleInput( this.pending, l ); + } + break; + } + + for( final IAEItemStack l : list ) + { + final long amt = this.getTotal( l ); + + if( amt <= 0 ) + { + this.deleteVisualStack( l ); + } + else + { + final IAEItemStack is = this.findVisualStack( l ); + is.setStackSize( amt ); + } + } + + this.setScrollBar(); + } + + private void handleInput( final IItemList s, final IAEItemStack l ) + { + IAEItemStack a = s.findPrecise( l ); + + if( l.getStackSize() <= 0 ) + { + if( a != null ) + { + a.reset(); + } + } + else + { + if( a == null ) + { + s.add( l.copy() ); + a = s.findPrecise( l ); + } + + if( a != null ) + { + a.setStackSize( l.getStackSize() ); + } + } + } + + private long getTotal( final IAEItemStack is ) + { + final IAEItemStack a = this.storage.findPrecise( is ); + final IAEItemStack b = this.active.findPrecise( is ); + final IAEItemStack c = this.pending.findPrecise( is ); + + long total = 0; + + if( a != null ) + { + total += a.getStackSize(); + } + + if( b != null ) + { + total += b.getStackSize(); + } + + if( c != null ) + { + total += c.getStackSize(); + } + + return total; + } + + private void deleteVisualStack( final IAEItemStack l ) + { + final Iterator i = this.visual.iterator(); + + while( i.hasNext() ) + { + final IAEItemStack o = i.next(); + if( o.equals( l ) ) + { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack( final IAEItemStack l ) + { + for( final IAEItemStack o : this.visual ) + { + if( o.equals( l ) ) + { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add( stack ); + + return stack; + } + + @Override + public Enum getSortBy() + { + return SortOrder.NAME; + } + + @Override + public Enum getSortDir() + { + return SortDir.ASCENDING; + } + + @Override + public Enum getSortDisplay() + { + return ViewItems.ALL; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftingStatus.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftingStatus.java new file mode 100644 index 0000000..05739ab --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiCraftingStatus.java @@ -0,0 +1,139 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import java.io.IOException; + +import org.lwjgl.input.Mouse; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiTabButton; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftingStatus; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwitchGuis; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; +import net.p455w0rd.wirelesscraftingterminal.helpers.WirelessTerminalGuiObject; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; +import appeng.api.AEApi; +import appeng.api.definitions.IDefinitions; +import appeng.api.definitions.IParts; +import appeng.api.storage.ITerminalHost; +import appeng.core.localization.GuiText; +import appeng.core.sync.GuiBridge; + + +public class GuiCraftingStatus extends GuiCraftingCPU +{ + + private final ContainerCraftingStatus status; + private GuiButton selectCPU; + + private GuiTabButton originalGuiBtn; + private int originalGui; + private ItemStack myIcon = null; + + public GuiCraftingStatus( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) + { + super( new ContainerCraftingStatus( inventoryPlayer, te ) ); + + this.status = (ContainerCraftingStatus) this.inventorySlots; + final Object target = this.status.getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); + + if( target instanceof WirelessTerminalGuiObject ) + { + for( final ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) + { + this.myIcon = wirelessTerminalStack; + } + + this.myIcon = RandomUtils.getWirelessTerm(inventoryPlayer); + + this.originalGui = WirelessCraftingTerminal.GUI_WCT; + } + } + + @Override + protected void actionPerformed( final GuiButton btn ) + { + super.actionPerformed( btn ); + + final boolean backwards = Mouse.isButtonDown( 1 ); + + if( btn == this.selectCPU ) + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + + if( btn == this.originalGuiBtn ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); + } + } + + @Override + public void initGui() + { + super.initGui(); + + this.selectCPU = new GuiButton( 0, this.guiLeft + 8, this.guiTop + this.ySize - 25, 150, 20, GuiText.CraftingCPU.getLocal() + ": " + GuiText.NoCraftingCPUs ); + // selectCPU.enabled = false; + this.buttonList.add( this.selectCPU ); + + if( this.myIcon != null ) + { + this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 213, this.guiTop - 4, this.myIcon, this.myIcon.getDisplayName(), itemRender ) ); + this.originalGuiBtn.setHideEdge( 13 ); + } + } + + @Override + public void drawScreen( final int mouseX, final int mouseY, final float btn ) + { + this.updateCPUButtonText(); + super.drawScreen( mouseX, mouseY, btn ); + } + + private void updateCPUButtonText() + { + String btnTextText = GuiText.NoCraftingJobs.getLocal(); + + if( this.status.selectedCpu >= 0 )// && status.selectedCpu < status.cpus.size() ) + { + if( this.status.myName.length() > 0 ) + { + final String name = this.status.myName.substring( 0, Math.min( 20, this.status.myName.length() ) ); + btnTextText = GuiText.CPUs.getLocal() + ": " + name; + } + else + { + btnTextText = GuiText.CPUs.getLocal() + ": #" + this.status.selectedCpu; + } + } + + if( this.status.noCPU ) + { + btnTextText = GuiText.NoCraftingJobs.getLocal(); + } + + this.selectCPU.displayString = btnTextText; + } + + @Override + protected String getGuiDisplayName( final String in ) + { + return in; // the cup name is on the button + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiFactory.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiFactory.java new file mode 100644 index 0000000..9c2cf3d --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiFactory.java @@ -0,0 +1,31 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import java.util.Set; + +import cpw.mods.fml.client.IModGuiFactory; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; + +public class GuiFactory implements IModGuiFactory { + + @Override + public void initialize(Minecraft minecraftInstance) { + // XD + } + + @Override + public Class mainConfigGuiClass() { + return WCTGuiConfig.class; + } + + @Override + public Set runtimeGuiCategories() { + return null; + } + + @Override + public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { + return null; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiMagnet.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiMagnet.java new file mode 100644 index 0000000..5e04006 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiMagnet.java @@ -0,0 +1,87 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import org.lwjgl.opengl.GL11; + +import appeng.helpers.InventoryAction; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.resources.I18n; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ResourceLocation; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerMagnet; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketInventoryAction; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketMagnetFilterMode; +import net.p455w0rd.wirelesscraftingterminal.handlers.LocaleHandler; + +public class GuiMagnet extends GuiContainer { + + private GuiButton modeBtn; + public static boolean mode = true; + private ItemStack magnetItem; + private ContainerMagnet container; + + public GuiMagnet(ContainerMagnet c) { + super(c); + this.xSize = 176; + this.ySize = 168; + magnetItem = c.heldItem; + this.mode = getMode(); + } + + @Override + protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int p_146976_2_, int p_146976_3_) { + bindTexture("magnetfilter.png"); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 168); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.mc.fontRenderer.drawString(LocaleHandler.MagnetFilterTitle.getLocal(), 7, 5, 4210752); + this.mc.fontRenderer.drawString(I18n.format("container.inventory"), 7, 74, 4210752); + } + + @Override + public void initGui() { + super.initGui(); + this.buttonList.clear(); + this.buttonList.add(this.modeBtn = new GuiButton(1, this.guiLeft + 108, this.guiTop + 3, 60, 10, getLabel(this.mode))); + } + + String getLabel(boolean filterMode) { + return filterMode ? "Whitelisting" : "Blacklisting"; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + if (btn == this.modeBtn) { + btn.displayString = getLabel(!this.mode); + this.mode = !this.mode; + setMode(this.mode); + } + } + + private synchronized void setMode(boolean mode) { + final PacketMagnetFilterMode p = new PacketMagnetFilterMode(mode); + NetworkHandler.instance.sendToServer( p ); + } + + private synchronized boolean getMode() { + NBTTagCompound nbtTC = magnetItem.getTagCompound(); + if (nbtTC.hasKey("Whitelisting")) { + return nbtTC.getBoolean("Whitelisting"); + } + return false; + } + + + public void bindTexture(final String file) { + final ResourceLocation loc = new ResourceLocation("ae2wct", "textures/gui/" + file); + this.mc.getTextureManager().bindTexture(loc); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiWirelessCraftingTerminal.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiWirelessCraftingTerminal.java new file mode 100644 index 0000000..6576cf7 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/GuiWirelessCraftingTerminal.java @@ -0,0 +1,1480 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import java.io.IOException; +import java.text.*; +import java.util.*; +import java.util.concurrent.TimeUnit; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import com.google.common.base.Joiner; +import com.google.common.base.Stopwatch; + +import appeng.api.config.ActionItems; +import appeng.api.config.SearchBoxMode; +import appeng.api.config.Settings; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.api.util.IConfigManager; +import appeng.api.util.IConfigurableObject; +import appeng.client.gui.widgets.GuiImgButton; +import appeng.client.gui.widgets.ISortSource; +import appeng.client.gui.widgets.ITooltip; +import appeng.container.slot.SlotRestrictedInput; +import appeng.core.AEConfig; +import appeng.core.localization.ButtonToolTips; +import appeng.core.localization.GuiText; +import appeng.helpers.InventoryAction; +import appeng.util.IConfigManagerHost; +import appeng.util.Platform; + +import cpw.mods.fml.common.ObfuscationReflectionHelper; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.gui.inventory.GuiInventory; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.client.resources.I18n; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiScrollbar; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiTabButton; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.GuiTrashButton; +import net.p455w0rd.wirelesscraftingterminal.client.gui.widgets.MEGuiTextField; +import net.p455w0rd.wirelesscraftingterminal.client.me.AppEngRenderItem; +import net.p455w0rd.wirelesscraftingterminal.client.me.InternalSlotME; +import net.p455w0rd.wirelesscraftingterminal.client.me.ItemRepo; +import net.p455w0rd.wirelesscraftingterminal.client.me.SlotDisconnected; +import net.p455w0rd.wirelesscraftingterminal.client.me.SlotME; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.*; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngSlot.hasCalculatedValidness; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryBooster; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketInventoryAction; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwapSlots; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwitchGuis; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; +import net.p455w0rd.wirelesscraftingterminal.handlers.LocaleHandler; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationRegistry; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationType; +import net.p455w0rd.wirelesscraftingterminal.integration.abstraction.INEI; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class GuiWirelessCraftingTerminal extends GuiContainer implements ISortSource, IConfigManagerHost +{ + + /* + * x and y size of the inventory window in pixels. Defined as float, passed as int + * These are used for drawing the player model. + */ + private float xSize_lo; + private float ySize_lo; + public static int tick = 0, GUI_HEIGHT = 240, GUI_WIDTH = 198, AE_ROW_HEIGHT = 18, AE_NUM_ROWS = 3, GUI_UPPER_HEIGHT = 35, GUI_SEARCH_ROW = 35, + SEARCH_X = 81, SEARCH_Y = 6, SEARCH_WIDTH = 88, SEARCH_HEIGHT = 10, SEARCH_MAXCHARS = 15, GUI_LOWER_HEIGHT, AE_TOTAL_ROWS_HEIGHT, + BUTTON_SEARCH_MODE_POS_X = -18, BUTTON_SEARCH_MODE_POS_Y = 68, BUTTON_SIZE = 16, NEI_EXTRA_SPACE = 30, slotYOffset; + protected static final int BUTTON_SEARCH_MODE_ID = 5; + protected static final long TOOLTIP_UPDATE_INTERVAL = 3000L; + private int currScreenWidth, currScreenHeight, previousMouseX = 0, previousMouseY = 0; + private static final String bgTexturePath = "gui/crafting.png"; + /** The inventory to render on screen */ + private final WCTInventoryBooster inventory; + private final ContainerWirelessCraftingTerminal containerWCT; + private boolean isFullScreen, init = true, reInit, wasResized = false; + public static GuiWirelessCraftingTerminal INSTANCE; + + private static boolean switchingGuis; + private final List meSlots = new LinkedList(); + // drag y + private final Set drag_click = new HashSet(); + private final AppEngRenderItem aeRenderItem = new AppEngRenderItem(); + private GuiScrollbar scrollBar = null; + private boolean disableShiftClick = false; + private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); + private ItemStack dbl_whichItem; + private Slot bl_clicked; + private boolean subGui; + + public static int craftingGridOffsetX = 80; + public static int craftingGridOffsetY; + + private static String memoryText = ""; + private static String memoryText2 = ""; + private final ItemRepo repo; + private final int offsetX = 8; + private final IConfigManager configSrc; + private final ItemStack[] myCurrentViewCells = new ItemStack[5]; + private GuiTabButton craftingStatusBtn; + private MEGuiTextField searchField; + private int perRow = 9; + private boolean customSortOrder = true; + private int maxRows = Integer.MAX_VALUE; + private GuiImgButton ViewBox; + private GuiImgButton SortByBox; + private GuiImgButton SortDirBox; + private GuiImgButton searchBoxSettings; + private GuiImgButton terminalStyleBox; + private GuiImgButton clearBtn; + private GuiTrashButton trashBtn; + public boolean devicePowered = false; + private boolean isNEIEnabled; + private boolean wasTextboxFocused = false; + private int screenResTicks=0; + + public GuiWirelessCraftingTerminal(Container container) + { + super(container); + this.INSTANCE = this; + this.containerWCT = (ContainerWirelessCraftingTerminal) container; + this.inventory = containerWCT.boosterInventory; + this.scrollBar = new GuiScrollbar(); + this.subGui = switchingGuis; + switchingGuis = false; + this.setScrollBar( scrollBar ); + this.repo = new ItemRepo( scrollBar, this ); + this.configSrc = ( (IConfigurableObject) this.inventorySlots ).getConfigManager(); + this.devicePowered = containerWCT.isPowered(); + ((ContainerWirelessCraftingTerminal) this.inventorySlots).setGui( this ); + this.isNEIEnabled = IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ); + } + + public void onReceiveFullList( final IItemList itemList ) + { + // + } + + public void postUpdate( final List list ) + { + for( final IAEItemStack is : list ) + { + this.repo.postUpdate( is ); + } + + this.repo.updateView(); + this.setScrollBar(); + } + + private void setScrollBar() + { + this.getScrollBar().setTop( 18 ).setLeft( 174 ).setHeight( (AE_NUM_ROWS + 3) * 18 - 2 ); + this.getScrollBar().setRange( 0, ( this.repo.size() + this.perRow - 1 ) / this.perRow - (AE_NUM_ROWS + 3), Math.max( 1, (AE_NUM_ROWS + 3)/ 6 ) ); + } + + @Override + protected void actionPerformed( final GuiButton btn ) + { + if( btn == this.craftingStatusBtn ) + { + NetworkHandler.instance.sendToServer( new PacketSwitchGuis( WirelessCraftingTerminal.GUI_CRAFTING_STATUS ) ); + } + + if( btn instanceof GuiImgButton ) + { + final boolean backwards = Mouse.isButtonDown( 1 ); + + final GuiImgButton iBtn = (GuiImgButton) btn; + if( iBtn.getSetting() != Settings.ACTIONS ) + { + final Enum cv = iBtn.getCurrentValue(); + final Enum next = Platform.rotateEnum( cv, backwards, iBtn.getSetting().getPossibleValues() ); + + if( btn == this.searchBoxSettings ) + { + AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); + } + else + { + try + { + NetworkHandler.instance.sendToServer( new PacketValueConfig( iBtn.getSetting().name(), next.name() ) ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + + iBtn.set( next ); + + if( next.getClass() == SearchBoxMode.class ) + { + this.reinitalize(); + } + } + if( this.clearBtn == btn ) + { + Slot s = null; + final Container c = this.inventorySlots; + for( final Object j : c.inventorySlots ) + { + if( j instanceof SlotCraftingMatrix ) + { + s = (Slot) j; + } + } + + if( s != null ) + { + final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, s.slotNumber, 0 ); + NetworkHandler.instance.sendToServer( p ); + } + } + } + if (btn instanceof GuiTrashButton) { + if( this.trashBtn == btn ) + { + Slot s = null; + final Container c = this.inventorySlots; + for( final Object j : c.inventorySlots ) + { + if( j instanceof SlotTrash ) + { + s = (Slot) j; + } + } + + if( s != null ) + { + if (s.getHasStack()) { + containerWCT.emptyTrash(); + } + } + } + } + } + + private void reinitalize() + { + this.buttonList.clear(); + this.initGui(); + } + + + + protected static String join( final Collection toolTip, final String delimiter ) + { + final Joiner joiner = Joiner.on( delimiter ); + + return joiner.join( toolTip ); + } + + protected int getQty( final GuiButton btn ) + { + try + { + final DecimalFormat df = new DecimalFormat( "+#;-#" ); + return df.parse( btn.displayString ).intValue(); + } + catch( final ParseException e ) + { + return 0; + } + } + + public boolean isSubGui() + { + return this.subGui; + } + + /** + * Initializes the GUI + */ + @Override + public void initGui() + { + Keyboard.enableRepeatEvents( true ); + this.getMeSlots().clear(); + for( int y = 0; y < AE_NUM_ROWS+3; y++ ) + { + for( int x = 0; x < this.perRow; x++ ) + { + this.getMeSlots().add( new InternalSlotME( this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18 ) ); + } + } + super.initGui(); + final List slots = this.getInventorySlots(); + final Iterator i = slots.iterator(); + while( i.hasNext() ) + { + if( i.next() instanceof SlotME ) + { + i.remove(); + } + } + + for( final InternalSlotME me : this.meSlots ) + { + slots.add( new SlotME( me ) ); + } + int offset = this.guiTop + 8; + + this.buttonList.clear(); + this.buttonList.add( this.clearBtn = new GuiImgButton( this.guiLeft + 134, this.GUI_HEIGHT - this.GUI_LOWER_HEIGHT + 46, Settings.ACTIONS, ActionItems.STASH ) ); + this.buttonList.add( this.trashBtn = new GuiTrashButton( this.guiLeft + 98, this.GUI_HEIGHT - this.GUI_LOWER_HEIGHT + 103 ) ); + this.clearBtn.setHalfSize( true ); + if( this.customSortOrder ) + { + this.buttonList.add( this.SortByBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting( Settings.SORT_BY ) ) ); + offset += 20; + } + + this.buttonList.add( this.ViewBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.VIEW_MODE, this.configSrc.getSetting( Settings.VIEW_MODE ) ) ); + offset += 20; + + this.buttonList.add( this.SortDirBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_DIRECTION, this.configSrc.getSetting( Settings.SORT_DIRECTION ) ) ); + offset += 20; + + this.buttonList.add( this.searchBoxSettings = new GuiImgButton( this.guiLeft - 18, offset, Settings.SEARCH_MODE, AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ) ) ); + offset += 20; + + this.searchField = new MEGuiTextField( this.fontRendererObj, SEARCH_X, SEARCH_Y, SEARCH_WIDTH, SEARCH_HEIGHT ); + + this.searchField.setEnableBackgroundDrawing( false ); + this.searchField.setMaxStringLength( 25 ); + this.searchField.setTextColor( 0xFFFFFF ); + this.searchField.setVisible( true ); + this.searchField.setEnabled(true); + + this.buttonList.add( this.craftingStatusBtn = new GuiTabButton( this.guiLeft + 169, this.guiTop - 4, 2 + 11 * 16, GuiText.CraftingStatus.getLocal(), itemRender ) ); + this.craftingStatusBtn.setHideEdge( 13 ); + + final Enum setting = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); + this.searchField.setFocused( SearchBoxMode.AUTOSEARCH == setting || SearchBoxMode.NEI_AUTOSEARCH == setting ); + + + if( this.isSubGui() || this.init ) + { + if (this.isSubGui()) { + this.searchField.setText( memoryText ); + this.repo.setSearchString( memoryText ); + } + this.repo.updateView(); + this.setScrollBar(); + } + } + + @SuppressWarnings( "unchecked" ) + private List getInventorySlots() + { + return this.inventorySlots.inventorySlots; + } + + /** + * Called every tick. It is used in this instance + * to detect screen size changes to automatically + * update the gui height. + * + * reInit variable is used to call initGui() on + * the next tick. It has to be called this way to + * update correctly. + * + * @author p455w0rd + */ + @Override + public void updateScreen() { + this.devicePowered = containerWCT.isPowered(); + this.repo.setPower( devicePowered ); + //this.repo.setPower( true ); + + super.updateScreen(); + if (this.init) { + this.currScreenWidth = this.mc.displayWidth; + this.currScreenHeight = this.mc.displayHeight; + this.isFullScreen = this.mc.isFullScreen(); + this.reInit=true; + this.init=false; + } + ++screenResTicks; + if (screenResTicks == 20) { + this.wasTextboxFocused = this.searchField.isFocused(); + screenResTicks = 0; + } + if (this.reInit) { + if (tick != 1) { + tick++; + } + else { + this.initGui(); + this.setScrollBar(); + if (this.wasResized == true) { + this.searchField.setFocused(this.wasTextboxFocused); + this.searchField.setText(this.repo.getSearchString()); + this.wasTextboxFocused = false; + this.wasResized=false; + } + containerWCT.updateSlots(slotYOffset); + this.reInit=false; + tick = 0; + } + } + if (hasScreenResChanged()) { + this.reInit = true; + this.wasResized=true; + } + //if (!this.mc.thePlayer.isEntityAlive() || this.mc.thePlayer.isDead) { + // this.mc.thePlayer.closeScreen(); + //} + //else { + // this block of variables is used to automatically + // reposition the slots in the container + GUI_HEIGHT = this.mc.displayHeight / 2; + AE_NUM_ROWS = Math.max(0, ((GUI_HEIGHT) - 240) / AE_ROW_HEIGHT); + if (isNEIEnabled && AE_NUM_ROWS >= 2) { + AE_NUM_ROWS -= 2; + GUI_HEIGHT -= AE_ROW_HEIGHT * 2 + 5; + this.clearBtn.yPosition = AE_TOTAL_ROWS_HEIGHT + GUI_SEARCH_ROW + GUI_UPPER_HEIGHT + 32; + this.trashBtn.yPosition = AE_TOTAL_ROWS_HEIGHT + GUI_SEARCH_ROW + GUI_UPPER_HEIGHT + 89; + } + else { + this.clearBtn.yPosition = AE_TOTAL_ROWS_HEIGHT + GUI_SEARCH_ROW + GUI_UPPER_HEIGHT + 13; + this.trashBtn.yPosition = AE_TOTAL_ROWS_HEIGHT + GUI_SEARCH_ROW + GUI_UPPER_HEIGHT + 68; + } + AE_TOTAL_ROWS_HEIGHT = AE_NUM_ROWS * AE_ROW_HEIGHT; + GUI_LOWER_HEIGHT = GUI_HEIGHT - AE_TOTAL_ROWS_HEIGHT - GUI_UPPER_HEIGHT; + slotYOffset = AE_TOTAL_ROWS_HEIGHT; + craftingGridOffsetY = slotYOffset + 83; + //} + } + + /** + * Detects if the window has been resized + * @return True if window has been resized + * @author p455w0rd + */ + private boolean hasScreenResChanged() { + if ((this.currScreenWidth != this.mc.displayWidth) || + (this.currScreenHeight != this.mc.displayHeight) || + (this.isFullScreen != this.mc.isFullScreen())) { + this.currScreenWidth = this.mc.displayWidth; + this.currScreenHeight = this.mc.displayHeight; + this.isFullScreen = this.mc.isFullScreen(); + return true; + } + return false; + } + + /** + * Draws the screen and tooltips. + */ + public void drawScreen(int mouseX, int mouseY, float btn) + { + super.drawScreen(mouseX, mouseY, btn); + this.xSize_lo = (float)mouseX; + this.ySize_lo = (float)mouseY; + this.xSize = GUI_WIDTH; + this.ySize = GUI_HEIGHT; + + final boolean hasClicked = Mouse.isButtonDown( 0 ); + if( hasClicked && this.scrollBar != null ) + { + this.scrollBar.click( this, mouseX - this.guiLeft, mouseY - this.guiTop ); + } + + for( final Object c : this.buttonList ) + { + if( c instanceof ITooltip ) + { + final ITooltip tooltip = (ITooltip) c; + final int x = tooltip.xPos(); // ((GuiImgButton) c).xPosition; + int y = tooltip.yPos(); // ((GuiImgButton) c).yPosition; + + if( x < mouseX && x + tooltip.getWidth() > mouseX && tooltip.isVisible() ) + { + if( y < mouseY && y + tooltip.getHeight() > mouseY ) + { + if( y < 15 ) + { + y = 15; + } + + final String msg = tooltip.getMessage(); + if( msg != null ) + { + this.drawTooltip( x + 11, y + 4, 0, msg ); + } + } + } + } + } + } + + public void drawTooltip( final int par2, final int par3, final int forceWidth, final String message ) + { + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + GL11.glDisable( GL12.GL_RESCALE_NORMAL ); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable( GL11.GL_LIGHTING ); + GL11.glDisable( GL11.GL_DEPTH_TEST ); + final String[] var4 = message.split( "\n" ); + + if( var4.length > 0 ) + { + int var5 = 0; + int var6; + int var7; + + for( var6 = 0; var6 < var4.length; ++var6 ) + { + var7 = this.fontRendererObj.getStringWidth( var4[var6] ); + + if( var7 > var5 ) + { + var5 = var7; + } + } + + var6 = par2 + 12; + var7 = par3 - 12; + int var9 = 8; + + if( var4.length > 1 ) + { + var9 += 2 + ( var4.length - 1 ) * 10; + } + + if( this.guiTop + var7 + var9 + 6 > this.height ) + { + var7 = this.height - var9 - this.guiTop - 6; + } + + if( forceWidth > 0 ) + { + var5 = forceWidth; + } + + this.zLevel = 300.0F; + itemRender.zLevel = 300.0F; + final int var10 = -267386864; + this.drawGradientRect( var6 - 3, var7 - 4, var6 + var5 + 3, var7 - 3, var10, var10 ); + this.drawGradientRect( var6 - 3, var7 + var9 + 3, var6 + var5 + 3, var7 + var9 + 4, var10, var10 ); + this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 + var9 + 3, var10, var10 ); + this.drawGradientRect( var6 - 4, var7 - 3, var6 - 3, var7 + var9 + 3, var10, var10 ); + this.drawGradientRect( var6 + var5 + 3, var7 - 3, var6 + var5 + 4, var7 + var9 + 3, var10, var10 ); + final int var11 = 1347420415; + final int var12 = ( var11 & 16711422 ) >> 1 | var11 & -16777216; + this.drawGradientRect( var6 - 3, var7 - 3 + 1, var6 - 3 + 1, var7 + var9 + 3 - 1, var11, var12 ); + this.drawGradientRect( var6 + var5 + 2, var7 - 3 + 1, var6 + var5 + 3, var7 + var9 + 3 - 1, var11, var12 ); + this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 - 3 + 1, var11, var11 ); + this.drawGradientRect( var6 - 3, var7 + var9 + 2, var6 + var5 + 3, var7 + var9 + 3, var12, var12 ); + + for( int var13 = 0; var13 < var4.length; ++var13 ) + { + String var14 = var4[var13]; + + if( var13 == 0 ) + { + var14 = '\u00a7' + Integer.toHexString( 15 ) + var14; + } + else + { + var14 = "\u00a77" + var14; + } + + this.fontRendererObj.drawStringWithShadow( var14, var6, var7, -1 ); + + if( var13 == 0 ) + { + var7 += 2; + } + + var7 += 10; + } + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + GL11.glPopAttrib(); + } + + public void bindTexture( final String base, final String file ) + { + final ResourceLocation loc = new ResourceLocation( base, "textures/" + file ); + this.mc.getTextureManager().bindTexture( loc ); + } + + /** + * Draw GUI Labels and item tooltips + */ + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) + { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + + if( this.scrollBar != null ) + { + this.scrollBar.draw( this ); + } + this.drawFG( ox, oy, mouseX, mouseY ); + } + + public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) { + String s = LocaleHandler.WirelessTermLabel.getLocal(); + this.mc.fontRenderer.drawString(s, 7, 5, 4210752); + this.mc.fontRenderer.drawString(I18n.format("container.inventory"), 7, AE_TOTAL_ROWS_HEIGHT + GUI_SEARCH_ROW + GUI_UPPER_HEIGHT + 3, 4210752); + if( this.searchField != null ) + { + this.searchField.drawTextBox(); + } + } + + /** + * Draw and piece together the background texture + */ + protected void drawGuiContainerBackgroundLayer(final float f, final int x, final int y) + { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.drawBG( ox, oy, x, y ); + + final List slots = this.getInventorySlots(); + for( final Slot slot : slots ) + { + if( slot instanceof OptionalSlotFake ) + { + final OptionalSlotFake fs = (OptionalSlotFake) slot; + if( fs.renderDisabled() ) + { + if( fs.isEnabled() ) + { + this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, 18 ); + } + else + { + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 0.4F ); + GL11.glEnable( GL11.GL_BLEND ); + this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, 18 ); + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + GL11.glPopAttrib(); + } + } + } + } + } + + public void drawBG(int ox, int oy, int x, int y) { + this.bindTexture(bgTexturePath); + + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, GUI_WIDTH, GUI_UPPER_HEIGHT); + + for ( int i = 0; i <= AE_NUM_ROWS; ++i) { + int yPos = this.guiTop + GUI_UPPER_HEIGHT + (i * AE_ROW_HEIGHT); + // Draw the texture + this.drawTexturedModalRect(this.guiLeft, yPos, 0, GUI_SEARCH_ROW, GUI_WIDTH, AE_ROW_HEIGHT); + } + + this.drawTexturedModalRect(this.guiLeft, this.guiTop + GUI_UPPER_HEIGHT + AE_TOTAL_ROWS_HEIGHT, 0, AE_ROW_HEIGHT + 17, GUI_WIDTH, GUI_LOWER_HEIGHT); + if (Reference.WCT_BOOSTER_ENABLED) { + this.drawTexturedModalRect(this.guiLeft + 132, this.guiTop + GUI_UPPER_HEIGHT + AE_TOTAL_ROWS_HEIGHT + 102, 237, 237, 19, 19); + } + GuiInventory.func_147046_a(this.guiLeft + 51, this.guiTop + GUI_UPPER_HEIGHT + AE_TOTAL_ROWS_HEIGHT + 112, 32, (float)(this.guiLeft + 51) - this.xSize_lo, (float)(this.guiTop + 95 + (AE_NUM_ROWS * AE_ROW_HEIGHT)) - this.ySize_lo, this.mc.thePlayer); + } + + @Override + protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) + { + + final Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); + + if( searchMode != SearchBoxMode.AUTOSEARCH && searchMode != SearchBoxMode.NEI_AUTOSEARCH ) + { + this.searchField.mouseClicked( xCoord - this.guiLeft, yCoord - this.guiTop, btn ); + } + + //if( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) + if( btn == 1 && this.searchField.isMouseIn( xCoord - this.guiLeft, yCoord - this.guiTop ) ) + { + this.searchField.setText( "" ); + this.repo.setSearchString( "" ); + this.repo.updateView(); + this.setScrollBar(); + } + + this.drag_click.clear(); + + if( btn == 1 ) + { + for( final Object o : this.buttonList ) + { + final GuiButton guibutton = (GuiButton) o; + if( guibutton.mousePressed( this.mc, xCoord, yCoord ) ) + { + super.mouseClicked( xCoord, yCoord, 0 ); + return; + } + } + } + + super.mouseClicked( xCoord, yCoord, btn ); + } + + @Override + protected void mouseClickMove( final int x, final int y, final int c, final long d ) + { + final Slot slot = this.getSlot( x, y ); + final ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); + + if( slot instanceof SlotFake && itemstack != null ) + { + this.drag_click.add( slot ); + if( this.drag_click.size() > 1 ) + { + for( final Slot dr : this.drag_click ) + { + final PacketInventoryAction p = new PacketInventoryAction( c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN : InventoryAction.PLACE_SINGLE, dr.slotNumber, 0 ); + NetworkHandler.instance.sendToServer( p ); + } + } + } + else + { + super.mouseClickMove( x, y, c, d ); + } + } + + @Override + protected void handleMouseClick( final Slot slot, final int slotIdx, final int ctrlDown, final int key ) + { + final EntityPlayer player = Minecraft.getMinecraft().thePlayer; + + if( slot instanceof SlotFake ) + { + final InventoryAction action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + + if( this.drag_click.size() > 1 ) + { + return; + } + + final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); + NetworkHandler.instance.sendToServer( p ); + + return; + } + + else if( slot instanceof SlotCraftingTerm ) + { + if( key == 6 ) + { + return; // prevent weird double clicks.. + } + + InventoryAction action = null; + if( key == 1 ) + { + action = InventoryAction.CRAFT_SHIFT; + } + else + { + action = ctrlDown == 1 ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM; + } + + final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); + NetworkHandler.instance.sendToServer( p ); + + return; + } + + if( Keyboard.isKeyDown( Keyboard.KEY_SPACE ) ) + { + if( this.enableSpaceClicking() ) + { + IAEItemStack stack = null; + if( slot instanceof SlotME ) + { + stack = ( (SlotME) slot ).getAEStack(); + } + + int slotNum = this.getInventorySlots().size(); + + if( !( slot instanceof SlotME ) && slot != null ) + { + slotNum = slot.slotNumber; + } + + ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).setTargetStack( stack ); + final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, slotNum, 0 ); + NetworkHandler.instance.sendToServer( p ); + return; + } + } + + if( slot instanceof SlotDisconnected ) + { + InventoryAction action = null; + + switch( key ) + { + case 0: // pickup / set-down. + action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + break; + + case 3: // creative dupe: + + if( player.capabilities.isCreativeMode ) + { + action = InventoryAction.CREATIVE_DUPLICATE; + } + + break; + + default: + case 4: // drop item: + case 6: + } + + if( action != null ) + { + final PacketInventoryAction p = new PacketInventoryAction( action, slot.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); + NetworkHandler.instance.sendToServer( p ); + } + + return; + } + + if( slot instanceof SlotME ) + { + InventoryAction action = null; + IAEItemStack stack = null; + + switch( key ) + { + case 0: // pickup / set-down. + action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + stack = ( (SlotME) slot ).getAEStack(); + + if( stack != null && action == InventoryAction.PICKUP_OR_SET_DOWN && stack.getStackSize() == 0 && player.inventory.getItemStack() == null ) + { + action = InventoryAction.AUTO_CRAFT; + } + + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + stack = ( (SlotME) slot ).getAEStack(); + break; + + case 3: // creative dupe: + + stack = ( (SlotME) slot ).getAEStack(); + if( stack != null && stack.isCraftable() ) + { + action = InventoryAction.AUTO_CRAFT; + } + else if( player.capabilities.isCreativeMode ) + { + final IAEItemStack slotItem = ( (SlotME) slot ).getAEStack(); + if( slotItem != null ) + { + action = InventoryAction.CREATIVE_DUPLICATE; + } + } + break; + + default: + case 4: // drop item: + case 6: + } + + if( action != null ) + { + ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).setTargetStack( stack ); + final PacketInventoryAction p = new PacketInventoryAction( action, this.getInventorySlots().size(), 0 ); + NetworkHandler.instance.sendToServer( p ); + } + + return; + } + + if( !this.disableShiftClick && isShiftKeyDown() ) + { + this.disableShiftClick = true; + + if( this.dbl_whichItem == null || this.bl_clicked != slot || this.dbl_clickTimer.elapsed( TimeUnit.MILLISECONDS ) > 150 ) + { + // some simple double click logic. + this.bl_clicked = slot; + this.dbl_clickTimer = Stopwatch.createStarted(); + if( slot != null ) + { + this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : null; + } + else + { + this.dbl_whichItem = null; + } + } + else if( this.dbl_whichItem != null ) + { + // a replica of the weird broken vanilla feature. + + final List slots = this.getInventorySlots(); + for( final Slot inventorySlot : slots ) + { + if( inventorySlot != null && inventorySlot.canTakeStack( this.mc.thePlayer ) && inventorySlot.getHasStack() && inventorySlot.inventory == slot.inventory && Container.func_94527_a( inventorySlot, this.dbl_whichItem, true ) ) + { + this.handleMouseClick( inventorySlot, inventorySlot.slotNumber, ctrlDown, 1 ); + } + } + } + + this.disableShiftClick = false; + } + + super.handleMouseClick( slot, slotIdx, ctrlDown, key ); + } + + @Override + protected boolean checkHotbarKeys( final int keyCode ) + { + final Slot theSlot; + + try + { + theSlot = ObfuscationReflectionHelper.getPrivateValue( GuiContainer.class, this, "theSlot", "field_147006_u", "f" ); + } + catch( final Throwable t ) + { + return false; + } + + if( this.mc.thePlayer.inventory.getItemStack() == null && theSlot != null ) + { + for( int j = 0; j < 9; ++j ) + { + if( keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode() ) + { + final List slots = this.getInventorySlots(); + for( final Slot s : slots ) + { + if( s.getSlotIndex() == j && s.inventory == ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).getPlayerInv() ) + { + if( !s.canTakeStack( ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).getPlayerInv().player ) ) + { + return false; + } + } + } + + if( theSlot.getSlotStackLimit() == 64 ) + { + this.handleMouseClick( theSlot, theSlot.slotNumber, j, 2 ); + return true; + } + else + { + for( final Slot s : slots ) + { + if( s.getSlotIndex() == j && s.inventory == ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).getPlayerInv() ) + { + NetworkHandler.instance.sendToServer( new PacketSwapSlots( s.slotNumber, theSlot.slotNumber ) ); + return true; + } + } + } + } + } + } + + return false; + } + + @Override + public void onGuiClosed() + { + super.onGuiClosed(); + this.subGui = true; // in case the gui is reopened later ( i'm looking at you NEI ) + Keyboard.enableRepeatEvents( false ); + memoryText = this.searchField.getText(); + } + + protected Slot getSlot( final int mouseX, final int mouseY ) + { + final List slots = this.getInventorySlots(); + for( final Slot slot : slots ) + { + // isPointInRegion + if( this.func_146978_c( slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY ) ) + { + return slot; + } + } + + return null; + } + + @Override + public void handleMouseInput() + { + super.handleMouseInput(); + + final int i = Mouse.getEventDWheel(); + if( i != 0 && isShiftKeyDown() ) + { + final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + this.mouseWheelEvent( x, y, i / Math.abs( i ) ); + } + else if( i != 0 && this.scrollBar != null ) + { + this.scrollBar.wheel( i ); + } + } + + private void mouseWheelEvent( final int x, final int y, final int wheel ) + { + final Slot slot = this.getSlot( x, y ); + if( slot instanceof SlotME ) + { + final IAEItemStack item = ( (SlotME) slot ).getAEStack(); + if( item != null ) + { + ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).setTargetStack( item ); + final InventoryAction direction = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; + final int times = Math.abs( wheel ); + final int inventorySize = this.getInventorySlots().size(); + for( int h = 0; h < times; h++ ) + { + final PacketInventoryAction p = new PacketInventoryAction( direction, inventorySize, 0 ); + NetworkHandler.instance.sendToServer( p ); + } + } + } + } + + protected boolean enableSpaceClicking() + { + return true; + } + + protected void drawItem( final int x, final int y, final ItemStack is ) + { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + GL11.glEnable( GL11.GL_LIGHTING ); + GL11.glEnable( GL12.GL_RESCALE_NORMAL ); + GL11.glEnable( GL11.GL_DEPTH_TEST ); + RenderHelper.enableGUIStandardItemLighting(); + itemRender.renderItemAndEffectIntoGUI( this.fontRendererObj, this.mc.renderEngine, is, x, y ); + GL11.glPopAttrib(); + + itemRender.zLevel = 0.0F; + this.zLevel = 0.0F; + } + + protected String getGuiDisplayName( final String in ) + { + return this.hasCustomInventoryName() ? this.getInventoryName() : in; + } + + private boolean hasCustomInventoryName() + { + if( this.inventorySlots instanceof ContainerWirelessCraftingTerminal ) + { + return ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).getCustomName() != null; + } + return false; + } + + private String getInventoryName() + { + return ( (ContainerWirelessCraftingTerminal) this.inventorySlots ).getCustomName(); + } + + private void drawSlot( final Slot s ) + { + if( s instanceof SlotME ) + { + final RenderItem pIR = this.setItemRender( this.aeRenderItem ); + try + { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + if( !this.isPowered() ) + { + GL11.glDisable( GL11.GL_LIGHTING ); + drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, 0x66111111 ); + GL11.glEnable( GL11.GL_LIGHTING ); + } + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + + this.aeRenderItem.setAeStack( ( (SlotME) s ).getAEStack() ); + + this.safeDrawSlot( s ); + } + catch( final Exception err ) + { + WCTLog.warning( "WCT prevented crash while drawing slot: " + err.toString() ); + } + this.setItemRender( pIR ); + return; + } + else + { + this.itemRender = new RenderItem(); + try + { + final ItemStack is = s.getStack(); + if( s instanceof AppEngSlot && ( ( (AppEngSlot) s ).renderIconWithItem() || is == null ) && ( ( (AppEngSlot) s ).shouldDisplay() ) ) + { + final AppEngSlot aes = (AppEngSlot) s; + if( aes.getIcon() >= 0 ) + { + this.bindTexture( "appliedenergistics2", "guis/states.png" ); + + GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + final Tessellator tessellator = Tessellator.instance; + try + { + final int uv_y = (int) Math.floor( aes.getIcon() / 16 ); + final int uv_x = aes.getIcon() - uv_y * 16; + + GL11.glEnable( GL11.GL_BLEND ); + GL11.glDisable( GL11.GL_LIGHTING ); + GL11.glEnable( GL11.GL_TEXTURE_2D ); + GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); + GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + final float par1 = aes.xDisplayPosition; + final float par2 = aes.yDisplayPosition; + final float par3 = uv_x * 16; + final float par4 = uv_y * 16; + + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ); + final float f1 = 0.00390625F; + final float f = 0.00390625F; + final float par6 = 16; + tessellator.addVertexWithUV( par1 + 0, par2 + par6, this.zLevel, ( par3 + 0 ) * f, ( par4 + par6 ) * f1 ); + final float par5 = 16; + tessellator.addVertexWithUV( par1 + par5, par2 + par6, this.zLevel, ( par3 + par5 ) * f, ( par4 + par6 ) * f1 ); + tessellator.addVertexWithUV( par1 + par5, par2 + 0, this.zLevel, ( par3 + par5 ) * f, ( par4 + 0 ) * f1 ); + tessellator.addVertexWithUV( par1 + 0, par2 + 0, this.zLevel, ( par3 + 0 ) * f, ( par4 + 0 ) * f1 ); + tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, 1.0f ); + tessellator.draw(); + } + catch( final Exception err ) + { + } + GL11.glPopAttrib(); + } + } + + if( is != null && s instanceof AppEngSlot ) + { + if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.NotAvailable ) + { + boolean isValid = s.isItemValid( is ) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected; + if( isValid && s instanceof SlotRestrictedInput ) + { + try + { + isValid = ( (SlotRestrictedInput) s ).isValid( is, this.mc.theWorld ); + } + catch( final Exception err ) + { + WCTLog.debug( err.getMessage() ); + } + } + ( (AppEngSlot) s ).setIsValid( isValid ? hasCalculatedValidness.Valid : hasCalculatedValidness.Invalid ); + } + + if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.Invalid ) + { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glDisable( GL11.GL_LIGHTING ); + drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, 0x66ff6666 ); + GL11.glEnable( GL11.GL_LIGHTING ); + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + } + + if( s instanceof AppEngSlot ) + { + ( (AppEngSlot) s ).setDisplay( true ); + this.safeDrawSlot( s ); + } + else + { + this.safeDrawSlot( s ); + } + + return; + } + catch( final Exception err ) + { + WCTLog.warning( "WCT prevented crash while drawing slot: " + err.toString() ); + } + } + // do the usual for non-ME Slots. + this.safeDrawSlot( s ); + } + + private RenderItem setItemRender( final RenderItem item ) + { + if( isNEIEnabled ) + { + return ( (INEI) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.NEI ) ).setItemRender( item ); + } + else + { + final RenderItem ri = itemRender; + itemRender = item; + return ri; + } + } + + @Override + protected void keyTyped( final char character, final int key ) + { + if( !this.checkHotbarKeys( key ) ) + { + if( character == ' ' && this.searchField.getText().isEmpty() ) + { + return; + } + + if( this.searchField.textboxKeyTyped( character, key ) ) + { + this.repo.setSearchString( this.searchField.getText() ); + this.repo.updateView(); + this.setScrollBar(); + } + else + { + super.keyTyped( character, key ); + } + } + } + + protected boolean isPowered() + { + return this.repo.hasPower(); + } + + private void safeDrawSlot( final Slot s ) + { + try + { + GuiContainer.class.getDeclaredMethod( "func_146977_a_original", Slot.class ).invoke( this, s ); + } + catch( final Exception err ) + { + } + } + + public void bindTexture( final String file ) + { + final ResourceLocation loc = new ResourceLocation( Reference.MODID, "textures/" + file ); + this.mc.getTextureManager().bindTexture( loc ); + } + + + public void func_146977_a( final Slot s ) + { + this.drawSlot( s ); + } + + protected GuiScrollbar getScrollBar() + { + return this.scrollBar; + } + + protected void setScrollBar( final GuiScrollbar myScrollBar ) + { + this.scrollBar = myScrollBar; + } + + protected List getMeSlots() + { + return this.meSlots; + } + + public static final synchronized boolean isSwitchingGuis() + { + return switchingGuis; + } + + public static final synchronized void setSwitchingGuis( final boolean switchingGuis ) + { + GuiWirelessCraftingTerminal.switchingGuis = switchingGuis; + } + + public List handleItemTooltip( final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip ) + { + if( stack != null ) + { + final Slot s = this.getSlot( mouseX, mouseY ); + if( s instanceof SlotME ) + { + final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; + + IAEItemStack myStack = null; + + try + { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } + catch( final Throwable ignore ) + { + } + + if( myStack != null ) + { + if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) + { + final String local = ButtonToolTips.ItemsStored.getLocal(); + final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ); + final String format = String.format( local, formattedAmount ); + + currentToolTip.add( "\u00a77" + format ); + } + + if( myStack.getCountRequestable() > 0 ) + { + final String local = ButtonToolTips.ItemsRequestable.getLocal(); + final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ); + final String format = String.format( local, formattedAmount ); + + currentToolTip.add( "\u00a77" + format ); + } + } + else if( stack.stackSize > BigNumber || ( stack.stackSize > 1 && stack.isItemDamaged() ) ) + { + final String local = ButtonToolTips.ItemsStored.getLocal(); + final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ); + final String format = String.format( local, formattedAmount ); + + currentToolTip.add( "\u00a77" + format ); + } + } + } + return currentToolTip; + } + + @Override + protected void renderToolTip( final ItemStack stack, final int x, final int y ) + { + final Slot s = this.getSlot( x, y ); + if( s instanceof SlotME && stack != null ) + { + final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; + + IAEItemStack myStack = null; + + try + { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } + catch( final Throwable ignore ) + { + } + + if( myStack != null ) + { + @SuppressWarnings( "unchecked" ) + final List currentToolTip = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); + + if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) + { + currentToolTip.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ) ); + } + + if( myStack.getCountRequestable() > 0 ) + { + currentToolTip.add( "Items Requestable: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ) ); + } + + this.drawTooltip( x, y, 0, join( currentToolTip, "\n" ) ); + } + else if( stack.stackSize > BigNumber ) + { + final List var4 = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); + var4.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ) ); + this.drawTooltip( x, y, 0, join( var4, "\n" ) ); + return; + } + } + super.renderToolTip( stack, x, y ); + // super.drawItemStackTooltip( stack, x, y ); + } + + @Override + public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) + { + if( this.SortByBox != null ) + { + this.SortByBox.set( this.configSrc.getSetting( Settings.SORT_BY ) ); + } + + if( this.SortDirBox != null ) + { + this.SortDirBox.set( this.configSrc.getSetting( Settings.SORT_DIRECTION ) ); + } + + if( this.ViewBox != null ) + { + this.ViewBox.set( this.configSrc.getSetting( Settings.VIEW_MODE ) ); + } + + this.repo.updateView(); + } + + public boolean isCustomSortOrder() + { + return this.customSortOrder; + } + + void setCustomSortOrder( final boolean customSortOrder ) + { + this.customSortOrder = customSortOrder; + } + + @Override + public Enum getSortBy() + { + return this.configSrc.getSetting( Settings.SORT_BY ); + } + + @Override + public Enum getSortDir() + { + return this.configSrc.getSetting( Settings.SORT_DIRECTION ); + } + + @Override + public Enum getSortDisplay() + { + return this.configSrc.getSetting( Settings.VIEW_MODE ); + } + + + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/WCTGuiConfig.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/WCTGuiConfig.java new file mode 100644 index 0000000..ad0196a --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/WCTGuiConfig.java @@ -0,0 +1,22 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui; + +import cpw.mods.fml.client.config.GuiConfig; +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.common.config.Configuration; +import net.p455w0rd.wirelesscraftingterminal.handlers.ConfigHandler; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class WCTGuiConfig extends GuiConfig { + + public WCTGuiConfig(GuiScreen guiScreen) + { + super(guiScreen, + new ConfigElement(ConfigHandler.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), + Reference.MODID, + false, + false, + GuiConfig.getAbridgedConfigPath(ConfigHandler.config.toString())); + } + +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiScrollbar.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiScrollbar.java new file mode 100644 index 0000000..3adbf3c --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiScrollbar.java @@ -0,0 +1,144 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui.widgets; + +import org.lwjgl.opengl.GL11; + +import appeng.client.gui.widgets.IScrollSource; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.p455w0rd.wirelesscraftingterminal.client.gui.AEBaseGui; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal; + +public class GuiScrollbar implements IScrollSource +{ + + private int displayX = 0; + private int displayY = 0; + private int width = 12; + private int height = 16; + private int pageSize = 1; + + private int maxScroll = 0; + private int minScroll = 0; + private int currentScroll = 0; + + public void draw( final GuiContainer g ) + { + if (g instanceof GuiWirelessCraftingTerminal) { + ((GuiWirelessCraftingTerminal) g).bindTexture( "minecraft", "gui/container/creative_inventory/tabs.png" ); + + } + else if (g instanceof AEBaseGui) { + ((AEBaseGui) g).bindTexture("minecraft", "gui/container/creative_inventory/tabs.png"); + } + + GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + if( this.getRange() == 0 ) + { + g.drawTexturedModalRect( this.displayX, this.displayY, 232 + this.width, 0, this.width, 15 ); + } + else + { + final int offset = ( this.currentScroll - this.minScroll ) * ( this.height - 15 ) / this.getRange(); + g.drawTexturedModalRect( this.displayX, offset + this.displayY, 232, 0, this.width, 15 ); + } + } + + private int getRange() + { + return this.maxScroll - this.minScroll; + } + + public int getLeft() + { + return this.displayX; + } + + public GuiScrollbar setLeft( final int v ) + { + this.displayX = v; + return this; + } + + public int getTop() + { + return this.displayY; + } + + public GuiScrollbar setTop( final int v ) + { + this.displayY = v; + return this; + } + + public int getWidth() + { + return this.width; + } + + public GuiScrollbar setWidth( final int v ) + { + this.width = v; + return this; + } + + public int getHeight() + { + return this.height; + } + + public GuiScrollbar setHeight( final int v ) + { + this.height = v; + return this; + } + + public void setRange( final int min, final int max, final int pageSize ) + { + this.minScroll = min; + this.maxScroll = max; + this.pageSize = pageSize; + + if( this.minScroll > this.maxScroll ) + { + this.maxScroll = this.minScroll; + } + + this.applyRange(); + } + + private void applyRange() + { + this.currentScroll = Math.max( Math.min( this.currentScroll, this.maxScroll ), this.minScroll ); + } + + @Override + public int getCurrentScroll() + { + return this.currentScroll; + } + + public void click( final GuiContainer aeBaseGui, final int x, final int y ) + { + if( this.getRange() == 0 ) + { + return; + } + + if( x > this.displayX && x <= this.displayX + this.width ) + { + if( y > this.displayY && y <= this.displayY + this.height ) + { + this.currentScroll = ( y - this.displayY ); + this.currentScroll = this.minScroll + ( ( this.currentScroll * 2 * this.getRange() / this.height ) ); + this.currentScroll = ( this.currentScroll + 1 ) >> 1; + this.applyRange(); + } + } + } + + public void wheel( int delta ) + { + delta = Math.max( Math.min( -delta, 1 ), -1 ); + this.currentScroll += delta * this.pageSize; + this.applyRange(); + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiTabButton.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiTabButton.java new file mode 100644 index 0000000..d5aea31 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiTabButton.java @@ -0,0 +1,147 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui.widgets; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.item.ItemStack; +import appeng.client.gui.widgets.ITooltip; +import appeng.client.texture.ExtraBlockTextures; + + +public class GuiTabButton extends GuiButton implements ITooltip +{ + private final RenderItem itemRenderer; + private final String message; + private int hideEdge = 0; + private int myIcon = -1; + private ItemStack myItem; + + public GuiTabButton( final int x, final int y, final int ico, final String message, final RenderItem ir ) + { + super( 0, 0, 16, "" ); + + this.xPosition = x; + this.yPosition = y; + this.width = 22; + this.height = 22; + this.myIcon = ico; + this.message = message; + this.itemRenderer = ir; + } + + /** + * Using itemstack as an icon + * + * @param x x pos of button + * @param y y pos of button + * @param ico used icon + * @param message mouse over message + * @param ir renderer + */ + public GuiTabButton( final int x, final int y, final ItemStack ico, final String message, final RenderItem ir ) + { + super( 0, 0, 16, "" ); + this.xPosition = x; + this.yPosition = y; + this.width = 22; + this.height = 22; + this.myItem = ico; + this.message = message; + this.itemRenderer = ir; + } + + @Override + public void drawButton( final Minecraft minecraft, final int x, final int y ) + { + if( this.visible ) + { + GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); + this.field_146123_n = x >= this.xPosition && y >= this.yPosition && x < this.xPosition + this.width && y < this.yPosition + this.height; + + int uv_x = ( this.hideEdge > 0 ? 11 : 13 ); + + final int offsetX = this.hideEdge > 0 ? 1 : 0; + + //this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, 0, 25, 22 ); + + if( this.myIcon >= 0 ) + { + final int uv_y = (int) Math.floor( this.myIcon / 16 ); + uv_x = this.myIcon - uv_y * 16; + + this.drawTexturedModalRect( offsetX + this.xPosition + 3, this.yPosition + 6, uv_x * 16, uv_y * 16, 16, 16 ); + } + + this.mouseDragged( minecraft, x, y ); + + if( this.myItem != null ) + { + this.zLevel = 100.0F; + this.itemRenderer.zLevel = 100.0F; + + GL11.glEnable( GL11.GL_LIGHTING ); + GL11.glEnable( GL12.GL_RESCALE_NORMAL ); + RenderHelper.enableGUIStandardItemLighting(); + final FontRenderer fontrenderer = minecraft.fontRenderer; + //this.itemRenderer.renderItemAndEffectIntoGUI( fontrenderer, minecraft.renderEngine, this.myItem, offsetX + this.xPosition + 3, this.yPosition + 6 ); + this.itemRenderer.renderItemIntoGUI( fontrenderer, minecraft.renderEngine, this.myItem, offsetX + this.xPosition + 3, this.yPosition + 6, false ); + GL11.glDisable( GL11.GL_LIGHTING ); + + this.itemRenderer.zLevel = 0.0F; + this.zLevel = 0.0F; + } + } + } + + @Override + public String getMessage() + { + return this.message; + } + + @Override + public int xPos() + { + return this.xPosition; + } + + @Override + public int yPos() + { + return this.yPosition; + } + + @Override + public int getWidth() + { + return 22; + } + + @Override + public int getHeight() + { + return 22; + } + + @Override + public boolean isVisible() + { + return this.visible; + } + + public int getHideEdge() + { + return this.hideEdge; + } + + public void setHideEdge( final int hideEdge ) + { + this.hideEdge = hideEdge; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiTrashButton.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiTrashButton.java new file mode 100644 index 0000000..6ccc93f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/GuiTrashButton.java @@ -0,0 +1,71 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui.widgets; + +import org.lwjgl.opengl.GL11; + +import appeng.client.gui.widgets.ITooltip; +import appeng.client.texture.ExtraBlockTextures; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.ResourceLocation; +import net.p455w0rd.wirelesscraftingterminal.handlers.LocaleHandler; + +public class GuiTrashButton extends GuiButton implements ITooltip { + + public GuiTrashButton(int x, int y) { + super(x, y, 8, ""); + this.xPosition = x; + this.yPosition = y; + this.width = 8; + this.height = 8; + } + + @Override + public void drawButton( final Minecraft mc, final int par2, final int par3 ) + { + if( this.visible ) + { + GL11.glPushMatrix(); + GL11.glTranslatef( this.xPosition, this.yPosition, 0.0F ); + GL11.glScalef( 0.5f, 0.5f, 0.5f ); + GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + mc.renderEngine.bindTexture( new ResourceLocation( "appliedenergistics2", "textures/guis/states.png" ) ); + this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; + this.drawTexturedModalRect( 0, 0, 256 - 16, 256 - 16, 16, 16 ); + this.drawTexturedModalRect( 0, 0, 6 * 16, 0, 16, 16 ); + this.mouseDragged(mc, par2, par3 ); + GL11.glPopMatrix(); + } + } + + @Override + public String getMessage() { + return EnumChatFormatting.WHITE + "" + LocaleHandler.EmptyTrash.getLocal() + "\n" + EnumChatFormatting.GRAY + "" + LocaleHandler.EmptyTrashDesc.getLocal(); + } + + @Override + public int xPos() { + return this.xPosition; + } + + @Override + public int yPos() { + return this.yPosition; + } + + @Override + public int getWidth() { + return this.width; + } + + @Override + public int getHeight() { + return this.height; + } + + @Override + public boolean isVisible() { + return this.visible; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/MEGuiTextField.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/MEGuiTextField.java new file mode 100644 index 0000000..2ae0c03 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/gui/widgets/MEGuiTextField.java @@ -0,0 +1,69 @@ +package net.p455w0rd.wirelesscraftingterminal.client.gui.widgets; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiTextField; + + +/** + * A modified version of the Minecraft text field. + * You can initialize it over the full element span. + * The mouse click area is increased to the full element + * subtracted with the defined padding. + * + * The rendering does pay attention to the size of the '_' caret. + */ +public class MEGuiTextField extends GuiTextField +{ + private static final int PADDING = 2; + + private final int _xPos; + private final int _yPos; + private final int _width; + private final int _height; + + /** + * Uses the values to instantiate a padded version of a text field. + * Pays attention to the '_' caret. + * + * @param fontRenderer renderer for the strings + * @param xPos absolute left position + * @param yPos absolute top position + * @param width absolute width + * @param height absolute height + */ + public MEGuiTextField( final FontRenderer fontRenderer, final int xPos, final int yPos, final int width, final int height ) + { + super( fontRenderer, xPos, yPos, width, height - 2 * PADDING ); + + this._xPos = xPos; + this._yPos = yPos; + this._width = width; + this._height = height; + } + + @Override + public void mouseClicked( final int xPos, final int yPos, final int button ) + { + super.mouseClicked( xPos, yPos, button ); + + final boolean requiresFocus = this.isMouseIn( xPos, yPos ); + + this.setFocused( requiresFocus ); + } + + /** + * Checks if the mouse is within the element + * + * @param xCoord current x coord of the mouse + * @param yCoord current y coord of the mouse + * + * @return true if mouse position is within the text field area + */ + public boolean isMouseIn( final int xCoord, final int yCoord ) + { + final boolean withinXRange = xCoord >= this._xPos && xCoord <= this._xPos + this._width; + final boolean withinYRange = this._yPos <= yCoord && yCoord < this._yPos + this._height; + + return withinXRange && withinYRange; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/AppEngRenderItem.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/AppEngRenderItem.java new file mode 100644 index 0000000..f846591 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/AppEngRenderItem.java @@ -0,0 +1,147 @@ +package net.p455w0rd.wirelesscraftingterminal.client.me; + +import javax.annotation.Nonnull; + +import org.lwjgl.opengl.GL11; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.item.ItemStack; + +import appeng.api.storage.data.IAEItemStack; +import appeng.core.AEConfig; +import appeng.core.localization.GuiText; +import appeng.util.ISlimReadableNumberConverter; +import appeng.util.IWideReadableNumberConverter; +import appeng.util.ReadableNumberConverter; + + +/** + * @author AlgorithmX2 + * @author thatsIch + * @version rv2 + * @since rv0 + */ +public class AppEngRenderItem extends RenderItem +{ + private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; + private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; + boolean useLg = AEConfig.instance.useTerminalUseLargeFont(); + private IAEItemStack aeStack = null; + + @Override + public void renderItemOverlayIntoGUI( final FontRenderer fontRenderer, final TextureManager textureManager, final ItemStack is, final int par4, final int par5, final String par6Str ) + { + if( is != null ) + { + final float scaleFactor = useLg ? 0.85f : 0.5f; + final float inverseScaleFactor = 1.0f / scaleFactor; + final int offset = useLg ? 0 : -1; + + final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag( false ); + + if( is.getItem().showDurabilityBar( is ) ) + { + final double health = is.getItem().getDurabilityForDisplay( is ); + final int j1 = (int) Math.round( 13.0D - health * 13.0D ); + final int k = (int) Math.round( 255.0D - health * 255.0D ); + + GL11.glDisable( GL11.GL_LIGHTING ); + GL11.glDisable( GL11.GL_DEPTH_TEST ); + GL11.glDisable( GL11.GL_TEXTURE_2D ); + GL11.glDisable( GL11.GL_ALPHA_TEST ); + GL11.glDisable( GL11.GL_BLEND ); + + final Tessellator tessellator = Tessellator.instance; + final int l = 255 - k << 16 | k << 8; + final int i1 = ( 255 - k ) / 4 << 16 | 16128; + + this.renderQuad( tessellator, par4 + 2, par5 + 13, 13, 2, 0 ); + this.renderQuad( tessellator, par4 + 2, par5 + 13, 12, 1, i1 ); + this.renderQuad( tessellator, par4 + 2, par5 + 13, j1, 1, l ); + + GL11.glEnable( GL11.GL_ALPHA_TEST ); + GL11.glEnable( GL11.GL_TEXTURE_2D ); + GL11.glEnable( GL11.GL_LIGHTING ); + GL11.glEnable( GL11.GL_DEPTH_TEST ); + GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + } + + if( is.stackSize == 0 ) + { + final String craftLabelText = useLg ? GuiText.LargeFontCraft.getLocal() : GuiText.SmallFontCraft.getLocal(); + + GL11.glDisable( GL11.GL_LIGHTING ); + GL11.glDisable( GL11.GL_DEPTH_TEST ); + GL11.glPushMatrix(); + GL11.glScaled( scaleFactor, scaleFactor, scaleFactor ); + + final int X = (int) ( ( (float) par4 + offset + 16.0f - fontRenderer.getStringWidth( craftLabelText ) * scaleFactor ) * inverseScaleFactor ); + final int Y = (int) ( ( (float) par5 + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); + fontRenderer.drawStringWithShadow( craftLabelText, X, Y, 16777215 ); + + GL11.glPopMatrix(); + GL11.glEnable( GL11.GL_LIGHTING ); + GL11.glEnable( GL11.GL_DEPTH_TEST ); + } + + final long amount = this.aeStack != null ? this.aeStack.getStackSize() : is.stackSize; + + if( amount != 0 ) + { + final String stackSize = this.getToBeRenderedStackSize( amount ); + + GL11.glDisable( GL11.GL_LIGHTING ); + GL11.glDisable( GL11.GL_DEPTH_TEST ); + GL11.glPushMatrix(); + GL11.glScaled( scaleFactor, scaleFactor, scaleFactor ); + + final int X = (int) ( ( (float) par4 + offset + 16.0f - fontRenderer.getStringWidth( stackSize ) * scaleFactor ) * inverseScaleFactor ); + final int Y = (int) ( ( (float) par5 + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); + fontRenderer.drawStringWithShadow( stackSize, X, Y, 16777215 ); + + GL11.glPopMatrix(); + GL11.glEnable( GL11.GL_LIGHTING ); + GL11.glEnable( GL11.GL_DEPTH_TEST ); + } + + fontRenderer.setUnicodeFlag( unicodeFlag ); + } + } + + private void renderQuad( final Tessellator par1Tessellator, final int par2, final int par3, final int par4, final int par5, final int par6 ) + { + par1Tessellator.startDrawingQuads(); + par1Tessellator.setColorOpaque_I( par6 ); + par1Tessellator.addVertex( par2, par3, 0.0D ); + par1Tessellator.addVertex( par2, par3 + par5, 0.0D ); + par1Tessellator.addVertex( par2 + par4, par3 + par5, 0.0D ); + par1Tessellator.addVertex( par2 + par4, par3, 0.0D ); + par1Tessellator.draw(); + } + + private String getToBeRenderedStackSize( final long originalSize ) + { + if( AEConfig.instance.useTerminalUseLargeFont() ) + { + return SLIM_CONVERTER.toSlimReadableForm( originalSize ); + } + else + { + return WIDE_CONVERTER.toWideReadableForm( originalSize ); + } + } + + public IAEItemStack getAeStack() + { + return this.aeStack; + } + + public void setAeStack( @Nonnull final IAEItemStack aeStack ) + { + this.aeStack = aeStack; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/ClientDCInternalInv.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/ClientDCInternalInv.java new file mode 100644 index 0000000..1c75c07 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/ClientDCInternalInv.java @@ -0,0 +1,53 @@ +package net.p455w0rd.wirelesscraftingterminal.client.me; + +import javax.annotation.Nonnull; + +import net.minecraft.util.StatCollector; + +import appeng.tile.inventory.AppEngInternalInventory; +import appeng.util.ItemSorters; + + +public class ClientDCInternalInv implements Comparable +{ + + private final String unlocalizedName; + private final AppEngInternalInventory inventory; + + private final long id; + private final long sortBy; + + public ClientDCInternalInv( final int size, final long id, final long sortBy, final String unlocalizedName ) + { + this.inventory = new AppEngInternalInventory( null, size ); + this.unlocalizedName = unlocalizedName; + this.id = id; + this.sortBy = sortBy; + } + + public String getName() + { + final String s = StatCollector.translateToLocal( this.unlocalizedName + ".name" ); + if( s.equals( this.unlocalizedName + ".name" ) ) + { + return StatCollector.translateToLocal( this.unlocalizedName ); + } + return s; + } + + @Override + public int compareTo( @Nonnull final ClientDCInternalInv o ) + { + return ItemSorters.compareLong( this.sortBy, o.sortBy ); + } + + public AppEngInternalInventory getInventory() + { + return this.inventory; + } + + public long getId() + { + return this.id; + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/InternalSlotME.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/InternalSlotME.java new file mode 100644 index 0000000..097f62d --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/InternalSlotME.java @@ -0,0 +1,48 @@ +package net.p455w0rd.wirelesscraftingterminal.client.me; + +import net.minecraft.item.ItemStack; + +import appeng.api.storage.data.IAEItemStack; + + +public class InternalSlotME +{ + + private final int offset; + private final int xPos; + private final int yPos; + private final ItemRepo repo; + + public InternalSlotME( final ItemRepo def, final int offset, final int displayX, final int displayY ) + { + this.repo = def; + this.offset = offset; + this.xPos = displayX; + this.yPos = displayY; + } + + ItemStack getStack() + { + return this.repo.getItem( this.offset ); + } + + IAEItemStack getAEStack() + { + return this.repo.getReferenceItem( this.offset ); + } + + boolean hasPower() + { + return this.repo.hasPower(); + } + + int getxPosition() + { + return this.xPos; + } + + int getyPosition() + { + return this.yPos; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/ItemRepo.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/ItemRepo.java new file mode 100644 index 0000000..76adbbd --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/ItemRepo.java @@ -0,0 +1,293 @@ +package net.p455w0rd.wirelesscraftingterminal.client.me; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.regex.Pattern; + +import javax.annotation.Nonnull; + +import net.minecraft.item.ItemStack; + +import cpw.mods.fml.relauncher.ReflectionHelper; + +import appeng.api.AEApi; +import appeng.api.config.SearchBoxMode; +import appeng.api.config.Settings; +import appeng.api.config.SortOrder; +import appeng.api.config.ViewItems; +import appeng.api.config.YesNo; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.client.gui.widgets.IScrollSource; +import appeng.client.gui.widgets.ISortSource; +import appeng.core.AEConfig; +import appeng.items.storage.ItemViewCell; +import appeng.util.ItemSorters; +import appeng.util.Platform; +import appeng.util.prioitylist.IPartitionList; + + +public class ItemRepo +{ + + private final IItemList list = AEApi.instance().storage().createItemList(); + private final ArrayList view = new ArrayList(); + private final ArrayList dsp = new ArrayList(); + private final IScrollSource src; + private final ISortSource sortSrc; + + private int rowSize = 9; + + private String searchString = ""; + private IPartitionList myPartitionList; + private String innerSearch = ""; + private String NEIWord = null; + private boolean hasPower; + + public ItemRepo( final IScrollSource src, final ISortSource sortSrc ) + { + this.src = src; + this.sortSrc = sortSrc; + } + + public IAEItemStack getReferenceItem( int idx ) + { + idx += this.src.getCurrentScroll() * this.rowSize; + + if( idx >= this.view.size() ) + { + return null; + } + return this.view.get( idx ); + } + + public ItemStack getItem( int idx ) + { + idx += this.src.getCurrentScroll() * this.rowSize; + + if( idx >= this.dsp.size() ) + { + return null; + } + return this.dsp.get( idx ); + } + + void setSearch( final String search ) + { + this.searchString = search == null ? "" : search; + } + + public void postUpdate( final IAEItemStack is ) + { + final IAEItemStack st = this.list.findPrecise( is ); + + if( st != null ) + { + st.reset(); + st.add( is ); + } + else + { + this.list.add( is ); + } + } + + public void setViewCell( final ItemStack[] list ) + { + this.myPartitionList = ItemViewCell.createFilter( list ); + this.updateView(); + } + + public void updateView() + { + this.view.clear(); + this.dsp.clear(); + + this.view.ensureCapacity( this.list.size() ); + this.dsp.ensureCapacity( this.list.size() ); + + final Enum viewMode = this.sortSrc.getSortDisplay(); + final Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); + if( searchMode == SearchBoxMode.NEI_AUTOSEARCH || searchMode == SearchBoxMode.NEI_MANUAL_SEARCH ) + { + this.updateNEI( this.searchString ); + } + + this.innerSearch = this.searchString; + final boolean terminalSearchToolTips = AEConfig.instance.settings.getSetting( Settings.SEARCH_TOOLTIPS ) != YesNo.NO; + // boolean terminalSearchMods = Configuration.INSTANCE.settings.getSetting( Settings.SEARCH_MODS ) != YesNo.NO; + + boolean searchMod = false; + if( this.innerSearch.startsWith( "@" ) ) + { + searchMod = true; + this.innerSearch = this.innerSearch.substring( 1 ); + } + + Pattern m = null; + try + { + m = Pattern.compile( this.innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE ); + } + catch( final Throwable ignore ) + { + try + { + m = Pattern.compile( Pattern.quote( this.innerSearch.toLowerCase() ), Pattern.CASE_INSENSITIVE ); + } + catch( final Throwable __ ) + { + return; + } + } + + boolean notDone = false; + for( IAEItemStack is : this.list ) + { + if( this.myPartitionList != null ) + { + if( !this.myPartitionList.isListed( is ) ) + { + continue; + } + } + + if( viewMode == ViewItems.CRAFTABLE && !is.isCraftable() ) + { + continue; + } + + if( viewMode == ViewItems.CRAFTABLE ) + { + is = is.copy(); + is.setStackSize( 0 ); + } + + if( viewMode == ViewItems.STORED && is.getStackSize() == 0 ) + { + continue; + } + + final String dspName = searchMod ? Platform.getModId( is ) : Platform.getItemDisplayName( is ); + notDone = true; + + if( m.matcher( dspName.toLowerCase() ).find() ) + { + this.view.add( is ); + notDone = false; + } + + if( terminalSearchToolTips && notDone ) + { + for( final Object lp : Platform.getTooltip( is ) ) + { + if( lp instanceof String && m.matcher( (CharSequence) lp ).find() ) + { + this.view.add( is ); + notDone = false; + break; + } + } + } + + /* + * if ( terminalSearchMods && notDone ) { if ( m.matcher( Platform.getMod( is.getItemStack() ) ).find() ) { + * view.add( is ); notDone = false; } } + */ + } + + final Enum SortBy = this.sortSrc.getSortBy(); + final Enum SortDir = this.sortSrc.getSortDir(); + + ItemSorters.setDirection( (appeng.api.config.SortDir) SortDir ); + ItemSorters.init(); + + if( SortBy == SortOrder.MOD ) + { + Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD ); + } + else if( SortBy == SortOrder.AMOUNT ) + { + Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE ); + } + else if( SortBy == SortOrder.INVTWEAKS ) + { + Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_INV_TWEAKS ); + } + else + { + Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_NAME ); + } + + for( final IAEItemStack is : this.view ) + { + this.dsp.add( is.getItemStack() ); + } + } + + private void updateNEI( final String filter ) + { + try + { + if( this.NEIWord == null || !this.NEIWord.equals( filter ) ) + { + final Class c = ReflectionHelper.getClass( this.getClass().getClassLoader(), "codechicken.nei.LayoutManager" ); + final Field fldSearchField = c.getField( "searchField" ); + final Object searchField = fldSearchField.get( c ); + + final Method a = searchField.getClass().getMethod( "setText", String.class ); + final Method b = searchField.getClass().getMethod( "onTextChange", String.class ); + + this.NEIWord = filter; + a.invoke( searchField, filter ); + b.invoke( searchField, "" ); + } + } + catch( final Throwable ignore ) + { + + } + } + + public int size() + { + return this.view.size(); + } + + public void clear() + { + this.list.resetStatus(); + } + + public boolean hasPower() + { + return this.hasPower; + } + + public void setPower( final boolean hasPower ) + { + this.hasPower = hasPower; + } + + public int getRowSize() + { + return this.rowSize; + } + + public void setRowSize( final int rowSize ) + { + this.rowSize = rowSize; + } + + public String getSearchString() + { + return this.searchString; + } + + public void setSearchString( @Nonnull final String searchString ) + { + this.searchString = searchString; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/SlotDisconnected.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/SlotDisconnected.java new file mode 100644 index 0000000..a6d3f70 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/SlotDisconnected.java @@ -0,0 +1,92 @@ +package net.p455w0rd.wirelesscraftingterminal.client.me; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngSlot; +import appeng.items.misc.ItemEncodedPattern; +import appeng.util.Platform; + + +public class SlotDisconnected extends AppEngSlot +{ + + private final ClientDCInternalInv mySlot; + + public SlotDisconnected( final ClientDCInternalInv me, final int which, final int x, final int y ) + { + super( me.getInventory(), which, x, y ); + this.mySlot = me; + } + + @Override + public boolean isItemValid( final ItemStack par1ItemStack ) + { + return false; + } + + @Override + public void putStack( final ItemStack par1ItemStack ) + { + + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + return false; + } + + @Override + public ItemStack getDisplayStack() + { + if( Platform.isClient() ) + { + final ItemStack is = super.getStack(); + if( is != null && is.getItem() instanceof ItemEncodedPattern ) + { + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ItemStack out = iep.getOutput( is ); + if( out != null ) + { + return out; + } + } + } + return super.getStack(); + } + + @Override + public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) + { + } + + @Override + public boolean getHasStack() + { + return this.getStack() != null; + } + + @Override + public int getSlotStackLimit() + { + return 0; + } + + @Override + public ItemStack decrStackSize( final int par1 ) + { + return null; + } + + @Override + public boolean isSlotInInventory( final IInventory par1iInventory, final int par2 ) + { + return false; + } + + public ClientDCInternalInv getSlot() + { + return this.mySlot; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/SlotME.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/SlotME.java new file mode 100644 index 0000000..48dfe9a --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/me/SlotME.java @@ -0,0 +1,92 @@ +package net.p455w0rd.wirelesscraftingterminal.client.me; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +import appeng.api.storage.data.IAEItemStack; + + +public class SlotME extends Slot +{ + + private final InternalSlotME mySlot; + + public SlotME( final InternalSlotME me ) + { + super( null, 0, me.getxPosition(), me.getyPosition() ); + this.mySlot = me; + } + + public IAEItemStack getAEStack() + { + if( this.mySlot.hasPower() ) + { + return this.mySlot.getAEStack(); + } + return null; + } + + @Override + public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) + { + } + + @Override + public boolean isItemValid( final ItemStack par1ItemStack ) + { + return false; + } + + @Override + public ItemStack getStack() + { + if( this.mySlot.hasPower() ) + { + return this.mySlot.getStack(); + } + return null; + } + + @Override + public boolean getHasStack() + { + if( this.mySlot.hasPower() ) + { + return this.getStack() != null; + } + return false; + } + + @Override + public void putStack( final ItemStack par1ItemStack ) + { + + } + + @Override + public int getSlotStackLimit() + { + return 0; + } + + @Override + public ItemStack decrStackSize( final int par1 ) + { + return null; + } + + @Override + public boolean isSlotInInventory( final IInventory par1iInventory, final int par2 ) + { + return false; + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + return false; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/textures/AEStateIconsEnum.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/textures/AEStateIconsEnum.java new file mode 100644 index 0000000..3e5469f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/textures/AEStateIconsEnum.java @@ -0,0 +1,130 @@ +package net.p455w0rd.wirelesscraftingterminal.client.textures; + +import net.minecraft.util.ResourceLocation; + +/** + * Icons stored in the AE2's "states" texture. + * + * @author Nividica + * + */ +public enum AEStateIconsEnum implements IStateIconTexture { + + // Redstone modes + REDSTONE_LOW(0, 0), REDSTONE_HIGH(16, 0), REDSTONE_PULSE(32, 0), REDSTONE_IGNORE(48, 0), + + // Slot backgrounds + VIEW_CELL_BACKGROUND(224, 64), UPGRADE_CARD_BACKGROUND(240, 208), ME_CELL_BACKGROUND(240, + 0), PATTERN_CELL_BACKGROUND(240, 128), + + // Buttons + REGULAR_BUTTON(240, 240), TAB_BUTTON(208, 0, 22, 22), + + // Sorting modes + SORT_MODE_ALPHABETIC(0, 64), SORT_MODE_AMOUNT(16, 64), SORT_MODE_MOD(80, 64), SORT_MODE_INVTWEAK(64, 64), + + // Sorting directions + SORT_DIR_ASC(0, 48), SORT_DIR_DEC(16, 48), + + // View types + VIEW_TYPE_STORED(0, 16), VIEW_TYPE_ALL(32, 16), VIEW_TYPE_CRAFT(48, 16), + + // Terminal styles + TERM_STYLE_TALL(0, 208), TERM_STYLE_SMALL(16, 208), + + // Search modes + SEARCH_MODE_AUTO(48, 32), SEARCH_MODE_MANUAL(64, 32), SEARCH_MODE_NEI_AUTO(80, 32), SEARCH_MODE_NEI_MANUAL(96, 32), + + // Misc + WRENCH(32, 64), DISABLED(0, 128), ENABLED(16, 128), SAVE(0, 176), DELETE(0, 192), CLEAR_GRID(96, 0), ARROW_DOWN(128, 0); + + /** + * Location of the AE states texture + */ + public static final ResourceLocation AE_STATES_TEXTURE = new ResourceLocation("appliedenergistics2", + "textures/guis/states.png"); + + /** + * Width and height of standard icons. + */ + public static final int STANDARD_ICON_SIZE = 16; + + /** + * X position in the texture this icon is located at. + */ + private int minU; + + /** + * Y position in the texture this icon is located at. + */ + private int minV; + + /** + * Width of the icon + */ + private int width; + + /** + * Height of the icon + */ + private int height; + + /** + * Standard icon constructor + * + * @param u + * @param v + */ + private AEStateIconsEnum(final int u, final int v) { + this(u, v, STANDARD_ICON_SIZE, STANDARD_ICON_SIZE); + } + + /** + * Icon constructor + * + * @param u + * @param v + * @param width + * @param height + */ + private AEStateIconsEnum(final int u, final int v, final int width, final int height) { + // Set the u + this.minU = u; + + // Set the v + this.minV = v; + + // Set width + this.width = width; + + // Set height + this.height = height; + + } + + @Override + public int getHeight() { + return this.height; + } + + @Override + public ResourceLocation getTexture() { + return AEStateIconsEnum.AE_STATES_TEXTURE; + } + + @Override + public int getU() { + return this.minU; + } + + @Override + public int getV() { + return this.minV; + } + + @Override + public int getWidth() { + return this.width; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/client/textures/IStateIconTexture.java b/src/java/net/p455w0rd/wirelesscraftingterminal/client/textures/IStateIconTexture.java new file mode 100644 index 0000000..a5930cb --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/client/textures/IStateIconTexture.java @@ -0,0 +1,49 @@ +package net.p455w0rd.wirelesscraftingterminal.client.textures; + +import javax.annotation.Nonnull; +import net.minecraft.util.ResourceLocation; + +/** + * Icon from a state texture. + * + * @author Nividica + * + */ +public interface IStateIconTexture +{ + /** + * Height of the icon. + * + * @return + */ + int getHeight(); + + /** + * Texture the icon is in. + * + * @return + */ + @Nonnull + ResourceLocation getTexture(); + + /** + * U coordinate of the icon. + * + * @return + */ + int getU(); + + /** + * V coordinate of the icon. + * + * @return + */ + int getV(); + + /** + * Width of the icon. + * + * @return + */ + int getWidth(); +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/WCTGuiHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/WCTGuiHandler.java new file mode 100644 index 0000000..5e3dceb --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/WCTGuiHandler.java @@ -0,0 +1,93 @@ +package net.p455w0rd.wirelesscraftingterminal.common; + +import appeng.api.AEApi; +import appeng.api.implementations.guiobjects.IPortableCell; +import appeng.api.storage.ITerminalHost; +import cpw.mods.fml.common.network.IGuiHandler; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTermHandler; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiCraftAmount; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiCraftConfirm; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiCraftingStatus; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiMagnet; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftAmount; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftConfirm; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftingStatus; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerMagnet; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.helpers.WirelessTerminalGuiObject; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + +public class WCTGuiHandler implements IGuiHandler { + + public void registerRenderers() { + } + + @Override + public Object getServerGuiElement(int guiId, EntityPlayer player, World world, int x, int y, int z) { + final IWirelessCraftingTermHandler wh = (IWirelessCraftingTermHandler) AEApi.instance().registries().wireless().getWirelessTerminalHandler(RandomUtils.getWirelessTerm(player.inventory)); + final WirelessTerminalGuiObject obj = new WirelessTerminalGuiObject(wh, RandomUtils.getWirelessTerm(player.inventory), player, world, x, y, z); + final IPortableCell terminal = (IPortableCell) obj; + + if (guiId == WirelessCraftingTerminal.GUI_WCT) { + return new ContainerWirelessCraftingTerminal(player, player.inventory); + } + + if (guiId == WirelessCraftingTerminal.GUI_CRAFTING_STATUS) { + return new ContainerCraftingStatus(player.inventory, (ITerminalHost) terminal); + } + + if (guiId == WirelessCraftingTerminal.GUI_CRAFT_AMOUNT) { + return new ContainerCraftAmount(player.inventory, (ITerminalHost) terminal); + } + + if (guiId == WirelessCraftingTerminal.GUI_CRAFT_CONFIRM) { + return new ContainerCraftConfirm(player.inventory, (ITerminalHost) terminal); + } + + if (guiId == WirelessCraftingTerminal.GUI_MAGNET) { + return new ContainerMagnet(player, player.inventory); + } + + return null; + } + + @Override + public Object getClientGuiElement(int guiId, EntityPlayer player, World world, int x, int y, int z) { + final IWirelessCraftingTermHandler wh = (IWirelessCraftingTermHandler) AEApi.instance().registries().wireless().getWirelessTerminalHandler(RandomUtils.getWirelessTerm(player.inventory)); + final WirelessTerminalGuiObject obj = new WirelessTerminalGuiObject(wh, RandomUtils.getWirelessTerm(player.inventory), player, world, x, y, z); + final IPortableCell terminal = (IPortableCell) obj; + + if (guiId == WirelessCraftingTerminal.GUI_WCT) { + return new GuiWirelessCraftingTerminal((ContainerWirelessCraftingTerminal) new ContainerWirelessCraftingTerminal(player, player.inventory)); + } + + if (guiId == WirelessCraftingTerminal.GUI_CRAFTING_STATUS) { + return new GuiCraftingStatus(player.inventory, (ITerminalHost) terminal); + } + + if (guiId == WirelessCraftingTerminal.GUI_CRAFT_AMOUNT) { + return new GuiCraftAmount(player.inventory, (ITerminalHost) terminal); + } + + if (guiId == WirelessCraftingTerminal.GUI_CRAFT_CONFIRM) { + return new GuiCraftConfirm(player.inventory, (ITerminalHost) terminal); + } + + if (guiId == WirelessCraftingTerminal.GUI_MAGNET) { + return new GuiMagnet(new ContainerMagnet(player, player.inventory)); + } + + return null; + } + + public static void launchGui(final int ID, final EntityPlayer player, final World world, final int x, final int y, final int z) { + player.openGui(WirelessCraftingTerminal.INSTANCE, ID, world, x, y, z); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/WirelessCraftingTerminal.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/WirelessCraftingTerminal.java new file mode 100644 index 0000000..f9ffc80 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/WirelessCraftingTerminal.java @@ -0,0 +1,93 @@ +package net.p455w0rd.wirelesscraftingterminal.common; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraftforge.common.MinecraftForge; +import cpw.mods.fml.common.*; +import cpw.mods.fml.common.Mod.*; +import cpw.mods.fml.common.event.*; +import cpw.mods.fml.common.network.NetworkRegistry; + +import java.io.File; + +import appeng.api.AEApi; +import appeng.api.features.IWirelessTermHandler; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.crash.IntegrationCrashEnhancement; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.creativetab.CreativeTabWCT; +import net.p455w0rd.wirelesscraftingterminal.handlers.AchievementHandler; +import net.p455w0rd.wirelesscraftingterminal.handlers.ConfigHandler; +import net.p455w0rd.wirelesscraftingterminal.handlers.KeybindHandler; +import net.p455w0rd.wirelesscraftingterminal.handlers.RecipeHandler; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationRegistry; +import net.p455w0rd.wirelesscraftingterminal.proxy.CommonProxy; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; + +@Mod(modid = Reference.MODID, acceptedMinecraftVersions = "[1.7.10]", name = Reference.NAME, version = Reference.VERSION, guiFactory = Reference.GUI_FACTORY, dependencies = "required-after:Forge@[" // require + // forge. + + net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion + + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion + + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion + + net.minecraftforge.common.ForgeVersion.buildVersion + ",);required-after:appliedenergistics2@[rv3-beta-1,);") + +public class WirelessCraftingTerminal { + + private static LoaderState WCTState = LoaderState.NOINIT; + public static CreativeTabs creativeTab; + + @Instance(Reference.MODID) + public static WirelessCraftingTerminal INSTANCE; + + @SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS, serverSide = Reference.SERVER_PROXY_CLASS) + public static CommonProxy proxy; + + private static int ae2wctGuiIndex = 0; + public static final int GUI_WCT = ++ae2wctGuiIndex; + public static final int GUI_CRAFTING_STATUS = ++ae2wctGuiIndex; + public static final int GUI_CRAFT_AMOUNT = ++ae2wctGuiIndex; + public static final int GUI_CRAFT_CONFIRM = ++ae2wctGuiIndex; + public static final int GUI_MAGNET = ++ae2wctGuiIndex; + + @EventHandler + public void preInit(FMLPreInitializationEvent event) { + if (!Loader.isModLoaded("wct-core")) { + proxy.missingCoreMod(); + } + long stopwatch = WCTLog.beginSection("PreInit"); + WirelessCraftingTerminal.WCTState = LoaderState.PREINITIALIZATION; + WirelessCraftingTerminal.INSTANCE = this; + creativeTab = new CreativeTabWCT(CreativeTabs.getNextID(), Reference.MODID).setNoScrollbar(); + WirelessCraftingTerminal.proxy.registerItems(); + ConfigHandler.init(new File(event.getModConfigurationDirectory(), Reference.CONFIG_FILE)); + FMLCommonHandler.instance().bus().register(proxy); + AEApi.instance().registries().wireless().registerWirelessHandler((IWirelessTermHandler) ItemEnum.WIRELESS_CRAFTING_TERMINAL.getItem()); + AchievementHandler.init(); + WCTLog.endSection("PreInit", stopwatch); + } + + @EventHandler + public void init(FMLInitializationEvent event) { + long stopwatch = WCTLog.beginSection("Init"); + WirelessCraftingTerminal.WCTState = LoaderState.INITIALIZATION; + RecipeHandler.addRecipes(true); + IntegrationRegistry.INSTANCE.init(); + WCTLog.endSection("Init", stopwatch); + } + + @EventHandler + public void postInit(final FMLPostInitializationEvent event) { + long stopwatch = WCTLog.beginSection("PostInit"); + IntegrationRegistry.INSTANCE.postInit(); + FMLCommonHandler.instance().registerCrashCallable(new IntegrationCrashEnhancement()); + NetworkRegistry.INSTANCE.registerGuiHandler(this.INSTANCE, new WCTGuiHandler()); + NetworkHandler.instance = new NetworkHandler("WCT"); + WirelessCraftingTerminal.proxy.removeItemsFromNEI(); + WCTLog.endSection("PostInit", stopwatch); + } + + public static LoaderState getLoaderState() { + return WirelessCraftingTerminal.WCTState; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/AEBaseContainer.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/AEBaseContainer.java new file mode 100644 index 0000000..63770a1 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/AEBaseContainer.java @@ -0,0 +1,1318 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTIActionHost; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTPlayerSource; +import net.p455w0rd.wirelesscraftingterminal.common.container.guisync.GuiSync; +import net.p455w0rd.wirelesscraftingterminal.common.container.guisync.SyncData; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngSlot; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotCraftingMatrix; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotCraftingTerm; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotDisabled; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotFake; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotInaccessible; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotPlayerHotBar; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotPlayerInv; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketInventoryAction; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketPartialItem; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; +import appeng.api.AEApi; +import appeng.api.config.Actionable; +import appeng.api.config.SecurityPermissions; +import appeng.api.implementations.guiobjects.IGuiItemObject; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridNode; +import appeng.api.networking.energy.IEnergyGrid; +import appeng.api.networking.energy.IEnergySource; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.security.ISecurityGrid; +import appeng.api.parts.IPart; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.data.IAEItemStack; +import appeng.client.me.InternalSlotME; +import appeng.client.me.SlotME; +import appeng.helpers.ICustomNameObject; +import appeng.helpers.InventoryAction; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; +import appeng.util.inv.AdaptorPlayerHand; +import appeng.util.item.AEItemStack; + + +public abstract class AEBaseContainer extends Container +{ + + private final InventoryPlayer invPlayer; + private final BaseActionSource mySrc; + private final HashSet locked = new HashSet(); + private final TileEntity tileEntity; + private final IPart part; + private final IGuiItemObject obj; + private final List dataChunks = new LinkedList(); + private final HashMap syncData = new HashMap(); + private boolean isContainerValid = true; + private String customName; + private ContainerOpenContext openContext; + private IMEInventoryHandler cellInv; + private IEnergySource powerSrc; + private boolean sentCustomName; + private int ticksSinceCheck = 900; + private IAEItemStack clientRequestedTargetItem = null; + + public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart ) + { + this( ip, myTile, myPart, null ); + } + + public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart, final IGuiItemObject gio ) + { + this.invPlayer = ip; + this.tileEntity = myTile; + this.part = myPart; + this.obj = gio; + this.mySrc = new WCTPlayerSource( ip.player, this.getActionHost() ); + this.prepareSync(); + } + + protected WCTIActionHost getActionHost() + { + if( this.obj instanceof WCTIActionHost ) + { + return (WCTIActionHost) this.obj; + } + + if( this.tileEntity instanceof WCTIActionHost ) + { + return (WCTIActionHost) this.tileEntity; + } + + if( this.part instanceof WCTIActionHost ) + { + return (WCTIActionHost) this.part; + } + + return null; + } + + private void prepareSync() + { + for( final Field f : this.getClass().getFields() ) + { + if( f.isAnnotationPresent( GuiSync.class ) ) + { + final GuiSync annotation = f.getAnnotation( GuiSync.class ); + if( this.syncData.containsKey( annotation.value() ) ) + { + WCTLog.warning( "Channel already in use: " + annotation.value() + " for " + f.getName() ); + } + else + { + this.syncData.put( annotation.value(), new SyncData( this, f, annotation ) ); + } + } + } + } + + public AEBaseContainer( final InventoryPlayer ip, final Object anchor ) + { + this.invPlayer = ip; + this.tileEntity = anchor instanceof TileEntity ? (TileEntity) anchor : null; + this.part = anchor instanceof IPart ? (IPart) anchor : null; + this.obj = anchor instanceof IGuiItemObject ? (IGuiItemObject) anchor : null; + + if( this.tileEntity == null && this.part == null && this.obj == null ) + { + throw new IllegalArgumentException( "Must have a valid anchor, instead " + anchor + " in " + ip ); + } + + this.mySrc = new WCTPlayerSource( ip.player, this.getActionHost() ); + + this.prepareSync(); + } + + public void postPartial( final PacketPartialItem packetPartialItem ) + { + this.dataChunks.add( packetPartialItem ); + if( packetPartialItem.getPageCount() == this.dataChunks.size() ) + { + this.parsePartials(); + } + } + + private void parsePartials() + { + int total = 0; + for( final PacketPartialItem ppi : this.dataChunks ) + { + total += ppi.getSize(); + } + + final byte[] buffer = new byte[total]; + int cursor = 0; + + for( final PacketPartialItem ppi : this.dataChunks ) + { + cursor = ppi.write( buffer, cursor ); + } + + try + { + final NBTTagCompound data = CompressedStreamTools.readCompressed( new ByteArrayInputStream( buffer ) ); + if( data != null ) + { + this.setTargetStack( AEApi.instance().storage().createItemStack( ItemStack.loadItemStackFromNBT( data ) ) ); + } + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + + this.dataChunks.clear(); + } + + public IAEItemStack getTargetStack() + { + return this.clientRequestedTargetItem; + } + + public void setTargetStack( final IAEItemStack stack ) + { + // client doesn't need to re-send, makes for lower overhead rapid packets. + if( Platform.isClient() ) + { + final ItemStack a = stack == null ? null : stack.getItemStack(); + final ItemStack b = this.clientRequestedTargetItem == null ? null : this.clientRequestedTargetItem.getItemStack(); + + if( Platform.isSameItemPrecise( a, b ) ) + { + return; + } + + final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final NBTTagCompound item = new NBTTagCompound(); + + if( stack != null ) + { + stack.writeToNBT( item ); + } + + try + { + CompressedStreamTools.writeCompressed( item, stream ); + + final int maxChunkSize = 30000; + final List miniPackets = new LinkedList(); + + final byte[] data = stream.toByteArray(); + + final ByteArrayInputStream bis = new ByteArrayInputStream( data, 0, stream.size() ); + while( bis.available() > 0 ) + { + final int nextBLock = bis.available() > maxChunkSize ? maxChunkSize : bis.available(); + final byte[] nextSegment = new byte[nextBLock]; + bis.read( nextSegment ); + miniPackets.add( nextSegment ); + } + bis.close(); + stream.close(); + + int page = 0; + for( final byte[] packet : miniPackets ) + { + final PacketPartialItem ppi = new PacketPartialItem( page, miniPackets.size(), packet ); + page++; + NetworkHandler.instance.sendToServer( ppi ); + } + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + return; + } + } + + this.clientRequestedTargetItem = stack == null ? null : stack.copy(); + } + + public BaseActionSource getActionSource() + { + return this.mySrc; + } + + public void verifyPermissions( final SecurityPermissions security, final boolean requirePower ) + { + if( Platform.isClient() ) + { + return; + } + + this.ticksSinceCheck++; + if( this.ticksSinceCheck < 20 ) + { + return; + } + + this.ticksSinceCheck = 0; + this.setValidContainer( this.isValidContainer() && this.hasAccess( security, requirePower ) ); + } + + protected boolean hasAccess( final SecurityPermissions perm, final boolean requirePower ) + { + final WCTIActionHost host = this.getActionHost(); + + if( host != null ) + { + final IGridNode gn = host.getActionableNode(); + if( gn != null ) + { + final IGrid g = gn.getGrid(); + if( g != null ) + { + if( requirePower ) + { + final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); + if( !eg.isNetworkPowered() ) + { + return false; + } + } + + final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); + if( sg.hasPermission( this.getInventoryPlayer().player, perm ) ) + { + return true; + } + } + } + } + + return false; + } + + public void lockPlayerInventorySlot( final int idx ) + { + this.locked.add( idx ); + } + + public Object getTarget() + { + if( this.tileEntity != null ) + { + return this.tileEntity; + } + if( this.part != null ) + { + return this.part; + } + if( this.obj != null ) + { + return this.obj; + } + return null; + } + + public InventoryPlayer getPlayerInv() + { + return this.getInventoryPlayer(); + } + + public TileEntity getTileEntity() + { + return this.tileEntity; + } + + public final void updateFullProgressBar( final int idx, final long value ) + { + if( this.syncData.containsKey( idx ) ) + { + this.syncData.get( idx ).update( value ); + return; + } + + this.updateProgressBar( idx, (int) value ); + } + + public void stringSync( final int idx, final String value ) + { + if( this.syncData.containsKey( idx ) ) + { + this.syncData.get( idx ).update( value ); + } + } + + protected void bindPlayerInventory( final InventoryPlayer inventoryPlayer, final int offsetX, final int offsetY ) + { + // bind player inventory + for( int i = 0; i < 3; i++ ) + { + for( int j = 0; j < 9; j++ ) + { + if( this.locked.contains( j + i * 9 + 9 ) ) + { + this.addSlotToContainer( new SlotDisabled( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18 ) ); + } + else + { + this.addSlotToContainer( new SlotPlayerInv( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18 ) ); + } + } + } + + // bind player hotbar + for( int i = 0; i < 9; i++ ) + { + if( this.locked.contains( i ) ) + { + this.addSlotToContainer( new SlotDisabled( inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); + } + else + { + this.addSlotToContainer( new SlotPlayerHotBar( inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); + } + } + } + + @Override + protected Slot addSlotToContainer( final Slot newSlot ) + { + if( newSlot instanceof AppEngSlot ) + { + final AppEngSlot s = (AppEngSlot) newSlot; + s.setContainer( this ); + return super.addSlotToContainer( newSlot ); + } + else + { + throw new IllegalArgumentException( "Invalid Slot [" + newSlot + "]for AE Container instead of AppEngSlot." ); + } + } + + @Override + public void detectAndSendChanges() + { + this.sendCustomName(); + + if( Platform.isServer() ) + { + for( final Object crafter : this.crafters ) + { + final ICrafting icrafting = (ICrafting) crafter; + + for( final SyncData sd : this.syncData.values() ) + { + sd.tick( icrafting ); + } + } + } + + super.detectAndSendChanges(); + } + + @Override + public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) + { + if( Platform.isClient() ) + { + return null; + } + + boolean hasMETiles = false; + for( final Object is : this.inventorySlots ) + { + if( is instanceof InternalSlotME ) + { + hasMETiles = true; + break; + } + } + + if( hasMETiles && Platform.isClient() ) + { + return null; + } + + final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! + + if( clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible ) + { + return null; + } + if( clickSlot != null && clickSlot.getHasStack() ) + { + ItemStack tis = clickSlot.getStack(); + + if( tis == null ) + { + return null; + } + + final List selectedSlots = new ArrayList(); + + /** + * Gather a list of valid destinations. + */ + if( clickSlot.isPlayerSide() ) + { + tis = this.shiftStoreItem( tis ); + + // target slots in the container... + for( final Object inventorySlot : this.inventorySlots ) + { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if( !( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) + { + if( cs.isItemValid( tis ) ) + { + selectedSlots.add( cs ); + } + } + } + } + else + { + // target slots in the container... + for( final Object inventorySlot : this.inventorySlots ) + { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if( ( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) + { + if( cs.isItemValid( tis ) ) + { + selectedSlots.add( cs ); + } + } + } + } + + /** + * Handle Fake Slot Shift clicking. + */ + if( selectedSlots.isEmpty() && clickSlot.isPlayerSide() ) + { + if( tis != null ) + { + // target slots in the container... + for( final Object inventorySlot : this.inventorySlots ) + { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + final ItemStack destination = cs.getStack(); + + if( !( cs.isPlayerSide() ) && cs instanceof SlotFake ) + { + if( Platform.isSameItemPrecise( destination, tis ) ) + { + return null; + } + else if( destination == null ) + { + cs.putStack( tis.copy() ); + cs.onSlotChanged(); + this.updateSlot( cs ); + return null; + } + } + } + } + } + + if( tis != null ) + { + // find partials.. + for( final Slot d : selectedSlots ) + { + if( d instanceof SlotDisabled || d instanceof SlotME ) + { + continue; + } + + if( d.isItemValid( tis ) ) + { + if( d.getHasStack() ) + { + final ItemStack t = d.getStack(); + + if( Platform.isSameItemPrecise( tis, t ) ) // t.isItemEqual(tis)) + { + int maxSize = t.getMaxStackSize(); + if( maxSize > d.getSlotStackLimit() ) + { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if( tis.stackSize < placeAble ) + { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if( tis.stackSize <= 0 ) + { + clickSlot.putStack( null ); + d.onSlotChanged(); + + // if ( hasMETiles ) updateClient(); + + this.updateSlot( clickSlot ); + this.updateSlot( d ); + return null; + } + else + { + this.updateSlot( d ); + } + } + } + } + } + + // any match.. + for( final Slot d : selectedSlots ) + { + if( d instanceof SlotDisabled || d instanceof SlotME ) + { + continue; + } + + if( d.isItemValid( tis ) ) + { + if( d.getHasStack() ) + { + final ItemStack t = d.getStack(); + + if( Platform.isSameItemPrecise( t, tis ) ) + { + int maxSize = t.getMaxStackSize(); + if( d.getSlotStackLimit() < maxSize ) + { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if( tis.stackSize < placeAble ) + { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if( tis.stackSize <= 0 ) + { + clickSlot.putStack( null ); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot( clickSlot ); + this.updateSlot( d ); + return null; + } + else + { + this.updateSlot( d ); + } + } + } + else + { + int maxSize = tis.getMaxStackSize(); + if( maxSize > d.getSlotStackLimit() ) + { + maxSize = d.getSlotStackLimit(); + } + + final ItemStack tmp = tis.copy(); + if( tmp.stackSize > maxSize ) + { + tmp.stackSize = maxSize; + } + + tis.stackSize -= tmp.stackSize; + d.putStack( tmp ); + + if( tis.stackSize <= 0 ) + { + clickSlot.putStack( null ); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot( clickSlot ); + this.updateSlot( d ); + return null; + } + else + { + this.updateSlot( d ); + } + } + } + } + } + + clickSlot.putStack( tis != null ? tis.copy() : null ); + } + + this.updateSlot( clickSlot ); + return null; + } + + @Override + public final void updateProgressBar( final int idx, final int value ) + { + if( this.syncData.containsKey( idx ) ) + { + this.syncData.get( idx ).update( (long) value ); + } + } + + @Override + public boolean canInteractWith( final EntityPlayer entityplayer ) + { + if( this.isValidContainer() ) + { + if( this.tileEntity instanceof IInventory ) + { + return ( (IInventory) this.tileEntity ).isUseableByPlayer( entityplayer ); + } + return true; + } + return false; + } + + @Override + public boolean canDragIntoSlot( final Slot s ) + { + return ( (AppEngSlot) s ).isDraggable(); + } + + public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) + { + if( slot >= 0 && slot < this.inventorySlots.size() ) + { + final Slot s = this.getSlot( slot ); + + if( s instanceof SlotCraftingTerm ) + { + switch( action ) + { + case CRAFT_SHIFT: + case CRAFT_ITEM: + case CRAFT_STACK: + ( (SlotCraftingTerm) s ).doClick( action, player ); + this.updateHeld( player ); + default: + } + } + + if( s instanceof SlotFake ) + { + final ItemStack hand = player.inventory.getItemStack(); + + switch( action ) + { + case PICKUP_OR_SET_DOWN: + + if( hand == null ) + { + s.putStack( null ); + } + else + { + s.putStack( hand.copy() ); + } + + break; + case PLACE_SINGLE: + + if( hand != null ) + { + final ItemStack is = hand.copy(); + is.stackSize = 1; + s.putStack( is ); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + + ItemStack is = s.getStack(); + if( is != null ) + { + if( hand == null ) + { + is.stackSize--; + } + else if( hand.isItemEqual( is ) ) + { + is.stackSize = Math.min( is.getMaxStackSize(), is.stackSize + 1 ); + } + else + { + is = hand.copy(); + is.stackSize = 1; + } + + s.putStack( is ); + } + else if( hand != null ) + { + is = hand.copy(); + is.stackSize = 1; + s.putStack( is ); + } + + break; + case CREATIVE_DUPLICATE: + case MOVE_REGION: + case SHIFT_CLICK: + default: + break; + } + } + + if( action == InventoryAction.MOVE_REGION ) + { + final List from = new LinkedList(); + + for( final Object j : this.inventorySlots ) + { + if( j instanceof Slot && j.getClass() == s.getClass() ) + { + from.add( (Slot) j ); + } + } + + for( final Slot fr : from ) + { + this.transferStackInSlot( player, fr.slotNumber ); + } + } + + return; + } + + // get target item. + final IAEItemStack slotItem = this.clientRequestedTargetItem; + + switch( action ) + { + case SHIFT_CLICK: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize( myItem.getMaxStackSize() ); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + myItem.stackSize = (int) ais.getStackSize(); + myItem = adp.simulateAdd( myItem ); + + if( myItem != null ) + { + ais.setStackSize( ais.getStackSize() - myItem.stackSize ); + } + + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + adp.addItems( ais.getItemStack() ); + } + } + break; + case ROLL_DOWN: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + final int releaseQty = 1; + final ItemStack isg = player.inventory.getItemStack(); + + if( isg != null && releaseQty > 0 ) + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( isg ); + ais.setStackSize( 1 ); + final IAEItemStack extracted = ais.copy(); + + ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais == null ) + { + final InventoryAdaptor ia = new AdaptorPlayerHand( player ); + + final ItemStack fail = ia.removeItems( 1, extracted.getItemStack(), null ); + if( fail == null ) + { + this.getCellInventory().extractItems( extracted, Actionable.MODULATE, this.getActionSource() ); + } + + this.updateHeld( player ); + } + } + + break; + case ROLL_UP: + case PICKUP_SINGLE: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( slotItem != null ) + { + int liftQty = 1; + final ItemStack item = player.inventory.getItemStack(); + + if( item != null ) + { + if( item.stackSize >= item.getMaxStackSize() ) + { + liftQty = 0; + } + if( !Platform.isSameItemPrecise( slotItem.getItemStack(), item ) ) + { + liftQty = 0; + } + } + + if( liftQty > 0 ) + { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize( 1 ); + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + final InventoryAdaptor ia = new AdaptorPlayerHand( player ); + + final ItemStack fail = ia.addItems( ais.getItemStack() ); + if( fail != null ) + { + this.getCellInventory().injectItems( ais, Actionable.MODULATE, this.getActionSource() ); + } + + this.updateHeld( player ); + } + } + } + break; + case PICKUP_OR_SET_DOWN: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( player.inventory.getItemStack() == null ) + { + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize( ais.getItemStack().getMaxStackSize() ); + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + player.inventory.setItemStack( ais.getItemStack() ); + } + else + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + } + else + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); + ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + player.inventory.setItemStack( ais.getItemStack() ); + } + else + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( player.inventory.getItemStack() == null ) + { + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + final long maxSize = ais.getItemStack().getMaxStackSize(); + ais.setStackSize( maxSize ); + ais = this.getCellInventory().extractItems( ais, Actionable.SIMULATE, this.getActionSource() ); + + if( ais != null ) + { + final long stackSize = Math.min( maxSize, ais.getStackSize() ); + ais.setStackSize( ( stackSize + 1 ) >> 1 ); + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + } + + if( ais != null ) + { + player.inventory.setItemStack( ais.getItemStack() ); + } + else + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + } + else + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); + ais.setStackSize( 1 ); + ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais == null ) + { + final ItemStack is = player.inventory.getItemStack(); + is.stackSize--; + if( is.stackSize <= 0 ) + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + } + + break; + case CREATIVE_DUPLICATE: + if( player.capabilities.isCreativeMode && slotItem != null ) + { + final ItemStack is = slotItem.getItemStack(); + is.stackSize = is.getMaxStackSize(); + player.inventory.setItemStack( is ); + this.updateHeld( player ); + } + break; + case MOVE_REGION: + + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( slotItem != null ) + { + final int playerInv = 9 * 4; + for( int slotNum = 0; slotNum < playerInv; slotNum++ ) + { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize( myItem.getMaxStackSize() ); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + myItem.stackSize = (int) ais.getStackSize(); + myItem = adp.simulateAdd( myItem ); + + if( myItem != null ) + { + ais.setStackSize( ais.getStackSize() - myItem.stackSize ); + } + + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + adp.addItems( ais.getItemStack() ); + } + else + { + return; + } + } + } + + break; + default: + break; + } + } + + protected void updateHeld( final EntityPlayerMP p ) + { + if( Platform.isServer() ) + { + try + { + NetworkHandler.instance.sendTo( new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.create( p.inventory.getItemStack() ) ), p ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + } + + private ItemStack shiftStoreItem( final ItemStack input ) + { + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return input; + } + final IAEItemStack ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), AEApi.instance().storage().createItemStack( input ), this.getActionSource() ); + if( ais == null ) + { + return null; + } + return ais.getItemStack(); + } + + private void updateSlot( final Slot clickSlot ) + { + // ??? + this.detectAndSendChanges(); + } + + private void sendCustomName() + { + if( !this.sentCustomName ) + { + this.sentCustomName = true; + if( Platform.isServer() ) + { + ICustomNameObject name = null; + + if( this.part instanceof ICustomNameObject ) + { + name = (ICustomNameObject) this.part; + } + + if( this.tileEntity instanceof ICustomNameObject ) + { + name = (ICustomNameObject) this.tileEntity; + } + + if( this.obj instanceof ICustomNameObject ) + { + name = (ICustomNameObject) this.obj; + } + + if( this instanceof ICustomNameObject ) + { + name = (ICustomNameObject) this; + } + + if( name != null ) + { + if( name.hasCustomName() ) + { + this.setCustomName( name.getCustomName() ); + } + + if( this.getCustomName() != null ) + { + try + { + NetworkHandler.instance.sendTo( new PacketValueConfig( "CustomName", this.getCustomName() ), (EntityPlayerMP) this.getInventoryPlayer().player ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + } + } + } + } + + public void swapSlotContents( final int slotA, final int slotB ) + { + final Slot a = this.getSlot( slotA ); + final Slot b = this.getSlot( slotB ); + + // NPE protection... + if( a == null || b == null ) + { + return; + } + + final ItemStack isA = a.getStack(); + final ItemStack isB = b.getStack(); + + // something to do? + if( isA == null && isB == null ) + { + return; + } + + // can take? + + if( isA != null && !a.canTakeStack( this.getInventoryPlayer().player ) ) + { + return; + } + + if( isB != null && !b.canTakeStack( this.getInventoryPlayer().player ) ) + { + return; + } + + // swap valid? + + if( isB != null && !a.isItemValid( isB ) ) + { + return; + } + + if( isA != null && !b.isItemValid( isA ) ) + { + return; + } + + ItemStack testA = isB == null ? null : isB.copy(); + ItemStack testB = isA == null ? null : isA.copy(); + + // can put some back? + if( testA != null && testA.stackSize > a.getSlotStackLimit() ) + { + if( testB != null ) + { + return; + } + + final int totalA = testA.stackSize; + testA.stackSize = a.getSlotStackLimit(); + testB = testA.copy(); + + testB.stackSize = totalA - testA.stackSize; + } + + if( testB != null && testB.stackSize > b.getSlotStackLimit() ) + { + if( testA != null ) + { + return; + } + + final int totalB = testB.stackSize; + testB.stackSize = b.getSlotStackLimit(); + testA = testB.copy(); + + testA.stackSize = totalB - testA.stackSize; + } + + a.putStack( testA ); + b.putStack( testB ); + } + + public void onUpdate( final String field, final Object oldValue, final Object newValue ) + { + + } + + public void onSlotChange( final Slot s ) + { + + } + + public boolean isValidForSlot( final Slot s, final ItemStack i ) + { + return true; + } + + public IMEInventoryHandler getCellInventory() + { + return this.cellInv; + } + + public void setCellInventory( final IMEInventoryHandler cellInv ) + { + this.cellInv = cellInv; + } + + public String getCustomName() + { + return this.customName; + } + + public void setCustomName( final String customName ) + { + this.customName = customName; + } + + public InventoryPlayer getInventoryPlayer() + { + return this.invPlayer; + } + + public boolean isValidContainer() + { + return this.isContainerValid; + } + + public void setValidContainer( final boolean isContainerValid ) + { + this.isContainerValid = isContainerValid; + } + + public ContainerOpenContext getOpenContext() + { + return this.openContext; + } + + public void setOpenContext( final ContainerOpenContext openContext ) + { + this.openContext = openContext; + } + + public IEnergySource getPowerSource() + { + return this.powerSrc; + } + + public void setPowerSource( final IEnergySource powerSrc ) + { + this.powerSrc = powerSrc; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftAmount.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftAmount.java new file mode 100644 index 0000000..e90d751 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftAmount.java @@ -0,0 +1,71 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import javax.annotation.Nonnull; + +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.world.World; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTIActionHost; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTPlayerSource; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotInaccessible; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryBooster; +import appeng.api.config.SecurityPermissions; +import appeng.api.networking.IGrid; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.ITerminalHost; +import appeng.api.storage.data.IAEItemStack; +import appeng.tile.inventory.AppEngInternalInventory; + + +public class ContainerCraftAmount extends AEBaseContainer +{ + + private final Slot craftingItem; + private IAEItemStack itemToCreate; + + public ContainerCraftAmount( final InventoryPlayer ip, final ITerminalHost te ) + { + super( ip, te ); + + this.craftingItem = new SlotInaccessible( new AppEngInternalInventory( null, 1 ), 0, 34, 53 ); + this.addSlotToContainer( this.getCraftingItem() ); + } + + @Override + public void detectAndSendChanges() + { + super.detectAndSendChanges(); + this.verifyPermissions( SecurityPermissions.CRAFT, false ); + } + + public IGrid getGrid() + { + final WCTIActionHost h = ( (WCTIActionHost) this.getTarget() ); + return h.getActionableNode().getGrid(); + } + + public World getWorld() + { + return this.getPlayerInv().player.worldObj; + } + + public BaseActionSource getActionSrc() + { + return new WCTPlayerSource( this.getPlayerInv().player, (WCTIActionHost) this.getTarget() ); + } + + public Slot getCraftingItem() + { + return this.craftingItem; + } + + public IAEItemStack getItemToCraft() + { + return this.itemToCreate; + } + + public void setItemToCraft( @Nonnull final IAEItemStack itemToCreate ) + { + this.itemToCreate = itemToCreate; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftConfirm.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftConfirm.java new file mode 100644 index 0000000..f6d87bd --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftConfirm.java @@ -0,0 +1,454 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.concurrent.Future; + +import javax.annotation.Nonnull; + +import com.google.common.collect.ImmutableSet; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatComponentText; +import net.minecraft.world.World; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTIActionHost; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTPlayerSource; +import net.p455w0rd.wirelesscraftingterminal.common.WCTGuiHandler; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.guisync.GuiSync; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryBooster; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketMEInventoryUpdate; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwitchGuis; +import net.p455w0rd.wirelesscraftingterminal.helpers.WirelessTerminalGuiObject; +import appeng.api.AEApi; +import appeng.api.config.Actionable; +import appeng.api.config.SecurityPermissions; +import appeng.api.networking.IGrid; +import appeng.api.networking.crafting.ICraftingCPU; +import appeng.api.networking.crafting.ICraftingGrid; +import appeng.api.networking.crafting.ICraftingJob; +import appeng.api.networking.crafting.ICraftingLink; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.storage.IStorageGrid; +import appeng.api.storage.IMEInventory; +import appeng.api.storage.ITerminalHost; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.util.Platform; + + +public class ContainerCraftConfirm extends AEBaseContainer +{ + + private final ArrayList cpus = new ArrayList(); + private Future job; + private ICraftingJob result; + @GuiSync( 0 ) + public long bytesUsed; + @GuiSync( 1 ) + public long cpuBytesAvail; + @GuiSync( 2 ) + public int cpuCoProcessors; + @GuiSync( 3 ) + public boolean autoStart = false; + @GuiSync( 4 ) + public boolean simulation = true; + @GuiSync( 5 ) + public int selectedCpu = -1; + @GuiSync( 6 ) + public boolean noCPU = true; + @GuiSync( 7 ) + public String myName = ""; + + public ContainerCraftConfirm( final InventoryPlayer ip, final ITerminalHost te ) + { + super( ip, te ); + } + + public void cycleCpu( final boolean next ) + { + if( next ) + { + this.setSelectedCpu( this.getSelectedCpu() + 1 ); + } + else + { + this.setSelectedCpu( this.getSelectedCpu() - 1 ); + } + + if( this.getSelectedCpu() < -1 ) + { + this.setSelectedCpu( this.cpus.size() - 1 ); + } + else if( this.getSelectedCpu() >= this.cpus.size() ) + { + this.setSelectedCpu( -1 ); + } + + if( this.getSelectedCpu() == -1 ) + { + this.setCpuAvailableBytes( 0 ); + this.setCpuCoProcessors( 0 ); + this.setName( "" ); + } + else + { + this.setName( this.cpus.get( this.getSelectedCpu() ).getName() ); + this.setCpuAvailableBytes( this.cpus.get( this.getSelectedCpu() ).getSize() ); + this.setCpuCoProcessors( this.cpus.get( this.getSelectedCpu() ).getProcessors() ); + } + } + + @Override + public void detectAndSendChanges() + { + if( Platform.isClient() ) + { + return; + } + + final ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); + final ImmutableSet cpuSet = cc.getCpus(); + + int matches = 0; + boolean changed = false; + for( final ICraftingCPU c : cpuSet ) + { + boolean found = false; + for( final CraftingCPURecord ccr : this.cpus ) + { + if( ccr.getCpu() == c ) + { + found = true; + } + } + + final boolean matched = this.cpuMatches( c ); + + if( matched ) + { + matches++; + } + + if( found == !matched ) + { + changed = true; + } + } + + if( changed || this.cpus.size() != matches ) + { + this.cpus.clear(); + for( final ICraftingCPU c : cpuSet ) + { + if( this.cpuMatches( c ) ) + { + this.cpus.add( new CraftingCPURecord( c.getAvailableStorage(), c.getCoProcessors(), c ) ); + } + } + + this.sendCPUs(); + } + + this.setNoCPU( this.cpus.isEmpty() ); + + super.detectAndSendChanges(); + + if( this.getJob() != null && this.getJob().isDone() ) + { + try + { + this.result = this.getJob().get(); + + if( !this.result.isSimulation() ) + { + this.setSimulation( false ); + if( this.isAutoStart() ) + { + this.startJob(); + return; + } + } + else + { + this.setSimulation( true ); + } + + try + { + final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); + final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); + final PacketMEInventoryUpdate c = this.result.isSimulation() ? new PacketMEInventoryUpdate( (byte) 2 ) : null; + + final IItemList plan = AEApi.instance().storage().createItemList(); + this.result.populatePlan( plan ); + + this.setUsedBytes( this.result.getByteTotal() ); + + for( final IAEItemStack out : plan ) + { + + IAEItemStack o = out.copy(); + o.reset(); + o.setStackSize( out.getStackSize() ); + + final IAEItemStack p = out.copy(); + p.reset(); + p.setStackSize( out.getCountRequestable() ); + + final IStorageGrid sg = this.getGrid().getCache( IStorageGrid.class ); + final IMEInventory items = sg.getItemInventory(); + + IAEItemStack m = null; + if( c != null && this.result.isSimulation() ) + { + m = o.copy(); + o = items.extractItems( o, Actionable.SIMULATE, this.getActionSource() ); + + if( o == null ) + { + o = m.copy(); + o.setStackSize( 0 ); + } + + m.setStackSize( m.getStackSize() - o.getStackSize() ); + } + + if( o.getStackSize() > 0 ) + { + a.appendItem( o ); + } + + if( p.getStackSize() > 0 ) + { + b.appendItem( p ); + } + + if( c != null && m != null && m.getStackSize() > 0 ) + { + c.appendItem( m ); + } + } + + for( final Object g : this.crafters ) + { + if( g instanceof EntityPlayer ) + { + NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); + NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); + if( c != null ) + { + NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); + } + } + } + } + catch( final IOException e ) + { + // :P + } + } + catch( final Throwable e ) + { + this.getPlayerInv().player.addChatMessage( new ChatComponentText( "Error: " + e.toString() ) ); + WCTLog.debug( e.getMessage() ); + this.setValidContainer( false ); + this.result = null; + } + + this.setJob( null ); + } + this.verifyPermissions( SecurityPermissions.CRAFT, false ); + } + + private IGrid getGrid() + { + final WCTIActionHost h = ( (WCTIActionHost) this.getTarget() ); + return h.getActionableNode().getGrid(); + } + + private boolean cpuMatches( final ICraftingCPU c ) + { + return c.getAvailableStorage() >= this.getUsedBytes() && !c.isBusy(); + } + + private void sendCPUs() + { + Collections.sort( this.cpus ); + + if( this.getSelectedCpu() >= this.cpus.size() ) + { + this.setSelectedCpu( -1 ); + this.setCpuAvailableBytes( 0 ); + this.setCpuCoProcessors( 0 ); + this.setName( "" ); + } + else if( this.getSelectedCpu() != -1 ) + { + this.setName( this.cpus.get( this.getSelectedCpu() ).getName() ); + this.setCpuAvailableBytes( this.cpus.get( this.getSelectedCpu() ).getSize() ); + this.setCpuCoProcessors( this.cpus.get( this.getSelectedCpu() ).getProcessors() ); + System.out.println("XD"); + } + } + + public void startJob() + { + int originalGui=0; + + final WCTIActionHost ah = this.getActionHost(); + if( ah instanceof WirelessTerminalGuiObject ) + { + originalGui = WirelessCraftingTerminal.GUI_WCT; + } + + if( this.result != null && !this.isSimulation() ) + { + final ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); + final ICraftingLink g = cc.submitJob( this.result, null, this.getSelectedCpu() == -1 ? null : this.cpus.get( this.getSelectedCpu() ).getCpu(), true, this.getActionSrc() ); + this.setAutoStart( false ); + if( g != null && originalGui > 0)// && this.getOpenContext() != null ) + { + NetworkHandler.instance.sendTo( new PacketSwitchGuis( originalGui ), (EntityPlayerMP) this.getInventoryPlayer().player ); + + //final TileEntity te = this.getOpenContext().getTile(); + //Platform.openGUI( this.getInventoryPlayer().player, te, this.getOpenContext().getSide(), originalGui ); + EntityPlayerMP player = (EntityPlayerMP) this.getInventoryPlayer().player; + World world = player.worldObj; + int x = player.serverPosX; + int y = player.serverPosY; + int z = player.serverPosZ; + WCTGuiHandler.launchGui(originalGui, player, world, x, y, z); + } + } + } + + private BaseActionSource getActionSrc() + { + return new WCTPlayerSource( this.getPlayerInv().player, (WCTIActionHost) this.getTarget() ); + } + + @Override + public void removeCraftingFromCrafters( final ICrafting c ) + { + super.removeCraftingFromCrafters( c ); + if( this.getJob() != null ) + { + this.getJob().cancel( true ); + this.setJob( null ); + } + } + + @Override + public void onContainerClosed( final EntityPlayer par1EntityPlayer ) + { + super.onContainerClosed( par1EntityPlayer ); + if( this.getJob() != null ) + { + this.getJob().cancel( true ); + this.setJob( null ); + } + } + + public World getWorld() + { + return this.getPlayerInv().player.worldObj; + } + + public boolean isAutoStart() + { + return this.autoStart; + } + + public void setAutoStart( final boolean autoStart ) + { + this.autoStart = autoStart; + } + + public long getUsedBytes() + { + return this.bytesUsed; + } + + private void setUsedBytes( final long bytesUsed ) + { + this.bytesUsed = bytesUsed; + } + + public long getCpuAvailableBytes() + { + return this.cpuBytesAvail; + } + + private void setCpuAvailableBytes( final long cpuBytesAvail ) + { + this.cpuBytesAvail = cpuBytesAvail; + } + + public int getCpuCoProcessors() + { + return this.cpuCoProcessors; + } + + private void setCpuCoProcessors( final int cpuCoProcessors ) + { + this.cpuCoProcessors = cpuCoProcessors; + } + + public int getSelectedCpu() + { + return this.selectedCpu; + } + + private void setSelectedCpu( final int selectedCpu ) + { + this.selectedCpu = selectedCpu; + } + + public String getName() + { + return this.myName; + } + + private void setName( @Nonnull final String myName ) + { + this.myName = myName; + } + + public boolean hasNoCPU() + { + return this.noCPU; + } + + private void setNoCPU( final boolean noCPU ) + { + this.noCPU = noCPU; + } + + public boolean isSimulation() + { + return this.simulation; + } + + private void setSimulation( final boolean simulation ) + { + this.simulation = simulation; + } + + private Future getJob() + { + return this.job; + } + + public void setJob( final Future job ) + { + this.job = job; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftingCPU.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftingCPU.java new file mode 100644 index 0000000..5776e44 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftingCPU.java @@ -0,0 +1,278 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import java.io.IOException; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ICrafting; +import net.minecraftforge.common.util.ForgeDirection; +import net.p455w0rd.wirelesscraftingterminal.common.container.guisync.GuiSync; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryBooster; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketMEInventoryUpdate; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; +import appeng.api.AEApi; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; +import appeng.api.networking.crafting.CraftingItemList; +import appeng.api.networking.crafting.ICraftingCPU; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.storage.IBaseMonitor; +import appeng.api.storage.IMEMonitorHandlerReceiver; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.helpers.ICustomNameObject; +import appeng.me.cluster.IAEMultiBlock; +import appeng.me.cluster.implementations.CraftingCPUCluster; +import appeng.tile.crafting.TileCraftingTile; +import appeng.util.Platform; + + +public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorHandlerReceiver, ICustomNameObject +{ + + private final IItemList list = AEApi.instance().storage().createItemList(); + private IGrid network; + private CraftingCPUCluster monitor = null; + private String cpuName = null; + + @GuiSync( 0 ) + public long eta = -1; + + public ContainerCraftingCPU( final InventoryPlayer ip, final Object te ) + { + super( ip, te ); + final IGridHost host = (IGridHost) ( te instanceof IGridHost ? te : null ); + + if( host != null ) + { + this.findNode( host, ForgeDirection.UNKNOWN ); + for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) + { + this.findNode( host, d ); + } + } + + if( te instanceof TileCraftingTile ) + { + this.setCPU( (ICraftingCPU) ( (IAEMultiBlock) te ).getCluster() ); + } + + if( this.getNetwork() == null && Platform.isServer() ) + { + this.setValidContainer( false ); + } + } + + private void findNode( final IGridHost host, final ForgeDirection d ) + { + if( this.getNetwork() == null ) + { + final IGridNode node = host.getGridNode( d ); + if( node != null ) + { + this.setNetwork( node.getGrid() ); + } + } + } + + protected void setCPU( final ICraftingCPU c ) + { + if( c == this.getMonitor() ) + { + return; + } + + if( this.getMonitor() != null ) + { + this.getMonitor().removeListener( this ); + } + + for( final Object g : this.crafters ) + { + if( g instanceof EntityPlayer ) + { + try + { + NetworkHandler.instance.sendTo( new PacketValueConfig( "CraftingStatus", "Clear" ), (EntityPlayerMP) g ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + } + + if( c instanceof CraftingCPUCluster ) + { + this.cpuName = c.getName(); + this.setMonitor( (CraftingCPUCluster) c ); + this.list.resetStatus(); + this.getMonitor().getListOfItem( this.list, CraftingItemList.ALL ); + this.getMonitor().addListener( this, null ); + this.setEstimatedTime( 0 ); + } + else + { + this.setMonitor( null ); + this.cpuName = ""; + this.setEstimatedTime( -1 ); + } + } + + public void cancelCrafting() + { + if( this.getMonitor() != null ) + { + this.getMonitor().cancel(); + } + this.setEstimatedTime( -1 ); + } + + @Override + public void removeCraftingFromCrafters( final ICrafting c ) + { + super.removeCraftingFromCrafters( c ); + + if( this.crafters.isEmpty() && this.getMonitor() != null ) + { + this.getMonitor().removeListener( this ); + } + } + + @Override + public void onContainerClosed( final EntityPlayer player ) + { + super.onContainerClosed( player ); + if( this.getMonitor() != null ) + { + this.getMonitor().removeListener( this ); + } + } + + @Override + public void detectAndSendChanges() + { + if( Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty() ) + { + try + { + if( this.getEstimatedTime() >= 0 ) + { + final long elapsedTime = this.getMonitor().getElapsedTime(); + final double remainingItems = this.getMonitor().getRemainingItemCount(); + final double startItems = this.getMonitor().getStartItemCount(); + final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems ); + this.setEstimatedTime( eta ); + } + + final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); + final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); + final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 ); + + for( final IAEItemStack out : this.list ) + { + a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) ); + b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) ); + c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) ); + } + + this.list.resetStatus(); + + for( final Object g : this.crafters ) + { + if( g instanceof EntityPlayer ) + { + if( !a.isEmpty() ) + { + NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); + } + + if( !b.isEmpty() ) + { + NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); + } + + if( !c.isEmpty() ) + { + NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); + } + } + } + } + catch( final IOException e ) + { + // :P + } + } + super.detectAndSendChanges(); + } + + @Override + public boolean isValid( final Object verificationToken ) + { + return true; + } + + @Override + public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource actionSource ) + { + for( IAEItemStack is : change ) + { + is = is.copy(); + is.setStackSize( 1 ); + this.list.add( is ); + } + } + + @Override + public void onListUpdate() + { + + } + + @Override + public String getCustomName() + { + return this.cpuName; + } + + @Override + public boolean hasCustomName() + { + return this.cpuName != null && this.cpuName.length() > 0; + } + + public long getEstimatedTime() + { + return this.eta; + } + + private void setEstimatedTime( final long eta ) + { + this.eta = eta; + } + + CraftingCPUCluster getMonitor() + { + return this.monitor; + } + + private void setMonitor( final CraftingCPUCluster monitor ) + { + this.monitor = monitor; + } + + IGrid getNetwork() + { + return this.network; + } + + private void setNetwork( final IGrid network ) + { + this.network = network; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftingStatus.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftingStatus.java new file mode 100644 index 0000000..d6b0c27 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerCraftingStatus.java @@ -0,0 +1,156 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.google.common.collect.ImmutableSet; + +import net.minecraft.entity.player.InventoryPlayer; +import net.p455w0rd.wirelesscraftingterminal.common.container.guisync.GuiSync; +import appeng.api.networking.crafting.ICraftingCPU; +import appeng.api.networking.crafting.ICraftingGrid; +import appeng.api.storage.ITerminalHost; + + +public class ContainerCraftingStatus extends ContainerCraftingCPU +{ + + private final List cpus = new ArrayList(); + @GuiSync( 5 ) + public int selectedCpu = -1; + @GuiSync( 6 ) + public boolean noCPU = true; + @GuiSync( 7 ) + public String myName = ""; + + public ContainerCraftingStatus( final InventoryPlayer ip, final ITerminalHost te ) + { + super( ip, te ); + } + + @Override + public void detectAndSendChanges() + { + final ICraftingGrid cc = this.getNetwork().getCache( ICraftingGrid.class ); + final ImmutableSet cpuSet = cc.getCpus(); + + int matches = 0; + boolean changed = false; + for( final ICraftingCPU c : cpuSet ) + { + boolean found = false; + for( final CraftingCPURecord ccr : this.cpus ) + { + if( ccr.getCpu() == c ) + { + found = true; + } + } + + final boolean matched = this.cpuMatches( c ); + + if( matched ) + { + matches++; + } + + if( found == !matched ) + { + changed = true; + } + } + + if( changed || this.cpus.size() != matches ) + { + this.cpus.clear(); + for( final ICraftingCPU c : cpuSet ) + { + if( this.cpuMatches( c ) ) + { + this.cpus.add( new CraftingCPURecord( c.getAvailableStorage(), c.getCoProcessors(), c ) ); + } + } + + this.sendCPUs(); + } + + this.noCPU = this.cpus.isEmpty(); + + super.detectAndSendChanges(); + } + + private boolean cpuMatches( final ICraftingCPU c ) + { + return c.isBusy(); + } + + private void sendCPUs() + { + Collections.sort( this.cpus ); + + if( this.selectedCpu >= this.cpus.size() ) + { + this.selectedCpu = -1; + this.myName = ""; + } + else if( this.selectedCpu != -1 ) + { + this.myName = this.cpus.get( this.selectedCpu ).getName(); + } + + if( this.selectedCpu == -1 && this.cpus.size() > 0 ) + { + this.selectedCpu = 0; + } + + if( this.selectedCpu != -1 ) + { + if( this.cpus.get( this.selectedCpu ).getCpu() != this.getMonitor() ) + { + this.setCPU( this.cpus.get( this.selectedCpu ).getCpu() ); + } + } + else + { + this.setCPU( null ); + } + } + + public void cycleCpu( final boolean next ) + { + if( next ) + { + this.selectedCpu++; + } + else + { + this.selectedCpu--; + } + + if( this.selectedCpu < -1 ) + { + this.selectedCpu = this.cpus.size() - 1; + } + else if( this.selectedCpu >= this.cpus.size() ) + { + this.selectedCpu = -1; + } + + if( this.selectedCpu == -1 && this.cpus.size() > 0 ) + { + this.selectedCpu = 0; + } + + if( this.selectedCpu == -1 ) + { + this.myName = ""; + this.setCPU( null ); + } + else + { + this.myName = this.cpus.get( this.selectedCpu ).getName(); + this.setCPU( this.cpus.get( this.selectedCpu ).getCpu() ); + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerMagnet.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerMagnet.java new file mode 100644 index 0000000..093ee61 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerMagnet.java @@ -0,0 +1,350 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotMagnetFilter; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryMagnetFilter; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + +public class ContainerMagnet extends Container { + + public final InventoryPlayer inventoryPlayer; + private EntityPlayer player; + public ItemStack heldItem; + public WCTInventoryMagnetFilter magnetInventory; + private final int playerInventorySize = 9 * 4; + private final int playerHotbarSize = 9; + private final int PLAYER_INV_START = 0, PLAYER_INV_END = 26, HOTBAR_START = 27, HOTBAR_END = 36, FILTERS_START = 37, + FILTERS_END = 56; + + public ContainerMagnet(EntityPlayer player, InventoryPlayer inventoryPlayer) { + this.inventoryPlayer = inventoryPlayer; + this.player = player; + this.heldItem = RandomUtils.getMagnet(inventoryPlayer); + this.magnetInventory = new WCTInventoryMagnetFilter(heldItem); + + // Add player inventory slots + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.addSlotToContainer(new Slot(this.inventoryPlayer, j + i * 9 + 9, j * 18 + 8, 86 + i * 18)); + } + } + + // Add hotbar slots + for (int i = 0; i < 9; ++i) { + this.addSlotToContainer(new Slot(this.inventoryPlayer, i, i * 18 + 8, 144)); + } + + // Add filter slots + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + this.addSlotToContainer(new SlotMagnetFilter(this.magnetInventory, j + i * 9, j * 18 + 8, 18 + i * 18)); + } + } + } + + private boolean isInHotbar(int slotNum) { + return (slotNum >= HOTBAR_START) && (slotNum <= HOTBAR_END); + } + + private boolean isInPlayerInventory(int slotNum) { + return (slotNum >= PLAYER_INV_START) && (slotNum <= PLAYER_INV_END); + } + + private boolean isInFilters(int slotNum) { + return (slotNum >= FILTERS_START) && (slotNum <= FILTERS_END); + } + + @Override + public boolean canInteractWith(EntityPlayer p) { + return true; + } + private boolean alreadyFiltered(ItemStack item) { + for (int i = 0; i < magnetInventory.getSizeInventory(); i++) { + if (isIdenticalItem(item, magnetInventory.getStackInSlot(i))) { + return true; + } + } + return false; + } + + @Override + public ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) { + if (slotNum < 0) { + return null; + } + if (getSlot(slotNum) == null) { + if (getSlot(slotNum) instanceof SlotMagnetFilter) { + arrangeSlots(); + } + return null; + } + //if (getSlot(slotNum).getStack() == RandomUtils.getMagnet(player.inventory)) { + // return null; + //} + if (getSlot(slotNum) instanceof SlotMagnetFilter) { + + SlotMagnetFilter slot = (SlotMagnetFilter) getSlot(slotNum); + ItemStack stack = null; + + ItemStack stackSlot = slot.getStack(); + if (alreadyFiltered(player.inventory.getItemStack()) && player.inventory.getItemStack() != null) { + return null; + } + if (stackSlot != null) { + stack = stackSlot.copy(); + } + + if (mouseButton == 2) { + fillPhantomSlot(slot, null, mouseButton); + } + else if (mouseButton == 0 || mouseButton == 1) { + InventoryPlayer playerInv = player.inventory; + + ItemStack stackHeld = playerInv.getItemStack(); + + if (stackSlot == null) { + if (stackHeld != null && slot.isItemValid(stackHeld)) { + fillPhantomSlot(slot, stackHeld, mouseButton); + } + } + else if (stackHeld == null) { + adjustPhantomSlot(slot, mouseButton, modifier); + } + else if (slot.isItemValid(stackHeld)) { + if (isIdenticalItem(stackSlot, stackHeld)) { + adjustPhantomSlot(slot, mouseButton, modifier); + } + else { + fillPhantomSlot(slot, stackHeld, mouseButton); + } + } + } + else if (mouseButton == 5) { + InventoryPlayer playerInv = player.inventory; + ItemStack stackHeld = playerInv.getItemStack(); + if (!slot.getHasStack()) { + fillPhantomSlot(slot, stackHeld, mouseButton); + } + } + return stack; + } + return super.slotClick(slotNum, mouseButton, modifier, player); + } + + private void arrangeSlots() { + int invSize = magnetInventory.getSizeInventory(); + for (int i = 0; i < invSize; i++) { + if (magnetInventory.getStackInSlot(i) == null) { + for (int j = 0; j < invSize; j++) { + if (j <= i) { + continue; + } + if (magnetInventory.getStackInSlot(j) != null) { + magnetInventory.setInventorySlotContents(i, magnetInventory.getStackInSlot(j)); + magnetInventory.decrStackSize(j, 1); + break; + } + } + } + } + } + + private void fillPhantomSlot(SlotMagnetFilter slot, ItemStack stackHeld, int mouseButton) { + if (!slot.canAdjustPhantom()) { + return; + } + if (stackHeld == null) { + slot.putStack(null); + return; + } + + int stackSize = mouseButton == 0 ? stackHeld.stackSize : 1; + if (stackSize > slot.getSlotStackLimit()) { + stackSize = slot.getSlotStackLimit(); + } + ItemStack phantomStack = stackHeld.copy(); + phantomStack.stackSize = stackSize; + ItemStack plainItem = new ItemStack(phantomStack.getItem(), 1); + + slot.putStack(phantomStack); + arrangeSlots(); + } + + private void adjustPhantomSlot(SlotMagnetFilter slot, int mouseButton, int modifier) { + if (!slot.canAdjustPhantom()) { + return; + } + ItemStack stackSlot = slot.getStack(); + int stackSize; + if (modifier == 1) { + stackSize = mouseButton == 0 ? (stackSlot.stackSize + 1) / 2 : stackSlot.stackSize * 2; + } + else { + stackSize = mouseButton == 0 ? stackSlot.stackSize - 1 : stackSlot.stackSize + 1; + } + + if (stackSize > slot.getSlotStackLimit()) { + stackSize = slot.getSlotStackLimit(); + } + + stackSlot.stackSize = stackSize; + + if (stackSlot.stackSize <= 0) { + stackSlot = null; + } + + slot.putStack(stackSlot); + arrangeSlots(); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer p, final int slotIndex) { + ItemStack itemStack = null; + Slot slot = (Slot) inventorySlots.get(slotIndex); + if (slot == null || !slot.getHasStack()) { + return null; + } + ItemStack stack = slot.getStack(); + itemStack = stack.copy(); + if (isInHotbar(slotIndex)) { + if (!mergeItemStack(stack, PLAYER_INV_START, PLAYER_INV_END + 1, false)) { + return null; + } + } + else if (isInPlayerInventory(slotIndex)) { + if (!mergeItemStack(stack, HOTBAR_START, HOTBAR_END + 1, false)) { + return null; + } + } + else { + return null; + } + if (stack.stackSize == 0) { + slot.putStack((ItemStack) null); + } + else { + slot.onSlotChanged(); + } + slot.onPickupFromSlot(p, stack); + return stack; + /* + * + * int numSlots = inventorySlots.size(); ItemStack stackInSlot = + * slot.getStack(); ItemStack originalStack = stackInSlot.copy(); + * + * slot.onSlotChange(stackInSlot, originalStack); if + * (stackInSlot.stackSize <= 0) { slot.putStack(null); } else { + * slot.onSlotChanged(); } + * + * if (stackInSlot.stackSize == originalStack.stackSize) { return null; + * } + * + * slot.onPickupFromSlot(player, stackInSlot); return originalStack; + */ + } + + public boolean isIdenticalItem(ItemStack lhs, ItemStack rhs) { + if (lhs == rhs) { + return true; + } + + if (lhs == null || rhs == null) { + return false; + } + + if (lhs.getItem() != rhs.getItem()) { + return false; + } + + if (lhs.getItemDamage() != OreDictionary.WILDCARD_VALUE) { + if (lhs.getItemDamage() != rhs.getItemDamage()) { + return false; + } + } + + return ItemStack.areItemStackTagsEqual(lhs, rhs); + } + + @Override + protected boolean mergeItemStack(ItemStack stack, int start, int end, boolean backwards) { + boolean flag1 = false; + int k = (backwards ? end - 1 : start); + Slot slot; + ItemStack itemstack1; + + if (stack.isStackable()) { + while (stack.stackSize > 0 && (!backwards && k < end || backwards && k >= start)) { + slot = (Slot) inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if (!slot.isItemValid(stack)) { + k += (backwards ? -1 : 1); + continue; + } + + if (itemstack1 != null && itemstack1.getItem() == stack.getItem() && (!stack.getHasSubtypes() || stack.getItemDamage() == itemstack1.getItemDamage()) && ItemStack.areItemStackTagsEqual(stack, itemstack1)) { + int l = itemstack1.stackSize + stack.stackSize; + + if (l <= stack.getMaxStackSize() && l <= slot.getSlotStackLimit()) { + stack.stackSize = 0; + itemstack1.stackSize = l; + magnetInventory.markDirty(); + flag1 = true; + } + else if (itemstack1.stackSize < stack.getMaxStackSize() && l < slot.getSlotStackLimit()) { + stack.stackSize -= stack.getMaxStackSize() - itemstack1.stackSize; + itemstack1.stackSize = stack.getMaxStackSize(); + magnetInventory.markDirty(); + flag1 = true; + } + } + + k += (backwards ? -1 : 1); + } + } + if (stack.stackSize > 0) { + k = (backwards ? end - 1 : start); + while (!backwards && k < end || backwards && k >= start) { + slot = (Slot) inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if (!slot.isItemValid(stack)) { + k += (backwards ? -1 : 1); + continue; + } + + if (itemstack1 == null) { + int l = stack.stackSize; + if (l <= slot.getSlotStackLimit()) { + slot.putStack(stack.copy()); + stack.stackSize = 0; + magnetInventory.markDirty(); + flag1 = true; + break; + } + else { + putStackInSlot(k, new ItemStack(stack.getItem(), slot.getSlotStackLimit(), stack.getItemDamage())); + stack.stackSize -= slot.getSlotStackLimit(); + magnetInventory.markDirty(); + flag1 = true; + } + } + + k += (backwards ? -1 : 1); + } + } + + return flag1; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerOpenContext.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerOpenContext.java new file mode 100644 index 0000000..99daef8 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerOpenContext.java @@ -0,0 +1,84 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +import appeng.api.parts.IPart; + + +public class ContainerOpenContext +{ + + private final boolean isItem; + private World w; + private int x; + private int y; + private int z; + private ForgeDirection side; + + public ContainerOpenContext( final Object myItem ) + { + final boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; + this.isItem = !isWorld; + } + + public TileEntity getTile() + { + if( this.isItem ) + { + return null; + } + return this.getWorld().getTileEntity( this.getX(), this.getY(), this.getZ() ); + } + + public ForgeDirection getSide() + { + return this.side; + } + + public void setSide( final ForgeDirection side ) + { + this.side = side; + } + + private int getZ() + { + return this.z; + } + + public void setZ( final int z ) + { + this.z = z; + } + + private int getY() + { + return this.y; + } + + public void setY( final int y ) + { + this.y = y; + } + + private int getX() + { + return this.x; + } + + public void setX( final int x ) + { + this.x = x; + } + + private World getWorld() + { + return this.w; + } + + public void setWorld( final World w ) + { + this.w = w; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerWirelessCraftingTerminal.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerWirelessCraftingTerminal.java new file mode 100644 index 0000000..af2a0fe --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/ContainerWirelessCraftingTerminal.java @@ -0,0 +1,1929 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.BufferOverflowException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.Nonnull; + +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.IMEMonitorHandlerReceiver; +import appeng.api.storage.ITerminalHost; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.api.util.IConfigManager; +import appeng.api.util.IConfigurableObject; +import appeng.client.me.InternalSlotME; +import appeng.client.me.SlotME; +import appeng.core.AEConfig; +import appeng.core.localization.PlayerMessages; +import appeng.helpers.IContainerCraftingPacket; +import appeng.helpers.ICustomNameObject; +import appeng.helpers.InventoryAction; +import appeng.tile.inventory.AppEngInternalInventory; +import appeng.tile.inventory.IAEAppEngInventory; +import appeng.tile.inventory.InvOperation; +import appeng.util.ConfigManager; +import appeng.util.IConfigManagerHost; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; +import appeng.util.inv.AdaptorPlayerHand; +import appeng.util.item.AEItemStack; +import appeng.api.AEApi; +import appeng.api.config.Actionable; +import appeng.api.config.PowerMultiplier; +import appeng.api.config.SecurityPermissions; +import appeng.api.config.Settings; +import appeng.api.config.SortDir; +import appeng.api.config.SortOrder; +import appeng.api.config.ViewItems; +import appeng.api.implementations.guiobjects.IPortableCell; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; +import appeng.api.networking.energy.IEnergyGrid; +import appeng.api.networking.energy.IEnergySource; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.security.ISecurityGrid; +import appeng.api.networking.storage.IBaseMonitor; +import appeng.container.ContainerNull; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.inventory.Slot; +import net.minecraft.inventory.SlotCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemArmor; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.IIcon; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.oredict.OreDictionary; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.items.ItemInfinityBooster; +import net.p455w0rd.wirelesscraftingterminal.items.ItemMagnet; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; +import net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTermHandler; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTIActionHost; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTPlayerSource; +import net.p455w0rd.wirelesscraftingterminal.common.container.guisync.GuiSync; +import net.p455w0rd.wirelesscraftingterminal.common.container.guisync.SyncData; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngCraftingSlot; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.AppEngSlot; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.NullSlot; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotArmor; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotBooster; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotCraftingMatrix; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotCraftingTerm; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotDisabled; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotFake; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotInaccessible; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotMagnet; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotPlayerHotBar; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotPlayerInv; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotTrash; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryBooster; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryCraftResult; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryCrafting; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryMagnet; +import net.p455w0rd.wirelesscraftingterminal.common.inventory.WCTInventoryTrash; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketInventoryAction; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketMEInventoryUpdate; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketPartialItem; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; +import net.p455w0rd.wirelesscraftingterminal.handlers.LocaleHandler; +import net.p455w0rd.wirelesscraftingterminal.helpers.WirelessTerminalGuiObject; + +public class ContainerWirelessCraftingTerminal extends Container + implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver, IAEAppEngInventory, IContainerCraftingPacket { + + private final ItemStack containerstack; + public WCTInventoryCrafting craftingGrid; + public final WCTInventoryBooster boosterInventory; + public final WCTInventoryMagnet magnetInventory; + public final WCTInventoryTrash trashInventory; + public final InventoryPlayer inventoryPlayer; + public ItemStack[] craftMatrixInventory; + public ItemStack craftItem; + private World worldObj; + private EntityPlayer player; + private static final int HOTBAR_START = 1, HOTBAR_END = HOTBAR_START + 8, INV_START = HOTBAR_END + 1, + INV_END = INV_START + 26, ARMOR_START = INV_END + 1, ARMOR_END = ARMOR_START + 3, + CRAFT_GRID_START = ARMOR_END + 1, CRAFT_GRID_END = CRAFT_GRID_START + 8, CRAFT_RESULT = CRAFT_GRID_END + 1, + BOOSTER_INDEX = 0, MAGNET_INDEX = CRAFT_RESULT + 1, TRASH_INDEX = MAGNET_INDEX + 1; + private int BOOSTER_Y_OFFSET = 139, HOTBAR_Y_OFFSET = 217, INV_Y_OFFSET = 159, ARMOR_Y_OFFSET = 83, + CRAFTMATRIX_Y_OFFSET = 83, CRAFTING_Y_OFFSET = 100, MAGNET_Y_OFFSET = BOOSTER_Y_OFFSET, TRASH_Y_OFFSET = MAGNET_Y_OFFSET; + public static int CRAFTING_SLOT_X_POS = 80, CRAFTING_SLOT_Y_POS = 83; + private SlotBooster boosterSlot; + private SlotMagnet magnetSlot; + private NullSlot nullSlot; + private Slot[] hotbarSlot; + private Slot[] inventorySlot; + private SlotArmor[] armorSlot; + private SlotCraftingMatrix[] craftMatrixSlot; + private SlotCraftingTerm craftingSlot; + private SlotTrash trashSlot; + private int firstCraftingSlotNumber = -1, lastCraftingSlotNumber = -1, craftingSlotNumber = -1; + + private final WirelessTerminalGuiObject obj; + private boolean isContainerValid = true; + private double powerMultiplier = 0.5; + private final IPortableCell civ; + private int ticks = 0; + private final IMEMonitor monitor; + private final IItemList items = AEApi.instance().storage().createItemList(); + private final IConfigManager clientCM; + private IConfigManager serverCM; + private IEnergySource powerSrc; + @GuiSync(98) + public static boolean hasPower = false; + private IConfigManagerHost gui; + private final BaseActionSource mySrc; + private final HashMap syncData = new HashMap(); + private final List dataChunks = new LinkedList(); + private IAEItemStack clientRequestedTargetItem = null; + private int ticksSinceCheck = 900; + private String customName; + private boolean sentCustomName; + private ContainerOpenContext openContext; + private final AppEngInternalInventory output = new AppEngInternalInventory( this, 1 ); + private final HashSet locked = new HashSet(); + private ItemWirelessCraftingTerminal thisItem; + private IGridNode networkNode; + private IMEInventoryHandler cellInv; + + /** + * Constructor for our custom container + * + * @author p455w0rd + */ + public ContainerWirelessCraftingTerminal(EntityPlayer player, InventoryPlayer inventoryPlayer) { + + this.clientCM = new ConfigManager(this); + this.clientCM.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.clientCM.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.clientCM.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + this.mySrc = new WCTPlayerSource(inventoryPlayer.player, this.getActionHost()); + this.customName = "WCTContainer"; + + this.boosterInventory = new WCTInventoryBooster(RandomUtils.getWirelessTerm(inventoryPlayer)); + this.magnetInventory = new WCTInventoryMagnet(RandomUtils.getWirelessTerm(inventoryPlayer)); + this.trashInventory = new WCTInventoryTrash(RandomUtils.getWirelessTerm(inventoryPlayer)); + this.containerstack = RandomUtils.getWirelessTerm(inventoryPlayer); + this.thisItem = (ItemWirelessCraftingTerminal) this.containerstack.getItem(); + this.worldObj = player.worldObj; + this.craftingGrid = new WCTInventoryCrafting(this, 3, 3, containerstack); + this.inventoryPlayer = inventoryPlayer; + this.player = player; + craftMatrixInventory = new ItemStack[9]; + hotbarSlot = new Slot[9]; + inventorySlot = new Slot[27]; + armorSlot = new SlotArmor[4]; + craftMatrixSlot = new SlotCraftingMatrix[9]; + + this.obj = getGuiObject(containerstack, player, worldObj, (int)player.posX, (int)player.posY, (int)player.posZ); + this.civ = (IPortableCell) this.obj; + // this.monitor = (IMEMonitor) this.civ; + //this.host = (ITerminalHost)civ; + final IGridNode node = ( (IGridHost) this.obj ).getGridNode( ForgeDirection.UNKNOWN ); + this.networkNode = node; + + this.prepareSync(); + + if (Platform.isServer()) { + this.serverCM = civ.getConfigManager(); + this.monitor = civ.getItemInventory(); + if (this.monitor != null) { + this.monitor.addListener(this, null); + setCellInventory( this.monitor ); + if (civ instanceof IPortableCell) { + setPowerSource((IEnergySource) this.civ); + } + } else { + this.setValidContainer(false); + } + } else { + this.monitor = null; + } + + if (Reference.WCT_BOOSTER_ENABLED) { + boosterSlot = new SlotBooster(this.boosterInventory, 0, 134, BOOSTER_Y_OFFSET); + this.addSlotToContainer(boosterSlot); + } + else { + nullSlot = new NullSlot(); + this.addSlotToContainer(nullSlot); + } + + // Add hotbar slots + for (int i = 0; i < 9; ++i) { + hotbarSlot[i] = new SlotPlayerHotBar(this.inventoryPlayer, i, i * 18 + 8, HOTBAR_Y_OFFSET); + this.addSlotToContainer(hotbarSlot[i]); + } + + int k=0; + + // Add player inventory slots + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + inventorySlot[k] = new SlotPlayerInv(this.inventoryPlayer, j + i * 9 + 9, j * 18 + 8, INV_Y_OFFSET + i * 18); + this.addSlotToContainer(inventorySlot[k]); + k++; + } + } + + // Add armor slots + for (int i = 0; i < 4; ++i) { + armorSlot[i] = new SlotArmor(this.player, this.inventoryPlayer, 39 - i, (int) 8.5, ARMOR_Y_OFFSET + i * 18, i); + this.addSlotToContainer(armorSlot[i]); + } + k=0; + // Add crafting grid slots + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + craftMatrixSlot[k] = new SlotCraftingMatrix(this, this.craftingGrid, j + i * 3, 80 + j * 18, CRAFTMATRIX_Y_OFFSET + i * 18); + this.addSlotToContainer(craftMatrixSlot[k]); + if (k == 0) { + this.firstCraftingSlotNumber = craftMatrixSlot[k].slotNumber; + } + k++; + } + } + this.lastCraftingSlotNumber = craftMatrixSlot[8].slotNumber; + + craftingSlot = new SlotCraftingTerm( this.getPlayerInv().player, this.mySrc, this.getPowerSource(), this.obj, this.craftingGrid, this.craftingGrid, this.output, 174, CRAFTING_Y_OFFSET, this ); + this.craftingSlotNumber = this.lastCraftingSlotNumber + 1; + // Add crafting result slot + this.addSlotToContainer(craftingSlot); + + magnetSlot = new SlotMagnet(this.magnetInventory, 152, MAGNET_Y_OFFSET); + this.addSlotToContainer(magnetSlot); + + trashSlot = new SlotTrash(trashInventory, 80, TRASH_Y_OFFSET, player); + trashSlot.setContainer(this); + this.addSlotToContainer(trashSlot); + + updateCraftingMatrix(); + + this.onCraftMatrixChanged(this.craftingGrid); + thisItem.checkForBooster(containerstack); + //FMLCommonHandler.instance().bus().register(magnetSlot); + } + + public void emptyTrash() { + this.trashSlot.clearStack(); + } + + public void setCellInventory( final IMEInventoryHandler cellInv ) + { + this.cellInv = cellInv; + } + + public void onSlotChange( final Slot s ) + { + + } + + @Override + protected Slot addSlotToContainer( final Slot newSlot ) + { + if( newSlot instanceof AppEngSlot ) + { + final AppEngSlot s = (AppEngSlot) newSlot; + s.setContainer( this ); + return super.addSlotToContainer( newSlot ); + } + else + { + throw new IllegalArgumentException( "Invalid Slot [" + newSlot + "] for WCT Container instead of AppEngSlot." ); + } + } + + @Override + public boolean canDragIntoSlot( final Slot s ) + { + return ( (AppEngSlot) s ).isDraggable(); + } + + @Override + public void onCraftMatrixChanged(final IInventory iinv) { + + final ContainerNull cn = new ContainerNull(); + final InventoryCrafting ic = new InventoryCrafting( cn, 3, 3 ); + + for( int x = 0; x < 9; x++ ) + { + ic.setInventorySlotContents( x, this.craftMatrixSlot[x].getStack() ); + } + + //this.output.setInventorySlotContents(0, CraftingManager.getInstance().findMatchingRecipe(ic, worldObj)); + this.craftingSlot.putStack(CraftingManager.getInstance().findMatchingRecipe( ic, this.worldObj )); + writeToNBT("crafting"); + } + + public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) + { + if( slot >= 0 && slot < this.inventorySlots.size() ) + { + final Slot s = this.getSlot( slot ); + + if( s instanceof SlotCraftingTerm ) + { + switch( action ) + { + case CRAFT_SHIFT: + case CRAFT_ITEM: + case CRAFT_STACK: + ( (SlotCraftingTerm) s ).doClick( action, player ); + this.updateHeld( player ); + default: + } + } + + if( s instanceof SlotFake ) + { + final ItemStack hand = player.inventory.getItemStack(); + + switch( action ) + { + case PICKUP_OR_SET_DOWN: + + if( hand == null ) + { + s.putStack( null ); + } + else + { + s.putStack( hand.copy() ); + } + + break; + case PLACE_SINGLE: + + if( hand != null ) + { + final ItemStack is = hand.copy(); + is.stackSize = 1; + s.putStack( is ); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + + ItemStack is = s.getStack(); + if( is != null ) + { + if( hand == null ) + { + is.stackSize--; + } + else if( hand.isItemEqual( is ) ) + { + is.stackSize = Math.min( is.getMaxStackSize(), is.stackSize + 1 ); + } + else + { + is = hand.copy(); + is.stackSize = 1; + } + + s.putStack( is ); + } + else if( hand != null ) + { + is = hand.copy(); + is.stackSize = 1; + s.putStack( is ); + } + + break; + case CREATIVE_DUPLICATE: + case MOVE_REGION: + case SHIFT_CLICK: + default: + break; + } + } + + if( action == InventoryAction.MOVE_REGION ) + { + final List from = new LinkedList(); + + for( final Object j : this.inventorySlots ) + { + if( j instanceof Slot && j.getClass() == s.getClass() ) + { + from.add( (Slot) j ); + } + } + + for( final Slot fr : from ) + { + this.transferStackInSlot( player, fr.slotNumber ); + } + } + + return; + } + + // get target item. + final IAEItemStack slotItem = this.clientRequestedTargetItem; + + switch( action ) + { + case SHIFT_CLICK: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize( myItem.getMaxStackSize() ); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + myItem.stackSize = (int) ais.getStackSize(); + myItem = adp.simulateAdd( myItem ); + + if( myItem != null ) + { + ais.setStackSize( ais.getStackSize() - myItem.stackSize ); + } + + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + adp.addItems( ais.getItemStack() ); + } + } + break; + case ROLL_DOWN: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + final int releaseQty = 1; + final ItemStack isg = player.inventory.getItemStack(); + + if( isg != null && releaseQty > 0 ) + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( isg ); + ais.setStackSize( 1 ); + final IAEItemStack extracted = ais.copy(); + + ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais == null ) + { + final InventoryAdaptor ia = new AdaptorPlayerHand( player ); + + final ItemStack fail = ia.removeItems( 1, extracted.getItemStack(), null ); + if( fail == null ) + { + this.getCellInventory().extractItems( extracted, Actionable.MODULATE, this.getActionSource() ); + } + + this.updateHeld( player ); + } + } + + break; + case ROLL_UP: + case PICKUP_SINGLE: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( slotItem != null ) + { + int liftQty = 1; + final ItemStack item = player.inventory.getItemStack(); + + if( item != null ) + { + if( item.stackSize >= item.getMaxStackSize() ) + { + liftQty = 0; + } + if( !Platform.isSameItemPrecise( slotItem.getItemStack(), item ) ) + { + liftQty = 0; + } + } + + if( liftQty > 0 ) + { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize( 1 ); + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + final InventoryAdaptor ia = new AdaptorPlayerHand( player ); + + final ItemStack fail = ia.addItems( ais.getItemStack() ); + if( fail != null ) + { + this.getCellInventory().injectItems( ais, Actionable.MODULATE, this.getActionSource() ); + } + + this.updateHeld( player ); + } + } + } + break; + case PICKUP_OR_SET_DOWN: + if( getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( player.inventory.getItemStack() == null ) + { + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize( ais.getItemStack().getMaxStackSize() ); + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + player.inventory.setItemStack( ais.getItemStack() ); + } + else + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + } + else + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); + ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + player.inventory.setItemStack( ais.getItemStack() ); + } + else + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( player.inventory.getItemStack() == null ) + { + if( slotItem != null ) + { + IAEItemStack ais = slotItem.copy(); + final long maxSize = ais.getItemStack().getMaxStackSize(); + ais.setStackSize( maxSize ); + ais = this.getCellInventory().extractItems( ais, Actionable.SIMULATE, this.getActionSource() ); + + if( ais != null ) + { + final long stackSize = Math.min( maxSize, ais.getStackSize() ); + ais.setStackSize( ( stackSize + 1 ) >> 1 ); + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + } + + if( ais != null ) + { + player.inventory.setItemStack( ais.getItemStack() ); + } + else + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + } + else + { + IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); + ais.setStackSize( 1 ); + ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais == null ) + { + final ItemStack is = player.inventory.getItemStack(); + is.stackSize--; + if( is.stackSize <= 0 ) + { + player.inventory.setItemStack( null ); + } + this.updateHeld( player ); + } + } + + break; + case CREATIVE_DUPLICATE: + if( player.capabilities.isCreativeMode && slotItem != null ) + { + final ItemStack is = slotItem.getItemStack(); + is.stackSize = is.getMaxStackSize(); + player.inventory.setItemStack( is ); + this.updateHeld( player ); + } + break; + case MOVE_REGION: + + if( this.getPowerSource() == null || this.getCellInventory() == null ) + { + return; + } + + if( slotItem != null ) + { + final int playerInv = 9 * 4; + for( int slotNum = 0; slotNum < playerInv; slotNum++ ) + { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize( myItem.getMaxStackSize() ); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + myItem.stackSize = (int) ais.getStackSize(); + myItem = adp.simulateAdd( myItem ); + + if( myItem != null ) + { + ais.setStackSize( ais.getStackSize() - myItem.stackSize ); + } + + ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); + if( ais != null ) + { + adp.addItems( ais.getItemStack() ); + } + else + { + return; + } + } + } + + break; + default: + break; + } + } + + public IMEInventoryHandler getCellInventory() { + return this.cellInv; + } + + protected void updateHeld( final EntityPlayerMP p ) + { + if( Platform.isServer() ) + { + try + { + NetworkHandler.instance.sendTo( new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.create( p.inventory.getItemStack() ) ), p ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + } + + private void updateCraftingMatrix() { + if (!this.containerstack.hasTagCompound()) { + this.containerstack.setTagCompound(new NBTTagCompound()); + } + NBTTagCompound stack = this.containerstack.getTagCompound(); + readMatrixNBT(stack); + for (int i = 0; i < 9; i++) { + this.craftingGrid.setInventorySlotContents(i, craftMatrixInventory[i]); + } + } + + @Override + public void saveChanges() + { + // :P + } + + @Override + public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) + { + // <3 + } + + @Override + public IGridNode getNetworkNode() { + return this.networkNode; + } + + @Override + public boolean useRealItems() { + return true; + } + + @Override + public IInventory getInventoryByName( final String name ) + { + if( name.equals( "player" ) || name.equals("container.inventory")) + { + return this.getInventoryPlayer(); + } + if( name.equals( "crafting" ) ) + { + return this.craftingGrid; + } + return null; + } + + @Override + public ItemStack[] getViewCells() + { + return null; + } + + public void updateSlots(int yOffset) { + int i, j, index = 0; + + this.getSlot(index).yDisplayPosition = BOOSTER_Y_OFFSET + yOffset; + + for (i = 0; i < 9; ++i) { + index++; + this.getSlot(index).yDisplayPosition = HOTBAR_Y_OFFSET + yOffset; + } + + for (i = 0; i < 3; ++i) { + for (j = 0; j < 9; ++j) { + index++; + this.getSlot(index).yDisplayPosition = INV_Y_OFFSET + yOffset + (18 * i); + } + } + + for (i = 0; i < 4; ++i) { + index++; + this.getSlot(index).yDisplayPosition = ARMOR_Y_OFFSET + yOffset + (18 * i); + } + + Reference.WCT_CRAFTMATRIX_Y_OFFSET = CRAFTMATRIX_Y_OFFSET + yOffset; + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + index++; + this.getSlot(index).yDisplayPosition = (CRAFTMATRIX_Y_OFFSET + yOffset) + (18 * i); + } + } + index++; + this.getSlot(index).yDisplayPosition = CRAFTING_Y_OFFSET + yOffset; + index++; + this.getSlot(index).yDisplayPosition = MAGNET_Y_OFFSET + yOffset; + index++; + this.getSlot(index).yDisplayPosition = TRASH_Y_OFFSET + yOffset; + } + + private WirelessTerminalGuiObject getGuiObject( final ItemStack it, final EntityPlayer player, final World w, final int x, final int y, final int z ) + { + if( it != null ) + { + final IWirelessCraftingTermHandler wh = (IWirelessCraftingTermHandler)AEApi.instance().registries().wireless().getWirelessTerminalHandler( it ); + if( wh != null ) + { + return new WirelessTerminalGuiObject( wh, it, player, w, x, y, z ); + } + } + + return null; + } + + @Override + public void detectAndSendChanges() { + + this.sendCustomName(); + + if (Platform.isSameItem(this.civ.getItemStack(), this.getPlayerInv().getCurrentItem())) { + this.getPlayerInv().setInventorySlotContents(this.getPlayerInv().currentItem, this.civ.getItemStack()); + } else { + this.setValidContainer(false); + } + + // drain 1 ae t + this.ticks++; + if (this.ticks > 10) { + this.civ.extractAEPower(this.getPowerMultiplier() * this.ticks, Actionable.MODULATE, + PowerMultiplier.CONFIG); + this.ticks = 0; + } + + if (Platform.isServer()) { + if (this.monitor != this.civ.getItemInventory()) { + this.setValidContainer(false); + } + + for (final Settings set : this.serverCM.getSettings()) { + final Enum sideLocal = this.serverCM.getSetting(set); + final Enum sideRemote = this.clientCM.getSetting(set); + + if (sideLocal != sideRemote) { + this.clientCM.putSetting(set, sideLocal); + for (final Object crafter : this.crafters) { + try { + NetworkHandler.instance.sendTo(new PacketValueConfig(set.name(), sideLocal.name()), + (EntityPlayerMP) crafter); + } catch (final IOException e) { + WCTLog.debug(e.getMessage()); + } + } + } + } + + if (!this.items.isEmpty()) { + try { + final IItemList monitorCache = this.monitor.getStorageList(); + + final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + + for (final IAEItemStack is : this.items) { + final IAEItemStack send = monitorCache.findPrecise(is); + if (send == null) { + is.setStackSize(0); + piu.appendItem(is); + } else { + piu.appendItem(send); + } + } + + if (!piu.isEmpty()) { + this.items.resetStatus(); + + for (final Object c : this.crafters) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } + } + } + } catch (final IOException e) { + WCTLog.debug(e.getMessage()); + } + } + + this.sendCustomName(); + if (Platform.isServer()) { + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + for (final SyncData sd : this.syncData.values()) { + sd.tick(icrafting); + } + } + } + } + boolean hasAxxess = hasAccess(SecurityPermissions.CRAFT, true) || hasAccess(SecurityPermissions.EXTRACT, true) || hasAccess(SecurityPermissions.INJECT, true); + if (!isInRange()) { + if (!isBoosterInstalled() || !Reference.WCT_BOOSTER_ENABLED) { + if (Platform.isServer() && this.isValidContainer()) { + this.getPlayerInv().player.addChatMessage(PlayerMessages.OutOfRange.get()); + } + this.setValidContainer(false); + } + if (!networkIsPowered()) { + if (Platform.isServer() && this.isValidContainer()) { + this.getPlayerInv().player.addChatMessage(new ChatComponentText(LocaleHandler.NoNetworkPower.getLocal())); + } + this.setValidContainer(false); + } + } + else if (!hasAxxess) { + if (Platform.isServer() && this.isValidContainer()) { + this.getPlayerInv().player.addChatMessage(PlayerMessages.CommunicationError.get()); + } + this.setValidContainer(false); + } + else { + this.setPowerMultiplier(AEConfig.instance.wireless_getDrainRate(this.obj.getRange())); + } + super.detectAndSendChanges(); + } + + public boolean isBoosterInstalled() { + Slot slot = getSlotFromInventory(this.boosterInventory, BOOSTER_INDEX); + if (slot == null) { + return false; + } + boolean hasStack = getSlotFromInventory(this.boosterInventory, BOOSTER_INDEX).getHasStack(); + if (hasStack) { + Item boosterSlotContents = getSlotFromInventory(this.boosterInventory, BOOSTER_INDEX).getStack().getItem(); + if (boosterSlotContents instanceof ItemInfinityBooster) { + return true; + } + } + return false; + } + + public boolean isMagnetInstalled() { + Slot slot = getSlotFromInventory(this.magnetInventory, MAGNET_INDEX); + if (slot == null) { + return false; + } + boolean hasStack = getSlotFromInventory(this.magnetInventory, MAGNET_INDEX).getHasStack(); + if (hasStack) { + Item magnetSlotContents = getSlotFromInventory(this.magnetInventory, MAGNET_INDEX).getStack().getItem(); + if (magnetSlotContents instanceof ItemMagnet) { + return true; + } + } + return false; + } + + public BaseActionSource getActionSource() { + return this.mySrc; + } + + @Override + public boolean canInteractWith(final EntityPlayer entityplayer) { + if (this.isValidContainer()) { + return true; + } + return false; + } + + private void sendCustomName() { + if (!this.sentCustomName) { + this.sentCustomName = true; + if (Platform.isServer()) { + ICustomNameObject name = null; + if (this.obj instanceof ICustomNameObject) { + name = (ICustomNameObject) this.obj; + } + + if (this instanceof ICustomNameObject) { + name = (ICustomNameObject) this; + } + + if (name != null) { + if (name.hasCustomName()) { + this.setCustomName(name.getCustomName()); + } + + if (this.getCustomName() != null) { + try { + NetworkHandler.instance.sendTo(new PacketValueConfig("CustomName", this.getCustomName()), + (EntityPlayerMP) this.getInventoryPlayer().player); + } catch (final IOException e) { + WCTLog.debug(e.getMessage()); + } + } + } + } + } + } + + public void setCustomName(final String customName) { + this.customName = customName; + } + + public String getCustomName() { + return this.customName; + } + + public void stringSync(final int idx, final String value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update(value); + } + } + + public void verifyPermissions(final SecurityPermissions security, final boolean requirePower) { + if (Platform.isClient()) { + return; + } + + this.ticksSinceCheck++; + if (this.ticksSinceCheck < 20) { + return; + } + + this.ticksSinceCheck = 0; + this.setValidContainer(this.isValidContainer() && this.hasAccess(security, requirePower)); + } + + protected boolean isInRange() { + return this.obj.rangeCheck(Reference.WCT_BOOSTER_ENABLED && this.isBoosterInstalled()); + } + + protected boolean networkIsPowered() { + final WCTIActionHost host = this.getActionHost(); + boolean test2 = false; + if (host != null) { + final IGridNode gn = host.getActionableNode(Reference.WCT_BOOSTER_ENABLED && this.isBoosterInstalled()); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (eg.isNetworkPowered()) { + return true; + } + } + } + } + return false; + } + + protected boolean hasAccess(final SecurityPermissions perm, final boolean requirePower) { + final WCTIActionHost host = this.getActionHost(); + + if (host != null) { + final IGridNode gn = host.getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(this.getInventoryPlayer().player, perm)) { + return true; + } + } + } + } + + return false; + } + + public void lockPlayerInventorySlot( final int idx ) + { + this.locked.add( idx ); + } + + public boolean isValidForSlot(final Slot s, final ItemStack i) { + return true; + } + + public void postPartial(final PacketPartialItem packetPartialItem) { + this.dataChunks.add(packetPartialItem); + if (packetPartialItem.getPageCount() == this.dataChunks.size()) { + this.parsePartials(); + } + } + + private void parsePartials() { + int total = 0; + for (final PacketPartialItem ppi : this.dataChunks) { + total += ppi.getSize(); + } + + final byte[] buffer = new byte[total]; + int cursor = 0; + + for (final PacketPartialItem ppi : this.dataChunks) { + cursor = ppi.write(buffer, cursor); + } + + try { + final NBTTagCompound data = CompressedStreamTools.readCompressed(new ByteArrayInputStream(buffer)); + if (data != null) { + this.setTargetStack(AEApi.instance().storage().createItemStack(ItemStack.loadItemStackFromNBT(data))); + } + } catch (final IOException e) { + WCTLog.debug(e.getMessage()); + } + + this.dataChunks.clear(); + } + + public IAEItemStack getTargetStack() { + return this.clientRequestedTargetItem; + } + + public void setTargetStack(final IAEItemStack stack) { + // client doesn't need to re-send, makes for lower overhead rapid + // packets. + if (Platform.isClient()) { + final ItemStack a = stack == null ? null : stack.getItemStack(); + final ItemStack b = this.clientRequestedTargetItem == null ? null + : this.clientRequestedTargetItem.getItemStack(); + + if (Platform.isSameItemPrecise(a, b)) { + return; + } + + final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final NBTTagCompound item = new NBTTagCompound(); + + if (stack != null) { + stack.writeToNBT(item); + } + + try { + CompressedStreamTools.writeCompressed(item, stream); + + final int maxChunkSize = 30000; + final List miniPackets = new LinkedList(); + + final byte[] data = stream.toByteArray(); + + final ByteArrayInputStream bis = new ByteArrayInputStream(data, 0, stream.size()); + while (bis.available() > 0) { + final int nextBLock = bis.available() > maxChunkSize ? maxChunkSize : bis.available(); + final byte[] nextSegment = new byte[nextBLock]; + bis.read(nextSegment); + miniPackets.add(nextSegment); + } + bis.close(); + stream.close(); + + int page = 0; + for (final byte[] packet : miniPackets) { + final PacketPartialItem ppi = new PacketPartialItem(page, miniPackets.size(), packet); + page++; + NetworkHandler.instance.sendToServer(ppi); + } + } catch (final IOException e) { + WCTLog.debug(e.getMessage()); + return; + } + } + + this.clientRequestedTargetItem = stack == null ? null : stack.copy(); + } + + private void prepareSync() { + for (final Field f : this.getClass().getFields()) { + if (f.isAnnotationPresent(GuiSync.class)) { + final GuiSync annotation = f.getAnnotation(GuiSync.class); + if (this.syncData.containsKey(annotation.value())) { + WCTLog.warning("Channel already in use: " + annotation.value() + " for " + f.getName()); + } else { + this.syncData.put(annotation.value(), new SyncData(this, f, annotation)); + } + } + } + } + + protected WCTIActionHost getActionHost() { + if (this.obj instanceof WCTIActionHost) { + return (WCTIActionHost) this.obj; + } + return null; + } + + @Override + public IConfigManager getConfigManager() { + if (Platform.isServer()) { + return this.serverCM; + } + return this.clientCM; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (this.getGui() != null) { + this.getGui().updateSetting(manager, settingName, newValue); + } + } + + private IConfigManagerHost getGui() { + return this.gui; + } + + public void setGui(@Nonnull final IConfigManagerHost gui) { + this.gui = gui; + } + + @Override + public void onListUpdate() { + for (final Object c : this.crafters) { + if (c instanceof ICrafting) { + final ICrafting cr = (ICrafting) c; + this.queueInventory(cr); + } + } + } + + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, + final BaseActionSource source) { + for (final IAEItemStack is : change) { + this.items.add(is); + } + } + + @Override + public boolean isValid(final Object verificationToken) { + return true; + } + + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.monitor != null) { + this.monitor.removeListener(this); + } + } + + @Override + public void addCraftingToCrafters(final ICrafting c) { + super.addCraftingToCrafters(c); + this.queueInventory(c); + } + + @Override + public void removeCraftingFromCrafters(final ICrafting c) { + super.removeCraftingFromCrafters(c); + + if (this.crafters.isEmpty() && this.monitor != null) { + this.monitor.removeListener(this); + } + } + + private void queueInventory(final ICrafting c) { + if (Platform.isServer() && c instanceof EntityPlayer && this.monitor != null) { + try { + PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + final IItemList monitorCache = this.monitor.getStorageList(); + + for (final IAEItemStack send : monitorCache) { + try { + piu.appendItem(send); + } catch (final BufferOverflowException boe) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + + piu = new PacketMEInventoryUpdate(); + piu.appendItem(send); + } + } + + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } catch (final IOException e) { + WCTLog.debug(e.getMessage()); + } + } + } + + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + // =] + } + + public IEnergySource getPowerSource() { + return this.powerSrc; + } + + public boolean isPowered() { + NBTTagCompound testnbt = this.containerstack.getTagCompound(); + double pwr = testnbt.getDouble("internalCurrentPower"); + return (pwr > 0.8); + } + + public void setPowerSource(final IEnergySource powerSrc) { + this.powerSrc = powerSrc; + } + + private double getPowerMultiplier() { + return this.powerMultiplier; + } + + void setPowerMultiplier(final double powerMultiplier) { + this.powerMultiplier = powerMultiplier; + } + + public InventoryPlayer getPlayerInv() { + return this.getInventoryPlayer(); + } + + public InventoryPlayer getInventoryPlayer() { + return this.inventoryPlayer; + } + + public boolean isValidContainer() { + return this.isContainerValid; + } + + public void setValidContainer(final boolean isContainerValid) { + this.isContainerValid = isContainerValid; + } + + public Object getTarget() { + if (this.obj != null) { + return this.obj; + } + return null; + } + + public ContainerOpenContext getOpenContext() { + return this.openContext; + } + + public void setOpenContext(final ContainerOpenContext openContext) { + this.openContext = openContext; + } + + + /** + * Fetches crafting matrix ItemStacks + * + * @param nbtTagCompound + * @author p455w0rd + */ + private void readMatrixNBT(NBTTagCompound nbtTagCompound) { + // Read in the ItemStacks in the inventory from NBT + NBTTagList tagList = nbtTagCompound.getTagList("CraftingMatrix", 10); + craftMatrixInventory = new ItemStack[9]; + for (int i = 0; i < tagList.tagCount(); ++i) { + NBTTagCompound tagCompound = (NBTTagCompound) tagList.getCompoundTagAt(i); + int slot = tagCompound.getByte("Slot"); + if (slot >= 0 && slot < craftMatrixInventory.length) { + craftMatrixInventory[slot] = ItemStack.loadItemStackFromNBT(tagCompound); + } + } + } + + /** + * Initiates external NBT saving methods that store inventory contents + */ + public void writeToNBT(String which) { + if (!this.containerstack.hasTagCompound()) { + this.containerstack.setTagCompound(new NBTTagCompound()); + } + switch (which) { + case "booster": + ((WCTInventoryBooster) boosterInventory).writeNBT(this.containerstack.getTagCompound()); + break; + case "crafting": + ((WCTInventoryCrafting) craftingGrid).writeNBT(this.containerstack.getTagCompound()); + break; + case "magnet": + ((WCTInventoryMagnet) magnetInventory).writeNBT(this.containerstack.getTagCompound()); + break; + case "trash": + ((WCTInventoryTrash) trashInventory).writeNBT(this.containerstack.getTagCompound()); + break; + case "all": + default: + ((WCTInventoryBooster) boosterInventory).writeNBT(this.containerstack.getTagCompound()); + ((WCTInventoryCrafting) craftingGrid).writeNBT(this.containerstack.getTagCompound()); + ((WCTInventoryMagnet) magnetInventory).writeNBT(this.containerstack.getTagCompound()); + ((WCTInventoryTrash) trashInventory).writeNBT(this.containerstack.getTagCompound()); + break; + } + } + + @Override + public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) { + final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! + ItemStack tis = clickSlot.getStack(); + if (tis == null) { + return null; + } + // Try to place armor in armor slot/booster in booster lost first + if (isInInventory(idx) || isInHotbar(idx)) { + if (tis.getItem() instanceof ItemArmor) { + int type = ((ItemArmor) tis.getItem()).armorType; + if (this.mergeItemStack(tis, ARMOR_START + type, ARMOR_START + type + 1, false)) { + clickSlot.clearStack(); + return null; + } + } + else if (tis.getItem() instanceof ItemInfinityBooster) { + if (this.mergeItemStack(tis, BOOSTER_INDEX, BOOSTER_INDEX + 1, false)) { + clickSlot.clearStack(); + return null; + } + } + else { + if (tis.getItem() instanceof ItemMagnet) { + if (this.mergeItemStack(tis, MAGNET_INDEX, MAGNET_INDEX + 1, false)) { + clickSlot.clearStack(); + return null; + } + } + } + } + + if( Platform.isClient() ) { + return null; + } + + boolean hasMETiles = false; + for( final Object is : this.inventorySlots ) { + if( is instanceof InternalSlotME ) { + hasMETiles = true; + break; + } + } + + if( hasMETiles && Platform.isClient() ) { + return null; + } + + + + if( clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible ) { + return null; + } + if( clickSlot != null && clickSlot.getHasStack() ) { + + final List selectedSlots = new ArrayList(); + + /** + * Gather a list of valid destinations. + */ + if( clickSlot.isPlayerSide() ) { + tis = this.shiftStoreItem( tis ); + + // target slots in the container... + for( final Object inventorySlot : this.inventorySlots ) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if( !( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !(cs instanceof AppEngCraftingSlot) ) { + if( cs.isItemValid( tis ) ) { + selectedSlots.add( cs ); + } + } + } + } + else { + // target slots in the container... + for( final Object inventorySlot : this.inventorySlots ) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if( ( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !(cs instanceof AppEngCraftingSlot) ) { + if( cs.isItemValid( tis ) ) { + selectedSlots.add( cs ); + } + } + } + } + + /** + * Handle Fake Slot Shift clicking. + */ + if( selectedSlots.isEmpty() && clickSlot.isPlayerSide() ) { + if( tis != null ) { + // target slots in the container... + for( final Object inventorySlot : this.inventorySlots ) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + final ItemStack destination = cs.getStack(); + + if( !( cs.isPlayerSide() ) && cs instanceof SlotFake ) { + if( Platform.isSameItemPrecise( destination, tis ) ) { + return null; + } + else if( destination == null ) { + cs.putStack( tis.copy() ); + cs.onSlotChanged(); + this.updateSlot( cs ); + return null; + } + } + } + } + } + + if( tis != null ) { + // find partials.. + for( final Slot d : selectedSlots ) { + if( d instanceof SlotDisabled || d instanceof SlotME ) { + continue; + } + + if( d.isItemValid( tis ) ) { + if( d.getHasStack() ) { + final ItemStack t = d.getStack(); + + if( Platform.isSameItemPrecise( tis, t ) ) // t.isItemEqual(tis)) + { + int maxSize = t.getMaxStackSize(); + if( maxSize > d.getSlotStackLimit() ) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if( tis.stackSize < placeAble ) { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if( tis.stackSize <= 0 ) { + clickSlot.putStack( null ); + d.onSlotChanged(); + + // if ( hasMETiles ) updateClient(); + + this.updateSlot( clickSlot ); + this.updateSlot( d ); + return null; + } + else { + this.updateSlot( d ); + } + } + } + } + } + + // any match.. + for( final Slot d : selectedSlots ) { + if( d instanceof SlotDisabled || d instanceof SlotME ) { + continue; + } + + if( d.isItemValid( tis ) ) { + if( d.getHasStack() ) { + final ItemStack t = d.getStack(); + + if( Platform.isSameItemPrecise( t, tis ) ) { + int maxSize = t.getMaxStackSize(); + if( d.getSlotStackLimit() < maxSize ) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if( tis.stackSize < placeAble ) { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if( tis.stackSize <= 0 ) { + clickSlot.putStack( null ); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot( clickSlot ); + this.updateSlot( d ); + return null; + } + else { + this.updateSlot( d ); + } + } + } + else { + int maxSize = tis.getMaxStackSize(); + if( maxSize > d.getSlotStackLimit() ) { + maxSize = d.getSlotStackLimit(); + } + + final ItemStack tmp = tis.copy(); + if( tmp.stackSize > maxSize ) { + tmp.stackSize = maxSize; + } + + tis.stackSize -= tmp.stackSize; + d.putStack( tmp ); + + if( tis.stackSize <= 0 ) { + clickSlot.putStack( null ); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot( clickSlot ); + this.updateSlot( d ); + return null; + } + else { + this.updateSlot( d ); + } + } + } + } + } + + clickSlot.putStack( tis != null ? tis.copy() : null ); + } + + this.updateSlot( clickSlot ); + return null; + } + + public void swapSlotContents( final int slotA, final int slotB ) + { + final Slot a = this.getSlot( slotA ); + final Slot b = this.getSlot( slotB ); + + // NPE protection... + if( a == null || b == null ) + { + return; + } + + final ItemStack isA = a.getStack(); + final ItemStack isB = b.getStack(); + + // something to do? + if( isA == null && isB == null ) + { + return; + } + + // can take? + + if( isA != null && !a.canTakeStack( this.getInventoryPlayer().player ) ) + { + return; + } + + if( isB != null && !b.canTakeStack( this.getInventoryPlayer().player ) ) + { + return; + } + + // swap valid? + + if( isB != null && !a.isItemValid( isB ) ) + { + return; + } + + if( isA != null && !b.isItemValid( isA ) ) + { + return; + } + + ItemStack testA = isB == null ? null : isB.copy(); + ItemStack testB = isA == null ? null : isA.copy(); + + // can put some back? + if( testA != null && testA.stackSize > a.getSlotStackLimit() ) + { + if( testB != null ) + { + return; + } + + final int totalA = testA.stackSize; + testA.stackSize = a.getSlotStackLimit(); + testB = testA.copy(); + + testB.stackSize = totalA - testA.stackSize; + } + + if( testB != null && testB.stackSize > b.getSlotStackLimit() ) + { + if( testA != null ) + { + return; + } + + final int totalB = testB.stackSize; + testB.stackSize = b.getSlotStackLimit(); + testA = testB.copy(); + + testA.stackSize = totalB - testA.stackSize; + } + + a.putStack( testA ); + b.putStack( testB ); + } + + private boolean isCraftMatrixSlot(AppEngSlot cs) { + return ( cs.getSlotIndex() >= this.firstCraftingSlotNumber ) && !( cs.getSlotIndex() <= this.lastCraftingSlotNumber ); + } + + private void updateSlot( final Slot clickSlot ) { + // ??? + this.detectAndSendChanges(); + } + + private ItemStack shiftStoreItem( final ItemStack input ) { + if( this.getPowerSource() == null || this.civ == null) { + return input; + } + final IAEItemStack ais = Platform.poweredInsert( this.getPowerSource(), this.civ, AEApi.instance().storage().createItemStack( input ), this.getActionSource() ); + if( ais == null ) { + return null; + } + return ais.getItemStack(); + } + + /** + * Checks to see if the given integer is within the range of hotbar slot + * index values + * + * @param index + * @return true/false + * @author p455w0rd + */ + private boolean isInHotbar(@Nonnull int index) { + return (index >= HOTBAR_START && index <= HOTBAR_END); + } + + /** + * Checks to see if the given integer is within the range of player + * inventory slot index values + * + * @param index + * @return true/false + * @author p455w0rd + */ + private boolean isInInventory(@Nonnull int index) { + return (index >= INV_START && index <= INV_END); + } + + /** + * Checks to see if the given integer is within the range of armor slot + * index values + * + * @param index + * @return true/false + * @author p455w0rd + */ + private boolean isInArmorSlot(@Nonnull int index) { + return (index >= ARMOR_START && index <= ARMOR_END); + } + + /** + * Checks to see if the given integer is equal to the infinity booster card + * slot index value + * + * @param index + * @return true/false + * @author p455w0rd + */ + private boolean isInBoosterSlot(@Nonnull int index) { + return (index == BOOSTER_INDEX); + } + + /** + * Checks to see if the given integer is equal to the crafting result slot + * index value + * + * @param index + * @return true/false + * @author p455w0rd + */ + private boolean isCraftResult(@Nonnull int index) { + return (index == CRAFT_RESULT); + } + + /** + * Checks to see if the given integer is within the range of crafting matrix + * slot index values + * + * @param index + * @return true/false + * @author p455w0rd + */ + private boolean isInCraftMatrix(@Nonnull int index) { + return (index >= CRAFT_GRID_START && index <= CRAFT_GRID_END); + } + + /** + * Checks if the ItemStack is an armor item or an Infinity Booster Card + * + * @param is + * @return + * @author p455w0rd + */ + private boolean notArmorOrBooster(ItemStack is) { + if ((is.getItem() instanceof ItemInfinityBooster) || (is.getItem() instanceof ItemArmor)) { + return false; + } else { + return true; + } + } + + /** + * Prevents player from moving item used to open the container + */ + + @Override + public ItemStack slotClick(int slot, int button, int flag, EntityPlayer player) { + if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack() == RandomUtils.getWirelessTerm(player.inventory)) { + return null; + } + return super.slotClick(slot, button, flag, player); + } + + public final void updateFullProgressBar( final int idx, final long value ) + { + if( this.syncData.containsKey( idx ) ) + { + this.syncData.get( idx ).update( value ); + return; + } + + this.updateProgressBar( idx, (int) value ); + } + + /** + * Handles shift-clicking of items whose maxStackSize is 1 + */ + + @Override + protected boolean mergeItemStack(ItemStack stack, int start, int end, boolean backwards) { + boolean flag1 = false; + int k = (backwards ? end - 1 : start); + Slot slot; + ItemStack itemstack1; + + if (stack.isStackable()) { + while (stack.stackSize > 0 && (!backwards && k < end || backwards && k >= start)) { + slot = (Slot) inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if (!slot.isItemValid(stack)) { + k += (backwards ? -1 : 1); + continue; + } + + if (itemstack1 != null && itemstack1.getItem() == stack.getItem() + && (!stack.getHasSubtypes() || stack.getItemDamage() == itemstack1.getItemDamage()) + && ItemStack.areItemStackTagsEqual(stack, itemstack1)) { + int l = itemstack1.stackSize + stack.stackSize; + + if (l <= stack.getMaxStackSize() && l <= slot.getSlotStackLimit()) { + stack.stackSize = 0; + itemstack1.stackSize = l; + boosterInventory.markDirty(); + flag1 = true; + } else if (itemstack1.stackSize < stack.getMaxStackSize() && l < slot.getSlotStackLimit()) { + stack.stackSize -= stack.getMaxStackSize() - itemstack1.stackSize; + itemstack1.stackSize = stack.getMaxStackSize(); + boosterInventory.markDirty(); + flag1 = true; + } + } + + k += (backwards ? -1 : 1); + } + } + if (stack.stackSize > 0) { + k = (backwards ? end - 1 : start); + while (!backwards && k < end || backwards && k >= start) { + slot = (Slot) inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if (!slot.isItemValid(stack)) { + k += (backwards ? -1 : 1); + continue; + } + + if (itemstack1 == null) { + int l = stack.stackSize; + if (l <= slot.getSlotStackLimit()) { + slot.putStack(stack.copy()); + stack.stackSize = 0; + boosterInventory.markDirty(); + flag1 = true; + break; + } else { + putStackInSlot(k, + new ItemStack(stack.getItem(), slot.getSlotStackLimit(), stack.getItemDamage())); + stack.stackSize -= slot.getSlotStackLimit(); + boosterInventory.markDirty(); + flag1 = true; + } + } + + k += (backwards ? -1 : 1); + } + } + + return flag1; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/CraftingCPURecord.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/CraftingCPURecord.java new file mode 100644 index 0000000..2285751 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/CraftingCPURecord.java @@ -0,0 +1,55 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container; + +import javax.annotation.Nonnull; + +import appeng.api.networking.crafting.ICraftingCPU; +import appeng.util.ItemSorters; + + +public class CraftingCPURecord implements Comparable +{ + + private final String myName; + private final ICraftingCPU cpu; + private final long size; + private final int processors; + + public CraftingCPURecord( final long size, final int coProcessors, final ICraftingCPU server ) + { + this.size = size; + this.processors = coProcessors; + this.cpu = server; + this.myName = server.getName(); + } + + @Override + public int compareTo( @Nonnull final CraftingCPURecord o ) + { + final int a = ItemSorters.compareLong( o.getProcessors(), this.getProcessors() ); + if( a != 0 ) + { + return a; + } + return ItemSorters.compareLong( o.getSize(), this.getSize() ); + } + + ICraftingCPU getCpu() + { + return this.cpu; + } + + String getName() + { + return this.myName; + } + + int getProcessors() + { + return this.processors; + } + + long getSize() + { + return this.size; + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/guisync/GuiSync.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/guisync/GuiSync.java new file mode 100644 index 0000000..de4ca9b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/guisync/GuiSync.java @@ -0,0 +1,19 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.guisync; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +/** + * Annotates that this field should be synchronized between the server and client. + * Requires the field to be public. + */ +@Retention( RetentionPolicy.RUNTIME ) +@Target( ElementType.FIELD ) +public @interface GuiSync +{ + + int value(); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/guisync/SyncData.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/guisync/SyncData.java new file mode 100644 index 0000000..3fcbf2b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/guisync/SyncData.java @@ -0,0 +1,202 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.guisync; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.EnumSet; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ICrafting; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketProgressBar; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; + +public class SyncData +{ + private final Container source; + private final Field field; + private final int channel; + private Object clientVersion; + + public SyncData( final Container container, final Field field, final GuiSync annotation ) + { + if (container instanceof ContainerWirelessCraftingTerminal) { + this.source = (ContainerWirelessCraftingTerminal) container; + } + else if (container instanceof AEBaseContainer) { + this.source = (AEBaseContainer) container; + } + else { + this.source = container; + } + this.clientVersion = null; + this.field = field; + this.channel = annotation.value(); + } + + public int getChannel() + { + return this.channel; + } + + public void tick( final ICrafting c ) + { + try + { + final Object val = this.field.get( this.source ); + if( val != null && this.clientVersion == null ) + { + this.send( c, val ); + } + else if( !val.equals( this.clientVersion ) ) + { + this.send( c, val ); + } + } + catch( final IllegalArgumentException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalAccessException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + + private void send( final ICrafting o, final Object val ) throws IOException + { + if( val instanceof String ) + { + if( o instanceof EntityPlayerMP ) + { + NetworkHandler.instance.sendTo( new PacketValueConfig( "SyncDat." + this.channel, (String) val ), (EntityPlayerMP) o ); + } + } + else if( this.field.getType().isEnum() ) + { + o.sendProgressBarUpdate( this.source, this.channel, ( (Enum) val ).ordinal() ); + } + else if( val instanceof Long || val.getClass() == long.class ) + { + //NetworkHandler.instance.sendTo( new PacketProgressBar( this.channel, (Long) val ), (EntityPlayerMP) o ); + } + else if( val instanceof Boolean || val.getClass() == boolean.class ) + { + o.sendProgressBarUpdate( this.source, this.channel, ( (Boolean) val ) ? 1 : 0 ); + } + else + { + o.sendProgressBarUpdate( this.source, this.channel, (Integer) val ); + } + + this.clientVersion = val; + } + + public void update( final Object val ) + { + try + { + final Object oldValue = this.field.get( this.source ); + if( val instanceof String ) + { + this.updateString( oldValue, (String) val ); + } + else + { + this.updateValue( oldValue, (Long) val ); + } + } + catch( final IllegalArgumentException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalAccessException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + + private void updateString( final Object oldValue, final String val ) + { + try + { + this.field.set( this.source, val ); + } + catch( final IllegalArgumentException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalAccessException e ) + { + WCTLog.debug( e.getMessage() ); + } + } + + private void updateValue( final Object oldValue, final long val ) + { + try + { + if( this.field.getType().isEnum() ) + { + final EnumSet valList = EnumSet.allOf( (Class) this.field.getType() ); + for( final Enum e : valList ) + { + if( e.ordinal() == val ) + { + this.field.set( this.source, e ); + break; + } + } + } + else + { + if( this.field.getType().equals( int.class ) ) + { + this.field.set( this.source, (int) val ); + } + else if( this.field.getType().equals( long.class ) ) + { + this.field.set( this.source, val ); + } + else if( this.field.getType().equals( boolean.class ) ) + { + this.field.set( this.source, val == 1 ); + } + else if( this.field.getType().equals( Integer.class ) ) + { + this.field.set( this.source, (int) val ); + } + else if( this.field.getType().equals( Long.class ) ) + { + this.field.set( this.source, val ); + } + else if( this.field.getType().equals( Boolean.class ) ) + { + this.field.set( this.source, val == 1 ); + } + } + + if (this.source instanceof ContainerWirelessCraftingTerminal) { + ((ContainerWirelessCraftingTerminal) this.source).onUpdate( this.field.getName(), oldValue, this.field.get( this.source ) ); + } + if (this.source instanceof AEBaseContainer) { + ((AEBaseContainer) this.source).onUpdate( this.field.getName(), oldValue, this.field.get( this.source ) ); + } + } + catch( final IllegalArgumentException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalAccessException e ) + { + WCTLog.debug( e.getMessage() ); + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/AppEngCraftingSlot.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/AppEngCraftingSlot.java new file mode 100644 index 0000000..6f0b88b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/AppEngCraftingSlot.java @@ -0,0 +1,179 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemHoe; +import net.minecraft.item.ItemPickaxe; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemSword; +import net.minecraft.item.ItemTool; +import net.minecraft.stats.AchievementList; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; + +import cpw.mods.fml.common.FMLCommonHandler; + + +public class AppEngCraftingSlot extends AppEngSlot +{ + + /** + * The craft matrix inventory linked to this result slot. + */ + private final IInventory craftMatrix; + + /** + * The player that is using the GUI where this slot resides. + */ + private final EntityPlayer thePlayer; + + /** + * The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. + */ + private int amountCrafted; + + public AppEngCraftingSlot( final EntityPlayer par1EntityPlayer, final IInventory par2IInventory, final IInventory par3IInventory, final int par4, final int par5, final int par6 ) + { + super( par3IInventory, par4, par5, par6 ); + this.thePlayer = par1EntityPlayer; + this.craftMatrix = par2IInventory; + } + + /** + * Check if the stack is a valid item for this slot. Always true beside for the armor slots. + */ + @Override + public boolean isItemValid( final ItemStack par1ItemStack ) + { + return false; + } + + /** + * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an + * internal count then calls onCrafting(item). + */ + @Override + protected void onCrafting( final ItemStack par1ItemStack, final int par2 ) + { + this.amountCrafted += par2; + this.onCrafting( par1ItemStack ); + } + + /** + * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. + */ + @Override + protected void onCrafting( final ItemStack par1ItemStack ) + { + par1ItemStack.onCrafting( this.thePlayer.worldObj, this.thePlayer, this.amountCrafted ); + this.amountCrafted = 0; + + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.crafting_table ) ) + { + this.thePlayer.addStat( AchievementList.buildWorkBench, 1 ); + } + + if( par1ItemStack.getItem() instanceof ItemPickaxe ) + { + this.thePlayer.addStat( AchievementList.buildPickaxe, 1 ); + } + + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.furnace ) ) + { + this.thePlayer.addStat( AchievementList.buildFurnace, 1 ); + } + + if( par1ItemStack.getItem() instanceof ItemHoe ) + { + this.thePlayer.addStat( AchievementList.buildHoe, 1 ); + } + + if( par1ItemStack.getItem() == Items.bread ) + { + this.thePlayer.addStat( AchievementList.makeBread, 1 ); + } + + if( par1ItemStack.getItem() == Items.cake ) + { + this.thePlayer.addStat( AchievementList.bakeCake, 1 ); + } + + if( par1ItemStack.getItem() instanceof ItemPickaxe && ( (ItemTool) par1ItemStack.getItem() ).func_150913_i() != Item.ToolMaterial.WOOD ) + { + this.thePlayer.addStat( AchievementList.buildBetterPickaxe, 1 ); + } + + if( par1ItemStack.getItem() instanceof ItemSword ) + { + this.thePlayer.addStat( AchievementList.buildSword, 1 ); + } + + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.enchanting_table ) ) + { + this.thePlayer.addStat( AchievementList.enchantments, 1 ); + } + + if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.bookshelf ) ) + { + this.thePlayer.addStat( AchievementList.bookcase, 1 ); + } + } + + @Override + public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) + { + FMLCommonHandler.instance().firePlayerCraftingEvent( par1EntityPlayer, par2ItemStack, this.craftMatrix ); + this.onCrafting( par2ItemStack ); + + for( int i = 0; i < this.craftMatrix.getSizeInventory(); ++i ) + { + final ItemStack itemstack1 = this.craftMatrix.getStackInSlot( i ); + + if( itemstack1 != null ) + { + this.craftMatrix.decrStackSize( i, 1 ); + + if( itemstack1.getItem().hasContainerItem( itemstack1 ) ) + { + final ItemStack itemstack2 = itemstack1.getItem().getContainerItem( itemstack1 ); + + if( itemstack2 != null && itemstack2.isItemStackDamageable() && itemstack2.getItemDamage() > itemstack2.getMaxDamage() ) + { + MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( this.thePlayer, itemstack2 ) ); + continue; + } + + if( !itemstack1.getItem().doesContainerItemLeaveCraftingGrid( itemstack1 ) || !this.thePlayer.inventory.addItemStackToInventory( itemstack2 ) ) + { + if( this.craftMatrix.getStackInSlot( i ) == null ) + { + this.craftMatrix.setInventorySlotContents( i, itemstack2 ); + } + else + { + this.thePlayer.dropPlayerItemWithRandomChoice( itemstack2, false ); + } + } + } + } + } + } + + /** + * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new + * stack. + */ + @Override + public ItemStack decrStackSize( final int par1 ) + { + if( this.getHasStack() ) + { + this.amountCrafted += Math.min( par1, this.getStack().stackSize ); + } + + return super.decrStackSize( par1 ); + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/AppEngSlot.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/AppEngSlot.java new file mode 100644 index 0000000..802ce3d --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/AppEngSlot.java @@ -0,0 +1,254 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import appeng.tile.inventory.AppEngInternalInventory; + + +public class AppEngSlot extends Slot +{ + + private final int defX; + private final int defY; + private boolean isDraggable = true; + private boolean isPlayerSide = false; + private Container myContainer = null; + private int IIcon = -1; + private hasCalculatedValidness isValid; + private boolean isDisplay = false; + + public AppEngSlot( final IInventory inv, final int idx, final int x, final int y ) + { + super( inv, idx, x, y ); + this.defX = x; + this.defY = y; + this.setIsValid( hasCalculatedValidness.NotAvailable ); + } + + public Slot setNotDraggable() + { + this.setDraggable( false ); + return this; + } + + public Slot setPlayerSide() + { + this.isPlayerSide = true; + return this; + } + + public String getTooltip() + { + return null; + } + + public void clearStack() + { + super.putStack( null ); + } + + @Override + public boolean isItemValid( final ItemStack par1ItemStack ) + { + if( this.isEnabled() ) + { + return super.isItemValid( par1ItemStack ); + } + return false; + } + + @Override + public ItemStack getStack() + { + if( !this.isEnabled() ) + { + return null; + } + + if( this.inventory.getSizeInventory() <= this.getSlotIndex() ) + { + return null; + } + + if( this.isDisplay() ) + { + this.setDisplay( false ); + return this.getDisplayStack(); + } + return super.getStack(); + } + + @Override + public void putStack( final ItemStack par1ItemStack ) + { + if( this.isEnabled() ) + { + super.putStack( par1ItemStack ); + + if( this.getContainer() != null ) + { + if (this.getContainer() instanceof ContainerWirelessCraftingTerminal) { + ((ContainerWirelessCraftingTerminal) this.getContainer()).onSlotChange( this ); + } + if (this.getContainer() instanceof AEBaseContainer) { + ((AEBaseContainer) this.getContainer()).onSlotChange( this ); + } + } + } + } + + @Override + public void onSlotChanged() + { + if( this.inventory instanceof AppEngInternalInventory ) + { + ( (AppEngInternalInventory) this.inventory ).markDirty( this.getSlotIndex() ); + } + else + { + super.onSlotChanged(); + } + + this.setIsValid( hasCalculatedValidness.NotAvailable ); + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + if( this.isEnabled() ) + { + return super.canTakeStack( par1EntityPlayer ); + } + return false; + } + + @Override + public boolean func_111238_b() + { + return this.isEnabled(); + } + + public ItemStack getDisplayStack() + { + return super.getStack(); + } + + public boolean isEnabled() + { + return true; + } + + public float getOpacityOfIcon() + { + return 0.4f; + } + + public boolean renderIconWithItem() + { + return false; + } + + public int getIcon() + { + return this.getIIcon(); + } + + public boolean isPlayerSide() + { + return this.isPlayerSide; + } + + public boolean shouldDisplay() + { + return this.isEnabled(); + } + + public int getX() + { + return this.defX; + } + + public int getY() + { + return this.defY; + } + + private int getIIcon() + { + return this.IIcon; + } + + public void setIIcon( final int iIcon ) + { + this.IIcon = iIcon; + } + + private boolean isDisplay() + { + return this.isDisplay; + } + + public void setDisplay( final boolean isDisplay ) + { + this.isDisplay = isDisplay; + } + + public boolean isDraggable() + { + return this.isDraggable; + } + + private void setDraggable( final boolean isDraggable ) + { + this.isDraggable = isDraggable; + } + + void setPlayerSide( final boolean isPlayerSide ) + { + this.isPlayerSide = isPlayerSide; + } + + public hasCalculatedValidness getIsValid() + { + return this.isValid; + } + + public void setIsValid( final hasCalculatedValidness isValid ) + { + this.isValid = isValid; + } + + Container getContainer() + { + if (this.myContainer instanceof ContainerWirelessCraftingTerminal) { + return (ContainerWirelessCraftingTerminal) this.myContainer; + } + if (this.myContainer instanceof AEBaseContainer) { + return (AEBaseContainer) this.myContainer; + } + return this.myContainer; + } + + public void setContainer( final Container myContainer ) + { + if (this.myContainer instanceof ContainerWirelessCraftingTerminal) { + this.myContainer = (ContainerWirelessCraftingTerminal) myContainer; + } + else if (this.myContainer instanceof AEBaseContainer) { + this.myContainer = (AEBaseContainer) myContainer; + } + else { + this.myContainer = myContainer; + } + } + + public enum hasCalculatedValidness + { + NotAvailable, Valid, Invalid + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/IOptionalSlotHost.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/IOptionalSlotHost.java new file mode 100644 index 0000000..094f14f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/IOptionalSlotHost.java @@ -0,0 +1,7 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +public interface IOptionalSlotHost +{ + + boolean isSlotEnabled( int idx ); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/NullSlot.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/NullSlot.java new file mode 100644 index 0000000..1220a30 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/NullSlot.java @@ -0,0 +1,82 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + + +public class NullSlot extends AppEngSlot +{ + + public NullSlot() + { + super( null, 0, 0, 0 ); + } + + @Override + public void onSlotChange( final ItemStack par1ItemStack, final ItemStack par2ItemStack ) + { + + } + + @Override + public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) + { + + } + + @Override + public boolean isItemValid( final ItemStack par1ItemStack ) + { + return false; + } + + @Override + public ItemStack getStack() + { + return null; + } + + @Override + public void putStack( final ItemStack par1ItemStack ) + { + + } + + @Override + public void onSlotChanged() + { + + } + + @Override + public int getSlotStackLimit() + { + return 0; + } + + @Override + public ItemStack decrStackSize( final int par1 ) + { + return null; + } + + @Override + public boolean isSlotInInventory( final IInventory par1IInventory, final int par2 ) + { + return false; + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + return false; + } + + @Override + public int getSlotIndex() + { + return 0; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/OptionalSlotFake.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/OptionalSlotFake.java new file mode 100644 index 0000000..3e43be4 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/OptionalSlotFake.java @@ -0,0 +1,74 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + + +public class OptionalSlotFake extends SlotFake +{ + + private final int srcX; + private final int srcY; + private final int groupNum; + private final IOptionalSlotHost host; + private boolean renderDisabled = true; + + public OptionalSlotFake( final IInventory inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) + { + super( inv, idx, x + offX * 18, y + offY * 18 ); + this.srcX = x; + this.srcY = y; + this.groupNum = groupNum; + this.host = containerBus; + } + + @Override + public ItemStack getStack() + { + if( !this.isEnabled() ) + { + if( this.getDisplayStack() != null ) + { + this.clearStack(); + } + } + + return super.getStack(); + } + + @Override + public boolean isEnabled() + { + if( this.host == null ) + { + return false; + } + + return this.host.isSlotEnabled( this.groupNum ); + } + + public boolean renderDisabled() + { + return this.isRenderDisabled(); + } + + private boolean isRenderDisabled() + { + return this.renderDisabled; + } + + public void setRenderDisabled( final boolean renderDisabled ) + { + this.renderDisabled = renderDisabled; + } + + public int getSourceX() + { + return this.srcX; + } + + public int getSourceY() + { + return this.srcY; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotArmor.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotArmor.java new file mode 100644 index 0000000..1fe35b1 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotArmor.java @@ -0,0 +1,66 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.Item; +import net.minecraft.item.ItemArmor; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; + +public class SlotArmor extends AppEngSlot { + + /* + * The armor type that can be placed on that slot, it uses the same values + * of armorType field on ItemArmor. Probably could've done just as well + * with vanilla armor slot class. if so, this will be removed in the future. + */ + final int armorType; + + final EntityPlayer player; + + /** + * Custom armor slot + * + * @param player + * @param inventory + * @param slot + * @param x + * @param y + * @param armorType + */ + public SlotArmor(EntityPlayer player, IInventory inventory, int slot, int x, int y, int armorType) { + super(inventory, slot, x, y); + this.player = player; + this.armorType = armorType; + } + + @Override + public int getSlotStackLimit() { + return 1; + } + + /** + * Checks to see if the item being put into the slot is a valid armor type + * + * @param stack + */ + @Override + public boolean isItemValid(ItemStack stack) { + Item item = (stack == null ? null : stack.getItem()); + return item != null && item.isValidArmor(stack, armorType, player); + } + + /** + * Sets the icon of the slot when no armor item is present + */ + @Override + @SideOnly(Side.CLIENT) + public IIcon getBackgroundIconIndex() + { + return ItemArmor.func_94602_b( this.armorType ); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotBooster.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotBooster.java new file mode 100644 index 0000000..fbb04fe --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotBooster.java @@ -0,0 +1,57 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.p455w0rd.wirelesscraftingterminal.items.ItemBoosterBGIcon; +import net.p455w0rd.wirelesscraftingterminal.items.ItemInfinityBooster; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.Minecraft; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; + +public class SlotBooster extends AppEngSlot +{ + + /** + * Custom slot for infinity booster card + * + * @param inv + * @param index + * @param xPos + * @param yPos + */ + public SlotBooster(IInventory inv, int index, int xPos, int yPos) + { + super(inv, index, xPos, yPos); + if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) { + this.backgroundIcon = ItemBoosterBGIcon.getIcon(); + } + } + + @SideOnly(Side.CLIENT) + @Override + public IIcon getBackgroundIconIndex() { + return this.backgroundIcon; + } + + /** + * Ensures only the infinity booster card can be placed in the custom slot + * + * @param is + */ + @Override + public boolean isItemValid(ItemStack is) + { + if (is != null) { + if (is.getItem() instanceof ItemInfinityBooster) + { + return true; + } + } + // Everything returns false except an instance of our Item + return false; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotCraftingMatrix.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotCraftingMatrix.java new file mode 100644 index 0000000..c4ce3b4 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotCraftingMatrix.java @@ -0,0 +1,46 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + + +public class SlotCraftingMatrix extends AppEngSlot +{ + + private final Container c; + + public SlotCraftingMatrix( final Container c, final IInventory par1iInventory, final int par2, final int par3, final int par4 ) + { + super( par1iInventory, par2, par3, par4 ); + this.c = c; + } + + @Override + public void clearStack() + { + super.clearStack(); + this.c.onCraftMatrixChanged( this.inventory ); + } + + @Override + public void putStack( final ItemStack par1ItemStack ) + { + super.putStack( par1ItemStack ); + this.c.onCraftMatrixChanged( this.inventory ); + } + + @Override + public boolean isPlayerSide() + { + return true; + } + + @Override + public ItemStack decrStackSize( final int par1 ) + { + final ItemStack is = super.decrStackSize( par1 ); + this.c.onCraftMatrixChanged( this.inventory ); + return is; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotCraftingTerm.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotCraftingTerm.java new file mode 100644 index 0000000..6f669d6 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotCraftingTerm.java @@ -0,0 +1,263 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; + +import appeng.api.config.Actionable; +import appeng.api.networking.energy.IEnergySource; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.IStorageMonitorable; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.container.ContainerNull; +import appeng.helpers.IContainerCraftingPacket; +import appeng.helpers.InventoryAction; +import appeng.items.storage.ItemViewCell; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; +import appeng.util.inv.AdaptorPlayerHand; +import appeng.util.item.AEItemStack; +import appeng.util.prioitylist.IPartitionList; + + +public class SlotCraftingTerm extends AppEngCraftingSlot +{ + + private final IInventory craftInv; + private final IInventory pattern; + + private final BaseActionSource mySrc; + private final IEnergySource energySrc; + private final IStorageMonitorable storage; + private final IContainerCraftingPacket container; + + public SlotCraftingTerm( final EntityPlayer player, final BaseActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IInventory cMatrix, final IInventory secondMatrix, final IInventory output, final int x, final int y, final IContainerCraftingPacket ccp ) + { + super( player, cMatrix, output, 0, x, y ); + this.energySrc = energySrc; + this.storage = storage; + this.mySrc = mySrc; + this.pattern = cMatrix; + this.craftInv = secondMatrix; + this.container = ccp; + } + + public IInventory getCraftingMatrix() + { + return this.craftInv; + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + return false; + } + + @Override + public void onPickupFromSlot( final EntityPlayer p, final ItemStack is ) + { + } + + public void doClick( final InventoryAction action, final EntityPlayer who ) + { + if( this.getStack() == null ) + { + return; + } + if( Platform.isClient() ) + { + return; + } + + final IMEMonitor inv = this.storage.getItemInventory(); + final int howManyPerCraft = this.getStack().stackSize; + int maxTimesToCraft = 0; + + InventoryAdaptor ia = null; + if( action == InventoryAction.CRAFT_SHIFT ) // craft into player inventory... + { + ia = InventoryAdaptor.getAdaptor( who, null ); + maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); + } + else if( action == InventoryAction.CRAFT_STACK ) // craft into hand, full stack + { + ia = new AdaptorPlayerHand( who ); + maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); + } + else + // pick up what was crafted... + { + ia = new AdaptorPlayerHand( who ); + maxTimesToCraft = 1; + } + + maxTimesToCraft = this.capCraftingAttempts( maxTimesToCraft ); + + if( ia == null ) + { + return; + } + + final ItemStack rs = Platform.cloneItemStack( this.getStack() ); + if( rs == null ) + { + return; + } + + for( int x = 0; x < maxTimesToCraft; x++ ) + { + if( ia.simulateAdd( rs ) == null ) + { + final IItemList all = inv.getStorageList(); + final ItemStack extra = ia.addItems( this.craftItem( who, rs, inv, all ) ); + if( extra != null ) + { + final List drops = new ArrayList(); + drops.add( extra ); + Platform.spawnDrops( who.worldObj, (int) who.posX, (int) who.posY, (int) who.posZ, drops ); + return; + } + } + } + } + + private int capCraftingAttempts( final int maxTimesToCraft ) + { + return maxTimesToCraft; + } + + private ItemStack craftItem( final EntityPlayer p, final ItemStack request, final IMEMonitor inv, final IItemList all ) + { + // update crafting matrix... + ItemStack is = this.getStack(); + + if( is != null && Platform.isSameItem( request, is ) ) + { + final ItemStack[] set = new ItemStack[this.getPattern().getSizeInventory()]; + + // add one of each item to the items on the board... + if( Platform.isServer() ) + { + final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); + for( int x = 0; x < 9; x++ ) + { + ic.setInventorySlotContents( x, this.getPattern().getStackInSlot( x ) ); + } + + final IRecipe r = Platform.findMatchingRecipe( ic, p.worldObj ); + + if( r == null ) + { + final Item target = request.getItem(); + if( target.isDamageable() && target.isRepairable() ) + { + boolean isBad = false; + for( int x = 0; x < ic.getSizeInventory(); x++ ) + { + final ItemStack pis = ic.getStackInSlot( x ); + if( pis == null ) + { + continue; + } + if( pis.getItem() != target ) + { + isBad = true; + } + } + if( !isBad ) + { + super.onPickupFromSlot( p, is ); + // actually necessary to cleanup this case... + p.openContainer.onCraftMatrixChanged( this.craftInv ); + return request; + } + } + return null; + } + + is = r.getCraftingResult( ic ); + + if( inv != null ) + { + for( int x = 0; x < this.getPattern().getSizeInventory(); x++ ) + { + if( this.getPattern().getStackInSlot( x ) != null ) + { + set[x] = Platform.extractItemsByRecipe( this.energySrc, this.mySrc, inv, p.worldObj, r, is, ic, this.getPattern().getStackInSlot( x ), x, all, Actionable.MODULATE, null ); + ic.setInventorySlotContents( x, set[x] ); + } + } + } + } + + if( this.preCraft( p, inv, set, is ) ) + { + this.makeItem( p, is ); + + this.postCraft( p, inv, set, is ); + } + + // shouldn't be necessary... + p.openContainer.onCraftMatrixChanged( this.craftInv ); + + return is; + } + + return null; + } + + private boolean preCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) + { + return true; + } + + private void makeItem( final EntityPlayer p, final ItemStack is ) + { + super.onPickupFromSlot( p, is ); + } + + private void postCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) + { + final List drops = new ArrayList(); + + // add one of each item to the items on the board... + if( Platform.isServer() ) + { + // set new items onto the crafting table... + for( int x = 0; x < this.craftInv.getSizeInventory(); x++ ) + { + if( this.craftInv.getStackInSlot( x ) == null ) + { + this.craftInv.setInventorySlotContents( x, set[x] ); + } + else if( set[x] != null ) + { + // eek! put it back! + final IAEItemStack fail = inv.injectItems( AEItemStack.create( set[x] ), Actionable.MODULATE, this.mySrc ); + if( fail != null ) + { + drops.add( fail.getItemStack() ); + } + } + } + } + + if( drops.size() > 0 ) + { + Platform.spawnDrops( p.worldObj, (int) p.posX, (int) p.posY, (int) p.posZ, drops ); + } + } + + IInventory getPattern() + { + return this.pattern; + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotDisabled.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotDisabled.java new file mode 100644 index 0000000..1fb8614 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotDisabled.java @@ -0,0 +1,27 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + + +public class SlotDisabled extends AppEngSlot +{ + + public SlotDisabled( final IInventory par1iInventory, final int slotIndex, final int x, final int y ) + { + super( par1iInventory, slotIndex, x, y ); + } + + @Override + public boolean isItemValid( final ItemStack par1ItemStack ) + { + return false; + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + return false; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotFake.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotFake.java new file mode 100644 index 0000000..3b34f27 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotFake.java @@ -0,0 +1,49 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + + +public class SlotFake extends AppEngSlot +{ + + public SlotFake( final IInventory inv, final int idx, final int x, final int y ) + { + super( inv, idx, x, y ); + } + + @Override + public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) + { + } + + @Override + public ItemStack decrStackSize( final int par1 ) + { + return null; + } + + @Override + public boolean isItemValid( final ItemStack par1ItemStack ) + { + return false; + } + + @Override + public void putStack( ItemStack is ) + { + if( is != null ) + { + is = is.copy(); + } + + super.putStack( is ); + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + return false; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotFakeCraftingMatrix.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotFakeCraftingMatrix.java new file mode 100644 index 0000000..6cac086 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotFakeCraftingMatrix.java @@ -0,0 +1,13 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.inventory.IInventory; + + +public class SlotFakeCraftingMatrix extends SlotFake +{ + + public SlotFakeCraftingMatrix( final IInventory inv, final int idx, final int x, final int y ) + { + super( inv, idx, x, y ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotInaccessible.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotInaccessible.java new file mode 100644 index 0000000..913938e --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotInaccessible.java @@ -0,0 +1,50 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + + +public class SlotInaccessible extends AppEngSlot +{ + + private ItemStack dspStack = null; + + public SlotInaccessible( final IInventory i, final int slotIdx, final int x, final int y ) + { + super( i, slotIdx, x, y ); + } + + @Override + public boolean isItemValid( final ItemStack i ) + { + return false; + } + + @Override + public void onSlotChanged() + { + super.onSlotChanged(); + this.dspStack = null; + } + + @Override + public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) + { + return false; + } + + @Override + public ItemStack getDisplayStack() + { + if( this.dspStack == null ) + { + final ItemStack dsp = super.getDisplayStack(); + if( dsp != null ) + { + this.dspStack = dsp.copy(); + } + } + return this.dspStack; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotMagnet.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotMagnet.java new file mode 100644 index 0000000..e5e86f4 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotMagnet.java @@ -0,0 +1,40 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.Entity; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.items.ItemMagnet; + +public class SlotMagnet extends AppEngSlot +{ + + /** + * Custom slot for magnet card + * + * @param inv + * @param index + * @param xPos + * @param yPos + */ + public SlotMagnet(IInventory inv, int xPos, int yPos) + { + super(inv, 0, xPos, yPos); + } + + /** + * Ensures only the infinity booster card can be placed in the custom slot + * + * @param is + */ + @Override + public boolean isItemValid(ItemStack is) + { + // Everything returns false except an instance of our Item + return ((is != null) && (is.getItem() instanceof ItemMagnet)); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotMagnetFilter.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotMagnetFilter.java new file mode 100644 index 0000000..4866dcc --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotMagnetFilter.java @@ -0,0 +1,75 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +public class SlotMagnetFilter extends Slot { + + private boolean isPhantom; + private boolean canAdjustPhantom = true; + private boolean canShift = true; + private int stackLimit; + + public SlotMagnetFilter(IInventory inventory, int slotIndex, int xPos, int yPos) { + super(inventory, slotIndex, xPos, yPos); + if (inventory == null) { + throw new IllegalArgumentException("Inventory must not be null"); + } + this.stackLimit = -1; + } + + public SlotMagnetFilter setPhantom() { + isPhantom = true; + return this; + } + + public SlotMagnetFilter blockShift() { + canShift = false; + return this; + } + + @Override + public void putStack(ItemStack itemStack) { + if (!isPhantom() || canAdjustPhantom()) { + super.putStack(itemStack); + } + } + + public SlotMagnetFilter setCanAdjustPhantom(boolean canAdjust) { + this.canAdjustPhantom = canAdjust; + return this; + } + + public SlotMagnetFilter setStackLimit(int limit) { + this.stackLimit = limit; + return this; + } + + public boolean isPhantom() { + return this.isPhantom; + } + + public boolean canAdjustPhantom() { + return canAdjustPhantom; + } + + @Override + public boolean canTakeStack(EntityPlayer stack) { + return !isPhantom(); + } + + public boolean canShift() { + return canShift; + } + + @Override + public int getSlotStackLimit() { + if (stackLimit < 0) { + return super.getSlotStackLimit(); + } else { + return stackLimit; + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotOutput.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotOutput.java new file mode 100644 index 0000000..9d7cc6b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotOutput.java @@ -0,0 +1,21 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + + +public class SlotOutput extends AppEngSlot +{ + + public SlotOutput( final IInventory a, final int b, final int c, final int d, final int i ) + { + super( a, b, c, d ); + this.setIIcon( i ); + } + + @Override + public boolean isItemValid( final ItemStack i ) + { + return false; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotPlayerHotBar.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotPlayerHotBar.java new file mode 100644 index 0000000..0e6f5db --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotPlayerHotBar.java @@ -0,0 +1,13 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.inventory.IInventory; + +public class SlotPlayerHotBar extends AppEngSlot +{ + + public SlotPlayerHotBar( final IInventory par1iInventory, final int par2, final int par3, final int par4 ) + { + super( par1iInventory, par2, par3, par4 ); + this.setPlayerSide( true ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotPlayerInv.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotPlayerInv.java new file mode 100644 index 0000000..2038afa --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotPlayerInv.java @@ -0,0 +1,17 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.inventory.IInventory; + + +//there is nothing special about this slot, its simply used to represent the players inventory, vs a container slot. + +public class SlotPlayerInv extends AppEngSlot +{ + + public SlotPlayerInv( final IInventory par1iInventory, final int par2, final int par3, final int par4 ) + { + super( par1iInventory, par2, par3, par4 ); + + this.setPlayerSide( true ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotTrash.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotTrash.java new file mode 100644 index 0000000..b0fe510 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/container/slot/SlotTrash.java @@ -0,0 +1,114 @@ +package net.p455w0rd.wirelesscraftingterminal.common.container.slot; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + +public class SlotTrash extends AppEngSlot { + + private final EntityPlayer entityPlayer; + private ItemStack itemStack; + private boolean shouldDeleteMouseStack; + private String name = "TrashSlot"; + + public SlotTrash(IInventory inv, int x, int y, EntityPlayer player) { + super(null, 0, x, y); + entityPlayer = player; + //readNBT(); + } + + @Override + public ItemStack getStack() { + return itemStack; + } + + @Override + public boolean getHasStack() { + return itemStack != null; + } + + @Override + public void putStack(ItemStack itemStack) { + shouldDeleteMouseStack = (this.itemStack != null); + this.itemStack = itemStack; + //writeNBT(); + } + + @Override + public int getSlotStackLimit() { + return Integer.MAX_VALUE; + } + + @Override + public void onSlotChanged() { + if (itemStack != null && shouldDeleteMouseStack) { + entityPlayer.inventory.setItemStack(null); + } + } + + @Override + public boolean isItemValid(ItemStack itemStack) { + return true; + } + + @Override + public boolean canTakeStack(EntityPlayer player) { + return true; + } + + @Override + public ItemStack decrStackSize(int amount) { + if (itemStack != null) { + ItemStack returnStack; + if (itemStack.stackSize <= amount) { + returnStack = itemStack; + itemStack = null; + shouldDeleteMouseStack = true; + //writeNBT(); + return returnStack; + } else { + returnStack = itemStack.splitStack(amount); + shouldDeleteMouseStack = false; + if (itemStack.stackSize == 0) { + itemStack = null; + shouldDeleteMouseStack = true; + } + //writeNBT(); + return returnStack; + } + } + return null; + } + + public void readNBT() { + NBTTagCompound nbtTagCompound = RandomUtils.getWirelessTerm(entityPlayer.inventory).getTagCompound(); + NBTTagList tagList = nbtTagCompound.getTagList(this.name, 10); + NBTTagCompound tagCompound = tagList.getCompoundTagAt(0); + if (tagCompound != null) { + itemStack = ItemStack.loadItemStackFromNBT(tagCompound); + } + } + + public void writeNBT() { + NBTTagCompound nbtTagCompound = RandomUtils.getWirelessTerm(entityPlayer.inventory).getTagCompound(); + NBTTagList tagList = new NBTTagList(); + if (itemStack != null) { + NBTTagCompound tagCompound = new NBTTagCompound(); + itemStack.writeToNBT(tagCompound); + tagList.appendTag(tagCompound); + } + nbtTagCompound.setTag(this.name, tagList); + } + + public void clearStack() { + if (itemStack != null) { + itemStack = null; + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryBooster.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryBooster.java new file mode 100644 index 0000000..cd5d434 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryBooster.java @@ -0,0 +1,139 @@ +package net.p455w0rd.wirelesscraftingterminal.common.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; +import net.p455w0rd.wirelesscraftingterminal.items.ItemInfinityBooster; + +public class WCTInventoryBooster implements IInventory { + + private String name = "BoosterSlot"; + private final ItemStack invItem; + private ItemStack[] inventory; + + public WCTInventoryBooster(ItemStack stack) { + super(); + inventory = new ItemStack[1]; + invItem = stack; + if (stack != null) { + if (!stack.hasTagCompound()) { + stack.setTagCompound(new NBTTagCompound()); + } + readFromNBT(stack.getTagCompound()); + } + } + + @Override + public int getSizeInventory() { + return 1; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return inventory[slot]; + } + + @Override + public String getInventoryName() { + return name; + } + + @Override + public boolean hasCustomInventoryName() { + return name.length() > 0; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public ItemStack decrStackSize(int slot, int amount) { + ItemStack stack = getStackInSlot(slot); + if (stack != null) { + if (stack.stackSize > amount) { + stack = stack.splitStack(amount); + markDirty(); + } + else { + setInventorySlotContents(slot, null); + } + } + return stack; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + if (inventory[slot] != null) { + ItemStack itemStack = inventory[slot]; + inventory[slot] = null; + return itemStack; + } + else { + return null; + } + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + inventory[slot] = stack; + + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + markDirty(); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } + + @Override + public void markDirty() { + writeNBT(invItem.getTagCompound()); + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack itemstack) { + return (itemstack.getItem() instanceof ItemInfinityBooster); + } + + public void readFromNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = nbtTagCompound.getTagList(this.name, 10); + inventory = new ItemStack[this.getSizeInventory()]; + for (int i = 0; i < tagList.tagCount(); ++i) { + NBTTagCompound tagCompound = (NBTTagCompound) tagList.getCompoundTagAt(i); + int slot = tagCompound.getInteger("Slot"); + if (slot >= 0 && slot < inventory.length) { + inventory[slot] = ItemStack.loadItemStackFromNBT(tagCompound); + } + } + } + + public void writeNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = new NBTTagList(); + for (int currentIndex = 0; currentIndex < inventory.length; ++currentIndex) { + if (inventory[currentIndex] != null) { + NBTTagCompound tagCompound = new NBTTagCompound(); + tagCompound.setInteger("Slot", currentIndex); + inventory[currentIndex].writeToNBT(tagCompound); + tagList.appendTag(tagCompound); + } + } + nbtTagCompound.setTag(this.name, tagList); + } + + @Override + public void openInventory() { + } + + @Override + public void closeInventory() { + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryCraftResult.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryCraftResult.java new file mode 100644 index 0000000..1cd2555 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryCraftResult.java @@ -0,0 +1,72 @@ +package net.p455w0rd.wirelesscraftingterminal.common.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +public class WCTInventoryCraftResult implements IInventory { + + private ItemStack[] stackResult = new ItemStack[1]; + + public int getSizeInventory() { + return 1; + } + + public ItemStack getStackInSlot(int slot) { + return this.stackResult[0]; + } + + public String getInventoryName() { + return "CraftResult"; + } + + public boolean hasCustomInventoryName() { + return true; + } + + public ItemStack decrStackSize(int slot, int amount) { + if (this.stackResult[0] != null) { + ItemStack itemstack = this.stackResult[0]; + this.stackResult[0] = null; + return itemstack; + } else { + return null; + } + } + + public ItemStack getStackInSlotOnClosing(int slot) { + if (this.stackResult[0] != null) { + ItemStack itemstack = this.stackResult[0]; + this.stackResult[0] = null; + return itemstack; + } else { + return null; + } + } + + public void setInventorySlotContents(int slot, ItemStack is) { + this.stackResult[0] = is; + } + + public int getInventoryStackLimit() { + return 64; + } + + public void markDirty() { + } + + public boolean isUseableByPlayer(EntityPlayer player) { + return true; + } + + public void openInventory() { + } + + public void closeInventory() { + } + + public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) { + return true; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryCrafting.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryCrafting.java new file mode 100644 index 0000000..e5eb483 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryCrafting.java @@ -0,0 +1,207 @@ +package net.p455w0rd.wirelesscraftingterminal.common.inventory; + +import appeng.api.storage.IMEInventory; +import appeng.me.storage.MEIInventoryWrapper; +import appeng.tile.inventory.AppEngInternalInventory; +import appeng.tile.inventory.IAEAppEngInventory; +import appeng.tile.inventory.InvOperation; +import appeng.util.Platform; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + +public class WCTInventoryCrafting extends AppEngInternalInventory { + + private ItemStack[] stackList; + private int inventoryWidth; + private Container eventHandler; + private final ItemStack invItem; + private IAEAppEngInventory te; + private final int size; + private boolean enableClientEvents = false; + + public WCTInventoryCrafting(Container container, int rows, int cols, ItemStack is) { + super((IAEAppEngInventory) container, rows * cols); + size = rows * cols; + this.stackList = new ItemStack[size]; + this.eventHandler = container; + this.inventoryWidth = rows; + this.invItem = is; + this.setTileEntity((IAEAppEngInventory) container); + } + + @Override + public int getSizeInventory() { + return this.stackList.length; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return slot >= this.getSizeInventory() ? null : this.stackList[slot]; + } + + public ItemStack getStackInRowAndColumn(int row, int col) { + if (row >= 0 && row < this.inventoryWidth) { + int k = row + col * this.inventoryWidth; + return this.getStackInSlot(k); + } else { + return null; + } + } + + public String getInventoryName() { + return "crafting"; + } + + public boolean hasCustomInventoryName() { + return true; + } + + public ItemStack getStackInSlotOnClosing(int slot) { + if (this.stackList[slot] != null) { + ItemStack itemstack = this.stackList[slot]; + this.stackList[slot] = null; + return itemstack; + } else { + return null; + } + } + + @Override + public ItemStack decrStackSize(final int slot, final int qty) { + if (this.stackList[slot] != null) { + final ItemStack split = this.getStackInSlot(slot); + ItemStack ns = null; + + if (qty >= split.stackSize) { + ns = this.stackList[slot]; + this.stackList[slot] = null; + } else { + ns = split.splitStack(qty); + } + + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory(this, slot, InvOperation.decreaseStackSize, ns, null); + } + + this.markDirty(); + return ns; + } + + return null; + } + + @Override + protected boolean eventsEnabled() { + return Platform.isServer() || this.isEnableClientEvents(); + } + + private boolean isEnableClientEvents() { + return this.enableClientEvents; + } + + public void setEnableClientEvents(final boolean enableClientEvents) { + this.enableClientEvents = enableClientEvents; + } + + @Override + public boolean isEmpty() { + for (int x = 0; x < this.size; x++) { + if (this.getStackInSlot(x) != null) { + return false; + } + } + return true; + } + + @Override + public IMEInventory getMEInventory() { + return new MEIInventoryWrapper(this, null); + } + + private IAEAppEngInventory getTileEntity() { + return this.te; + } + + @Override + public void setTileEntity(final IAEAppEngInventory te) { + this.te = te; + } + + /* + * @Override public ItemStack decrStackSize(int slot, int amount) { if + * (this.stackList[slot] != null) { ItemStack itemstack; if + * (this.stackList[slot].stackSize <= amount) { itemstack = + * this.stackList[slot]; this.stackList[slot] = null; + * this.eventHandler.onCraftMatrixChanged(this); return itemstack; } else { + * itemstack = this.stackList[slot].splitStack(amount); + * + * if (this.stackList[slot].stackSize == 0) { this.stackList[slot] = null; } + * + * this.eventHandler.onCraftMatrixChanged(this); return itemstack; } } else + * { return getStackInSlot(slot); } } + */ + public void setInventorySlotContents(int slot, ItemStack stack) { + this.stackList[slot] = stack; + this.eventHandler.onCraftMatrixChanged(this); + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + markDirty(); + } + + public int getInventoryStackLimit() { + return 64; + } + + @Override + public void markDirty(final int slotIndex) { + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory(this, slotIndex, InvOperation.markDirty, null, null); + } + } + + public void markDirty() { + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory(this, -1, InvOperation.markDirty, null, null); + } + for (int i = 0; i < getSizeInventory(); ++i) { + if (getStackInSlot(i) != null && getStackInSlot(i).stackSize == 0) { + stackList[i] = null; + } + } + writeNBT(invItem.getTagCompound()); + } + + public boolean isUseableByPlayer(EntityPlayer player) { + return true; + } + + public void openInventory() { + } + + public void closeInventory() { + } + + public boolean isItemValidForSlot(int slot, ItemStack stack) { + return !(stack.getItem() instanceof ItemWirelessCraftingTerminal); + } + + public void writeNBT(NBTTagCompound nbtTagCompound) { + // Write the ItemStacks in the inventory to NBT + NBTTagList tagList = new NBTTagList(); + for (int currentIndex = 0; currentIndex < stackList.length; ++currentIndex) { + if (stackList[currentIndex] != null) { + NBTTagCompound tagCompound = new NBTTagCompound(); + tagCompound.setByte("Slot", (byte) currentIndex); + stackList[currentIndex].writeToNBT(tagCompound); + tagList.appendTag(tagCompound); + } + } + nbtTagCompound.setTag("CraftingMatrix", tagList); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryMagnet.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryMagnet.java new file mode 100644 index 0000000..23d3acd --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryMagnet.java @@ -0,0 +1,139 @@ +package net.p455w0rd.wirelesscraftingterminal.common.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; +import net.p455w0rd.wirelesscraftingterminal.items.ItemMagnet; + +public class WCTInventoryMagnet implements IInventory { + + private String name = "MagnetSlot"; + private final ItemStack invItem; + private ItemStack[] inventory; + + public WCTInventoryMagnet(ItemStack stack) { + super(); + inventory = new ItemStack[1]; + invItem = stack; + if (stack != null) { + if (!stack.hasTagCompound()) { + stack.setTagCompound(new NBTTagCompound()); + } + readFromNBT(stack.getTagCompound()); + } + } + + @Override + public int getSizeInventory() { + return 1; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return inventory[slot]; + } + + @Override + public String getInventoryName() { + return name; + } + + @Override + public boolean hasCustomInventoryName() { + return name.length() > 0; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public ItemStack decrStackSize(int slot, int amount) { + ItemStack stack = getStackInSlot(slot); + if (stack != null) { + if (stack.stackSize > amount) { + stack = stack.splitStack(amount); + markDirty(); + } + else { + setInventorySlotContents(slot, null); + } + } + return stack; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + if (inventory[slot] != null) { + ItemStack itemStack = inventory[slot]; + inventory[slot] = null; + return itemStack; + } + else { + return null; + } + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + inventory[slot] = stack; + + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + markDirty(); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } + + @Override + public void markDirty() { + writeNBT(invItem.getTagCompound()); + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack itemstack) { + return (itemstack.getItem() instanceof ItemMagnet); + } + + public void readFromNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = nbtTagCompound.getTagList(this.name, 10); + inventory = new ItemStack[this.getSizeInventory()]; + for (int i = 0; i < tagList.tagCount(); ++i) { + NBTTagCompound tagCompound = (NBTTagCompound) tagList.getCompoundTagAt(i); + int slot = tagCompound.getInteger("Slot"); + if (slot >= 0 && slot < inventory.length) { + inventory[slot] = ItemStack.loadItemStackFromNBT(tagCompound); + } + } + } + + public void writeNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = new NBTTagList(); + for (int currentIndex = 0; currentIndex < inventory.length; ++currentIndex) { + if (inventory[currentIndex] != null) { + NBTTagCompound tagCompound = new NBTTagCompound(); + tagCompound.setInteger("Slot", currentIndex); + inventory[currentIndex].writeToNBT(tagCompound); + tagList.appendTag(tagCompound); + } + } + nbtTagCompound.setTag(this.name, tagList); + } + + @Override + public void openInventory() { + } + + @Override + public void closeInventory() { + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryMagnetFilter.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryMagnetFilter.java new file mode 100644 index 0000000..6967df5 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryMagnetFilter.java @@ -0,0 +1,135 @@ +package net.p455w0rd.wirelesscraftingterminal.common.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; +import net.p455w0rd.wirelesscraftingterminal.items.ItemInfinityBooster; + +public class WCTInventoryMagnetFilter implements IInventory { + + private String name = "MagnetFilter"; + private final ItemStack invItem; + private ItemStack[] inventory; + + public WCTInventoryMagnetFilter(ItemStack stack) { + super(); + inventory = new ItemStack[27]; + invItem = stack; + if (!stack.hasTagCompound()) { + stack.setTagCompound(new NBTTagCompound()); + } + readFromNBT(stack.getTagCompound()); + } + + @Override + public int getSizeInventory() { + return 27; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return inventory[slot]; + } + + @Override + public String getInventoryName() { + return name; + } + + @Override + public boolean hasCustomInventoryName() { + return name.length() > 0; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public ItemStack decrStackSize(int slot, int amount) { + ItemStack stack = getStackInSlot(slot); + if (stack != null) { + if (stack.stackSize > amount) { + stack = stack.splitStack(amount); + markDirty(); + } else { + setInventorySlotContents(slot, null); + } + } + return stack; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + if (inventory[slot] != null) { + ItemStack itemStack = inventory[slot]; + inventory[slot] = null; + return itemStack; + } else { + return null; + } + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + inventory[slot] = stack; + + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + markDirty(); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } + + @Override + public void markDirty() { + writeNBT(invItem.getTagCompound()); + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack itemstack) { + return (itemstack.getItem() instanceof ItemInfinityBooster); + } + + public void readFromNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = nbtTagCompound.getTagList(this.name, 10); + inventory = new ItemStack[this.getSizeInventory()]; + for (int i = 0; i < tagList.tagCount(); ++i) { + NBTTagCompound tagCompound = (NBTTagCompound) tagList.getCompoundTagAt(i); + int slot = tagCompound.getInteger("Slot"); + if (slot >= 0 && slot < inventory.length) { + inventory[slot] = ItemStack.loadItemStackFromNBT(tagCompound); + } + } + } + + public void writeNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = new NBTTagList(); + for (int currentIndex = 0; currentIndex < inventory.length; ++currentIndex) { + if (inventory[currentIndex] != null) { + NBTTagCompound tagCompound = new NBTTagCompound(); + tagCompound.setInteger("Slot", currentIndex); + inventory[currentIndex].writeToNBT(tagCompound); + tagList.appendTag(tagCompound); + } + } + nbtTagCompound.setTag(this.name, tagList); + } + + @Override + public void openInventory() { + } + + @Override + public void closeInventory() { + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryTrash.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryTrash.java new file mode 100644 index 0000000..5de2a12 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/inventory/WCTInventoryTrash.java @@ -0,0 +1,138 @@ +package net.p455w0rd.wirelesscraftingterminal.common.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.Constants; + +public class WCTInventoryTrash implements IInventory { + + private String name = "TrashSlot"; + private final ItemStack invItem; + private ItemStack[] inventory; + + public WCTInventoryTrash(ItemStack stack) { + super(); + inventory = new ItemStack[1]; + invItem = stack; + if (stack != null) { + if (!invItem.hasTagCompound()) { + invItem.setTagCompound(new NBTTagCompound()); + } + readFromNBT(invItem.getTagCompound()); + } + } + + @Override + public int getSizeInventory() { + return 1; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return inventory[slot]; + } + + @Override + public String getInventoryName() { + return name; + } + + @Override + public boolean hasCustomInventoryName() { + return name.length() > 0; + } + + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public ItemStack decrStackSize(int slot, int amount) { + ItemStack stack = getStackInSlot(slot); + if (stack != null) { + if (stack.stackSize > amount) { + stack = stack.splitStack(amount); + markDirty(); + } + else { + setInventorySlotContents(slot, null); + } + } + return stack; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + if (inventory[slot] != null) { + ItemStack itemStack = inventory[slot]; + inventory[slot] = null; + return itemStack; + } + else { + return null; + } + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + inventory[slot] = stack; + + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + markDirty(); + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } + + @Override + public void markDirty() { + writeNBT(invItem.getTagCompound()); + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack itemstack) { + return true; + } + + public void readFromNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = nbtTagCompound.getTagList(this.name, 10); + inventory = new ItemStack[this.getSizeInventory()]; + for (int i = 0; i < tagList.tagCount(); ++i) { + NBTTagCompound tagCompound = (NBTTagCompound) tagList.getCompoundTagAt(i); + int slot = tagCompound.getInteger("Slot"); + if (slot >= 0 && slot < inventory.length) { + inventory[slot] = ItemStack.loadItemStackFromNBT(tagCompound); + } + } + } + + public void writeNBT(NBTTagCompound nbtTagCompound) { + NBTTagList tagList = new NBTTagList(); + for (int currentIndex = 0; currentIndex < inventory.length; ++currentIndex) { + if (inventory[currentIndex] != null) { + NBTTagCompound tagCompound = new NBTTagCompound(); + tagCompound.setInteger("Slot", currentIndex); + inventory[currentIndex].writeToNBT(tagCompound); + tagList.appendTag(tagCompound); + } + } + nbtTagCompound.setTag(this.name, tagList); + } + + @Override + public void openInventory() { + } + + @Override + public void closeInventory() { + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/registries/EnumCache.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/registries/EnumCache.java new file mode 100644 index 0000000..ccc8cf5 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/registries/EnumCache.java @@ -0,0 +1,22 @@ +package net.p455w0rd.wirelesscraftingterminal.common.registries; + +import appeng.api.config.SortDir; +import appeng.api.config.SortOrder; +import appeng.api.config.ViewItems; + +public class EnumCache { + /** + * SortDir + */ + public static final SortDir[] AE_SORT_DIRECTIONS = SortDir.values(); + + /** + * SortOrder + */ + public static final SortOrder[] AE_SORT_ORDERS = SortOrder.values(); + + /** + * ViewItems + */ + public static final ViewItems[] AE_VIEW_ITEMS = ViewItems.values(); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/utils/RandomUtils.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/utils/RandomUtils.java new file mode 100644 index 0000000..362048f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/utils/RandomUtils.java @@ -0,0 +1,111 @@ +package net.p455w0rd.wirelesscraftingterminal.common.utils; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemMagnet; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + +public class RandomUtils { + + @SideOnly(Side.CLIENT) + public static String color(String color) { + switch (color) { + case "white": + return EnumChatFormatting.WHITE.toString(); + case "black": + return EnumChatFormatting.BLACK.toString(); + case "green": + return EnumChatFormatting.GREEN.toString(); + case "red": + return EnumChatFormatting.RED.toString(); + case "yellow": + return EnumChatFormatting.YELLOW.toString(); + case "aqua": + return EnumChatFormatting.AQUA.toString(); + case "blue": + return EnumChatFormatting.BLUE.toString(); + case "italics": + return EnumChatFormatting.ITALIC.toString(); + case "bold": + return EnumChatFormatting.BOLD.toString(); + default: + case "gray": + return EnumChatFormatting.GRAY.toString(); + } + } + + public static ItemStack getWirelessTerm(InventoryPlayer playerInv) { + if (playerInv.player.getHeldItem() != null && playerInv.player.getHeldItem().getItem() instanceof ItemWirelessCraftingTerminal) { + return playerInv.player.getHeldItem(); + } + ItemStack wirelessTerm = null; + int invSize = playerInv.getSizeInventory(); + if (invSize <= 0) { + return null; + } + for (int i = 0; i < invSize; ++i) { + ItemStack item = playerInv.getStackInSlot(i); + if (item == null) { + continue; + } + if (item.getItem() instanceof ItemWirelessCraftingTerminal) { + wirelessTerm = item; + break; + } + if (wirelessTerm == null) { + continue; + } + } + if (wirelessTerm == null) { + if (playerInv.player.getHeldItem() != null) { + return playerInv.player.getHeldItem(); + } + else { + return ItemEnum.WIRELESS_CRAFTING_TERMINAL.getStack(); + } + } + else { + return wirelessTerm; + } + } + + public static ItemStack getMagnet(InventoryPlayer playerInv) { + if (playerInv.player.getHeldItem() != null && playerInv.player.getHeldItem().getItem() instanceof ItemMagnet) { + return playerInv.player.getHeldItem(); + } + ItemStack magnetItem = null; + int invSize = playerInv.getSizeInventory(); + if (invSize <= 0) { + return null; + } + for (int i = 0; i < invSize; ++i) { + ItemStack item = playerInv.getStackInSlot(i); + if (item == null) { + continue; + } + if (item.getItem() instanceof ItemMagnet) { + magnetItem = item; + break; + } + if (magnetItem == null) { + continue; + } + } + if (magnetItem == null) { + if (playerInv.player.getHeldItem() != null) { + return playerInv.player.getHeldItem(); + } + else { + return ItemEnum.WIRELESS_CRAFTING_TERMINAL.getStack(); + } + } + else { + return magnetItem; + } + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/common/utils/WCTLog.java b/src/java/net/p455w0rd/wirelesscraftingterminal/common/utils/WCTLog.java new file mode 100644 index 0000000..76ad491 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/common/utils/WCTLog.java @@ -0,0 +1,73 @@ +package net.p455w0rd.wirelesscraftingterminal.common.utils; + +import javax.annotation.Nonnull; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; + +public class WCTLog { + public static final Logger log = LogManager.getLogger("Wireless Crafting Terminal"); + + /** + * Displays the section header. + */ + public static long beginSection(final String section) { + log.info(String.format("-=-=-=-=-=-=-=[START] %s=-=-=-=-=-=-=-", section)); + return System.currentTimeMillis(); + } + + /** + * Logs a debug statement. + * + * @param format + * @param data + */ + public static void debug(final String format, final Object... data) { + log.debug(String.format(format, data)); + } + + /** + * Displays the section footer. + */ + public static void endSection(final String section, final long sectionStartTime) { + log.info(String.format("-=-=-=-=-=-=-=[FINISH] %s in %dms=-=-=-=-=-=-=-", section, (System.currentTimeMillis() - sectionStartTime))); + } + + /** + * Logs basic info. + * + * @param format + * @param data + */ + public static void info(final String format, final Object... data) { + log.info(String.format(format, data)); + } + + /** + * Logs an error. + * + * @param format + * @param data + */ + public static void severe(final String format, final Object... data) { + log.error(String.format(format, data)); + } + + /** + * Logs a warning. + * + * @param format + * @param data + */ + public static void warning(final String format, final Object... data) { + log.warn(String.format(format, data)); + } + + public static void integration( @Nonnull final Throwable exception ) + { + log.debug( exception ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/crash/BaseCrashEnhancement.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/crash/BaseCrashEnhancement.java new file mode 100644 index 0000000..cc11234 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/crash/BaseCrashEnhancement.java @@ -0,0 +1,28 @@ +package net.p455w0rd.wirelesscraftingterminal.core.crash; + +import cpw.mods.fml.common.ICrashCallable; + + +abstract class BaseCrashEnhancement implements ICrashCallable +{ + private final String name; + private final String value; + + public BaseCrashEnhancement( final String name, final String value ) + { + this.name = name; + this.value = value; + } + + @Override + public final String call() throws Exception + { + return this.value; + } + + @Override + public final String getLabel() + { + return this.name; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/crash/IntegrationCrashEnhancement.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/crash/IntegrationCrashEnhancement.java new file mode 100644 index 0000000..68f702f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/crash/IntegrationCrashEnhancement.java @@ -0,0 +1,11 @@ +package net.p455w0rd.wirelesscraftingterminal.core.crash; + +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationRegistry; + +public class IntegrationCrashEnhancement extends BaseCrashEnhancement +{ + public IntegrationCrashEnhancement() + { + super( "AE2 Integration", IntegrationRegistry.INSTANCE.getStatus() ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/WCTPacket.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/WCTPacket.java new file mode 100644 index 0000000..972b6e9 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/WCTPacket.java @@ -0,0 +1,46 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync; + +import io.netty.buffer.ByteBuf; + +import net.minecraft.entity.player.EntityPlayer; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import cpw.mods.fml.common.network.internal.FMLProxyPacket; + +public abstract class WCTPacket { + + private WCTPacketHandlerBase.PacketTypes id; + private ByteBuf p; + + public void serverPacketData(final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player) { + throw new UnsupportedOperationException("This packet ( " + this.getPacketID() + " does not implement a server side handler."); + } + + public final int getPacketID() { + return WCTPacketHandlerBase.PacketTypes.getID(this.getClass()).ordinal(); + } + + public void clientPacketData(final INetworkInfo network, final WCTPacket packet, final EntityPlayer player) { + throw new UnsupportedOperationException("This packet ( " + this.getPacketID() + " does not implement a client side handler."); + } + + protected void configureWrite(final ByteBuf data) { + data.capacity(data.readableBytes()); + this.p = data; + } + + public FMLProxyPacket getProxy() { + if (this.p.array().length > 2 * 1024 * 1024) { + throw new IllegalArgumentException("Sorry WCT made a " + this.p.array().length + " byte packet by accident!"); + } + + final FMLProxyPacket pp = new FMLProxyPacket(this.p, NetworkHandler.instance.getChannel()); + + //if (AEConfig.instance.isFeatureEnabled(AEFeature.PacketLogging)) { + // WCTLog.info(this.getClass().getName() + " : " + pp.payload().readableBytes()); + //} + + return pp; + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/WCTPacketHandlerBase.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/WCTPacketHandlerBase.java new file mode 100644 index 0000000..a4d5b21 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/WCTPacketHandlerBase.java @@ -0,0 +1,85 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.DecoderException; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacketHandlerBase.PacketTypes; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketCraftRequest; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketInventoryAction; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketMEInventoryUpdate; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketMagnetFilterMode; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketNEIRecipe; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketOpenWirelessTerm; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketPartialItem; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwapSlots; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketSwitchGuis; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketValueConfig; + +public class WCTPacketHandlerBase { + private static final Map, PacketTypes> REVERSE_LOOKUP = new HashMap, WCTPacketHandlerBase.PacketTypes>(); + + public enum PacketTypes { + PACKET_INVENTORY_ACTION(PacketInventoryAction.class), + + PACKET_ME_INVENTORY_UPDATE(PacketMEInventoryUpdate.class), + + //PACKET_CONFIG_BUTTON( PacketConfigButton.class ), + + PACKET_VALUE_CONFIG(PacketValueConfig.class), + + PACKET_SWITCH_GUIS(PacketSwitchGuis.class), + + PACKET_SWAP_SLOTS(PacketSwapSlots.class), + + PACKET_RECIPE_NEI(PacketNEIRecipe.class), + + PACKET_PARTIAL_ITEM(PacketPartialItem.class), + + PACKET_CRAFTING_REQUEST(PacketCraftRequest.class), + + PACKET_MAGNETFILTER_MODE(PacketMagnetFilterMode.class), + + PACKET_OPENWIRELESSTERM(PacketOpenWirelessTerm.class); + + private final Class packetClass; + private final Constructor packetConstructor; + + PacketTypes(final Class c) { + this.packetClass = c; + + Constructor x = null; + try { + x = this.packetClass.getConstructor(ByteBuf.class); + } + catch (final NoSuchMethodException ignored) { + } + catch (final SecurityException ignored) { + } + catch (final DecoderException ignored) { + } + + this.packetConstructor = x; + REVERSE_LOOKUP.put(this.packetClass, this); + + if (this.packetConstructor == null) { + throw new IllegalStateException("Invalid Packet Class " + c + ", must be constructable on DataInputStream"); + } + } + + public static PacketTypes getPacket(final int id) { + return (values())[id]; + } + + static PacketTypes getID(final Class c) { + return REVERSE_LOOKUP.get(c); + } + + public WCTPacket parsePacket(final ByteBuf in) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return this.packetConstructor.newInstance(in); + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/AppEngClientPacketHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/AppEngClientPacketHandler.java new file mode 100644 index 0000000..3c3c755 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/AppEngClientPacketHandler.java @@ -0,0 +1,47 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.network; + +import java.lang.reflect.InvocationTargetException; + +import io.netty.buffer.ByteBuf; + +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacketHandlerBase; +import cpw.mods.fml.common.network.internal.FMLProxyPacket; + +public class AppEngClientPacketHandler extends WCTPacketHandlerBase implements IPacketHandler +{ + + @Override + public void onPacketData( final INetworkInfo network, final FMLProxyPacket packet, EntityPlayer player ) + { + final ByteBuf stream = packet.payload(); + + player = Minecraft.getMinecraft().thePlayer; + + try + { + final int packetType = stream.readInt(); + final WCTPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); + pack.clientPacketData( network, pack, player ); + } + catch( final InstantiationException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalAccessException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalArgumentException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final InvocationTargetException e ) + { + WCTLog.debug( e.getMessage() ); + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/AppEngServerPacketHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/AppEngServerPacketHandler.java new file mode 100644 index 0000000..41b181c --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/AppEngServerPacketHandler.java @@ -0,0 +1,47 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.network; + +import java.lang.reflect.InvocationTargetException; + +import io.netty.buffer.ByteBuf; + +import net.minecraft.entity.player.EntityPlayer; + +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacketHandlerBase; + +import cpw.mods.fml.common.network.internal.FMLProxyPacket; + + +public final class AppEngServerPacketHandler extends WCTPacketHandlerBase implements IPacketHandler +{ + + @Override + public void onPacketData( final INetworkInfo manager, final FMLProxyPacket packet, final EntityPlayer player ) + { + final ByteBuf stream = packet.payload(); + + try + { + final int packetType = stream.readInt(); + final WCTPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); + pack.serverPacketData( manager, pack, player ); + } + catch( final InstantiationException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalAccessException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final IllegalArgumentException e ) + { + WCTLog.debug( e.getMessage() ); + } + catch( final InvocationTargetException e ) + { + WCTLog.debug( e.getMessage() ); + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/INetworkInfo.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/INetworkInfo.java new file mode 100644 index 0000000..1d15920 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/INetworkInfo.java @@ -0,0 +1,5 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.network; + +public interface INetworkInfo { + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/IPacketHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/IPacketHandler.java new file mode 100644 index 0000000..6b14fdf --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/IPacketHandler.java @@ -0,0 +1,12 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.network; + +import net.minecraft.entity.player.EntityPlayer; + +import cpw.mods.fml.common.network.internal.FMLProxyPacket; + + +public interface IPacketHandler +{ + + void onPacketData( INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player ); +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/NetworkHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/NetworkHandler.java new file mode 100644 index 0000000..b130da8 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/network/NetworkHandler.java @@ -0,0 +1,111 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.network; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.NetHandlerPlayServer; + +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; +import cpw.mods.fml.common.network.FMLEventChannel; +import cpw.mods.fml.common.network.FMLNetworkEvent.ClientCustomPacketEvent; +import cpw.mods.fml.common.network.FMLNetworkEvent.ServerConnectionFromClientEvent; +import cpw.mods.fml.common.network.FMLNetworkEvent.ServerCustomPacketEvent; +import cpw.mods.fml.common.network.NetworkRegistry; + + +public class NetworkHandler +{ + + public static NetworkHandler instance; + + private final FMLEventChannel ec; + private final String myChannelName; + + private final IPacketHandler clientHandler; + private final IPacketHandler serveHandler; + + public NetworkHandler( final String channelName ) + { + FMLCommonHandler.instance().bus().register( this ); + this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel( this.myChannelName = channelName ); + this.ec.register( this ); + + this.clientHandler = this.createClientSide(); + this.serveHandler = this.createServerSide(); + } + + private IPacketHandler createClientSide() + { + try + { + return new AppEngClientPacketHandler(); + } + catch( final Throwable t ) + { + return null; + } + } + + private IPacketHandler createServerSide() + { + try + { + return new AppEngServerPacketHandler(); + } + catch( final Throwable t ) + { + return null; + } + } + + @SubscribeEvent + public void serverPacket( final ServerCustomPacketEvent ev ) + { + final NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.packet.handler(); + if( this.serveHandler != null ) + { + this.serveHandler.onPacketData( null, ev.packet, srv.playerEntity ); + } + } + + @SubscribeEvent + public void clientPacket( final ClientCustomPacketEvent ev ) + { + if( this.clientHandler != null ) + { + this.clientHandler.onPacketData( null, ev.packet, null ); + } + } + + public String getChannel() + { + return this.myChannelName; + } + + public void sendToAll( final WCTPacket message ) + { + this.ec.sendToAll( message.getProxy() ); + } + + public void sendTo( final WCTPacket message, final EntityPlayerMP player ) + { + this.ec.sendTo( message.getProxy(), player ); + } + + public void sendToAllAround( final WCTPacket message, final NetworkRegistry.TargetPoint point ) + { + this.ec.sendToAllAround( message.getProxy(), point ); + } + + public void sendToDimension( final WCTPacket message, final int dimensionId ) + { + this.ec.sendToDimension( message.getProxy(), dimensionId ); + } + + public void sendToServer( final WCTPacket message ) + { + this.ec.sendToServer( message.getProxy() ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketCraftRequest.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketCraftRequest.java new file mode 100644 index 0000000..fc1a1ec --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketCraftRequest.java @@ -0,0 +1,114 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import java.util.concurrent.Future; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.p455w0rd.wirelesscraftingterminal.common.WCTGuiHandler; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftAmount; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftConfirm; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerOpenContext; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; +import appeng.api.networking.crafting.ICraftingGrid; +import appeng.api.networking.crafting.ICraftingJob; +import appeng.util.Platform; + + +public class PacketCraftRequest extends WCTPacket +{ + + private final long amount; + private final boolean heldShift; + + // automatic. + public PacketCraftRequest( final ByteBuf stream ) + { + this.heldShift = stream.readBoolean(); + this.amount = stream.readLong(); + } + + public PacketCraftRequest( final int craftAmt, final boolean shift ) + { + this.amount = craftAmt; + this.heldShift = shift; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeBoolean( shift ); + data.writeLong( this.amount ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + if( player.openContainer instanceof ContainerCraftAmount ) + { + final ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; + final Object target = cca.getTarget(); + if( target instanceof IGridHost ) + { + final IGridHost gh = (IGridHost) target; + final IGridNode gn = gh.getGridNode( ForgeDirection.UNKNOWN ); + if( gn == null ) + { + return; + } + + final IGrid g = gn.getGrid(); + if( g == null || cca.getItemToCraft() == null ) + { + return; + } + + cca.getItemToCraft().setStackSize( this.amount ); + + Future futureJob = null; + try + { + final ICraftingGrid cg = g.getCache( ICraftingGrid.class ); + futureJob = cg.beginCraftingJob( cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null ); + + //final ContainerOpenContext context = cca.getOpenContext(); + //if( context != null ) + //{ + //final TileEntity te = context.getTile(); + int x = player.serverPosX; + int y = player.serverPosY; + int z = player.serverPosZ; + + WCTGuiHandler.launchGui(WirelessCraftingTerminal.GUI_CRAFT_CONFIRM, player, player.worldObj, x, y, z); + + if( player.openContainer instanceof ContainerCraftConfirm ) + { + final ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; + ccc.setAutoStart( this.heldShift ); + ccc.setJob( futureJob ); + cca.detectAndSendChanges(); + } + //} + } + catch( final Throwable e ) + { + if( futureJob != null ) + { + futureJob.cancel( true ); + } + WCTLog.debug( e.getMessage() ); + } + } + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketInventoryAction.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketInventoryAction.java new file mode 100644 index 0000000..c0cf3d3 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketInventoryAction.java @@ -0,0 +1,181 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import java.io.IOException; + +import appeng.api.storage.data.IAEItemStack; +import appeng.client.ClientHelper; +import appeng.helpers.InventoryAction; +import appeng.util.Platform; +import appeng.util.item.AEItemStack; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.tileentity.TileEntity; +import net.p455w0rd.wirelesscraftingterminal.common.WCTGuiHandler; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftAmount; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerOpenContext; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; + +public class PacketInventoryAction extends WCTPacket +{ + + private final InventoryAction action; + private final int slot; + private final long id; + private final IAEItemStack slotItem; + + // automatic. + public PacketInventoryAction( final ByteBuf stream ) throws IOException + { + this.action = InventoryAction.values()[stream.readInt()]; + this.slot = stream.readInt(); + this.id = stream.readLong(); + final boolean hasItem = stream.readBoolean(); + if( hasItem ) + { + this.slotItem = AEItemStack.loadItemStackFromPacket( stream ); + } + else + { + this.slotItem = null; + } + } + + // api + public PacketInventoryAction( final InventoryAction action, final int slot, final IAEItemStack slotItem ) throws IOException + { + + if( Platform.isClient() ) + { + throw new IllegalStateException( "invalid packet, client cannot post inv actions with stacks." ); + } + + this.action = action; + this.slot = slot; + this.id = 0; + this.slotItem = slotItem; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeInt( action.ordinal() ); + data.writeInt( slot ); + data.writeLong( this.id ); + + if( slotItem == null ) + { + data.writeBoolean( false ); + } + else + { + data.writeBoolean( true ); + slotItem.writeToPacket( data ); + } + + this.configureWrite( data ); + } + + // api + public PacketInventoryAction( final InventoryAction action, final int slot, final long id ) + { + this.action = action; + this.slot = slot; + this.id = id; + this.slotItem = null; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeInt( action.ordinal() ); + data.writeInt( slot ); + data.writeLong( id ); + data.writeBoolean( false ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + final EntityPlayerMP sender = (EntityPlayerMP) player; + Container baseContainer = sender.openContainer; + ContainerOpenContext context = null; + if( sender.openContainer instanceof ContainerWirelessCraftingTerminal ) { + baseContainer = (ContainerWirelessCraftingTerminal) sender.openContainer; + context = ((ContainerWirelessCraftingTerminal) baseContainer).getOpenContext(); + } + + if( sender.openContainer instanceof AEBaseContainer ) { + baseContainer = (AEBaseContainer) sender.openContainer; + context = ((AEBaseContainer) baseContainer).getOpenContext(); + } + + if( this.action == InventoryAction.AUTO_CRAFT ) + { + //if( context != null ) + //{ + //final TileEntity te = context.getTile(); + + int x = player.serverPosX; + int y = player.serverPosY; + int z = player.serverPosZ; + + WCTGuiHandler.launchGui(WirelessCraftingTerminal.GUI_CRAFT_AMOUNT, player, player.worldObj, x, y, z); + + if( sender.openContainer instanceof ContainerCraftAmount ) + { + final ContainerCraftAmount cca = (ContainerCraftAmount) sender.openContainer; + + if (baseContainer instanceof ContainerWirelessCraftingTerminal) { + if( ((ContainerWirelessCraftingTerminal) baseContainer).getTargetStack() != null ) + { + cca.getCraftingItem().putStack( ((ContainerWirelessCraftingTerminal) baseContainer).getTargetStack().getItemStack() ); + cca.setItemToCraft( ((ContainerWirelessCraftingTerminal) baseContainer).getTargetStack() ); + } + } + + if (baseContainer instanceof AEBaseContainer) { + if( ((AEBaseContainer) baseContainer).getTargetStack() != null ) + { + cca.getCraftingItem().putStack( ((AEBaseContainer) baseContainer).getTargetStack().getItemStack() ); + cca.setItemToCraft( ((AEBaseContainer) baseContainer).getTargetStack() ); + } + } + + cca.detectAndSendChanges(); + } + //} + } + else + { + if (baseContainer instanceof ContainerWirelessCraftingTerminal) { + ((ContainerWirelessCraftingTerminal) baseContainer).doAction( sender, this.action, this.slot, this.id ); + } + if (baseContainer instanceof AEBaseContainer) { + ((AEBaseContainer) baseContainer).doAction( sender, this.action, this.slot, this.id ); + } + } + } + + @Override + public void clientPacketData( final INetworkInfo network, final WCTPacket packet, final EntityPlayer player ) + { + if( this.action == InventoryAction.UPDATE_HAND ) + { + if( this.slotItem == null ) + { + ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( null ); + } + else + { + ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( this.slotItem.getItemStack() ); + } + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketMEInventoryUpdate.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketMEInventoryUpdate.java new file mode 100644 index 0000000..e769f0b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketMEInventoryUpdate.java @@ -0,0 +1,192 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.BufferOverflowException; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +import javax.annotation.Nullable; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiCraftConfirm; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiCraftingCPU; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; +import cpw.mods.fml.common.network.internal.FMLProxyPacket; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import appeng.api.storage.data.IAEItemStack; +import appeng.util.item.AEItemStack; + + +public class PacketMEInventoryUpdate extends WCTPacket +{ + private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; + private static final int OPERATION_BYTE_LIMIT = 2 * 1024; + private static final int TEMP_BUFFER_SIZE = 1024; + private static final int STREAM_MASK = 0xff; + + // input. + @Nullable + private final List list; + // output... + private final byte ref; + + @Nullable + private final ByteBuf data; + @Nullable + private final GZIPOutputStream compressFrame; + + private int writtenBytes = 0; + private boolean empty = true; + + // automatic. + public PacketMEInventoryUpdate( final ByteBuf stream ) throws IOException + { + this.data = null; + this.compressFrame = null; + this.list = new LinkedList(); + this.ref = stream.readByte(); + + final GZIPInputStream gzReader = new GZIPInputStream( new InputStream() + { + @Override + public int read() throws IOException + { + if( stream.readableBytes() <= 0 ) + { + return -1; + } + + return stream.readByte() & STREAM_MASK; + } + } ); + + final ByteBuf uncompressed = Unpooled.buffer( stream.readableBytes() ); + final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; + while( gzReader.available() != 0 ) + { + final int bytes = gzReader.read( tmp ); + if( bytes > 0 ) + { + uncompressed.writeBytes( tmp, 0, bytes ); + } + } + gzReader.close(); + + while( uncompressed.readableBytes() > 0 ) + { + this.list.add( AEItemStack.loadItemStackFromPacket( uncompressed ) ); + } + + this.empty = this.list.isEmpty(); + } + + // api + public PacketMEInventoryUpdate() throws IOException + { + this( (byte) 0 ); + } + + // api + public PacketMEInventoryUpdate( final byte ref ) throws IOException + { + this.ref = ref; + this.data = Unpooled.buffer( OPERATION_BYTE_LIMIT ); + this.data.writeInt( this.getPacketID() ); + this.data.writeByte( this.ref ); + + this.compressFrame = new GZIPOutputStream( new OutputStream() + { + @Override + public void write( final int value ) throws IOException + { + PacketMEInventoryUpdate.this.data.writeByte( value ); + } + } ); + + this.list = null; + } + + @Override + @SideOnly( Side.CLIENT ) + public void clientPacketData( final INetworkInfo network, final WCTPacket packet, final EntityPlayer player ) + { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + + if( gs instanceof GuiCraftConfirm ) + { + ( (GuiCraftConfirm) gs ).postUpdate( this.list, this.ref ); + } + + if( gs instanceof GuiCraftingCPU ) + { + ( (GuiCraftingCPU) gs ).postUpdate( this.list, this.ref ); + } + + if( gs instanceof GuiWirelessCraftingTerminal ) + { + ( (GuiWirelessCraftingTerminal) gs ).postUpdate( this.list ); + } + + } + + @Nullable + @Override + public FMLProxyPacket getProxy() + { + try + { + this.compressFrame.close(); + + this.configureWrite( this.data ); + return super.getProxy(); + } + catch( final IOException e ) + { + WCTLog.debug( e.getMessage() ); + } + + return null; + } + + public void appendItem( final IAEItemStack is ) throws IOException, BufferOverflowException + { + final ByteBuf tmp = Unpooled.buffer( OPERATION_BYTE_LIMIT ); + is.writeToPacket( tmp ); + + this.compressFrame.flush(); + if( this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT ) + { + throw new BufferOverflowException(); + } + else + { + this.writtenBytes += tmp.readableBytes(); + this.compressFrame.write( tmp.array(), 0, tmp.readableBytes() ); + this.empty = false; + } + } + + public int getLength() + { + return this.data.readableBytes(); + } + + public boolean isEmpty() + { + return this.empty; + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketMagnetFilterMode.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketMagnetFilterMode.java new file mode 100644 index 0000000..96f0190 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketMagnetFilterMode.java @@ -0,0 +1,58 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import cpw.mods.fml.common.FMLCommonHandler; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiMagnet; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemMagnet; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + +public class PacketMagnetFilterMode extends WCTPacket { + + boolean isWhitelisting; + + public PacketMagnetFilterMode( final ByteBuf stream ) + { + this.isWhitelisting = stream.readBoolean(); + } + + public PacketMagnetFilterMode(final boolean isWhitelisting) { + this.isWhitelisting = isWhitelisting; + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + GuiMagnet.mode = this.isWhitelisting; + } + final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + data.writeBoolean(this.isWhitelisting); + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + ItemStack magnetItem = RandomUtils.getMagnet(player.inventory); + if (!(magnetItem.getItem() instanceof ItemMagnet)) { + return; + } + if (magnetItem != null) { + if (!magnetItem.hasTagCompound()) { + magnetItem.setTagCompound(new NBTTagCompound()); + } + magnetItem.getTagCompound().setBoolean("Whitelisting", this.isWhitelisting); + } + } + + @Override + public void clientPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + GuiMagnet.mode = this.isWhitelisting; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketNEIRecipe.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketNEIRecipe.java new file mode 100644 index 0000000..637d824 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketNEIRecipe.java @@ -0,0 +1,244 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.oredict.OreDictionary; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; +import appeng.api.config.Actionable; +import appeng.api.config.FuzzyMode; +import appeng.api.config.SecurityPermissions; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridNode; +import appeng.api.networking.energy.IEnergyGrid; +import appeng.api.networking.security.ISecurityGrid; +import appeng.api.networking.storage.IStorageGrid; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.container.ContainerNull; +import appeng.helpers.IContainerCraftingPacket; +import appeng.items.storage.ItemViewCell; +import appeng.util.InventoryAdaptor; +import appeng.util.Platform; +import appeng.util.item.AEItemStack; +import appeng.util.prioitylist.IPartitionList; + + +public class PacketNEIRecipe extends WCTPacket +{ + + private ItemStack[][] recipe; + + // automatic. + public PacketNEIRecipe( final ByteBuf stream ) throws IOException + { + final ByteArrayInputStream bytes = new ByteArrayInputStream( stream.array() ); + bytes.skip( stream.readerIndex() ); + final NBTTagCompound comp = CompressedStreamTools.readCompressed( bytes ); + if( comp != null ) + { + this.recipe = new ItemStack[9][]; + for( int x = 0; x < this.recipe.length; x++ ) + { + final NBTTagList list = comp.getTagList( "#" + x, 10 ); + if( list.tagCount() > 0 ) + { + this.recipe[x] = new ItemStack[list.tagCount()]; + for( int y = 0; y < list.tagCount(); y++ ) + { + this.recipe[x][y] = ItemStack.loadItemStackFromNBT( list.getCompoundTagAt( y ) ); + } + } + } + } + } + + // api + public PacketNEIRecipe( final NBTTagCompound recipe ) throws IOException + { + final ByteBuf data = Unpooled.buffer(); + + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream outputStream = new DataOutputStream( bytes ); + + data.writeInt( this.getPacketID() ); + + CompressedStreamTools.writeCompressed( recipe, outputStream ); + data.writeBytes( bytes.toByteArray() ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + final EntityPlayerMP pmp = (EntityPlayerMP) player; + final Container con = pmp.openContainer; + + if( con instanceof IContainerCraftingPacket ) + { + final IContainerCraftingPacket cct = (IContainerCraftingPacket) con; + final IGridNode node = cct.getNetworkNode(); + if( node != null ) + { + final IGrid grid = node.getGrid(); + if( grid == null ) + { + return; + } + + final IStorageGrid inv = grid.getCache( IStorageGrid.class ); + final IEnergyGrid energy = grid.getCache( IEnergyGrid.class ); + final ISecurityGrid security = grid.getCache( ISecurityGrid.class ); + final IInventory craftMatrix = cct.getInventoryByName( "crafting" ); + final IInventory playerInventory = cct.getInventoryByName( "container.inventory" ); + + final Actionable realForFake = Actionable.MODULATE; + + if( inv != null && this.recipe != null && security != null ) + { + final InventoryCrafting testInv = new InventoryCrafting( new ContainerNull(), 3, 3 ); + for( int x = 0; x < 9; x++ ) + { + if( this.recipe[x] != null && this.recipe[x].length > 0 ) + { + testInv.setInventorySlotContents( x, this.recipe[x][0] ); + } + } + + final IRecipe r = Platform.findMatchingRecipe( testInv, pmp.worldObj ); + + if( r != null && security.hasPermission( player, SecurityPermissions.EXTRACT ) ) + { + final ItemStack is = r.getCraftingResult( testInv ); + + if( is != null ) + { + final IMEMonitor storage = inv.getItemInventory(); + final IItemList all = storage.getStorageList(); + final ItemStack[] nullStack = new ItemStack[0]; + final IPartitionList filter = ItemViewCell.createFilter( nullStack ); + + for( int x = 0; x < craftMatrix.getSizeInventory(); x++ ) + { + final ItemStack patternItem = testInv.getStackInSlot( x ); + + ItemStack currentItem = craftMatrix.getStackInSlot( x ); + if( currentItem != null ) + { + testInv.setInventorySlotContents( x, currentItem ); + final ItemStack newItemStack = r.matches( testInv, pmp.worldObj ) ? r.getCraftingResult( testInv ) : null; + testInv.setInventorySlotContents( x, patternItem ); + + if( newItemStack == null || !Platform.isSameItemPrecise( newItemStack, is ) ) + { + final IAEItemStack in = AEItemStack.create( currentItem ); + if( in != null ) + { + final IAEItemStack out = Platform.poweredInsert( energy, storage, in, cct.getActionSource() ); + if( out != null ) + { + craftMatrix.setInventorySlotContents( x, out.getItemStack() ); + } + else + { + craftMatrix.setInventorySlotContents( x, null ); + } + + currentItem = craftMatrix.getStackInSlot( x ); + } + } + } + + // True if we need to fetch an item for the recipe + if( patternItem != null && currentItem == null ) + { + // Grab from network by recipe + ItemStack whichItem = Platform.extractItemsByRecipe( energy, cct.getActionSource(), storage, player.worldObj, r, is, testInv, patternItem, x, all, realForFake, filter ); + //ItemStack whichItem = Platform.extractItemsByRecipe( energy, cct.getActionSource(), storage, player.worldObj, r, is, testInv, patternItem, x, all, realForFake, null ); + + // If that doesn't get it, grab exact items from network (?) + // TODO see if this code is necessary + + if( whichItem == null ) + { + for( int y = 0; y < this.recipe[x].length; y++ ) + { + final IAEItemStack request = AEItemStack.create( this.recipe[x][y] ); + if( request != null ) + { + if( filter == null || filter.isListed( request ) ) + { + request.setStackSize( 1 ); + final IAEItemStack out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() ); + if( out != null ) + { + whichItem = out.getItemStack(); + break; + } + } + } + } + } + + + // If that doesn't work, grab from the player's inventory + if( whichItem == null && playerInventory != null ) + { + whichItem = this.extractItemFromPlayerInventory( player, realForFake, patternItem ); + } + + craftMatrix.setInventorySlotContents( x, whichItem ); + } + } + con.onCraftMatrixChanged( craftMatrix ); + } + } + } + } + } + } + + /** + * Tries to extract an item from the player inventory. Does account for fuzzy items. + * + * @param player the {@link EntityPlayer} to extract from + * @param mode the {@link Actionable} to simulate or modulate the operation + * @param patternItem which {@link ItemStack} to extract + * @return null or a found {@link ItemStack} + */ + private ItemStack extractItemFromPlayerInventory( final EntityPlayer player, final Actionable mode, final ItemStack patternItem ) + { + final InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); + final AEItemStack request = AEItemStack.create( patternItem ); + final boolean isSimulated = mode == Actionable.SIMULATE; + final boolean checkFuzzy = request.isOre() || patternItem.getItemDamage() == OreDictionary.WILDCARD_VALUE || patternItem.hasTagCompound() || patternItem.isItemStackDamageable(); + + if( !checkFuzzy ) + { + return ia.removeItems( 1, patternItem, null ); + } + else + { + return ia.removeSimilarItems( 1, patternItem, FuzzyMode.IGNORE_ALL, null ); + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketOpenWirelessTerm.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketOpenWirelessTerm.java new file mode 100644 index 0000000..1311f57 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketOpenWirelessTerm.java @@ -0,0 +1,56 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ContainerPlayer; +import net.minecraft.world.World; +import net.p455w0rd.wirelesscraftingterminal.api.WCTApi; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; + +public class PacketOpenWirelessTerm extends WCTPacket { + + // automatic. + public PacketOpenWirelessTerm(final ByteBuf stream) { + + } + + public PacketOpenWirelessTerm() { + if( Platform.isClient() ) { + EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; + //WCTApi.instance().interact().openWirelessCraftingTerminalGui(player); + } + final ByteBuf data = Unpooled.buffer(); + data.writeInt( this.getPacketID() ); + this.configureWrite( data ); + } + + @Override + public void serverPacketData(final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player) { + World world = player.worldObj; + int x = (int) player.posX; + int y = (int) player.posY; + int z = (int) player.posZ; + //WCTGuiHandler.launchGui(WirelessCraftingTerminal.GUI_WCT, player, world, x, y, z); + if (player.openContainer instanceof ContainerPlayer) { + //WCTApi.instance().interact().openWirelessCraftingTerminalGui(player); + player.openGui(WirelessCraftingTerminal.INSTANCE, WirelessCraftingTerminal.GUI_WCT, world, x, y, z); + } + } + + @Override + public void clientPacketData(final INetworkInfo network, final WCTPacket packet, final EntityPlayer player) { + World world = player.worldObj; + int x = (int) player.posX; + int y = (int) player.posY; + int z = (int) player.posZ; + //WCTGuiHandler.launchGui(WirelessCraftingTerminal.GUI_WCT, player, world, x, y, z); + //WCTApi.instance().interact().openWirelessCraftingTerminalGui(player); + player.openGui(WirelessCraftingTerminal.INSTANCE, WirelessCraftingTerminal.GUI_WCT, world, x, y, z); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketPartialItem.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketPartialItem.java new file mode 100644 index 0000000..3367e66 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketPartialItem.java @@ -0,0 +1,69 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +import net.minecraft.entity.player.EntityPlayer; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; + + +public class PacketPartialItem extends WCTPacket +{ + + private final short pageNum; + private final byte[] data; + + // automatic. + public PacketPartialItem( final ByteBuf stream ) + { + this.pageNum = stream.readShort(); + stream.readBytes( this.data = new byte[stream.readableBytes()] ); + } + + // api + public PacketPartialItem( final int page, final int maxPages, final byte[] buf ) + { + + final ByteBuf data = Unpooled.buffer(); + + this.pageNum = (short) ( page | ( maxPages << 8 ) ); + this.data = buf; + data.writeInt( this.getPacketID() ); + data.writeShort( this.pageNum ); + data.writeBytes( buf ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + if( player.openContainer instanceof ContainerWirelessCraftingTerminal ) + { + ( (ContainerWirelessCraftingTerminal) player.openContainer ).postPartial( this ); + } + if( player.openContainer instanceof AEBaseContainer ) + { + ( (AEBaseContainer) player.openContainer ).postPartial( this ); + } + } + + public int getPageCount() + { + return this.pageNum >> 8; + } + + public int getSize() + { + return this.data.length; + } + + public int write( final byte[] buffer, final int cursor ) + { + System.arraycopy( this.data, 0, buffer, cursor, this.data.length ); + return cursor + this.data.length; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketProgressBar.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketProgressBar.java new file mode 100644 index 0000000..eae22f1 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketProgressBar.java @@ -0,0 +1,69 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; + + +public class PacketProgressBar extends WCTPacket +{ + + private final short id; + private final long value; + + // automatic. + public PacketProgressBar( final ByteBuf stream ) + { + this.id = stream.readShort(); + this.value = stream.readLong(); + } + + // api + public PacketProgressBar( final int shortID, final long value ) + { + this.id = (short) shortID; + this.value = value; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeShort( shortID ); + data.writeLong( value ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + final Container c = player.openContainer; + if( c instanceof ContainerWirelessCraftingTerminal ) + { + ( (ContainerWirelessCraftingTerminal) c ).updateFullProgressBar( this.id, this.value ); + } + if( c instanceof AEBaseContainer ) + { + ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); + } + } + + @Override + public void clientPacketData( final INetworkInfo network, final WCTPacket packet, final EntityPlayer player ) + { + final Container c = player.openContainer; + if( c instanceof ContainerWirelessCraftingTerminal ) + { + ( (ContainerWirelessCraftingTerminal) c ).updateFullProgressBar( this.id, this.value ); + } + if( c instanceof AEBaseContainer ) + { + ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketSwapSlots.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketSwapSlots.java new file mode 100644 index 0000000..b0fd982 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketSwapSlots.java @@ -0,0 +1,49 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; + +public class PacketSwapSlots extends WCTPacket +{ + + private final int slotA; + private final int slotB; + + // automatic. + public PacketSwapSlots( final ByteBuf stream ) + { + this.slotA = stream.readInt(); + this.slotB = stream.readInt(); + } + + // api + public PacketSwapSlots( final int slotA, final int slotB ) + { + final ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeInt( this.slotA = slotA ); + data.writeInt( this.slotB = slotB ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + if ( player != null) + { + if (player.openContainer instanceof ContainerWirelessCraftingTerminal) { + ( (ContainerWirelessCraftingTerminal) player.openContainer ).swapSlotContents( this.slotA, this.slotB ); + } + if (player.openContainer instanceof AEBaseContainer) { + ( (AEBaseContainer) player.openContainer ).swapSlotContents( this.slotA, this.slotB ); + } + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketSwitchGuis.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketSwitchGuis.java new file mode 100644 index 0000000..e431e46 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketSwitchGuis.java @@ -0,0 +1,82 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import appeng.util.Platform; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.WCTGuiHandler; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; + +public class PacketSwitchGuis extends WCTPacket +{ + + private final int newGui; + + // automatic. + public PacketSwitchGuis( final ByteBuf stream ) + { + this.newGui = stream.readInt(); + } + + // api + public PacketSwitchGuis( final int newGui ) + { + this.newGui = newGui; + + if( Platform.isClient() ) + { + GuiWirelessCraftingTerminal.setSwitchingGuis( true ); + } + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + data.writeInt( newGui ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + World world = player.worldObj; + if (world.isRemote) { + int x = player.serverPosX; + int y = player.serverPosY; + int z = player.serverPosZ; + WCTGuiHandler.launchGui(newGui, player, world, x, y, z); + } + else { + int x = (int)player.posX; + int y = (int)player.posY; + int z = (int)player.posZ; + WCTGuiHandler.launchGui(newGui, player, world, x, y, z); + } + + /* + final Container c = player.openContainer; + if( c instanceof ContainerWirelessCraftingTerminal ) + { + final ContainerWirelessCraftingTerminal bc = (ContainerWirelessCraftingTerminal) c; + final ContainerOpenContext context = bc.getOpenContext(); + if( context != null ) + { + final TileEntity te = context.getTile(); + Platform.openGUI( player, te, context.getSide(), this.newGui ); + } + } + */ + } + + @Override + public void clientPacketData( final INetworkInfo network, final WCTPacket packet, final EntityPlayer player ) + { + GuiWirelessCraftingTerminal.setSwitchingGuis( true ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketValueConfig.java b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketValueConfig.java new file mode 100644 index 0000000..f14e7ac --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/core/sync/packets/PacketValueConfig.java @@ -0,0 +1,178 @@ +package net.p455w0rd.wirelesscraftingterminal.core.sync.packets; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import appeng.api.config.FuzzyMode; +import appeng.api.config.Settings; +import appeng.api.util.IConfigManager; +import appeng.api.util.IConfigurableObject; +import appeng.helpers.IMouseWheelItem; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiCraftingCPU; +import net.p455w0rd.wirelesscraftingterminal.common.container.AEBaseContainer; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftConfirm; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftingCPU; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerCraftingStatus; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.core.sync.WCTPacket; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.INetworkInfo; + +public class PacketValueConfig extends WCTPacket +{ + + private final String Name; + private final String Value; + + // automatic. + public PacketValueConfig( final ByteBuf stream ) throws IOException + { + final DataInputStream dis = new DataInputStream( new ByteArrayInputStream( stream.array(), stream.readerIndex(), stream.readableBytes() ) ); + this.Name = dis.readUTF(); + this.Value = dis.readUTF(); + // dis.close(); + } + + // api + public PacketValueConfig( final String name, final String value ) throws IOException + { + this.Name = name; + this.Value = value; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt( this.getPacketID() ); + + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final DataOutputStream dos = new DataOutputStream( bos ); + dos.writeUTF( name ); + dos.writeUTF( value ); + // dos.close(); + + data.writeBytes( bos.toByteArray() ); + + this.configureWrite( data ); + } + + @Override + public void serverPacketData( final INetworkInfo manager, final WCTPacket packet, final EntityPlayer player ) + { + final Container c = player.openContainer; + + if( this.Name.equals( "Item" ) && RandomUtils.getWirelessTerm(player.inventory) != null && RandomUtils.getWirelessTerm(player.inventory).getItem() instanceof IMouseWheelItem ) + { + final ItemStack is = RandomUtils.getWirelessTerm(player.inventory); + final IMouseWheelItem si = (IMouseWheelItem) is.getItem(); + si.onWheel( is, this.Value.equals( "WheelUp" ) ); + } + else if( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftingStatus ) + { + final ContainerCraftingStatus qk = (ContainerCraftingStatus) c; + qk.cycleCpu( this.Value.equals( "Next" ) ); + } + else if( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftConfirm ) + { + final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.cycleCpu( this.Value.equals( "Next" ) ); + } + else if( this.Name.equals( "Terminal.Start" ) && c instanceof ContainerCraftConfirm ) + { + final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.startJob(); + } + else if( this.Name.equals( "TileCrafting.Cancel" ) && c instanceof ContainerCraftingCPU ) + { + final ContainerCraftingCPU qk = (ContainerCraftingCPU) c; + qk.cancelCrafting(); + } + else if( c instanceof IConfigurableObject ) + { + final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); + + for( final Settings e : cm.getSettings() ) + { + if( e.name().equals( this.Name ) ) + { + final Enum def = cm.getSetting( e ); + + try + { + cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); + } + catch( final IllegalArgumentException err ) + { + // :P + } + + break; + } + } + } + } + + @Override + public void clientPacketData( final INetworkInfo network, final WCTPacket packet, final EntityPlayer player ) + { + final Container c = player.openContainer; + + if( this.Name.equals( "CustomName" )) + { + if (c instanceof ContainerWirelessCraftingTerminal) { + ( (ContainerWirelessCraftingTerminal) c ).setCustomName( this.Value ); + } + if (c instanceof AEBaseContainer) { + ( (AEBaseContainer) c ).setCustomName( this.Value ); + } + } + else if( this.Name.startsWith( "SyncDat." ) ) + { + if (c instanceof ContainerWirelessCraftingTerminal) { + ( (ContainerWirelessCraftingTerminal) c ).stringSync( Integer.parseInt( this.Name.substring( 8 ) ), this.Value ); + } + if (c instanceof AEBaseContainer) { + ( (AEBaseContainer) c ).stringSync( Integer.parseInt( this.Name.substring( 8 ) ), this.Value ); + } + } + else if( this.Name.equals( "CraftingStatus" ) && this.Value.equals( "Clear" ) ) + { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + if( gs instanceof GuiCraftingCPU ) + { + ( (GuiCraftingCPU) gs ).clearItems(); + } + } + else if( c instanceof IConfigurableObject ) + { + final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); + + for( final Settings e : cm.getSettings() ) + { + if( e.name().equals( this.Name ) ) + { + final Enum def = cm.getSetting( e ); + + try + { + cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); + } + catch( final IllegalArgumentException err ) + { + // :P + } + + break; + } + } + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/creativetab/CreativeTabWCT.java b/src/java/net/p455w0rd/wirelesscraftingterminal/creativetab/CreativeTabWCT.java new file mode 100644 index 0000000..4e111a7 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/creativetab/CreativeTabWCT.java @@ -0,0 +1,22 @@ +package net.p455w0rd.wirelesscraftingterminal.creativetab; + +import cpw.mods.fml.relauncher.SideOnly; +import cpw.mods.fml.relauncher.Side; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class CreativeTabWCT extends CreativeTabs +{ + public CreativeTabWCT(int id, String unlocalizedName) { + super(id, unlocalizedName); + } + + @Override + public Item getTabIconItem() { + return ItemEnum.WCT_DUMMY_ICON.getItem(); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/AchievementHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/AchievementHandler.java new file mode 100644 index 0000000..cf878a9 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/AchievementHandler.java @@ -0,0 +1,79 @@ +package net.p455w0rd.wirelesscraftingterminal.handlers; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Set; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.PlayerEvent; +import cpw.mods.fml.relauncher.Side; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; +import net.minecraft.potion.Potion; +import net.minecraft.stats.Achievement; +import net.minecraft.stats.AchievementList; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; +import net.minecraftforge.common.AchievementPage; +import net.minecraftforge.common.util.FakePlayer; +import net.minecraftforge.event.entity.player.AchievementEvent; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemInfinityBooster; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class AchievementHandler { + + private static ItemInfinityBooster booster = (ItemInfinityBooster) ItemEnum.BOOSTER_ICON.getItem(); + public static final Achievement wctAch = new Achievement("achievement.wctAchievement", "wctAchievement", 0, 0, ItemEnum.WCT_DUMMY_ICON.getItem(), (Achievement) null); + public static final Achievement boosterAch = new Achievement("achievment.boosterAchievement", "boosterAchievement", 0, 2, booster.hasEffect(true), wctAch); + public static final Achievement magnetAch = new Achievement("achievement.magnetAchievement", "magnetAchievement", 2, 0, ItemEnum.MAGNET_CARD.getItem(), wctAch); + private static final AchievementPage achPage = new AchievementPage("Wireless Crafting Term", wctAch, boosterAch, magnetAch); + + public static void init() { + registerAchievements(); + registerPage(); + //addAchievementToPage(wctAch); + } + + public static void registerAchievements() { + if (!AchievementList.achievementList.contains(wctAch)) { + wctAch.initIndependentStat().registerStat(); + boosterAch.initIndependentStat().registerStat().setSpecial(); + magnetAch.initIndependentStat().registerStat(); + } + } + + public static void registerPage() { + if (AchievementPage.getAchievementPage("Wireless Crafting Term") == null) { + AchievementPage.registerAchievementPage(achPage); + } + } + + public static void addAchievementToPage(Achievement a) { + addAchievementToPage(a, false, null); + } + + public static void addAchievementToPage(Achievement a, boolean hidden, EntityPlayer player) { + if (hidden) { + if (player != null && FMLCommonHandler.instance().getSide() == Side.CLIENT) { + if (!isAchievementUnlocked(player, wctAch) || achPage.getAchievements().contains(boosterAch)) { + return; + } + } + } + achPage.getAchievements().add(a); + } + + public static boolean isAchievementUnlocked(EntityPlayer p, Achievement a) { + return ((EntityPlayerMP) p).func_147099_x().hasAchievementUnlocked(a); + } + + public static void triggerAch(Achievement a, EntityPlayer p) { + p.addStat(a, 1); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/ConfigHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/ConfigHandler.java new file mode 100644 index 0000000..f994cb7 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/ConfigHandler.java @@ -0,0 +1,112 @@ +package net.p455w0rd.wirelesscraftingterminal.handlers; + +import java.io.File; + +import cpw.mods.fml.client.event.ConfigChangedEvent; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationRegistry; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationType; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class ConfigHandler { + public static Configuration config; + public static boolean enableInfinityBooster; + public static boolean enableEasyMode; + public static int ae2wctMaxPower = Reference.WCT_MAX_POWER; + private static boolean doSave; + public static boolean firstLoad = true; + private static int pwrInCfgFile; + + public static void init(File configFile) { + if (config == null) { + config = new Configuration(configFile); + } + doSave = false; + loadConfig(); + } + + @SubscribeEvent + public void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { + if (event.modID.equalsIgnoreCase(Reference.MODID)) { + loadConfig(); + } + } + + private static void loadConfig() { + String pwrDesc = LocaleHandler.MaxPowerDesc.getLocal() + " [default: 1600000, min: 800000, max:6400000]"; + String boosterDesc = LocaleHandler.InfinityBoosterCfgDesc.getLocal(); + String easyModeDesc = LocaleHandler.EasyModeDesc.getLocal(); + enableInfinityBooster = config.getBoolean("enableInfinityBooster", Configuration.CATEGORY_GENERAL, true, boosterDesc); + enableEasyMode = config.getBoolean("enableEasyMode", Configuration.CATEGORY_GENERAL, false, easyModeDesc); + /* + * I did the max power cfg loading like this because while using + * Configuration#getInt did enforce the min/max values in-game, it + * didn't properly update the config file + */ + Property pwrCfgKey = config.get(Configuration.CATEGORY_GENERAL, "ae2wctMaxPower", Reference.WCT_MAX_POWER); + pwrCfgKey.comment = pwrDesc; + pwrCfgKey.setDefaultValue(Reference.WCT_MAX_POWER); + + pwrInCfgFile = pwrCfgKey.getInt(); + ae2wctMaxPower = pwrInCfgFile; + if (pwrInCfgFile > 6400000) { + ae2wctMaxPower = 6400000; + pwrCfgKey.setValue(ae2wctMaxPower); + pwrCfgKey.comment = pwrDesc; + doSave = true; + } else if (pwrInCfgFile < 800000) { + ae2wctMaxPower = 800000; + pwrCfgKey.setValue(ae2wctMaxPower); + pwrCfgKey.comment = pwrDesc; + doSave = true; + } + + Reference.WCT_BOOSTER_ENABLED = enableInfinityBooster; + Reference.WCT_EASYMODE_ENABLED = enableEasyMode; + Reference.WCT_MAX_POWER = ae2wctMaxPower; + + if (config.hasChanged() || doSave) { + config.save(); + reloadRecipes(); + removeBooster(); + removeBoosterIcon(); + } + } + + public static void reloadRecipes() { + WCTLog.info("Reinitializing Recipes"); + RecipeHandler.removeRecipes(); + RecipeHandler.addRecipes(); + } + + public static void removeBoosterIcon() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + if (!codechicken.nei.api.ItemInfo.hiddenItems.contains(ItemEnum.BOOSTER_ICON.getStack())) { + codechicken.nei.api.API.hideItem(ItemEnum.BOOSTER_ICON.getStack()); + } + } + } + + public static void removeBooster() { + if (Reference.WCT_BOOSTER_ENABLED) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + if (codechicken.nei.api.ItemInfo.hiddenItems.contains(ItemEnum.BOOSTER_CARD.getStack())) { + codechicken.nei.api.ItemInfo.hiddenItems.remove(ItemEnum.BOOSTER_CARD.getStack()); + } + } + ItemEnum.BOOSTER_CARD.getItem().setCreativeTab(WirelessCraftingTerminal.creativeTab); + } else { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + codechicken.nei.api.API.hideItem(ItemEnum.BOOSTER_CARD.getStack()); + } + ItemEnum.BOOSTER_CARD.getItem().setCreativeTab(null); + } + ItemEnum.WIRELESS_CRAFTING_TERMINAL.getItem().setCreativeTab(WirelessCraftingTerminal.creativeTab); + ItemEnum.MAGNET_CARD.getItem().setCreativeTab(WirelessCraftingTerminal.creativeTab); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/KeybindHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/KeybindHandler.java new file mode 100644 index 0000000..31f6b40 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/KeybindHandler.java @@ -0,0 +1,54 @@ +package net.p455w0rd.wirelesscraftingterminal.handlers; + +import org.lwjgl.input.Keyboard; + +import cpw.mods.fml.client.FMLClientHandler; +import cpw.mods.fml.client.registry.ClientRegistry; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent; +import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent; +import cpw.mods.fml.common.gameevent.TickEvent.Phase; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.client.settings.KeyBinding; +import net.minecraft.inventory.ContainerPlayer; +import net.p455w0rd.wirelesscraftingterminal.api.WCTApi; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketOpenWirelessTerm; + +@SideOnly(Side.CLIENT) +public class KeybindHandler { + + public static KeyBinding openTerminal; + public static KeyBinding openMagnetFilter; + public static KeyBinding disableMagnet; + + public static void registerKeybinds() { + openTerminal = new KeyBinding("key.OpenTerminal", Keyboard.CHAR_NONE, "key.categories.ae2wct"); + openMagnetFilter = new KeyBinding("key.OpenMagnetFilter", Keyboard.CHAR_NONE, "key.categories.ae2wct"); + disableMagnet = new KeyBinding("key.DisableMagnet", Keyboard.CHAR_NONE, "key.categories.ae2wct"); + ClientRegistry.registerKeyBinding(openTerminal); + ClientRegistry.registerKeyBinding(openMagnetFilter); + ClientRegistry.registerKeyBinding(disableMagnet); + } + + @SubscribeEvent + public void onKeyInput(KeyInputEvent event) { + //if (event.phase == Phase.END) { + EntityClientPlayerMP p = (EntityClientPlayerMP) Minecraft.getMinecraft().thePlayer; + if (openTerminal.isPressed()) { + //if (p.openContainer != null && p.openContainer instanceof ContainerPlayer) { + //WCTApi.instance().interact().openWirelessCraftingTerminalGui(p); + if (!FMLClientHandler.instance().isGUIOpen(GuiWirelessCraftingTerminal.class)) { + NetworkHandler.instance.sendToServer( new PacketOpenWirelessTerm() ); + } + //} + } + //} + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/LocaleHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/LocaleHandler.java new file mode 100644 index 0000000..c594b30 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/LocaleHandler.java @@ -0,0 +1,30 @@ +package net.p455w0rd.wirelesscraftingterminal.handlers; + +import net.minecraft.util.StatCollector; + +public enum LocaleHandler { + + TitleDesc, InfinityBoosterDesc, WirelessTermLabel("gui.labels.ae2wct"), + MaxPowerDesc("config.ae2wct"), InfinityBoosterCfgDesc("config.ae2wct"), EasyModeDesc("config.ae2wct"), + MagnetDesc, MagnetDesc2, PressShift, OnlyWorks, LinkStatus, Installed, NotInstalled, Active, Inactive, + Status, EmptyTrash, EmptyTrashDesc, MagnetFilterTitle, NoNetworkPower("chatmessages.ae2wct"), FilterMode, + Whitelisting, Blacklisting; + + private final String root; + + LocaleHandler() { + this.root = "gui.tooltips.ae2wct"; + } + + LocaleHandler(final String r) { + this.root = r; + } + + public String getLocal() { + return StatCollector.translateToLocal(this.getUnlocalized()); + } + + public String getUnlocalized() { + return this.root + '.' + this.toString(); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/NEIRecipeHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/NEIRecipeHandler.java new file mode 100644 index 0000000..4b16ae5 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/NEIRecipeHandler.java @@ -0,0 +1,46 @@ +package net.p455w0rd.wirelesscraftingterminal.handlers; + +import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.TemplateRecipeHandler; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraftforge.oredict.ShapedOreRecipe; + +public class NEIRecipeHandler extends TemplateRecipeHandler { + + public static NEIRecipeHandler INSTANCE; + + public NEIRecipeHandler() { + INSTANCE = this; + } + + @Override + public String getRecipeName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getGuiTexture() { + // TODO Auto-generated method stub + return null; + } + + public void removeCachedRecipe(IRecipe r) { + ItemStack recipeOutput = null; + if (r instanceof ShapedOreRecipe) { + ShapedOreRecipe recipe = (ShapedOreRecipe) r; + recipeOutput = recipe.getRecipeOutput(); + } + System.out.println("test"); + if (recipeOutput == null) { return; } + for (int i = 0; i < arecipes.size(); i++) { + PositionedStack cachedResult = getResultStack(i); + PositionedStack recipeResult = new PositionedStack(recipeOutput, 119, 24); + if (cachedResult == recipeResult) { + System.out.println("match!"); + } + } + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/RecipeHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/RecipeHandler.java new file mode 100644 index 0000000..ab7274d --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/handlers/RecipeHandler.java @@ -0,0 +1,116 @@ +package net.p455w0rd.wirelesscraftingterminal.handlers; + +import java.util.ArrayList; +import java.util.Iterator; + +import cpw.mods.fml.common.registry.GameRegistry; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.item.crafting.ShapedRecipes; +import net.minecraftforge.oredict.ShapedOreRecipe; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemInfinityBooster; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class RecipeHandler { + + public static ArrayList recipeList = new ArrayList(); + + public static void init() { + Item multiMaterial = GameRegistry.findItem("appliedenergistics2", "item.ItemMultiMaterial"); + Item multiPart = GameRegistry.findItem("appliedenergistics2", "item.ItemMultiPart"); + Item itemWAP = GameRegistry.findItem("appliedenergistics2", "tile.BlockWireless"); + Item ae2WirelessTerm = GameRegistry.findItem("appliedenergistics2", "item.ToolWirelessTerminal"); + Item blockSpatialIO = GameRegistry.findItem("appliedenergistics2", "tile.BlockSpatialPylon"); + Item blockCraftingStorage = GameRegistry.findItem("appliedenergistics2", "tile.BlockCraftingStorage"); + + // Is easy mode enabled? + if (Reference.WCT_EASYMODE_ENABLED) { + + // Wireless Crafting Terminal + recipeList.add(new ShapedOreRecipe(ItemEnum.WIRELESS_CRAFTING_TERMINAL.getStack(), new Object[] { "a", "b", "c", Character.valueOf('a'), new ItemStack(multiMaterial, 1, 41), Character.valueOf('b'), new ItemStack(multiPart, 1, 360), Character.valueOf('c'), new ItemStack(ae2WirelessTerm, 1, 0) })); + + // Magnet Card + recipeList.add(new ShapedOreRecipe(ItemEnum.MAGNET_CARD.getStack(), new Object[] { + "a b", "cdc", "ccc", + Character.valueOf('a'), "dustRedstone", + Character.valueOf('b'), "gemLapis", + Character.valueOf('c'), "ingotIron", + Character.valueOf('d'), new ItemStack(multiMaterial, 1, 28) })); + + // Is Booster Card Enabled? + if (Reference.WCT_BOOSTER_ENABLED) { + // Infinity Booster Card + recipeList.add(new ShapedOreRecipe(ItemEnum.BOOSTER_CARD.getStack(), new Object[] { "abc", "ded", "cba", Character.valueOf('a'), new ItemStack(blockSpatialIO, 1, 0), Character.valueOf('b'), new ItemStack(multiMaterial, 1, 42), Character.valueOf('c'), new ItemStack(blockCraftingStorage, 1, 3), Character.valueOf('d'), new ItemStack(multiMaterial, 1, 48), Character.valueOf('e'), new ItemStack(itemWAP, 1, 0) })); + } + } + else { + // Wireless Crafting Terminal + recipeList.add(new ShapedOreRecipe(ItemEnum.WIRELESS_CRAFTING_TERMINAL.getStack(), new Object[] { "aba", "cdc", "efe", Character.valueOf('a'), new ItemStack(multiMaterial, 1, 9), Character.valueOf('b'), new ItemStack(itemWAP, 1, 0), Character.valueOf('c'), new ItemStack(multiMaterial, 1, 12), Character.valueOf('d'), new ItemStack(multiPart, 1, 360), Character.valueOf('e'), new ItemStack(multiMaterial, 1, 38), Character.valueOf('f'), new ItemStack(multiMaterial, 1, 47) })); + + // Magnet Card + recipeList.add(new ShapedOreRecipe(ItemEnum.MAGNET_CARD.getStack(), new Object[] { + "abc", "ded", "ddd", + Character.valueOf('a'), "blockRedstone", + Character.valueOf('b'), new ItemStack(multiPart, 1, 301), + Character.valueOf('c'), "blockLapis", + Character.valueOf('d'), "blockIron", + Character.valueOf('e'), new ItemStack(multiMaterial, 1, 28) })); + } + + } + + public static void addRecipes() { + addRecipes(false); + } + + public static void addRecipes(boolean init) { + if (init) { + init(); + } + if (recipeList.size() == 0) { + return; + } + for (IRecipe recipe : recipeList) { + GameRegistry.addRecipe(recipe); + WCTLog.info("Added Recipe for " + recipe.getRecipeOutput().getDisplayName()); + } + recipeList.clear(); + init(); + } + + public static void removeRecipes() { + if (recipeList.size() == 0) { + return; + } + Iterator iterator = CraftingManager.getInstance().getRecipeList().iterator(); + while (iterator.hasNext()) { + ItemStack r = iterator.next().getRecipeOutput(); + for (IRecipe recipe : recipeList) { + ItemStack recipeOutput = recipe.getRecipeOutput(); + if (r != null && r.getItem() == recipeOutput.getItem()) { + iterator.remove(); + WCTLog.info("Removed Recipe for " + r.getDisplayName()); + } + } + } + recipeList.clear(); + init(); + /* + * ItemStack recipeRegistryItem = null; ArrayList recipeRegistry = + * (ArrayList) CraftingManager.getInstance().getRecipeList(); for (int i + * = 0; i < recipeRegistry.size(); i++) { IRecipe tmpRecipe = (IRecipe) + * recipeRegistry.get(i); if (tmpRecipe instanceof ShapedOreRecipe) { + * ShapedOreRecipe recipeRegistryRecipe = (ShapedOreRecipe)tmpRecipe; + * recipeRegistryItem = recipeRegistryRecipe.getRecipeOutput(); } else { + * continue; } for (IRecipe recipe : recipeList) { ItemStack + * recipeOutput = recipe.getRecipeOutput(); if + * (ItemStack.areItemStacksEqual(recipeOutput, recipeRegistryItem)) { + * recipeRegistry.remove(i); } } } + */ + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/helpers/Reflected.java b/src/java/net/p455w0rd/wirelesscraftingterminal/helpers/Reflected.java new file mode 100644 index 0000000..1f2cf1f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/helpers/Reflected.java @@ -0,0 +1,17 @@ +package net.p455w0rd.wirelesscraftingterminal.helpers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +/** + * Marker interface to help identify invocation of reflection + */ +@Retention( RetentionPolicy.SOURCE ) +@Target( { ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD } ) +public @interface Reflected +{ + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/helpers/WirelessTerminalGuiObject.java b/src/java/net/p455w0rd/wirelesscraftingterminal/helpers/WirelessTerminalGuiObject.java new file mode 100644 index 0000000..62a325a --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/helpers/WirelessTerminalGuiObject.java @@ -0,0 +1,382 @@ +package net.p455w0rd.wirelesscraftingterminal.helpers; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTIActionHost; +import appeng.api.AEApi; +import appeng.api.config.AccessRestriction; +import appeng.api.config.Actionable; +import appeng.api.config.PowerMultiplier; +import appeng.api.features.ILocatable; +import appeng.api.features.IWirelessTermHandler; +import appeng.api.implementations.guiobjects.IPortableCell; +import appeng.api.implementations.tiles.IWirelessAccessPoint; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; +import appeng.api.networking.IMachineSet; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.security.IActionHost; +import appeng.api.networking.storage.IStorageGrid; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.IMEMonitorHandlerReceiver; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.api.util.AECableType; +import appeng.api.util.DimensionalCoord; +import appeng.api.util.IConfigManager; +import appeng.container.interfaces.IInventorySlotAware; +import appeng.tile.networking.TileWireless; + + +public class WirelessTerminalGuiObject implements IPortableCell, IActionHost, IInventorySlotAware, WCTIActionHost +{ + + private final ItemStack effectiveItem; + private final IWirelessTermHandler wth; + private final String encryptionKey; + private final EntityPlayer myPlayer; + private IGrid targetGrid; + private IStorageGrid sg; + private IMEMonitor itemStorage; + private IWirelessAccessPoint myWap; + private double sqRange = Double.MAX_VALUE; + private double myRange = Double.MAX_VALUE; + private final int inventorySlot; + + public WirelessTerminalGuiObject( final IWirelessTermHandler wh, final ItemStack is, final EntityPlayer ep, final World w, final int x, final int y, final int z ) + { + this.encryptionKey = wh.getEncryptionKey( is ); + this.effectiveItem = is; + this.myPlayer = ep; + this.wth = wh; + this.inventorySlot = x; + + ILocatable obj = null; + + try + { + final long encKey = Long.parseLong( this.encryptionKey ); + obj = AEApi.instance().registries().locatable().getLocatableBy( encKey ); + } + catch( final NumberFormatException err ) + { + // :P + } + + if( obj instanceof IGridHost ) + { + final IGridNode n = ((IGridHost) obj).getGridNode( ForgeDirection.UNKNOWN ); + if( n != null ) + { + this.targetGrid = n.getGrid(); + if( this.targetGrid != null ) + { + this.sg = this.targetGrid.getCache( IStorageGrid.class ); + if( this.sg != null ) + { + this.itemStorage = this.sg.getItemInventory(); + } + } + } + } + } + + public double getRange() + { + return this.myRange; + } + + @Override + public IMEMonitor getItemInventory() + { + if( this.sg == null ) + { + return null; + } + return this.sg.getItemInventory(); + } + + @Override + public IMEMonitor getFluidInventory() + { + if( this.sg == null ) + { + return null; + } + return this.sg.getFluidInventory(); + } + + @Override + public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) + { + if( this.itemStorage != null ) + { + this.itemStorage.addListener( l, verificationToken ); + } + } + + @Override + public void removeListener( final IMEMonitorHandlerReceiver l ) + { + if( this.itemStorage != null ) + { + this.itemStorage.removeListener( l ); + } + } + + @Override + public IItemList getAvailableItems( final IItemList out ) + { + if( this.itemStorage != null ) + { + return this.itemStorage.getAvailableItems( out ); + } + return out; + } + + @Override + public IItemList getStorageList() + { + if( this.itemStorage != null ) + { + return this.itemStorage.getStorageList(); + } + return null; + } + + @Override + public AccessRestriction getAccess() + { + if( this.itemStorage != null ) + { + return this.itemStorage.getAccess(); + } + return AccessRestriction.NO_ACCESS; + } + + @Override + public boolean isPrioritized( final IAEItemStack input ) + { + if( this.itemStorage != null ) + { + return this.itemStorage.isPrioritized( input ); + } + return false; + } + + @Override + public boolean canAccept( final IAEItemStack input ) + { + if( this.itemStorage != null ) + { + return this.itemStorage.canAccept( input ); + } + return false; + } + + @Override + public int getPriority() + { + if( this.itemStorage != null ) + { + return this.itemStorage.getPriority(); + } + return 0; + } + + @Override + public int getSlot() + { + if( this.itemStorage != null ) + { + return this.itemStorage.getSlot(); + } + return 0; + } + + @Override + public boolean validForPass( final int i ) + { + return this.itemStorage.validForPass( i ); + } + + @Override + public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) + { + if( this.itemStorage != null ) + { + return this.itemStorage.injectItems( input, type, src ); + } + return input; + } + + @Override + public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) + { + if( this.itemStorage != null ) + { + return this.itemStorage.extractItems( request, mode, src ); + } + return null; + } + + @Override + public StorageChannel getChannel() + { + if( this.itemStorage != null ) + { + return this.itemStorage.getChannel(); + } + return StorageChannel.ITEMS; + } + + @Override + public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) + { + if( this.wth != null && this.effectiveItem != null ) + { + if( mode == Actionable.SIMULATE ) + { + return this.wth.hasPower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; + } + return this.wth.usePower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; + } + return 0.0; + } + + @Override + public ItemStack getItemStack() + { + return this.effectiveItem; + } + + @Override + public IConfigManager getConfigManager() + { + return this.wth.getConfigManager( this.effectiveItem ); + } + + @Override + public IGridNode getGridNode( final ForgeDirection dir ) + { + return this.getActionableNode(); + } + + @Override + public AECableType getCableConnectionType( final ForgeDirection dir ) + { + return AECableType.NONE; + } + + @Override + public void securityBreak() + { + + } + + @Override + public IGridNode getActionableNode() { + return getActionableNode(false); + } + + public IGridNode getActionableNode(boolean ignoreRange) + { + this.rangeCheck(ignoreRange); + if( this.myWap != null ) + { + return this.myWap.getActionableNode(); + } + return null; + } + + public boolean rangeCheck() { + return rangeCheck(false); + } + + public boolean rangeCheck(boolean ignoreRange) + { + this.sqRange = this.myRange = Double.MAX_VALUE; + + if( this.targetGrid != null && this.itemStorage != null ) + { + if( this.myWap != null ) + { + if( this.myWap.getGrid() == this.targetGrid ) + { + if( this.testWap( this.myWap ) ) + { + return true; + } + } + return false; + } + + final IMachineSet tw = this.targetGrid.getMachines( TileWireless.class ); + + this.myWap = null; + + for( final IGridNode n : tw ) + { + final IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); + if( this.testWap( wap, ignoreRange ) ) + { + this.myWap = wap; + } + } + + return this.myWap != null; + } + return false; + } + + private boolean testWap(final IWirelessAccessPoint wap) { + return testWap(wap, false); + } + + private boolean testWap( final IWirelessAccessPoint wap, boolean ignoreRange ) + { + double rangeLimit = wap.getRange(); + rangeLimit *= rangeLimit; + + final DimensionalCoord dc = wap.getLocation(); + + if( dc.getWorld() == this.myPlayer.worldObj ) + { + final double offX = dc.x - this.myPlayer.posX; + final double offY = dc.y - this.myPlayer.posY; + final double offZ = dc.z - this.myPlayer.posZ; + + final double r = offX * offX + offY * offY + offZ * offZ; + if( r < rangeLimit && this.sqRange > r && !ignoreRange) + { + if( wap.isActive() ) + { + this.sqRange = r; + this.myRange = Math.sqrt( r ); + return true; + } + } + else { + if( wap.isActive() ) + { + this.sqRange = r; + this.myRange = Math.sqrt( r ); + return true; + } + } + } + return false; + } + + @Override + public int getInventorySlot() + { + return this.inventorySlot; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTAPIImplementation.java b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTAPIImplementation.java new file mode 100644 index 0000000..f218606 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTAPIImplementation.java @@ -0,0 +1,66 @@ +package net.p455w0rd.wirelesscraftingterminal.implementation; + +import cpw.mods.fml.common.LoaderState; +import net.p455w0rd.wirelesscraftingterminal.api.IWCTInteractionHelper; +import net.p455w0rd.wirelesscraftingterminal.api.IWCTItems; +import net.p455w0rd.wirelesscraftingterminal.api.WCTApi; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; + +public class WCTAPIImplementation extends WCTApi { + + private final WCTItems items; + private final WCTInteractionHelper interactionHelper; + + private static WCTAPIImplementation INSTANCE = null; + + private WCTAPIImplementation() + { + this.items = new WCTItems(); + this.interactionHelper = new WCTInteractionHelper(); + } + + public static WCTAPIImplementation instance() + { + // Has the singleton been created? + if( WCTAPIImplementation.INSTANCE == null ) + { + // Ensure that preinit has finished. + if( !WCTAPIImplementation.hasFinishedPreInit() ) + { + return null; + } + // Create the singleton. + WCTAPIImplementation.INSTANCE = new WCTAPIImplementation(); + } + return WCTAPIImplementation.INSTANCE; + } + + protected static boolean hasFinishedPreInit() + { + // Ensure that ThE has finished the PreInit phase + if( WirelessCraftingTerminal.getLoaderState() == LoaderState.NOINIT ) + { + // Invalid state, API can not yet load. + WCTLog.warning( "API is not available until WCT finishes the PreInit phase." ); + return false; + } + + return true; + } + + @Override + public IWCTInteractionHelper interact() + { + return this.interactionHelper; + } + + @Override + public IWCTItems items() + { + return this.items; + } + + + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTInteractionHelper.java b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTInteractionHelper.java new file mode 100644 index 0000000..57c3cd8 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTInteractionHelper.java @@ -0,0 +1,100 @@ +package net.p455w0rd.wirelesscraftingterminal.implementation; + +import java.util.ArrayList; + +import appeng.api.implementations.tiles.IWirelessAccessPoint; +import appeng.core.localization.PlayerMessages; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.FakePlayer; +import net.p455w0rd.wirelesscraftingterminal.api.IWCTInteractionHelper; +import net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTermHandler; +import net.p455w0rd.wirelesscraftingterminal.common.WCTGuiHandler; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; + +public class WCTInteractionHelper implements IWCTInteractionHelper { + + @Override + public void openWirelessCraftingTerminalGui(final EntityPlayer player) { + // Valid player? + if ((player == null) || (player instanceof FakePlayer)) { + return; + } + + if (player.worldObj.isRemote) { + return; + } + + InventoryPlayer inv = player.inventory; + int invSize = inv.getSizeInventory(); + if (invSize <= 0) { + return; + } + + // Get the item the first wireless terminal + ItemStack wirelessTerminal = null; + + for (int i = 0; i < invSize; ++i) { + ItemStack item = inv.getStackInSlot(i); + if (item == null) { + continue; + } + if (item.getItem() instanceof ItemWirelessCraftingTerminal) { + wirelessTerminal = item; + break; + } + } + // Ensure the stack is valid + if ((wirelessTerminal == null)) { + // Invalid terminal + return; + } + + // Get the interface + IWirelessCraftingTermHandler terminalInterface = (IWirelessCraftingTermHandler) wirelessTerminal.getItem(); + + // Ensure the terminal has power + if (terminalInterface.getAECurrentPower(wirelessTerminal) == 0) { + // Terminal is dead + player.addChatMessage(PlayerMessages.DeviceNotPowered.get()); + return; + } + + // Ensure the terminal is linked + if (!isTerminalLinked(terminalInterface, wirelessTerminal)) { + // Unlinked terminal + player.addChatMessage(PlayerMessages.DeviceNotLinked.get()); + return; + } + + // Get the encryption key + String encKey = terminalInterface.getEncryptionKey(wirelessTerminal); + + // Are any AP's in range? + ArrayList accessPoints = WirelessAELink.locateAPsInRangeOfPlayer(player, encKey); + + // Error occured + if (accessPoints == null) { + player.addChatMessage(PlayerMessages.StationCanNotBeLocated.get()); + } + // None in range + /* + * else if( accessPoints.isEmpty() ) { player.addChatMessage( + * PlayerMessages.OutOfRange.get() ); player.addChatMessage(new + * ChatComponentText("XX")); } + */ + // Attempt to launch the gui + // NOTE: Range check done in here + else { + WCTGuiHandler.launchGui(WirelessCraftingTerminal.GUI_WCT, player, player.worldObj, (int) player.posX, (int) player.posY, (int) player.posZ); + } + + } + + public static boolean isTerminalLinked(final IWirelessCraftingTermHandler wirelessTerminal, final ItemStack wirelessTerminalItemstack) { + return (!wirelessTerminal.getEncryptionKey(wirelessTerminalItemstack).isEmpty()); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTItemDescription.java b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTItemDescription.java new file mode 100644 index 0000000..90820d7 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTItemDescription.java @@ -0,0 +1,47 @@ +package net.p455w0rd.wirelesscraftingterminal.implementation; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.p455w0rd.wirelesscraftingterminal.api.IWCTItemDescription; + +public class WCTItemDescription implements IWCTItemDescription { + + private Item myItem = null; + private int itemMeta = 0; + + WCTItemDescription( final Item item, final int meta ) + { + this.myItem = item; + this.itemMeta = meta; + } + + WCTItemDescription( final ItemStack stack ) + { + this( stack.getItem(), stack.getItemDamage() ); + } + + @Override + public int getDamage() + { + return this.itemMeta; + } + + @Override + public Item getItem() + { + return this.myItem; + } + + @Override + public ItemStack getStack() + { + return this.getStacks( 1 ); + } + + @Override + public ItemStack getStacks( final int amount ) + { + return new ItemStack( this.myItem, amount, this.itemMeta ); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTItems.java b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTItems.java new file mode 100644 index 0000000..a09f452 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WCTItems.java @@ -0,0 +1,15 @@ +package net.p455w0rd.wirelesscraftingterminal.implementation; + +import net.p455w0rd.wirelesscraftingterminal.api.IWCTItems; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; + +public class WCTItems extends IWCTItems { + + WCTItems() { + this.InfinityBoosterCard = new WCTItemDescription(ItemEnum.BOOSTER_CARD.getStack()); + this.WirelessCraftingTerminal = new WCTItemDescription(ItemEnum.WIRELESS_CRAFTING_TERMINAL.getStack()); + this.WCTDummyIcon = new WCTItemDescription(ItemEnum.WCT_DUMMY_ICON.getStack()); + this.WCTBoosterBGIcon = new WCTItemDescription(ItemEnum.WCT_BOOSTER_BG_ICON.getStack()); + this.MagnetCard = new WCTItemDescription(ItemEnum.MAGNET_CARD.getStack()); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WirelessAELink.java b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WirelessAELink.java new file mode 100644 index 0000000..dfb22b4 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/implementation/WirelessAELink.java @@ -0,0 +1,468 @@ +package net.p455w0rd.wirelesscraftingterminal.implementation; + +import java.util.ArrayList; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import appeng.api.AEApi; +import appeng.api.implementations.tiles.IWirelessAccessPoint; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridNode; +import appeng.api.networking.IMachineSet; +import appeng.api.networking.energy.IEnergyGrid; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.storage.IStorageGrid; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.IStorageMonitorable; +import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.util.DimensionalCoord; +import appeng.tile.misc.TileSecurity; +import appeng.tile.networking.TileWireless; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.MachineSource; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTPlayerSource; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTIActionHost; + +/** + * Provides wireless access to a ME network. + * + * @author Nividica + * + */ +public abstract class WirelessAELink implements IStorageMonitorable { + /** + * The player who owns this link. + */ + protected final EntityPlayer player; + + /** + * Encryption key used to access the network. + */ + protected final String encryptionKey; + + /** + * Access point used to communicate with the AE network. + */ + protected IWirelessAccessPoint accessPoint; + + /** + * Where in the world is the access point. + */ + protected DimensionalCoord apLocation = null; + + /** + * Network source representing the player + */ + protected BaseActionSource actionSource; + + public WirelessAELink( final @Nullable EntityPlayer player, @Nonnull final String encryptionKey ) + { + // Set the player + this.player = player; + + // Set the enc key + this.encryptionKey = encryptionKey; + + // Link with the AP + this.linkWithNewAP(); + } + + /** + * Checks if the AP at the specified location and has the specified range, + * is close enough to communicate with. + * + * @param APLocation + * @param APRange + * @param world + * @param x + * @param y + * @param z + * @return + */ + private static boolean isAPInRange( final DimensionalCoord APLocation, final double APRange, final World world, final int x, final int y, + final int z ) + { + // Is the AP in the same world? + if( !APLocation.isInWorld( world ) ) + { + return false; + } + + // Calculate the square distance + double squareDistance = getSquaredDistanceFromAP( APLocation, x, y, z ); + + // Return if close enough to use AP + return squareDistance <= ( APRange * APRange ); + } + + /** + * @param world + * @param x + * @param y + * @param z + * @param grid + * @return + */ + private static ArrayList locateAPsInRange( final World world, final int x, final int y, final int z, final IGrid grid ) + { + // Get all AP's on the grid + IMachineSet accessPoints = grid.getMachines( TileWireless.class ); + if( accessPoints.isEmpty() ) + { + return null; + } + + // Create the list + ArrayList aps = new ArrayList(); + + // Loop over AP's and see if any are close enough to communicate with + for( IGridNode APNode : accessPoints ) + { + // Get the AP + IWirelessAccessPoint AP = (IWirelessAccessPoint)APNode.getMachine(); + + // Is the AP active? + if( AP.isActive() ) + { + // Close enough to the AP? + if( isAPInRange( AP.getLocation(), AP.getRange(), world, x, y, z ) ) + { + aps.add( AP ); + } + } + } + + return aps; + } + + /** + * Returns the squared distance the specified coords are from the Access Point. + * + * @param locationAP + * @param x + * @param y + * @param z + * @return + */ + protected static double getSquaredDistanceFromAP( final DimensionalCoord locationAP, final int x, final int y, final int z ) + { + if( locationAP == null ) + { + return Double.MAX_VALUE; + } + + // Calculate the distance from the AP + int dX = locationAP.x - x, dY = locationAP.y - y, dZ = locationAP.z - z; + + // Calculate the square distance + return( ( dX * dX ) + ( dY * dY ) + ( dZ * dZ ) ); + } + + /** + * Returns an unsorted list of AP's in range. + * + * @param world + * @param x + * @param y + * @param z + * @param encryptionKey + * @return Null on error, list of AP's in range otherwise. + */ + public static ArrayList locateAPsInRange( final World world, final int x, final int y, final int z, + final String encryptionKey ) + { + // Get the encryption key + long encryptionValue; + try + { + encryptionValue = Long.parseLong( encryptionKey ); + } + catch( NumberFormatException e ) + { + // Invalid security key + return null; + } + + // Get the linked source + Object source = AEApi.instance().registries().locatable().getLocatableBy( encryptionValue ); + + // Ensure it is a security terminal + if( !( source instanceof TileSecurity ) ) + { + // Invalid security terminal + return null; + } + + // Get the terminal + TileSecurity securityHost = (TileSecurity)source; + + // Get the grid + IGrid grid; + try + { + grid = securityHost.getGridNode( ForgeDirection.UNKNOWN ).getGrid(); + } + catch( Exception e ) + { + // Can not find the grid + return null; + } + + return locateAPsInRange( world, x, y, z, grid ); + } + + /** + * Returns an unsorted list of AP's in range. + * + * @param player + * @param encryptionKey + * @return Null on error, list of AP's in range otherwise. + */ + public static ArrayList locateAPsInRangeOfPlayer( final EntityPlayer player, final String encryptionKey ) + { + return locateAPsInRange( player.worldObj, + (int)Math.floor( player.posX ), + (int)Math.floor( player.posY ), + (int)Math.floor( player.posZ ), encryptionKey ); + } + + /** + * Checks if the AP is still active and in range. + * + * @return + */ + private boolean isAPInRangeAndActive() + { + // Has AP? + if( this.accessPoint != null ) + { + // Is active? + if( this.accessPoint.isActive() ) + { + // In range? + return isAPInRange( this.apLocation, this.accessPoint.getRange(), this.getUserWorld(), + this.getUserPositionX(), this.getUserPositionY(), this.getUserPositionZ() ); + } + } + return false; + } + + /** + * Locates the closest AP in range and links with it. + * + * @return True if AP linked with. + */ + private boolean linkWithNewAP() + { + World w = this.getUserWorld(); + int x = this.getUserPositionX(); + int y = this.getUserPositionY(); + int z = this.getUserPositionZ(); + + IGrid grid = null; + if( this.accessPoint != null ) + { + try + { + grid = this.accessPoint.getGrid(); + } + catch( Exception e ) + { + } + } + + // Get a list of AP's in range + ArrayList apList; + if( grid != null ) + { + apList = locateAPsInRange( w, x, y, z, grid ); + } + else + { + apList = locateAPsInRange( w, x, y, z, this.encryptionKey ); + } + + if( ( apList == null ) || ( apList.isEmpty() ) ) + { + // No valid AP's found + this.accessPoint = null; + return false; + } + + // Get the closest + IWirelessAccessPoint closest = null; + double closestDistance = Double.MAX_VALUE; + for( IWirelessAccessPoint ap : apList ) + { + double dist = getSquaredDistanceFromAP( ap.getLocation(), x, y, z ); + if( dist < closestDistance ) + { + closestDistance = dist; + closest = ap; + } + } + + // Set the closest as the AP to use + this.setAP( closest ); + + return true; + } + + /** + * Set's the access point used for communication. + * + * @param accessPoint + */ + private void setAP( final IWirelessAccessPoint accessPoint ) + { + // Set the access point + this.accessPoint = accessPoint; + + // Get the location of the access point + this.apLocation = this.accessPoint.getLocation(); + + // Create the action source + if( this.player != null ) + { + this.actionSource = new WCTPlayerSource( this.player, (WCTIActionHost) this.accessPoint ); + } + else + { + this.actionSource = new MachineSource( (WCTIActionHost) this.accessPoint ); + } + } + + /** + * Return the x position of the user. + * + * @return + */ + protected abstract int getUserPositionX(); + + /** + * Return the y position of the user. + * + * @return + */ + protected abstract int getUserPositionY(); + + /** + * Return the z position of the user. + * + * @return + */ + protected abstract int getUserPositionZ(); + + /** + * Return the world the user is in. + * + * @return + */ + protected abstract World getUserWorld(); + + /** + * Is there enough local power to communicate with the AP? + * + * @return + */ + protected abstract boolean hasPowerToCommunicate(); + + public IEnergyGrid getEnergyGrid() + { + // Check AP + if( this.accessPoint == null ) + { + return null; + } + + try + { + // Get the energy grid + return this.accessPoint.getActionableNode().getGrid().getCache( IEnergyGrid.class ); + } + catch( Exception e ) + { + // Ignored + } + + return null; + } + + @Override + public IMEMonitor getFluidInventory() + { + // Check connectivity + if( ( this.accessPoint == null ) || !this.isConnected() ) + { + return null; + } + + try + { + // Get the storage grid + IStorageGrid storageGrid = this.accessPoint.getActionableNode().getGrid().getCache( IStorageGrid.class ); + + // Return the monitor + return storageGrid.getFluidInventory(); + } + catch( Exception e ) + { + // Ignored + } + + return null; + } + + @Override + public IMEMonitor getItemInventory() + { + // Check connectivity + if( ( this.accessPoint == null ) || !this.isConnected() ) + { + return null; + } + + try + { + // Get the storage grid + IStorageGrid storageGrid = this.accessPoint.getActionableNode().getGrid().getCache( IStorageGrid.class ); + + // Return the monitor + return storageGrid.getItemInventory(); + } + catch( Exception e ) + { + // Ignored + } + + return null; + } + + /** + * Checks if the AP is still connected. + * + * @return + */ + public boolean isConnected() + { + // Is there power? + if( !this.hasPowerToCommunicate() ) + { + return false; + } + + // Is the current AP still good? + if( this.isAPInRangeAndActive() ) + { + // Current AP is still connected. + return true; + } + + // Attempt to link with a new AP + return this.linkWithNewAP(); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IIntegrationModule.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IIntegrationModule.java new file mode 100644 index 0000000..e3b3d90 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IIntegrationModule.java @@ -0,0 +1,8 @@ +package net.p455w0rd.wirelesscraftingterminal.integration; + +public interface IIntegrationModule +{ + void init() throws Throwable; + + void postInit(); +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationHelper.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationHelper.java new file mode 100644 index 0000000..d080b82 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationHelper.java @@ -0,0 +1,10 @@ +package net.p455w0rd.wirelesscraftingterminal.integration; + +public class IntegrationHelper +{ + + public static void testClassExistence( final Object o, final Class clz ) + { + clz.isInstance( o ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationNode.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationNode.java new file mode 100644 index 0000000..c18e06c --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationNode.java @@ -0,0 +1,146 @@ +package net.p455w0rd.wirelesscraftingterminal.integration; + +import java.lang.reflect.Field; + +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.ModAPIManager; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.ModNotInstalled; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; + + +public final class IntegrationNode +{ + + private final String displayName; + private final String modID; + private final IntegrationType shortName; + private IntegrationStage state = IntegrationStage.PRE_INIT; + private IntegrationStage failedStage = IntegrationStage.PRE_INIT; + private Throwable exception = null; + private String name = null; + private Class classValue = null; + private Object instance; + private IIntegrationModule mod = null; + + public IntegrationNode( final String displayName, final String modID, final IntegrationType shortName, final String name ) + { + this.displayName = displayName; + this.shortName = shortName; + this.modID = modID; + this.name = name; + } + + @Override + public String toString() + { + return this.getShortName().name() + ':' + this.getState().name(); + } + + boolean isActive() + { + if( this.getState() == IntegrationStage.PRE_INIT ) + { + this.call( IntegrationStage.PRE_INIT ); + } + + return this.getState() != IntegrationStage.FAILED; + } + + void call( final IntegrationStage stage ) + { + if( this.getState() != IntegrationStage.FAILED ) + { + if( this.getState().ordinal() > stage.ordinal() ) + { + return; + } + + try + { + switch( stage ) + { + case PRE_INIT: + final ModAPIManager apiManager = ModAPIManager.INSTANCE; + boolean enabled = this.modID == null || Loader.isModLoaded( this.modID ) || apiManager.hasAPI( this.modID ); + + if( enabled ) + { + this.classValue = this.getClass().getClassLoader().loadClass( this.name ); + this.mod = (IIntegrationModule) this.classValue.getConstructor().newInstance(); + final Field f = this.classValue.getField( "instance" ); + f.set( this.classValue, this.setInstance( this.mod ) ); + } + else + { + throw new ModNotInstalled( this.modID ); + } + + this.setState( IntegrationStage.INIT ); + + break; + case INIT: + this.mod.init(); + this.setState( IntegrationStage.POST_INIT ); + + break; + case POST_INIT: + this.mod.postInit(); + this.setState( IntegrationStage.READY ); + + break; + case FAILED: + default: + break; + } + } + catch( final Throwable t ) + { + this.failedStage = stage; + this.exception = t; + this.setState( IntegrationStage.FAILED ); + } + } + + if( stage == IntegrationStage.POST_INIT ) + { + if( this.getState() == IntegrationStage.FAILED ) + { + WCTLog.info( this.displayName + " - Integration Disabled" ); + if( !( this.exception instanceof ModNotInstalled ) ) + { + WCTLog.integration( this.exception ); + } + } + else + { + WCTLog.info( this.displayName + " - Integration Enable" ); + } + } + } + + Object getInstance() + { + return this.instance; + } + + private Object setInstance( final Object instance ) + { + this.instance = instance; + return instance; + } + + IntegrationType getShortName() + { + return this.shortName; + } + + IntegrationStage getState() + { + return this.state; + } + + private void setState( final IntegrationStage state ) + { + this.state = state; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationRegistry.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationRegistry.java new file mode 100644 index 0000000..3c75b61 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationRegistry.java @@ -0,0 +1,100 @@ +package net.p455w0rd.wirelesscraftingterminal.integration; + +import java.util.Collection; +import java.util.LinkedList; + +import javax.annotation.Nonnull; + +import cpw.mods.fml.relauncher.FMLLaunchHandler; +import cpw.mods.fml.relauncher.Side; + + +public enum IntegrationRegistry +{ + INSTANCE; + + private static final String PACKAGE_PREFIX = "net.p455w0rd.wirelesscraftingterminal.integration.modules."; + + private final Collection modules = new LinkedList(); + + public void add( final IntegrationType type ) + { + if( type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER ) + { + return; + } + + if( type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT ) + { + return; + } + + this.modules.add( new IntegrationNode( type.dspName, type.modID, type, PACKAGE_PREFIX + type.name() ) ); + } + + public void init() + { + for( final IntegrationNode node : this.modules ) + { + node.call( IntegrationStage.PRE_INIT ); + } + + for( final IntegrationNode node : this.modules ) + { + node.call( IntegrationStage.INIT ); + } + } + + public void postInit() + { + for( final IntegrationNode node : this.modules ) + { + node.call( IntegrationStage.POST_INIT ); + } + } + + public String getStatus() + { + final StringBuilder builder = new StringBuilder( this.modules.size() * 3 ); + + for( final IntegrationNode node : this.modules ) + { + if( builder.length() != 0 ) + { + builder.append( ", " ); + } + + final String integrationState = node.getShortName() + ":" + ( node.getState() == IntegrationStage.FAILED ? "OFF" : "ON" ); + builder.append( integrationState ); + } + + return builder.toString(); + } + + public boolean isEnabled( final IntegrationType name ) + { + for( final IntegrationNode node : this.modules ) + { + if( node.getShortName() == name ) + { + return node.isActive(); + } + } + return false; + } + + @Nonnull + public Object getInstance( final IntegrationType name ) + { + for( final IntegrationNode node : this.modules ) + { + if( node.getShortName() == name && node.isActive() ) + { + return node.getInstance(); + } + } + + throw new IllegalStateException( "integration with " + name.name() + " is disabled." ); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationSide.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationSide.java new file mode 100644 index 0000000..17cb3e4 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationSide.java @@ -0,0 +1,6 @@ +package net.p455w0rd.wirelesscraftingterminal.integration; + +public enum IntegrationSide +{ + CLIENT, SERVER, BOTH +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationStage.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationStage.java new file mode 100644 index 0000000..32158f0 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationStage.java @@ -0,0 +1,10 @@ +package net.p455w0rd.wirelesscraftingterminal.integration; + +public enum IntegrationStage +{ + + PRE_INIT, INIT, POST_INIT, + + FAILED, READY + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationType.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationType.java new file mode 100644 index 0000000..c184d93 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/IntegrationType.java @@ -0,0 +1,25 @@ +package net.p455w0rd.wirelesscraftingterminal.integration; + +public enum IntegrationType +{ + + RFItem( IntegrationSide.BOTH, "RedstoneFlux Power - Items", "CoFHAPI" ), + + //Waila( IntegrationSide.BOTH, "Waila", "Waila" ), + + //InvTweaks( IntegrationSide.CLIENT, "Inventory Tweaks", "inventorytweaks" ), + + NEI( IntegrationSide.CLIENT, "Not Enough Items", "NotEnoughItems" ); + + public final IntegrationSide side; + public final String dspName; + public final String modID; + + IntegrationType( final IntegrationSide side, final String name, final String modid ) + { + this.side = side; + this.dspName = name; + this.modID = modid; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/abstraction/INEI.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/abstraction/INEI.java new file mode 100644 index 0000000..580b96f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/abstraction/INEI.java @@ -0,0 +1,11 @@ +package net.p455w0rd.wirelesscraftingterminal.integration.abstraction; + +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.inventory.Slot; + +public interface INEI { + + void drawSlot(Slot s); + + RenderItem setItemRender(RenderItem renderItem); +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEI.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEI.java new file mode 100644 index 0000000..326e233 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEI.java @@ -0,0 +1,288 @@ +package net.p455w0rd.wirelesscraftingterminal.integration.modules; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import appeng.api.AEApi; +import appeng.api.storage.data.IAEItemStack; +import appeng.util.Platform; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.client.me.AppEngRenderItem; +import net.p455w0rd.wirelesscraftingterminal.common.container.ContainerWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotCraftingMatrix; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotFakeCraftingMatrix; +import net.p455w0rd.wirelesscraftingterminal.common.utils.WCTLog; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketNEIRecipe; +import net.p455w0rd.wirelesscraftingterminal.helpers.Reflected; +import net.p455w0rd.wirelesscraftingterminal.integration.IIntegrationModule; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationHelper; +import net.p455w0rd.wirelesscraftingterminal.integration.abstraction.INEI; +import net.p455w0rd.wirelesscraftingterminal.integration.modules.NEIHelpers.NEIAEShapedRecipeHandler; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; +import codechicken.nei.PositionedStack; +import codechicken.nei.api.API; +import codechicken.nei.api.IOverlayHandler; +import codechicken.nei.api.IStackPositioner; +import codechicken.nei.guihook.GuiContainerManager; +import codechicken.nei.guihook.IContainerTooltipHandler; +import codechicken.nei.recipe.IRecipeHandler; + +public class NEI implements INEI, IContainerTooltipHandler, IIntegrationModule { + @Reflected + public static NEI instance; + + private final Class apiClass; + + @Reflected + public NEI() throws ClassNotFoundException { + IntegrationHelper.testClassExistence(this, codechicken.nei.api.API.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.api.IStackPositioner.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.guihook.GuiContainerManager.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.PositionedStack.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.recipe.IRecipeHandler.class); + this.apiClass = Class.forName("codechicken.nei.api.API"); + } + + @Override + public void init() throws Throwable { + // large stack tooltips + GuiContainerManager.addTooltipHandler( this ); + + // wireless crafting terminal... + + API.registerGuiOverlay(net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal.class, "crafting", new WCTSlotPositioner()); + API.registerGuiOverlayHandler(net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal.class, new WCTOverlayHandler(), "crafting"); + API.registerRecipeHandler(new NEIAEShapedRecipeHandler()); + + /* + final Method registerGuiOverlay = this.apiClass.getDeclaredMethod("registerGuiOverlay", Class.class, String.class, IStackPositioner.class); + registerGuiOverlay.invoke(this.apiClass, net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal.class, "crafting", + new WCTSlotPositioner()); + + final Class overlayHandler = Class.forName("codechicken.nei.api.IOverlayHandler"); + WCTOverlayHandler craftingOverlayHandler = new WCTOverlayHandler(); + final Method registrar = this.apiClass.getDeclaredMethod("registerGuiOverlayHandler", Class.class, overlayHandler, String.class); + registrar.invoke(this.apiClass, net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal.class, + craftingOverlayHandler, "crafting"); + */ + + + // final Class defaultHandler = + // NEICraftingHandler.class; + // final Constructor defaultConstructor = defaultHandler.getConstructor( + // int.class, int.class ); + + } + + @Override + public void postInit() { + + } + + @Override + public void drawSlot(final Slot s) { + if (s == null) { + return; + } + + final ItemStack stack = s.getStack(); + + if (stack == null) { + return; + } + + final Minecraft mc = Minecraft.getMinecraft(); + final FontRenderer fontRenderer = mc.fontRenderer; + final int x = s.xDisplayPosition; + final int y = s.yDisplayPosition; + + GuiContainerManager.drawItems.renderItemAndEffectIntoGUI(fontRenderer, mc.getTextureManager(), stack, x, y); + GuiContainerManager.drawItems.renderItemOverlayIntoGUI(fontRenderer, mc.getTextureManager(), stack, x, y, + String.valueOf(stack.stackSize)); + } + + @Override + public RenderItem setItemRender(final RenderItem renderItem) { + try { + final RenderItem ri = GuiContainerManager.drawItems; + GuiContainerManager.drawItems = renderItem; + return ri; + } catch (final Throwable t) { + throw new IllegalStateException("Invalid version of NEI, please update", t); + } + } + + @Override + public List handleTooltip(final GuiContainer arg0, final int arg1, final int arg2, + final List current) { + return current; + } + + @Override + public List handleItemDisplayName(final GuiContainer arg0, final ItemStack arg1, + final List current) { + return current; + } + + @Override + public List handleItemTooltip(final GuiContainer guiScreen, final ItemStack stack, final int mouseX, + final int mouseY, final List currentToolTip) { + if (guiScreen instanceof GuiWirelessCraftingTerminal) { + return ((GuiWirelessCraftingTerminal) guiScreen).handleItemTooltip(stack, mouseX, mouseY, currentToolTip); + } + + return currentToolTip; + } + + static final int NEI_REGULAR_SLOT_OFFSET_X = 25; + static final int NEI_REGULAR_SLOT_OFFSET_Y = 6; + + public class WCTSlotPositioner implements IStackPositioner { + + @Override + public ArrayList positionStacks(final ArrayList stacks) { + // Adjust the position of the ghost stacks to match the crafting + // grid slots + + for (final PositionedStack positionedStack : stacks) { + if (positionedStack.items != null && positionedStack.items.length > 0) { + positionedStack.relx += ContainerWirelessCraftingTerminal.CRAFTING_SLOT_X_POS + - NEI.NEI_REGULAR_SLOT_OFFSET_X; + positionedStack.rely += ContainerWirelessCraftingTerminal.CRAFTING_SLOT_Y_POS + - NEI.NEI_REGULAR_SLOT_OFFSET_Y; + } + } + return stacks; + } + } + + public class WCTOverlayHandler implements IOverlayHandler { + /** + * Reduces regular slot offsets to 0, 1, or 2 + */ + private static final int REGULAR_SLOT_INDEX_DIVISOR = 18; + + /** + * Adds NEI ingredients to the WCT crafting grid. + * + * @param ingredient + * @param overlayItems + * @return + */ + private boolean addCraftingItems(final PositionedStack ingredient, final IAEItemStack[] overlayItems) { + // Calculate the slot positions + int slotX = (ingredient.relx - NEI.NEI_REGULAR_SLOT_OFFSET_X) + / WCTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR; + int slotY = (ingredient.rely - NEI.NEI_REGULAR_SLOT_OFFSET_Y) + / WCTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR; + // Calculate the slot index + int slotIndex = slotX + (slotY * 3); + // Add the item to the list + overlayItems[slotIndex] = AEApi.instance().storage().createItemStack(ingredient.item); + return true; + } + + protected boolean addIngredientToItems(final PositionedStack ingredient, final IAEItemStack[] overlayItems) { + // Pass to regular handler + return this.addCraftingItems(ingredient, overlayItems); + } + + protected void addItemsToGUI(final IAEItemStack[] overlayItems) { + // Send the list to the server + // Packet_S_WCT.sendSetCrafting_NEI(Minecraft.getMinecraft().thePlayer, + // overlayItems); + } + + @Override + public void overlayRecipe( final GuiContainer gui, final IRecipeHandler recipe, final int recipeIndex, final boolean shift ) + { + try + { + final List ingredients = recipe.getIngredientStacks( recipeIndex ); + this.overlayRecipe( gui, ingredients, shift ); + } + catch( final Exception ignored ) + { + } + catch( final Error ignored ) + { + } + } + + private void overlayRecipe( final GuiContainer gui, final List ingredients, final boolean shift ) + { + try + { + final NBTTagCompound recipe = new NBTTagCompound(); + + if( gui instanceof GuiWirelessCraftingTerminal ) + { + for( final PositionedStack positionedStack : ingredients ) + { + final int col = ( positionedStack.relx - 25 ) / 18; + final int row = ( positionedStack.rely - 6 ) / 18; + if( positionedStack.items != null && positionedStack.items.length > 0 ) + { + for( final Slot slot : (List) gui.inventorySlots.inventorySlots ) + { + if( slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix ) + { + if( slot.getSlotIndex() == col + row * 3 ) + { + final NBTTagList tags = new NBTTagList(); + final List list = new LinkedList(); + + // prefer regular crystals. + for( int x = 0; x < positionedStack.items.length; x++ ) + { + if( !Platform.isRecipePrioritized( positionedStack.items[x] ) ) + { + list.add( 0, positionedStack.items[x] ); + } + else + { + list.add( positionedStack.items[x] ); + } + } + + for( final ItemStack is : list ) + { + final NBTTagCompound tag = new NBTTagCompound(); + is.writeToNBT( tag ); + tags.appendTag( tag ); + } + + recipe.setTag( "#" + slot.getSlotIndex(), tags ); + break; + } + } + } + } + } + + NetworkHandler.instance.sendToServer( new PacketNEIRecipe( recipe ) ); + } + } + catch( final Exception ignored ) + { + } + catch( final Error ignored ) + { + } + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java new file mode 100644 index 0000000..f7c4eb9 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java @@ -0,0 +1,243 @@ +package net.p455w0rd.wirelesscraftingterminal.integration.modules.NEIHelpers; + +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.gui.inventory.GuiCrafting; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.MissingIngredientError; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.RegistrationError; +import net.p455w0rd.wirelesscraftingterminal.api.recipes.IIngredient; +import net.p455w0rd.wirelesscraftingterminal.api.recipes.game.ShapedRecipe; +import codechicken.nei.NEIClientUtils; +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; +import codechicken.nei.api.DefaultOverlayRenderer; +import codechicken.nei.api.IOverlayHandler; +import codechicken.nei.api.IRecipeOverlayRenderer; +import codechicken.nei.api.IStackPositioner; +import codechicken.nei.recipe.RecipeInfo; +import codechicken.nei.recipe.TemplateRecipeHandler; + +import appeng.core.AEConfig; +import appeng.util.Platform; + + +public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler +{ + + @Override + public void loadTransferRects() + { + this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); + } + + @Override + public void loadCraftingRecipes( final String outputId, final Object... results ) + { + if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapedRecipeHandler.class ) ) + { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for( final IRecipe recipe : recipes ) + { + if( ( recipe instanceof ShapedRecipe ) ) + { + if( ( (ShapedRecipe) recipe ).isEnabled() ) + { + final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); + cachedRecipe.computeVisuals(); + this.arecipes.add( cachedRecipe ); + } + } + } + } + else + { + super.loadCraftingRecipes( outputId, results ); + } + } + + @Override + public void loadCraftingRecipes( final ItemStack result ) + { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for( final IRecipe recipe : recipes ) + { + if( ( recipe instanceof ShapedRecipe ) ) + { + if( ( (ShapedRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) + { + final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); + cachedRecipe.computeVisuals(); + this.arecipes.add( cachedRecipe ); + } + } + } + } +/* + @Override + public void loadUsageRecipes( final ItemStack ingredient ) + { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for( final IRecipe recipe : recipes ) + { + if( ( recipe instanceof ShapedRecipe ) ) + { + final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); + + if( ( (ShapedRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) + { + cachedRecipe.computeVisuals(); + if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) + { + cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); + this.arecipes.add( cachedRecipe ); + } + } + } + } + } +*/ + @Override + public String getGuiTexture() + { + return "textures/gui/container/crafting_table.png"; + } + + @Override + public String getOverlayIdentifier() + { + return "crafting"; + } + + @Override + public Class getGuiClass() + { + return GuiCrafting.class; + } + + @Override + public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) + { + return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) + { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); + if( renderer != null ) + { + return renderer; + } + + final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); + if( positioner == null ) + { + return null; + } + + return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); + } + + @Override + public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) + { + final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); + if( handler != null ) + { + return handler; + } + + return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); + } + + private boolean isRecipe2x2( final int recipe ) + { + for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) + { + if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) + { + return false; + } + } + return true; + } + + @Override + public String getRecipeName() + { + return NEIClientUtils.translate( "recipe.shaped" ); + } + + private class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe + { + + private final List ingredients; + private final PositionedStack result; + + public CachedShapedRecipe( final ShapedRecipe recipe ) + { + this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); + this.ingredients = new ArrayList(); + this.setIngredients( recipe.getWidth(), recipe.getHeight(), recipe.getIngredients() ); + } + + private void setIngredients( final int width, final int height, final Object[] items ) + { + final boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); + for( int x = 0; x < width; x++ ) + { + for( int y = 0; y < height; y++ ) + { + if( items[( y * width + x )] != null ) + { + final IIngredient ing = (IIngredient) items[( y * width + x )]; + + try + { + final ItemStack[] is = ing.getItemStackSet(); + final PositionedStack stack = new PositionedStack( useSingleItems ? Platform.findPreferred( is ) : is, 25 + x * 18, 6 + y * 18, false ); + stack.setMaxSize( 1 ); + this.ingredients.add( stack ); + } + catch( final RegistrationError ignored ) + { + + } + catch( final MissingIngredientError ignored ) + { + + } + } + } + } + } + + @Override + public PositionedStack getResult() + { + return this.result; + } + + @Override + public List getIngredients() + { + return this.getCycledIngredients( NEIAEShapedRecipeHandler.this.cycleticks / 20, this.ingredients ); + } + + private void computeVisuals() + { + for( final PositionedStack p : this.ingredients ) + { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java new file mode 100644 index 0000000..941e795 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java @@ -0,0 +1,244 @@ +package net.p455w0rd.wirelesscraftingterminal.integration.modules.NEIHelpers; + +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.gui.inventory.GuiCrafting; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.item.crafting.IRecipe; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.MissingIngredientError; +import net.p455w0rd.wirelesscraftingterminal.api.exceptions.RegistrationError; +import net.p455w0rd.wirelesscraftingterminal.api.recipes.IIngredient; +import net.p455w0rd.wirelesscraftingterminal.api.recipes.game.ShapelessRecipe; +import codechicken.nei.NEIClientUtils; +import codechicken.nei.NEIServerUtils; +import codechicken.nei.PositionedStack; +import codechicken.nei.api.DefaultOverlayRenderer; +import codechicken.nei.api.IOverlayHandler; +import codechicken.nei.api.IRecipeOverlayRenderer; +import codechicken.nei.api.IStackPositioner; +import codechicken.nei.recipe.RecipeInfo; +import codechicken.nei.recipe.TemplateRecipeHandler; + +import appeng.core.AEConfig; +import appeng.util.Platform; + + +public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler +{ + + @Override + public void loadTransferRects() + { + this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); + } + + @Override + public void loadCraftingRecipes( final String outputId, final Object... results ) + { + if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapelessRecipeHandler.class ) ) + { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for( final IRecipe recipe : recipes ) + { + if( ( recipe instanceof ShapelessRecipe ) ) + { + if( ( (ShapelessRecipe) recipe ).isEnabled() ) + { + final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); + cachedRecipe.computeVisuals(); + this.arecipes.add( cachedRecipe ); + } + } + } + } + else + { + super.loadCraftingRecipes( outputId, results ); + } + } + + @Override + public void loadCraftingRecipes( final ItemStack result ) + { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for( final IRecipe recipe : recipes ) + { + if( ( recipe instanceof ShapelessRecipe ) ) + { + if( ( (ShapelessRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) + { + final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); + cachedRecipe.computeVisuals(); + this.arecipes.add( cachedRecipe ); + } + } + } + } + + @Override + public void loadUsageRecipes( final ItemStack ingredient ) + { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for( final IRecipe recipe : recipes ) + { + if( ( recipe instanceof ShapelessRecipe ) ) + { + final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); + + if( ( (ShapelessRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) + { + cachedRecipe.computeVisuals(); + if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) + { + cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); + this.arecipes.add( cachedRecipe ); + } + } + } + } + } + + @Override + public String getGuiTexture() + { + return "textures/gui/container/crafting_table.png"; + } + + @Override + public String getOverlayIdentifier() + { + return "crafting"; + } + + @Override + public Class getGuiClass() + { + return GuiCrafting.class; + } + + @Override + public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) + { + return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) + { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); + if( renderer != null ) + { + return renderer; + } + + final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); + if( positioner == null ) + { + return null; + } + + return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); + } + + @Override + public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) + { + final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); + if( handler != null ) + { + return handler; + } + + return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); + } + + private boolean isRecipe2x2( final int recipe ) + { + for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) + { + if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) + { + return false; + } + } + return true; + } + + @Override + public String getRecipeName() + { + return NEIClientUtils.translate( "recipe.shapeless" ); + } + + private class CachedShapelessRecipe extends TemplateRecipeHandler.CachedRecipe + { + + private final List ingredients; + private final PositionedStack result; + + public CachedShapelessRecipe( final ShapelessRecipe recipe ) + { + this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); + this.ingredients = new ArrayList(); + this.setIngredients( recipe.getInput().toArray() ); + } + + @Override + public PositionedStack getResult() + { + return this.result; + } + + @Override + public List getIngredients() + { + return this.getCycledIngredients( NEIAEShapelessRecipeHandler.this.cycleticks / 20, this.ingredients ); + } + + private void setIngredients( final Object[] items ) + { + final boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); + for( int x = 0; x < 3; x++ ) + { + for( int y = 0; y < 3; y++ ) + { + if( items.length > ( y * 3 + x ) ) + { + final IIngredient ing = (IIngredient) items[( y * 3 + x )]; + + try + { + final ItemStack[] is = ing.getItemStackSet(); + final PositionedStack stack = new PositionedStack( useSingleItems ? Platform.findPreferred( is ) : ing.getItemStackSet(), 25 + x * 18, 6 + y * 18, false ); + stack.setMaxSize( 1 ); + this.ingredients.add( stack ); + } + catch( final RegistrationError ignored ) + { + + } + catch( final MissingIngredientError ignored ) + { + + } + } + } + } + } + + private void computeVisuals() + { + for( final PositionedStack p : this.ingredients ) + { + p.generatePermutations(); + } + + this.result.generatePermutations(); + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEICraftingHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEICraftingHandler.java new file mode 100644 index 0000000..d889ce8 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/NEIHelpers/NEICraftingHandler.java @@ -0,0 +1,107 @@ +package net.p455w0rd.wirelesscraftingterminal.integration.modules.NEIHelpers; + +import java.util.LinkedList; +import java.util.List; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.p455w0rd.wirelesscraftingterminal.client.gui.GuiWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotCraftingMatrix; +import net.p455w0rd.wirelesscraftingterminal.common.container.slot.SlotFakeCraftingMatrix; +import net.p455w0rd.wirelesscraftingterminal.core.sync.network.NetworkHandler; +import net.p455w0rd.wirelesscraftingterminal.core.sync.packets.PacketNEIRecipe; +import codechicken.nei.PositionedStack; +import codechicken.nei.api.IOverlayHandler; +import codechicken.nei.recipe.IRecipeHandler; + +import appeng.util.Platform; + + +public class NEICraftingHandler implements IOverlayHandler +{ + + public NEICraftingHandler( final int x, final int y ) + { + } + + @Override + public void overlayRecipe( final GuiContainer gui, final IRecipeHandler recipe, final int recipeIndex, final boolean shift ) + { + try + { + final List ingredients = recipe.getIngredientStacks( recipeIndex ); + this.overlayRecipe( gui, ingredients, shift ); + } + catch( final Exception ignored ) + { + } + catch( final Error ignored ) + { + } + } + + private void overlayRecipe( final GuiContainer gui, final List ingredients, final boolean shift ) + { + try + { + final NBTTagCompound recipe = new NBTTagCompound(); + + if( gui instanceof GuiWirelessCraftingTerminal ) + { + for( final PositionedStack positionedStack : ingredients ) + { + final int col = ( positionedStack.relx - 25 ) / 18; + final int row = ( positionedStack.rely - 6 ) / 18; + if( positionedStack.items != null && positionedStack.items.length > 0 ) + { + for( final Slot slot : (List) gui.inventorySlots.inventorySlots ) + { + if( slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix ) + { + if( slot.getSlotIndex() == col + row * 3 ) + { + final NBTTagList tags = new NBTTagList(); + final List list = new LinkedList(); + + // prefer pure crystals. + for( int x = 0; x < positionedStack.items.length; x++ ) + { + if( Platform.isRecipePrioritized( positionedStack.items[x] ) ) + { + list.add( 0, positionedStack.items[x] ); + } + else + { + list.add( positionedStack.items[x] ); + } + } + + for( final ItemStack is : list ) + { + final NBTTagCompound tag = new NBTTagCompound(); + is.writeToNBT( tag ); + tags.appendTag( tag ); + } + + recipe.setTag( "#" + slot.getSlotIndex(), tags ); + break; + } + } + } + } + } + + NetworkHandler.instance.sendToServer( new PacketNEIRecipe( recipe ) ); + } + } + catch( final Exception ignored ) + { + } + catch( final Error ignored ) + { + } + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/RFItem.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/RFItem.java new file mode 100644 index 0000000..488f607 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/RFItem.java @@ -0,0 +1,27 @@ +package net.p455w0rd.wirelesscraftingterminal.integration.modules; + +import net.p455w0rd.wirelesscraftingterminal.helpers.Reflected; +import net.p455w0rd.wirelesscraftingterminal.integration.IIntegrationModule; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationHelper; + +public class RFItem implements IIntegrationModule +{ + @Reflected + public static RFItem instance; + + @Reflected + public RFItem() + { + IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyContainerItem.class ); + } + + @Override + public void init() + { + } + + @Override + public void postInit() + { + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/helpers/NullRFHandler.java b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/helpers/NullRFHandler.java new file mode 100644 index 0000000..bd7dc0a --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/integration/modules/helpers/NullRFHandler.java @@ -0,0 +1,34 @@ +package net.p455w0rd.wirelesscraftingterminal.integration.modules.helpers; + +import net.minecraftforge.common.util.ForgeDirection; + +import cofh.api.energy.IEnergyReceiver; + + +public class NullRFHandler implements IEnergyReceiver +{ + + @Override + public int receiveEnergy( final ForgeDirection from, final int maxReceive, final boolean simulate ) + { + return 0; + } + + @Override + public int getEnergyStored( final ForgeDirection from ) + { + return 0; + } + + @Override + public int getMaxEnergyStored( final ForgeDirection from ) + { + return 0; + } + + @Override + public boolean canConnectEnergy( final ForgeDirection from ) + { + return true; + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemAE2WCTDummyIcon.java b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemAE2WCTDummyIcon.java new file mode 100644 index 0000000..5010a3f --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemAE2WCTDummyIcon.java @@ -0,0 +1,15 @@ +package net.p455w0rd.wirelesscraftingterminal.items; + +import net.minecraft.item.Item; +import net.p455w0rd.wirelesscraftingterminal.creativetab.CreativeTabWCT; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class ItemAE2WCTDummyIcon extends Item { + public ItemAE2WCTDummyIcon() + { + super(); + setUnlocalizedName("ae2wctDummyIcon"); + setTextureName(Reference.MODID + ":wirelessCraftingTerminal"); + setMaxStackSize(0); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemBoosterBGIcon.java b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemBoosterBGIcon.java new file mode 100644 index 0000000..426012d --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemBoosterBGIcon.java @@ -0,0 +1,37 @@ +package net.p455w0rd.wirelesscraftingterminal.items; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class ItemBoosterBGIcon extends Item { + + public static IIcon[] boosterIcon; + + public ItemBoosterBGIcon() { + super(); + setUnlocalizedName("boosterBG"); + setTextureName(Reference.MODID + ":boosterBG"); + setMaxStackSize(0); + boosterIcon = new IIcon[1]; + } + + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(IIconRegister register) + { + boosterIcon[0] = register.registerIcon(Reference.MODID + ":" + this.getUnlocalizedName().substring(5)); + } + + @SideOnly(Side.CLIENT) + //@Override + public static IIcon getIcon() + { + return boosterIcon[0]; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemEnum.java b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemEnum.java new file mode 100644 index 0000000..120c48b --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemEnum.java @@ -0,0 +1,54 @@ +package net.p455w0rd.wirelesscraftingterminal.items; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public enum ItemEnum { + BOOSTER_CARD ("infinityBoosterCard", new ItemInfinityBooster().setUnlocalizedName("infinityBoosterCard")), + BOOSTER_ICON ("infinityBoosterIcon", new ItemInfinityBooster().setUnlocalizedName("infinityBoosterIcon")), + WIRELESS_CRAFTING_TERMINAL ("wirelessCraftingTerminal", new ItemWirelessCraftingTerminal()), + WCT_DUMMY_ICON ("ae2wctDummyIcon", new ItemAE2WCTDummyIcon()), + MAGNET_CARD ("magnetCard", new ItemMagnet().setUnlocalizedName("magnetCard")), + WCT_BOOSTER_BG_ICON ("boosterBG", new ItemBoosterBGIcon()); + + private final String internalName; + private Item item; + public static final ItemEnum[] VALUES = ItemEnum.values(); + + private ItemEnum( final String internalName, final Item item ) + { + this.internalName = internalName; + + this.item = item; + } + + public ItemStack getDMGStack( final int damageValue ) + { + return this.getDMGStack( damageValue, 1 ); + } + + public ItemStack getDMGStack( final int damageValue, final int size ) + { + return new ItemStack( this.item, size, damageValue ); + } + + public String getInternalName() + { + return this.internalName; + } + + public Item getItem() + { + return this.item; + } + + public ItemStack getStack() + { + return this.getStack( 1 ); + } + + public ItemStack getStack( final int size ) + { + return new ItemStack( this.item, size ); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemInfinityBooster.java b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemInfinityBooster.java new file mode 100644 index 0000000..2df7a4d --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemInfinityBooster.java @@ -0,0 +1,81 @@ +package net.p455w0rd.wirelesscraftingterminal.items; + +import java.util.List; + +import org.apache.commons.lang3.text.WordUtils; +import org.lwjgl.input.Keyboard; + +import com.google.common.base.Splitter; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.creativetab.CreativeTabWCT; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; +import net.p455w0rd.wirelesscraftingterminal.handlers.LocaleHandler; + +public class ItemInfinityBooster extends Item { + + public boolean showEffect = false; + + public ItemInfinityBooster() { + super(); + this.setTextureName(Reference.MODID + ":infinityBoosterCard"); + this.setMaxStackSize(1); + } + + public Item hasEffect(boolean hasEffect) { + this.showEffect = hasEffect; + return this; + } + + @SideOnly(Side.CLIENT) + @Override + public boolean hasEffect(ItemStack is, int pass) { + return this.showEffect; + } + + @Override + public int getMaxItemUseDuration(ItemStack stack) { + return 1; + } + + @Override + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack is, EntityPlayer player, List list, boolean par4) { + String shift = LocaleHandler.PressShift.getLocal().replace("Shift", color("yellow") + "" + color("bold") + "" + color("italics") + "Shift" + color("gray")); + list.add(color("aqua") + "==========================="); + if (isShiftKeyDown()) { + String info = LocaleHandler.InfinityBoosterDesc.getLocal(); + for (String line : Splitter.on("\n").split(WordUtils.wrap(info, 37, "\n", false))) { + list.add(line.trim()); + } + list.add(""); + String onlyWorks = LocaleHandler.OnlyWorks.getLocal(); + for (String line : Splitter.on("\n").split(WordUtils.wrap(onlyWorks, 27, "\n", false))) { + list.add(color("white") + "" + color("bold") + "" + color("italics") + line.trim()); + } + } + else { + list.add(shift); + } + super.addInformation(is, player, list, par4); + } + + @SideOnly(Side.CLIENT) + private String color(String color) { + return RandomUtils.color(color); + } + + @SideOnly(Side.CLIENT) + public static boolean isShiftKeyDown() { + return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemMagnet.java b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemMagnet.java new file mode 100644 index 0000000..f30f938 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemMagnet.java @@ -0,0 +1,390 @@ +package net.p455w0rd.wirelesscraftingterminal.items; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.text.WordUtils; +import org.lwjgl.input.Keyboard; + +import com.google.common.base.Splitter; + +import appeng.api.AEApi; +import appeng.api.config.SecurityPermissions; +import appeng.api.implementations.guiobjects.IPortableCell; +import appeng.api.networking.IGrid; +import appeng.api.networking.IGridNode; +import appeng.api.networking.energy.IEnergyGrid; +import appeng.api.networking.energy.IEnergySource; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.security.IActionHost; +import appeng.api.networking.security.ISecurityGrid; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.data.IAEItemStack; +import appeng.util.Platform; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.Event.Result; +import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.gameevent.PlayerEvent.ItemPickupEvent; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.item.EntityXPOrb; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.EntityItemPickupEvent; +import net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTermHandler; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTIActionHost; +import net.p455w0rd.wirelesscraftingterminal.api.networking.security.WCTPlayerSource; +import net.p455w0rd.wirelesscraftingterminal.common.WCTGuiHandler; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.handlers.LocaleHandler; +import net.p455w0rd.wirelesscraftingterminal.helpers.WirelessTerminalGuiObject; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +/** + * Jotato's amazing magnet item from QuantumFlux adpated for use in the Wireless + * Crafting Terminal + * + * @author p455w0rd, Jotato + * + */ +public class ItemMagnet extends Item { + + private int distanceFromPlayer; + private WirelessTerminalGuiObject obj; + private WCTIActionHost wctAH; + private IPortableCell civ; + private IEnergySource powerSrc; + private IMEMonitor monitor; + private IMEInventoryHandler cellInv; + private BaseActionSource mySrc; + private ItemStack thisItemStack; + + public ItemMagnet() { + super(); + setMaxStackSize(1); + this.distanceFromPlayer = 16; + canRepair = false; + setMaxDamage(0); + setTextureName(Reference.MODID + ":magnetCard"); + } + + @SideOnly(Side.CLIENT) + @Override + public boolean hasEffect(ItemStack item) { + return isActivated(item); + } + + public void setItemStack(ItemStack is) { + this.thisItemStack = is; + } + + public ItemStack getItemStack() { + if (thisItemStack != null && (thisItemStack.getItem() instanceof ItemMagnet)) { + return thisItemStack; + } + return null; + } + + @Override + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack is, EntityPlayer player, List list, boolean par4) { + list.add(color("aqua") + "==========================="); + String shift = LocaleHandler.PressShift.getLocal().replace("Shift", color("yellow") + "" + color("bold") + "" + color("italics") + "Shift" + color("gray")); + if (isShiftKeyDown()) { + String info = LocaleHandler.MagnetDesc.getLocal(); + for (String line : Splitter.on("\n").split(WordUtils.wrap(info, 37, "\n", false))) { + list.add(line.trim()); + } + + list.add(""); + list.add(LocaleHandler.MagnetDesc2.getLocal()); + + list.add(""); + list.add(LocaleHandler.Status.getLocal() + ": " + (isActivated(is) ? color("green") + "" + LocaleHandler.Active.getLocal() : color("red") + "" + LocaleHandler.Inactive.getLocal())); + String white = LocaleHandler.Whitelisting.getLocal(); + String black = LocaleHandler.Blacklisting.getLocal(); + + list.add(LocaleHandler.FilterMode.getLocal() + ": " + color("white") + "" + (getMode(is) ? white : black)); + list.add(""); + + String onlyWorks = LocaleHandler.OnlyWorks.getLocal(); + for (String line : Splitter.on("\n").split(WordUtils.wrap(onlyWorks, 27, "\n", false))) { + list.add(color("white") + "" + color("bold") + "" + color("italics") + "" + line.trim()); + } + + } + else { + list.add(shift); + } + } + + @SideOnly(Side.CLIENT) + private String color(String color) { + return RandomUtils.color(color); + } + + @SideOnly(Side.CLIENT) + public static boolean isShiftKeyDown() { + return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + } + + @Override + public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer player) { + if (!world.isRemote) { + if (player.isSneaking()) { + item.setItemDamage(item.getItemDamage() == 0 ? 1 : 0); + } + else { + int x = (int) player.posX; + int y = (int) player.posY; + int z = (int) player.posZ; + WCTGuiHandler.launchGui(WirelessCraftingTerminal.GUI_MAGNET, player, world, x, y, z); + } + } + return item; + } + + @SuppressWarnings("rawtypes") + // @Override + public void doMagnet(ItemStack item, World world, EntityPlayer player, ItemStack wirelessTerm) { + if (world.isRemote || getItemStack() == null) + return; + if (!isActivated(item)) + return; + if (player == null) + return; + List filteredList = getFilteredItems(this.getItemStack()); + // items + Iterator iterator = getEntitiesInRange(EntityItem.class, world, (int) player.posX, (int) player.posY, (int) player.posZ, this.distanceFromPlayer).iterator(); + while (iterator.hasNext()) { + + EntityItem itemToGet = (EntityItem) iterator.next(); + itemToGet.delayBeforeCanPickup = 50; + + EntityItemPickupEvent pickupEvent = new EntityItemPickupEvent(player, itemToGet); + ItemPickupEvent itemPickupEvent = new ItemPickupEvent(player, itemToGet); + MinecraftForge.EVENT_BUS.post(pickupEvent); + ItemStack itemStackToGet = itemToGet.getEntityItem(); + int stackSize = itemStackToGet.stackSize; + + if (this.obj == null) { + this.obj = getGuiObject(wirelessTerm, player, world, (int) player.posX, (int) player.posY, (int) player.posZ); + this.civ = (IPortableCell) this.obj; + this.powerSrc = (IEnergySource) this.civ; + this.wctAH = (WCTIActionHost) this.powerSrc; + this.monitor = civ.getItemInventory(); + this.cellInv = this.monitor; + this.mySrc = new WCTPlayerSource(player, (WCTIActionHost) this.obj); + } + + if (obj.rangeCheck(isBoosterInstalled(wirelessTerm) && Reference.WCT_BOOSTER_ENABLED) && hasNetworkAccess(SecurityPermissions.INJECT, true, player, wirelessTerm)) { + IAEItemStack ais = AEApi.instance().storage().createItemStack(itemStackToGet); + ais.setStackSize(stackSize); + if (!itemToGet.isDead) { + + // whitelist + if (getMode(this.getItemStack())) { + if (isItemFiltered(itemStackToGet, filteredList) || filteredList == null || filteredList.size() == 0) { + itemToGet.setDead(); + doInject(ais, pickupEvent, stackSize, player, itemToGet, itemStackToGet, world); + continue; + } + else { + if (pickupEvent.getResult() == Result.ALLOW || itemPickupEvent.getResult() == Result.ALLOW || stackSize <= 0 || player.inventory.addItemStackToInventory(itemStackToGet)) { + player.onItemPickup(itemToGet, stackSize); + world.playSoundAtEntity(player, "random.pop", 0.15F, ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } + } + FMLCommonHandler.instance().bus().post(itemPickupEvent); + } + // blacklist + else { + if (!isItemFiltered(itemStackToGet, filteredList) && filteredList != null && filteredList.size() > 0) { + itemToGet.setDead(); + doInject(ais, pickupEvent, stackSize, player, itemToGet, itemStackToGet, world); + continue; + } + else { + if (pickupEvent.getResult() == Result.ALLOW || itemPickupEvent.getResult() == Result.ALLOW || stackSize <= 0 || player.inventory.addItemStackToInventory(itemStackToGet)) { + player.onItemPickup(itemToGet, stackSize); + world.playSoundAtEntity(player, "random.pop", 0.15F, ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } + } + FMLCommonHandler.instance().bus().post(itemPickupEvent); + } + + } + } + else { + if (pickupEvent.getResult() == Result.ALLOW || stackSize <= 0 || player.inventory.addItemStackToInventory(itemStackToGet)) { + player.onItemPickup(itemToGet, stackSize); + world.playSoundAtEntity(player, "random.pop", 0.15F, ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } + } + } + + // xp + iterator = getEntitiesInRange(EntityXPOrb.class, world, (int) player.posX, (int) player.posY, (int) player.posZ, this.distanceFromPlayer).iterator(); + while (iterator.hasNext()) { + EntityXPOrb xpToGet = (EntityXPOrb) iterator.next(); + if (xpToGet.isDead || xpToGet.isInvisible()) { + continue; + } + int xpAmount = xpToGet.xpValue; + xpToGet.xpValue = 0; + player.xpCooldown = 0; + player.addExperience(xpAmount); + xpToGet.setDead(); + xpToGet.setInvisible(true); + world.playSoundAtEntity(player, "random.orb", 0.08F, 0.5F * ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.8F)); + } + } + + private void doInject(IAEItemStack ais, EntityItemPickupEvent pickupEvent, int stackSize, EntityPlayer player, EntityItem itemToGet, ItemStack itemStackToGet, World world) { + ais = Platform.poweredInsert(this.powerSrc, this.cellInv, ais, this.mySrc); + if (ais != null) { + if (pickupEvent.getResult() == Result.ALLOW || stackSize <= 0) { + player.onItemPickup(itemToGet, stackSize); + player.inventory.addItemStackToInventory(itemStackToGet); + world.playSoundAtEntity(player, "random.pop", 0.15F, ((world.rand.nextFloat() - world.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } + } + } + + private boolean hasNetworkAccess(final SecurityPermissions perm, final boolean requirePower, EntityPlayer player, ItemStack wirelessTerm) { + final WCTIActionHost host = (WCTIActionHost) this.obj; + + if (host != null) { + final IGridNode gn = host.getActionableNode(Reference.WCT_BOOSTER_ENABLED && this.isBoosterInstalled(wirelessTerm)); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(player, perm)) { + return true; + } + } + } + } + return false; + } + + private boolean isItemFiltered(ItemStack is, List itemList) { + if (is != null && itemList != null) { + Iterator thisList = itemList.iterator(); + while (thisList.hasNext()) { + ItemStack thisItemStack = (ItemStack) thisList.next(); + Item thisItem = (Item) thisItemStack.getItem(); + if (is.getItem() == thisItem) { + return true; + } + } + } + return false; + } + + private List getFilteredItems(ItemStack magnetItem) { + if (magnetItem.getItem() instanceof ItemMagnet) { + if (magnetItem.hasTagCompound()) { + NBTTagCompound nbtTC = magnetItem.getTagCompound(); + if (!nbtTC.hasKey("MagnetFilter")) { + return null; + } + NBTTagList tagList = nbtTC.getTagList("MagnetFilter", 10); + boolean test1 = false; + if (tagList.tagCount() > 0 && tagList != null) { + List itemList = new ArrayList(); + for (int i = 0; i < tagList.tagCount(); i++) { + itemList.add(ItemStack.loadItemStackFromNBT(tagList.getCompoundTagAt(i))); + } + return itemList; + } + } + } + return null; + } + + private boolean isBoosterInstalled(ItemStack wirelessTerm) { + if (wirelessTerm.getItem() instanceof ItemWirelessCraftingTerminal) { + if (wirelessTerm.hasTagCompound()) { + NBTTagList boosterNBTList = wirelessTerm.getTagCompound().getTagList("BoosterSlot", 10); + if (boosterNBTList != null) { + NBTTagCompound boosterTagCompound = boosterNBTList.getCompoundTagAt(0); + if (boosterTagCompound != null) { + ItemStack boosterCard = ItemStack.loadItemStackFromNBT(boosterTagCompound); + if (boosterCard != null) { + return (boosterCard.getItem() instanceof ItemInfinityBooster); + } + } + } + } + } + return false; + } + + // true=whitelist (default:whitelist) + private boolean getMode(ItemStack magnetItem) { + if (magnetItem.getItem() instanceof ItemMagnet) { + if (magnetItem.hasTagCompound()) { + NBTTagCompound nbtTC = magnetItem.getTagCompound(); + if (nbtTC.hasKey("Whitelisting")) { + return nbtTC.getBoolean("Whitelisting"); + } + } + } + return true; + } + + private WirelessTerminalGuiObject getGuiObject(final ItemStack it, final EntityPlayer player, final World w, final int x, final int y, final int z) { + if (it != null) { + final IWirelessCraftingTermHandler wh = (IWirelessCraftingTermHandler) AEApi.instance().registries().wireless().getWirelessTerminalHandler(it); + if (wh != null) { + return new WirelessTerminalGuiObject(wh, it, player, w, x, y, z); + } + } + + return null; + } + + @SuppressWarnings("rawtypes") + public static List getEntitiesInRange(Class entityType, World world, int x, int y, int z, int distance) { + return world.getEntitiesWithinAABB(entityType, AxisAlignedBB.getBoundingBox(x - distance, y - distance, z - distance, x + distance, y + distance, z + distance)); + } + + public ItemStack getStack() { + return this.getStack(1); + } + + public ItemStack getStack(final int size) { + return new ItemStack(this, size); + } + + protected boolean isActivated(ItemStack item) { + return item.getItemDamage() == 1; + } + + @Override + public int getMaxItemUseDuration(ItemStack stack) { + return 1; + } + +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemWirelessCraftingTerminal.java b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemWirelessCraftingTerminal.java new file mode 100644 index 0000000..3ab49c5 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/items/ItemWirelessCraftingTerminal.java @@ -0,0 +1,404 @@ +package net.p455w0rd.wirelesscraftingterminal.items; + +import java.util.List; + +import org.lwjgl.input.Keyboard; + +import com.google.common.base.Optional; + +import appeng.api.config.AccessRestriction; +import appeng.api.config.PowerMultiplier; +import appeng.api.config.PowerUnits; +import appeng.api.config.Settings; +import appeng.api.config.SortDir; +import appeng.api.config.SortOrder; +import appeng.api.config.ViewItems; +import appeng.api.util.IConfigManager; +import appeng.items.tools.powered.powersink.AEBasePoweredItem; +import appeng.util.ConfigManager; +import appeng.util.IConfigManagerHost; +import appeng.util.Platform; +import cofh.api.energy.IEnergyContainerItem; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.entity.EntityClientPlayerMP; +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ContainerPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; +import net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTermHandler; +import net.p455w0rd.wirelesscraftingterminal.api.WCTApi; +import net.p455w0rd.wirelesscraftingterminal.common.utils.RandomUtils; +import net.p455w0rd.wirelesscraftingterminal.handlers.LocaleHandler; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class ItemWirelessCraftingTerminal extends AEBasePoweredItem implements IWirelessCraftingTermHandler, IEnergyContainerItem { + + private static final String LINK_KEY_STRING = "key"; + public static double GLOBAL_POWER_MULTIPLIER = PowerMultiplier.CONFIG.multiplier; + private static final String POWER_NBT_KEY = "internalCurrentPower"; + private static final String BOOSTER_SLOT_NBT = "BoosterSlot"; + private static final String MAGNET_SLOT_NBT = "MagnetSlot"; + + public ItemWirelessCraftingTerminal() { + super(Reference.WCT_MAX_POWER, Optional. absent()); + //this.setFeature(EnumSet.of(AEFeature.WirelessAccessTerminal, AEFeature.PoweredTools)); + this.setUnlocalizedName("wirelessCraftingTerminal"); + this.setTextureName(Reference.MODID + ":wirelessCraftingTerminal"); + this.setMaxStackSize(1); + } + + @SideOnly(Side.CLIENT) + @Override + public boolean hasEffect(ItemStack is, int pass) { + return checkForBooster(is); + } + + public boolean checkForBooster(final ItemStack wirelessTerminal) { + if (wirelessTerminal.hasTagCompound()) { + NBTTagList boosterNBTList = wirelessTerminal.getTagCompound().getTagList(BOOSTER_SLOT_NBT, 10); + if (boosterNBTList != null) { + NBTTagCompound boosterTagCompound = boosterNBTList.getCompoundTagAt(0); + if (boosterTagCompound != null) { + ItemStack boosterCard = ItemStack.loadItemStackFromNBT(boosterTagCompound); + if (boosterCard != null) { + return ((boosterCard.getItem() instanceof ItemInfinityBooster) && Reference.WCT_BOOSTER_ENABLED); + } + } + } + } + return false; + } + + private boolean isMagnetInstalled(final ItemStack wirelessTerminal) { + if (wirelessTerminal.hasTagCompound()) { + NBTTagList magnetNBTList = wirelessTerminal.getTagCompound().getTagList(MAGNET_SLOT_NBT, 10); + if (magnetNBTList != null) { + NBTTagCompound magnetTagCompound = magnetNBTList.getCompoundTagAt(0); + if (magnetTagCompound != null) { + ItemStack magnetCard = ItemStack.loadItemStackFromNBT(magnetTagCompound); + if (magnetCard != null) { + return ((magnetCard.getItem() instanceof ItemMagnet)); + } + } + } + } + return false; + } + + @Override + public void onUpdate(final ItemStack is, final World w, final Entity e, int i, boolean f) { + if (!(e instanceof EntityPlayer)) { + return; + } + EntityPlayer p = (EntityPlayer) e; + ItemStack wirelessTerminal = null; + InventoryPlayer inv = p.inventory; + wirelessTerminal = RandomUtils.getWirelessTerm(inv); + if (wirelessTerminal == null || !(wirelessTerminal.getItem() instanceof ItemWirelessCraftingTerminal)) { + return; + } + this.checkForBooster(wirelessTerminal); + } + + @Override + public ItemStack onItemRightClick(final ItemStack itemStack, final World world, final EntityPlayer player) { + if (world.isRemote) { + return itemStack; + } + // Open the gui + WCTApi.instance().interact().openWirelessCraftingTerminalGui(player); + return itemStack; + } + + @Override + public String getEncryptionKey(final ItemStack wirelessTerminal) { + if (wirelessTerminal == null) { + return null; + } + // Ensure the terminal has a tag + if (wirelessTerminal.hasTagCompound()) { + // Get the security terminal source key + String sourceKey = wirelessTerminal.getTagCompound().getString(LINK_KEY_STRING); + + // Ensure the source is not empty nor null + if ((sourceKey != null) && (!sourceKey.isEmpty())) { + // The terminal is linked. + return sourceKey; + } + } + + // Terminal is unlinked. + return ""; + } + + @Override + public void setEncryptionKey(final ItemStack wirelessTerminal, final String sourceKey, final String name) { + final NBTTagCompound tag = ensureTagCompound(wirelessTerminal); + tag.setString(ItemWirelessCraftingTerminal.LINK_KEY_STRING, sourceKey); + } + + @Override + public boolean canHandle(final ItemStack is) { + return true; + } + + @Override + public boolean usePower(final EntityPlayer player, final double amount, final ItemStack is) { + return this.extractAEPower(is, amount) >= amount - 0.5; + } + + @Override + public boolean hasPower(final EntityPlayer player, final double amt, final ItemStack is) { + return this.getAECurrentPower(is) >= amt; + } + + @Override + public IConfigManager getConfigManager(final ItemStack target) { + final ConfigManager out = new ConfigManager(new IConfigManagerHost() { + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + final NBTTagCompound data = Platform.openNbtData(target); + manager.writeToNBT(data); + } + }); + + out.registerSetting(Settings.SORT_BY, SortOrder.NAME); + out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + + out.readFromNBT((NBTTagCompound) Platform.openNbtData(target).copy()); + return out; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public void getCheckedSubItems(Item item, CreativeTabs creativeTab, List itemList) { + List itemList2 = itemList; + itemList2.add(new ItemStack(item)); + ItemStack is = new ItemStack(item); + injectAEPower(is, Reference.WCT_MAX_POWER); + itemList2.add(is); + } + + @Override + public boolean showDurabilityBar(ItemStack is) { + double aeCurrPower = getAECurrentPower(is); + double aeMaxPower = getAEMaxPower(is); + if ((int) aeCurrPower >= (int) aeMaxPower) { + return false; + } + return true; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(ItemStack is, EntityPlayer player, List list, boolean displayMore) { + String shift = LocaleHandler.PressShift.getLocal().replace("Shift", color("yellow") + "" + color("bold") + "" + color("italics") + "Shift" + color("gray")); + final NBTTagCompound tag = ensureTagCompound(is); + + String encKey = tag.getString("key"); + String pctTxtColor = color("white") + ""; + double aeCurrPower = getAECurrentPower(is); + double aeCurrPowerPct = (int) Math.floor(aeCurrPower / Reference.WCT_MAX_POWER * 1e4) / 1e2; + if ((int) aeCurrPowerPct >= 75) { + pctTxtColor = color("green") + ""; + } + if ((int) aeCurrPowerPct <= 5) { + pctTxtColor = color("red") + ""; + } + list.add(color("aqua") + "==========================="); + list.add(StatCollector.translateToLocal("gui.appliedenergistics2.StoredEnergy") + ": " + pctTxtColor + (int) aeCurrPower + " AE - " + aeCurrPowerPct + "%"); + if (isShiftKeyDown()) { + String linked = color("red") + StatCollector.translateToLocal("gui.appliedenergistics2.Unlinked"); + if (encKey != null && !encKey.isEmpty()) { + linked = color("blue") + StatCollector.translateToLocal("gui.appliedenergistics2.Linked"); + } + list.add(LocaleHandler.LinkStatus.getLocal() + ": " + linked); + String boosterStatus = (checkForBooster(is) ? color("green") + "" + LocaleHandler.Installed.getLocal() : color("red") + "" + LocaleHandler.NotInstalled.getLocal()); + String magnetStatus = (isMagnetInstalled(is) ? color("green") + "" + LocaleHandler.Installed.getLocal() : color("red") + "" + LocaleHandler.NotInstalled.getLocal()); + if (Reference.WCT_BOOSTER_ENABLED) { + list.add(getItemName("infinityBoosterCard") + ": " + boosterStatus); + } + list.add(getItemName("magnetCard") + ": " + magnetStatus); + } + else { + list.add(shift); + } + } + + @SideOnly(Side.CLIENT) + private String color(String color) { + return RandomUtils.color(color); + } + + @SideOnly(Side.CLIENT) + private static String getItemName(String item) { + return StatCollector.translateToLocal("item." + item + ".name"); + } + + @SideOnly(Side.CLIENT) + public static boolean isShiftKeyDown() { + return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); + + } + + private double getInternalBattery(final ItemStack is, final batteryOperation op, final double adjustment) { + final NBTTagCompound data = ensureTagCompound(is); + + double currentStorage = data.getDouble(POWER_NBT_KEY); + final double maxStorage = this.getAEMaxPower(is); + + switch (op) { + case INJECT: + currentStorage += adjustment; + if (currentStorage > maxStorage) { + final double diff = currentStorage - maxStorage; + data.setDouble(POWER_NBT_KEY, maxStorage); + return diff; + } + data.setDouble(POWER_NBT_KEY, currentStorage); + return 0; + case EXTRACT: + if (currentStorage > adjustment) { + currentStorage -= adjustment; + data.setDouble(POWER_NBT_KEY, currentStorage); + return adjustment; + } + data.setDouble(POWER_NBT_KEY, 0); + return currentStorage; + default: + break; + } + + return currentStorage; + } + + @Override + public double getDurabilityForDisplay(ItemStack is) { + return 1 - getAECurrentPower(is) / this.getAEMaxPower(is); + } + + private NBTTagCompound ensureTagCompound(ItemStack is) { + if (!is.hasTagCompound()) { + is.setTagCompound(new NBTTagCompound()); + } + return is.getTagCompound(); + } + + @Override + public double getAECurrentPower(final ItemStack is) { + return this.getInternalBattery(is, batteryOperation.STORAGE, 0); + } + + @Override + public AccessRestriction getPowerFlow(ItemStack is) { + return AccessRestriction.WRITE; + } + + @Override + public double injectAEPower(final ItemStack is, final double amt) { + return this.getInternalBattery(is, batteryOperation.INJECT, amt); + } + + @Override + public double extractAEPower(final ItemStack is, final double amt) { + return this.getInternalBattery(is, batteryOperation.EXTRACT, amt); + } + + @Override + public double getAEMaxPower(ItemStack is) { + return Reference.WCT_MAX_POWER; + } + + @Override + public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) { + if (container == null) { + return 0; + } + if (simulate) { + double current = PowerUnits.AE.convertTo(PowerUnits.RF, getAECurrentPower(container)); + double max = PowerUnits.AE.convertTo(PowerUnits.RF, getAEMaxPower(container)); + if (max - current >= maxReceive) { + return maxReceive; + } else { + return (int) (max - current); + } + } else { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, injectAEPower(container, PowerUnits.RF.convertTo(PowerUnits.AE, maxReceive))); + } + } + + @Override + public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) { + if (container == null) { + return 0; + } + if (simulate) { + if (getEnergyStored(container) >= maxExtract) { + return maxExtract; + } else { + return getEnergyStored(container); + } + } else { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, extractAEPower(container, PowerUnits.RF.convertTo(PowerUnits.AE, maxExtract))); + } + } + + @Override + public int getEnergyStored(ItemStack container) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, getAECurrentPower(container)); + } + + @Override + public int getMaxEnergyStored(ItemStack container) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, getAEMaxPower(container)); + } + + private enum batteryOperation { + STORAGE, INJECT, EXTRACT + } + + @Override + public boolean isDamageable() { + return false; + } + + @Override + public boolean isDamaged(final ItemStack stack) { + return false; + } + + @Override + public boolean isRepairable() { + return false; + } + + @SideOnly(Side.CLIENT) + @Override + public boolean isFull3D() { + return false; + } + + @Override + public int getMaxDamage() { + return 0; + } + + @Override + public int getDamage(ItemStack stack) { + return 0; + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/proxy/ClientProxy.java b/src/java/net/p455w0rd/wirelesscraftingterminal/proxy/ClientProxy.java new file mode 100644 index 0000000..9164fa7 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/proxy/ClientProxy.java @@ -0,0 +1,40 @@ +package net.p455w0rd.wirelesscraftingterminal.proxy; + +import cpw.mods.fml.common.FMLCommonHandler; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.MinecraftForge; +import net.p455w0rd.wirelesscraftingterminal.common.WirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.handlers.KeybindHandler; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationRegistry; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationType; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.transformer.MissingCoreMod; + +public class ClientProxy extends CommonProxy { + + public ClientProxy() { + MinecraftForge.EVENT_BUS.register(this); + KeybindHandler.registerKeybinds(); + //MinecraftForge.EVENT_BUS.register(new KeybindHandler()); + FMLCommonHandler.instance().bus().register(new KeybindHandler()); + } + + @Override + public void removeItemsFromNEI() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + codechicken.nei.api.API.hideItem(new ItemStack(ItemEnum.WCT_BOOSTER_BG_ICON.getItem(), 1)); + codechicken.nei.api.API.hideItem(new ItemStack(ItemEnum.WCT_DUMMY_ICON.getItem(), 1)); + return; + } + } + + public void registerRenderers() { + // No renderers...yet =] + } + + @Override + public void missingCoreMod() { + throw new MissingCoreMod(); + } + +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/proxy/CommonProxy.java b/src/java/net/p455w0rd/wirelesscraftingterminal/proxy/CommonProxy.java new file mode 100644 index 0000000..c861913 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/proxy/CommonProxy.java @@ -0,0 +1,208 @@ +package net.p455w0rd.wirelesscraftingterminal.proxy; + +import java.util.Random; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.PlayerEvent; +import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import cpw.mods.fml.common.registry.GameRegistry; +import cpw.mods.fml.relauncher.Side; +import net.minecraft.entity.boss.EntityDragon; +import net.minecraft.entity.boss.EntityWither; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.stats.Achievement; +import net.minecraft.stats.AchievementList; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; +import net.minecraftforge.common.AchievementPage; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.FakePlayer; +import net.minecraftforge.event.entity.living.LivingDropsEvent; +import net.minecraftforge.event.entity.player.AchievementEvent; +import net.p455w0rd.wirelesscraftingterminal.handlers.AchievementHandler; +import net.p455w0rd.wirelesscraftingterminal.handlers.ConfigHandler; +import net.p455w0rd.wirelesscraftingterminal.items.ItemEnum; +import net.p455w0rd.wirelesscraftingterminal.items.ItemMagnet; +import net.p455w0rd.wirelesscraftingterminal.items.ItemWirelessCraftingTerminal; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + +public class CommonProxy { + + Achievement wctAch = AchievementHandler.wctAch; + Achievement boosterAch = AchievementHandler.boosterAch; + Achievement magnetAch = AchievementHandler.magnetAch; + + public CommonProxy() { + MinecraftForge.EVENT_BUS.register( this ); + FMLCommonHandler.instance().bus().register(new ConfigHandler()); + } + public void registerItems() { + for (ItemEnum item : ItemEnum.VALUES) { + GameRegistry.registerItem(item.getItem(), item.getInternalName()); + } + } + + public void removeItemsFromNEI() { + } + + public void registerRenderers() { + // Ignored server side. + } + + public void missingCoreMod() { + throw new IllegalStateException("Unable to Load WCT Core Mod, please verify that WCT is properly install in the mods folder, with a .jar extension."); + } + + @SubscribeEvent + public void tickEvent(TickEvent.PlayerTickEvent e) { + ItemStack wirelessTerm = null; + EntityPlayer player = e.player; + IInventory playerInv; + if (player instanceof EntityPlayerMP) { + playerInv = player.inventory.player.inventory; + } + else { + playerInv = player.inventory; + } + int invSize = playerInv.getSizeInventory(); + if (invSize <= 0) { + return; + } + for (int i = 0; i < invSize; ++i) { + ItemStack item = playerInv.getStackInSlot(i); + if (item == null) { + continue; + } + if (item.getItem() instanceof ItemWirelessCraftingTerminal) { + wirelessTerm = item; + } + if (wirelessTerm == null) { + continue; + } + if (wirelessTerm.hasTagCompound()) { + NBTTagCompound nbtTC = wirelessTerm.getTagCompound(); + NBTTagList tagList = nbtTC.getTagList("MagnetSlot", 10); + if (tagList != null) { + NBTTagCompound magCompound = tagList.getCompoundTagAt(0); + if (magCompound != null) { + ItemStack magnetItem = ItemStack.loadItemStackFromNBT(magCompound); + if (magnetItem != null) { + ((ItemMagnet) magnetItem.getItem()).setItemStack(magnetItem); + if (magnetItem.getItem() instanceof ItemMagnet) { + ((ItemMagnet) magnetItem.getItem()).doMagnet(magnetItem, e.player.worldObj, e.player, wirelessTerm); + continue; + } + } + } + } + } + } + } + + + @SubscribeEvent + public void onPlayerLogin(PlayerLoggedInEvent e) { + // SSP Login + if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { + boolean hasWCTAch = ((EntityPlayerMP) e.player).func_147099_x().hasAchievementUnlocked(AchievementHandler.wctAch); + boolean hasBoosterAch = ((EntityPlayerMP) e.player).func_147099_x().hasAchievementUnlocked(AchievementHandler.boosterAch); + + ConfigHandler.removeBooster(); + ConfigHandler.removeBoosterIcon(); + + if (ConfigHandler.firstLoad) { + ConfigHandler.firstLoad = false; + } + else { + ConfigHandler.reloadRecipes(); + } + // Was using this for hidden booster achievement + // it was giving me too much of a headache..mayeb + // i'll implement in the future + /* + AchievementPage achPg = AchievementPage.getAchievementPage("Wireless Crafting Term"); + if (achPg != null && AchievementList.achievementList.contains(AchievementHandler.boosterAch) && !achPg.getAchievements().contains(AchievementHandler.boosterAch)) { + AchievementList.achievementList.remove(AchievementHandler.boosterAch); + } + if ((Reference.WCT_BOOSTER_ENABLED && hasWCTAch) || hasBoosterAch) { + AchievementHandler.addAchievementToPage(AchievementHandler.boosterAch, true, e.player); + } + */ + } + } + + @SubscribeEvent + public void onMobDrop(LivingDropsEvent event) { + if (!Reference.WCT_EASYMODE_ENABLED && Reference.WCT_BOOSTER_ENABLED) { + if (event.entity instanceof EntityWither || event.entity instanceof EntityDragon) { + ItemStack stack = new ItemStack(ItemEnum.BOOSTER_CARD.getItem()); + EntityItem drop = new EntityItem(event.entity.worldObj, event.entity.posX, event.entity.posY, event.entity.posZ, stack); + Random rand = new Random(); + int n = rand.nextInt(50) + 1; + if (n == 25) { + event.drops.add(drop); + } + } + } + } + + @SubscribeEvent + public void onPlayerCraftingEvent(final PlayerEvent.ItemCraftedEvent event) { + boolean hasWCTAch = ((EntityPlayerMP) event.player).func_147099_x().hasAchievementUnlocked(AchievementHandler.wctAch); + if (event.player == null || event.player.isDead || event.player instanceof FakePlayer || event.crafting == null) { + return; + } + if (event.crafting.getItem() == ItemEnum.WIRELESS_CRAFTING_TERMINAL.getItem()) { + AchievementHandler.triggerAch(wctAch, event.player); + } + if (event.crafting.getItem() == ItemEnum.MAGNET_CARD.getItem() && hasWCTAch) { + AchievementHandler.triggerAch(magnetAch, event.player); + } + /* + if (event.crafting.getItem() == ItemEnum.WIRELESS_CRAFTING_TERMINAL.getItem()) { + AchievementHandler.triggerAch(wctAch, event.player); + if (Reference.WCT_BOOSTER_ENABLED) { + AchievementHandler.addAchievementToPage(AchievementHandler.boosterAch, true, event.player); + } + } + */ + if (Reference.WCT_BOOSTER_ENABLED && Reference.WCT_EASYMODE_ENABLED && hasWCTAch) { + if (event.crafting.getItem() == ItemEnum.BOOSTER_CARD.getItem()) { + AchievementHandler.triggerAch(boosterAch, event.player); + } + } + } + + /* + @SubscribeEvent + public void achievementGetEvent(AchievementEvent event) { + int index = AchievementList.achievementList.indexOf(wctAch); + if (event.achievement.equals(AchievementList.achievementList.get(index))) { + if (Reference.WCT_BOOSTER_ENABLED) { + EnumChatFormatting purple = EnumChatFormatting.LIGHT_PURPLE; + EnumChatFormatting green = EnumChatFormatting.GREEN; + event.entityPlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.ITALIC + "" + purple + "[" + green + "Wireless Crafting Terminal" + purple + "]: " + green + " New" + purple + " Achievment" + green + " Unlocked" + purple + "!")); + } + } + } + */ + + @SubscribeEvent + public void pickupEvent(PlayerEvent.ItemPickupEvent e) { + if (Reference.WCT_BOOSTER_ENABLED && !Reference.WCT_EASYMODE_ENABLED) { + if (e.pickedUp.getEntityItem().getItem() == ItemEnum.BOOSTER_CARD.getItem()) { + if (AchievementHandler.isAchievementUnlocked(e.player, wctAch)) { + AchievementHandler.triggerAch(boosterAch, e.player); + } + } + } + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/reference/Reference.java b/src/java/net/p455w0rd/wirelesscraftingterminal/reference/Reference.java new file mode 100644 index 0000000..58a4206 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/reference/Reference.java @@ -0,0 +1,16 @@ +package net.p455w0rd.wirelesscraftingterminal.reference; + +public class Reference { + public static final String MODID = "ae2wct"; + public static final String VERSION = "1.7.10-1.0-alpha-1"; + public static final String NAME = "AE2 Wireless Crafting Terminal"; + public static final String SERVER_PROXY_CLASS = "net.p455w0rd.wirelesscraftingterminal.proxy.CommonProxy"; + public static final String CLIENT_PROXY_CLASS = "net.p455w0rd.wirelesscraftingterminal.proxy.ClientProxy"; + public static final String GUI_FACTORY = "net.p455w0rd.wirelesscraftingterminal.client.gui.GuiFactory"; + public static final String CREDITS_LIST = "brandon3055, Techjar, AlgorythmX2, thatsIch, Nividica, squeek502, M3gaFr3ak, DrummerMC, cpw, LexManos, Pahimar, diesieben07, Wuppy, Jabelar, blay09, SirSengir, mezz"; + public static final String CONFIG_FILE = "WirelessCraftingTerminal.cfg"; + public static int WCT_MAX_POWER = 1600000; + public static boolean WCT_BOOSTER_ENABLED = true; + public static boolean WCT_EASYMODE_ENABLED = false; + public static int WCT_CRAFTMATRIX_Y_OFFSET = 100; +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/Integration.java b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/Integration.java new file mode 100644 index 0000000..e614b32 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/Integration.java @@ -0,0 +1,34 @@ +package net.p455w0rd.wirelesscraftingterminal.transformer; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationType; + +public @interface Integration +{ + @Retention( RetentionPolicy.RUNTIME ) + @Target( ElementType.TYPE ) + @interface InterfaceList + { + Interface[] value(); + } + + @Retention( RetentionPolicy.RUNTIME ) + @Target( ElementType.TYPE ) + @interface Interface + { + String iface(); + + IntegrationType iname(); + } + + @Retention( RetentionPolicy.RUNTIME ) + @Target( ElementType.METHOD ) + @interface Method + { + IntegrationType iname(); + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/MissingCoreMod.java b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/MissingCoreMod.java new file mode 100644 index 0000000..1a64e31 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/MissingCoreMod.java @@ -0,0 +1,82 @@ +package net.p455w0rd.wirelesscraftingterminal.transformer; + +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiErrorScreen; + +import cpw.mods.fml.client.CustomModLoadingErrorDisplayException; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + + +@SideOnly( Side.CLIENT ) +public final class MissingCoreMod extends CustomModLoadingErrorDisplayException +{ + private static final int SHADOW_WHITE = 0xeeeeee; + private static final int COLOR_WHITE = 0xffffff; + private static final long serialVersionUID = -966774766922821652L; + private static final int SCREEN_OFFSET = 15; + + private boolean deobf = false; + + @Override + public void initGui( final GuiErrorScreen errorScreen, final FontRenderer fontRenderer ) + { + final Class clz = errorScreen.getClass(); + try + { + clz.getField( "mc" ); + this.deobf = true; + } + catch( final Throwable ignored ) + { + + } + } + + @Override + public void drawScreen( final GuiErrorScreen errorScreen, final FontRenderer fontRenderer, final int mouseRelX, final int mouseRelY, final float tickTime ) + { + int offset = 10; + this.drawCenteredString( fontRenderer, "Sorry, couldn't load WCT properly.", errorScreen.width / 2, offset, COLOR_WHITE ); + + offset += SCREEN_OFFSET; + this.drawCenteredString( fontRenderer, "Please make sure that WCT is installed into your mods folder.", errorScreen.width / 2, offset, SHADOW_WHITE ); + + offset += 2 * SCREEN_OFFSET; + + if( this.deobf ) + { + offset += SCREEN_OFFSET; + this.drawCenteredString( fontRenderer, "In a developer environment add the following too your args,", errorScreen.width / 2, offset, COLOR_WHITE ); + + offset += SCREEN_OFFSET; + this.drawCenteredString( fontRenderer, "-Dfml.coreMods.load=net.p455w0rd.wirelesscraftingterminal.transformer.WCTCore", errorScreen.width / 2, offset, SHADOW_WHITE ); + } + else + { + this.drawCenteredString( fontRenderer, "You're launcher may refer to this by different names,", errorScreen.width / 2, offset, COLOR_WHITE ); + + offset += SCREEN_OFFSET + 5; + + this.drawCenteredString( fontRenderer, "MultiMC calls this tab \"Loader Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); + + offset += SCREEN_OFFSET; + this.drawCenteredString( fontRenderer, "Magic Launcher calls this tab \"External Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); + + offset += SCREEN_OFFSET; + this.drawCenteredString( fontRenderer, "Most other launchers refer to this tab as just \"Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); + + offset += 2 * SCREEN_OFFSET; + this.drawCenteredString( fontRenderer, "Also make sure that the WCT file is a .jar, and not a .zip", errorScreen.width / 2, offset, COLOR_WHITE ); + } + } + + private void drawCenteredString( final FontRenderer fontRenderer, final String string, final int x, final int y, final int colour ) + { + final String reEncoded = string.replaceAll( "\\P{InBasic_Latin}", "" ); + final int reEncodedWidth = fontRenderer.getStringWidth( reEncoded ); + final int centeredX = x - reEncodedWidth / 2; + + fontRenderer.drawStringWithShadow( string, centeredX, y, colour ); + } +} \ No newline at end of file diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/WCTCore.java b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/WCTCore.java new file mode 100644 index 0000000..39ecf71 --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/WCTCore.java @@ -0,0 +1,137 @@ +package net.p455w0rd.wirelesscraftingterminal.transformer; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.Nullable; + +import com.google.common.collect.Lists; +import com.google.common.eventbus.EventBus; + +import cpw.mods.fml.common.DummyModContainer; +import cpw.mods.fml.common.LoadController; +import cpw.mods.fml.common.Mod.EventHandler; +import cpw.mods.fml.common.ModMetadata; +import cpw.mods.fml.common.event.FMLInitializationEvent; +import cpw.mods.fml.relauncher.FMLRelaunchLog; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; +import cpw.mods.fml.common.versioning.ArtifactVersion; +import cpw.mods.fml.common.versioning.VersionParser; +import net.p455w0rd.wirelesscraftingterminal.reference.Reference; + + + +@MCVersion( "1.7.10" ) +public final class WCTCore extends DummyModContainer implements IFMLLoadingPlugin +{ + private final ModMetadata metadata = new ModMetadata(); + + public WCTCore() + { + FMLRelaunchLog.info( "[WCT] Core Init" ); + this.metadata.autogenerated = false; + this.metadata.authorList.add( "p455w0rd" ); + this.metadata.credits = "AlgorithmX2"; + this.metadata.modId = this.getModId(); + this.metadata.version = this.getVersion(); + this.metadata.name = this.getName(); + this.metadata.url = "http://p455w0rd.net/mc"; + this.metadata.description = "Embedded Coremod for Wireless Crafting Terminal"; + this.metadata.autogenerated = false; + this.metadata.dependencies=this.getDependencies(); + this.metadata.requiredMods=this.getRequirements(); + } + + @EventHandler + public void load( final FMLInitializationEvent event ) + { + } + + @Override + public List getDependencies() + { + List deps = Lists.newArrayList(); + deps.add(VersionParser.parseVersionReference("appliedenergistics2-core")); + return deps; + } + + @Override + public Set getRequirements() + { + Set reqDeps = new HashSet(); + reqDeps.add(VersionParser.parseVersionReference("appliedenergistics2-core")); + return reqDeps; + } + + + @Override + public String[] getASMTransformerClass() + { + return null; + } + + @Override + public String getModContainerClass() + { + return "net.p455w0rd.wirelesscraftingterminal.transformer.WCTCore"; + } + + @Nullable + @Override + public String getSetupClass() + { + return null; + } + + @Override + public void injectData( final Map data ) + { + + } + + @Override + public String getAccessTransformerClass() + { + return "net.p455w0rd.wirelesscraftingterminal.transformer.asm.ASMIntegration"; + } + + @Override + public ModMetadata getMetadata() + { + return this.metadata; + } + + @Override + public String getModId() + { + return "wct-core"; + } + + @Override + public String getName() + { + return "Wireless Crafting Terminal Core"; + } + + @Override + public String getVersion() + { + return Reference.VERSION; + } + + @Override + public boolean registerBus( final EventBus bus, final LoadController controller ) + { + return true; + } + + @Override + public String getDisplayVersion() + { + return this.getVersion(); + } +} diff --git a/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/asm/ASMIntegration.java b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/asm/ASMIntegration.java new file mode 100644 index 0000000..cc910dc --- /dev/null +++ b/src/java/net/p455w0rd/wirelesscraftingterminal/transformer/asm/ASMIntegration.java @@ -0,0 +1,180 @@ +package net.p455w0rd.wirelesscraftingterminal.transformer.asm; + +import java.util.Iterator; + +import javax.annotation.Nullable; + +import org.apache.logging.log4j.Level; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; + +import net.minecraft.launchwrapper.IClassTransformer; +import net.p455w0rd.wirelesscraftingterminal.helpers.Reflected; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationRegistry; +import net.p455w0rd.wirelesscraftingterminal.integration.IntegrationType; +import net.p455w0rd.wirelesscraftingterminal.transformer.Integration; +import cpw.mods.fml.relauncher.FMLRelaunchLog; + +@Reflected +public final class ASMIntegration implements IClassTransformer { + @Reflected + public ASMIntegration() { + + /** + * Side, Display Name, ModID ClassPostFix + */ + + for (final IntegrationType type : IntegrationType.values()) { + IntegrationRegistry.INSTANCE.add(type); + } + + } + + @Nullable + @Override + public byte[] transform(final String name, final String transformedName, final byte[] basicClass) { + if (basicClass == null || transformedName.startsWith("net.p455w0rd.wirelesscraftingterminal.transformer")) { + return basicClass; + } + + if (transformedName.startsWith("net.p455w0rd.wirelesscraftingterminal.")) { + final ClassNode classNode = new ClassNode(); + final ClassReader classReader = new ClassReader(basicClass); + classReader.accept(classNode, 0); + + try { + final boolean reWrite = this.removeOptionals(classNode); + + if (reWrite) { + final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + return writer.toByteArray(); + } + } catch (final Throwable t) { + t.printStackTrace(); + } + } + return basicClass; + } + + private boolean removeOptionals(final ClassNode classNode) { + boolean changed = false; + + if (classNode.visibleAnnotations != null) { + for (final AnnotationNode an : classNode.visibleAnnotations) { + if (this.hasAnnotation(an, Integration.Interface.class)) { + if (this.stripInterface(classNode, Integration.Interface.class, an)) { + changed = true; + } + } else if (this.hasAnnotation(an, Integration.InterfaceList.class)) { + for (final Object o : ((Iterable) an.values.get(1))) { + if (this.stripInterface(classNode, Integration.InterfaceList.class, (AnnotationNode) o)) { + changed = true; + } + } + } + } + } + + final Iterator i = classNode.methods.iterator(); + while (i.hasNext()) { + final MethodNode mn = i.next(); + + if (mn.visibleAnnotations != null) { + for (final AnnotationNode an : mn.visibleAnnotations) { + if (this.hasAnnotation(an, Integration.Method.class)) { + if (this.stripMethod(classNode, mn, i, Integration.Method.class, an)) { + changed = true; + } + } + } + } + } + + if (changed) { + this.log("Updated " + classNode.name); + } + + return changed; + } + + private boolean hasAnnotation(final AnnotationNode ann, final Class annotation) { + return ann.desc.equals(Type.getDescriptor(annotation)); + } + + private boolean stripInterface(final ClassNode classNode, final Class class1, final AnnotationNode an) { + if (an.values.size() != 4) { + throw new IllegalArgumentException("Unable to handle Interface annotation on " + classNode.name); + } + + String iFace = null; + + if (an.values.get(0).equals("iface")) { + iFace = (String) an.values.get(1); + } else if (an.values.get(2).equals("iface")) { + iFace = (String) an.values.get(3); + } + + String iName = null; + if (an.values.get(0).equals("iname")) { + iName = ((String[]) an.values.get(1))[1]; + } else if (an.values.get(2).equals("iname")) { + iName = ((String[]) an.values.get(3))[1]; + } + + if (iName != null && iFace != null) { + final IntegrationType type = IntegrationType.valueOf(iName); + if (!IntegrationRegistry.INSTANCE.isEnabled(type)) { + this.log("Removing Interface " + iFace + " from " + classNode.name + " because " + iName + + " integration is disabled."); + classNode.interfaces.remove(iFace.replace('.', '/')); + return true; + } else { + this.log("Allowing Interface " + iFace + " from " + classNode.name + " because " + iName + + " integration is enabled."); + } + } else { + throw new IllegalStateException("Unable to handle Method annotation on " + classNode.name); + } + + return false; + } + + private boolean stripMethod(final ClassNode classNode, final MethodNode mn, final Iterator i, + final Class class1, final AnnotationNode an) { + if (an.values.size() != 2) { + throw new IllegalArgumentException("Unable to handle Method annotation on " + classNode.name); + } + + String iName = null; + + if (an.values.get(0).equals("iname")) { + iName = ((String[]) an.values.get(1))[1]; + } + + if (iName != null) { + final IntegrationType type = IntegrationType.valueOf(iName); + if (!IntegrationRegistry.INSTANCE.isEnabled(type)) { + this.log("Removing Method " + mn.name + " from " + classNode.name + " because " + iName + + " integration is disabled."); + i.remove(); + return true; + } else { + this.log("Allowing Method " + mn.name + " from " + classNode.name + " because " + iName + + " integration is enabled."); + } + } else { + throw new IllegalStateException("Unable to handle Method annotation on " + classNode.name); + } + + return false; + } + + private void log(final String string) { + FMLRelaunchLog.log("WCT-CORE", Level.INFO, string); + } +} diff --git a/src/resources/META-INF/MANIFEST.MF b/src/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000..02ccabc --- /dev/null +++ b/src/resources/META-INF/MANIFEST.MF @@ -0,0 +1,4 @@ +Manifest-Version: 1.0 +FMLCorePlugin: net.p455w0rd.wirelesscraftingterminal.transformer.WCTCore +FMLCorePluginContainsFMLMod: true + diff --git a/src/resources/assets/ae2wct/lang/en_US.lang b/src/resources/assets/ae2wct/lang/en_US.lang new file mode 100644 index 0000000..7a85161 --- /dev/null +++ b/src/resources/assets/ae2wct/lang/en_US.lang @@ -0,0 +1,54 @@ +//**************************// +//WIRELESS CRAFTING TEMRINAL// +//**************************// + +//Items +item.wirelessCraftingTerminal.name=Wireless Crafting Terminal +item.infinityBoosterCard.name=Infinity Booster Card +item.magnetCard.name=Magnet Card +itemGroup.ae2wct=ยง9AE2 Wireless Crafting Terminal + +//Tooltips +gui.tooltips.ae2wct.PressShift=Hold Shift for Info +gui.tooltips.ae2wct.OnlyWorks=Only works when in Wireless Crafting Terminal slot! +gui.tooltips.ae2wct.TitleDesc=Description +gui.tooltips.ae2wct.InfinityBoosterDesc=Allows a linked AE2 Wireless Crafting Terminal to be used at any distance and across dimensions. +gui.tooltips.ae2wct.MagnetDesc=A magnet that automagically inserts items into the AE network. +gui.tooltips.ae2wct.MagnetDesc2=Right-click to set filter +gui.tooltips.ae2wct.LinkStatus=Link Status +gui.tooltips.ae2wct.Installed=Installed +gui.tooltips.ae2wct.NotInstalled=Not Installed +gui.tooltips.ae2wct.Active=Active +gui.tooltips.ae2wct.Inactive=Inactive +gui.tooltips.ae2wct.Status=Status +gui.tooltips.ae2wct.EmptyTrash=Empty Trash +gui.tooltips.ae2wct.EmptyTrashDesc=Delete contents of the Trash slot +gui.tooltips.ae2wct.MagnetFilterTitle=Magnet Filter +gui.tooltips.ae2wct.FilterMode=Filter Mode +gui.tooltips.ae2wct.Whitelisting=Whitelisting +gui.tooltips.ae2wct.Blacklisting=Blacklisting + +//Labels +gui.labels.ae2wct.WirelessTermLabel=Wireless Term + +//Config Descriptions +config.ae2wct.MaxPowerDesc=Maximum Power in AE units the wireless terminal can hold +config.ae2wct.InfinityBoosterCfgDesc=Enable Infinite Range Booster Upgrade +config.ae2wct.EasyModeDesc=Enable Easy Mode (Easier Recipes+Infinity Booster Recipe) + +//Achievements +achievement.wctAchievement=Digital Crafting Over WiFi +achievement.wctAchievement.desc=Craft a Wireless Crafting Terminal +achievement.boosterAchievement=Interdimensional Crafting Sack +achievement.boosterAchievement.desc=Aquire an Infinity Booster Card +achievement.magnetAchievement=Digital Hoover +achievement.magnetAchievement.desc=Craft a Magnet Card + +//Chat Messages +chatmessages.ae2wct.NoNetworkPower=Network has no power! + +//Keybindings +key.OpenTerminal=Open Wireless Crafting Terminal +key.OpenMagnetFilter=Open Magnet Filter GUI +key.DisableMagnet=Deactivate Magnet +key.categories.ae2wct=Wireless Crafting Terminal \ No newline at end of file diff --git a/src/resources/assets/ae2wct/textures/gui/crafting.png b/src/resources/assets/ae2wct/textures/gui/crafting.png new file mode 100644 index 0000000..6ed6c4b Binary files /dev/null and b/src/resources/assets/ae2wct/textures/gui/crafting.png differ diff --git a/src/resources/assets/ae2wct/textures/gui/magnetfilter.png b/src/resources/assets/ae2wct/textures/gui/magnetfilter.png new file mode 100644 index 0000000..978c164 Binary files /dev/null and b/src/resources/assets/ae2wct/textures/gui/magnetfilter.png differ diff --git a/src/resources/assets/ae2wct/textures/items/boosterBG.png b/src/resources/assets/ae2wct/textures/items/boosterBG.png new file mode 100644 index 0000000..83a8925 Binary files /dev/null and b/src/resources/assets/ae2wct/textures/items/boosterBG.png differ diff --git a/src/resources/assets/ae2wct/textures/items/infinityBoosterCard.png b/src/resources/assets/ae2wct/textures/items/infinityBoosterCard.png new file mode 100644 index 0000000..2523795 Binary files /dev/null and b/src/resources/assets/ae2wct/textures/items/infinityBoosterCard.png differ diff --git a/src/resources/assets/ae2wct/textures/items/magnetBG.png b/src/resources/assets/ae2wct/textures/items/magnetBG.png new file mode 100644 index 0000000..57fe403 Binary files /dev/null and b/src/resources/assets/ae2wct/textures/items/magnetBG.png differ diff --git a/src/resources/assets/ae2wct/textures/items/magnetCard.png b/src/resources/assets/ae2wct/textures/items/magnetCard.png new file mode 100644 index 0000000..221f149 Binary files /dev/null and b/src/resources/assets/ae2wct/textures/items/magnetCard.png differ diff --git a/src/resources/assets/ae2wct/textures/items/wirelessCraftingTerminal.png b/src/resources/assets/ae2wct/textures/items/wirelessCraftingTerminal.png new file mode 100644 index 0000000..cfb7a72 Binary files /dev/null and b/src/resources/assets/ae2wct/textures/items/wirelessCraftingTerminal.png differ diff --git a/src/resources/mcmod.info b/src/resources/mcmod.info new file mode 100644 index 0000000..3534165 --- /dev/null +++ b/src/resources/mcmod.info @@ -0,0 +1,16 @@ +[ +{ + "modid": "ae2wct", + "name": "AE2 Wireless Crafting Terminal", + "description": "Adds a wireless version of the AE2 Crafting Terminal", + "version": "1.7.10-0.1a", + "mcversion": "1.7.10", + "url": "http://p455w0rd.net/", + "updateUrl": "", + "authorList": ["TheRealp455w0rd"], + "credits": "TheRealp455w0rd", + "logoFile": "", + "screenshots": [], + "dependencies": ["Applied Energistics 2"] +} +] diff --git a/src/resources/pack.mcmeta b/src/resources/pack.mcmeta new file mode 100644 index 0000000..53220b6 --- /dev/null +++ b/src/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "pack_format": 1, + "description": "Resources used for AE2 Wireless Crafting Terminal" + } +}