20 Commits
1.12 ... 1.15

Author SHA1 Message Date
Christian Knaapen
a6bb10f06d Version update 2021-01-31 13:38:23 +01:00
Christian Knaapen
bc6bebe387 Fixed radial menu icons not rendering. Partially fixed shader. 2020-09-03 20:37:50 +02:00
Christian Knaapen
a7961c22a6 Started on GUI for player settings. 2020-08-27 02:24:04 +02:00
Christian Knaapen
96e9e9bb3b Retina display fix 2020-08-26 21:11:51 +02:00
Christian Knaapen
4b22cea9ab Fixes from 1.14 (Fixed freezing when looking up + setting NBT data). 2020-08-25 15:43:15 +02:00
Christian Knaapen
d440325b2a Shader works partially 2020-08-25 15:36:43 +02:00
Christian Knaapen
4bab684369 Working on block previews, updated mappings. 2020-08-24 22:35:13 +02:00
Christian Knaapen
804ed4354b Modifier rendering complete (lines and planes) 2020-08-24 18:18:30 +02:00
Christian Knaapen
31f3cf3233 More work on rendering, mostly test code and a custom rendertype. 2020-08-23 19:27:36 +02:00
Christian Knaapen
e22ad0c311 Initial 1.15 commit 2020-03-15 15:05:57 +01:00
Christian Knaapen
74d74390d2 Fixed undo/redo crashing. 2020-03-15 13:24:13 +01:00
Christian Knaapen
f764fac778 Fixed randomizer bag not opening. Fixed server crash. 2020-03-08 15:10:16 +01:00
Christian Knaapen
42661f884c Removed reach condition for crafting recipes, too much effort to maintain for such a small feature.
Fixed saving modifier settings on closing the gui (don't override onClose() but removed()).
2019-12-23 15:55:32 +01:00
Christian Knaapen
df27697ecb Fixed checkbox graphics (copied GuiCheckBox from previous version). Fixed missing icons in radial menu (moved texture stitch event to ModEventHandler). 2019-12-23 15:13:43 +01:00
Christian Knaapen
fb622bcf99 Removed logging in network messages. 2019-12-23 13:10:25 +01:00
Christian Knaapen
4e3b1ef2ce Fixed crash when placing ladders. Tweaked circle, cylinder and sphere to have the same outer radius whether they are full or hollow. 2019-12-23 13:08:02 +01:00
Christian Knaapen
83b23fe763 Fixed screens, except containerscreen. Fixed clientproxy and BlockRayTraceResult (cast if type = block). 2019-12-06 15:23:05 +01:00
Christian Knaapen
ac429ca64e Initial 1.14 commit. Migrated using xml mapping (in User\.IntelliJIdea2019.3\config\migration). Went through all classes to fix minor issues.
Main tasks left to do: screens, blockBreak animation, ClientProxy/BlockRayTraceResult.
2019-12-04 20:43:40 +01:00
Christian Knaapen
1e51589bde Implemented sphere. Added icons for circle, cylinder, sphere, circle start corner and start center. 2019-12-04 17:36:26 +01:00
Christian Knaapen
6c34b09223 1.13 branch commit, taken from 1.13 repository commit 491113040c350791a403f18752d98c0faa966e6b. For rest of history see repository at https://bitbucket.org/Requios/effortless-building-1.13/src/master/ 2019-12-04 15:40:52 +01:00
103 changed files with 4191 additions and 2942 deletions

62
.gitignore vendored
View File

@@ -1,43 +1,25 @@
## Based on GitHub's Eclipse .gitignore # eclipse
bin
classes/
run/
.gradle/
build/
gradle-app.setting
## IntelliJ IDEA
.idea/
*.iml
*.iws
*.ipr
## Eclipse
eclipse/
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch *.launch
.settings
.metadata
.classpath
.project
# CDT-specific # idea
.cproject out
*.ipr
*.iws
*.iml
.idea
# PDT-specific # gradle
.buildpath build
.gradle
# other
eclipse
run
# Files from Forge MDK
forge*changelog.txt

520
LICENSE.txt Normal file
View File

@@ -0,0 +1,520 @@
Unless noted below, Minecraft Forge, Forge Mod Loader, and all
parts herein are licensed under the terms of the LGPL 2.1 found
here http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt and
copied below.
Homepage: http://minecraftforge.net/
https://github.com/MinecraftForge/MinecraftForge
A note on authorship:
All source artifacts are property of their original author, with
the exclusion of the contents of the patches directory and others
copied from it from time to time. Authorship of the contents of
the patches directory is retained by the Minecraft Forge project.
This is because the patches are partially machine generated
artifacts, and are changed heavily due to the way forge works.
Individual attribution within them is impossible.
Consent:
All contributions to Forge must consent to the release of any
patch content to the Forge project.
A note on infectivity:
The LGPL is chosen specifically so that projects may depend on Forge
features without being infected with its license. That is the
purpose of the LGPL. Mods and others using this code via ordinary
Java mechanics for referencing libraries are specifically not bound
by Forge's license for the Mod code.
=== MCP Data ===
This software includes data from the Minecraft Coder Pack (MCP), with kind permission
from them. The license to MCP data is not transitive - distribution of this data by
third parties requires independent licensing from the MCP team. This data is not
redistributable without permission from the MCP team.
=== Sharing ===
I grant permission for some parts of FML to be redistributed outside the terms of the LGPL, for the benefit of
the minecraft modding community. All contributions to these parts should be licensed under the same additional grant.
-- Runtime patcher --
License is granted to redistribute the runtime patcher code (src/main/java/net/minecraftforge/fml/common/patcher
and subdirectories) under any alternative open source license as classified by the OSI (http://opensource.org/licenses)
-- ASM transformers --
License is granted to redistribute the ASM transformer code (src/main/java/net/minecraftforge/common/asm/ and subdirectories)
under any alternative open source license as classified by the OSI (http://opensource.org/licenses)
=========================================================================
This software includes portions from the Apache Maven project at
http://maven.apache.org/ specifically the ComparableVersion.java code. It is
included based on guidelines at
http://www.softwarefreedom.org/resources/2007/gpl-non-gpl-collaboration.html
with notices intact. The only change is a non-functional change of package name.
This software contains a partial repackaging of javaxdelta, a BSD licensed program for generating
binary differences and applying them, sourced from the subversion at http://sourceforge.net/projects/javaxdelta/
authored by genman, heikok, pivot.
The only changes are to replace some Trove collection types with standard Java collections, and repackaged.
=========================================================================
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS

View File

@@ -1,3 +0,0 @@
This is the version for Minecraft 1.12.
1.13 can be found here: https://bitbucket.org/Requios/effortless-building-1.13/src/master/

53
README.txt Normal file
View File

@@ -0,0 +1,53 @@
-------------------------------------------
Source installation information for modders
-------------------------------------------
This code follows the Minecraft Forge installation methodology. It will apply
some small patches to the vanilla MCP source code, giving you and it access
to some of the data and functions you need to build a successful mod.
Note also that the patches are built against "unrenamed" MCP source code (aka
srgnames) - this means that you will not be able to read them directly against
normal code.
Source pack installation information:
Standalone source installation
==============================
See the Forge Documentation online for more detailed instructions:
http://mcforge.readthedocs.io/en/latest/gettingstarted/
Step 1: Open your command-line and browse to the folder where you extracted the zip file.
Step 2: You're left with a choice.
If you prefer to use Eclipse:
1. Run the following command: "gradlew genEclipseRuns" (./gradlew genEclipseRuns if you are on Mac/Linux)
2. Open Eclipse, Import > Existing Gradle Project > Select Folder
or run "gradlew eclipse" to generate the project.
(Current Issue)
4. Open Project > Run/Debug Settings > Edit runClient and runServer > Environment
5. Edit MOD_CLASSES to show [modid]%%[Path]; 2 times rather then the generated 4.
If you prefer to use IntelliJ:
1. Open IDEA, and import project.
2. Select your build.gradle file and have it import.
3. Run the following command: "gradlew genIntellijRuns" (./gradlew genIntellijRuns if you are on Mac/Linux)
4. Refresh the Gradle Project in IDEA if required.
If at any point you are missing libraries in your IDE, or you've run into problems you can run "gradlew --refresh-dependencies" to refresh the local cache. "gradlew clean" to reset everything {this does not affect your code} and then start the processs again.
Should it still not work,
Refer to #ForgeGradle on EsperNet for more information about the gradle environment.
or the Forge Project Discord discord.gg/UvedJ9m
Forge source installation
=========================
MinecraftForge ships with this code and installs it as part of the forge
installation process, no further action is required on your part.
LexManos' Install Video
=======================
https://www.youtube.com/watch?v=8VEdtQLuLO0&feature=youtu.be
For more details update more often refer to the Forge Forums:
http://www.minecraftforge.net/forum/index.php/topic,14048.0.html

View File

@@ -1,82 +1,146 @@
buildscript { buildscript {
repositories { repositories {
maven { url = 'https://files.minecraftforge.net/maven' }
jcenter() jcenter()
maven { url = "http://files.minecraftforge.net/maven" } mavenCentral()
} }
dependencies { dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '3.+', changing: true
} }
} }
apply plugin: 'net.minecraftforge.gradle.forge' apply plugin: 'net.minecraftforge.gradle'
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. // Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'eclipse'
apply plugin: 'maven-publish'
version = '1.15.2-2.21'
group = 'nl.requios.effortlessbuilding' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'effortlessbuilding'
version = "1.12.2-2.16" sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.
group = "nl.requios.effortlessbuilding" // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = "effortlessbuilding"
sourceCompatibility = targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.
compileJava {
sourceCompatibility = targetCompatibility = '1.8'
}
minecraft { minecraft {
version = "1.12.2-14.23.5.2825" // The mappings can be changed at any time, and must be in the following format.
runDir = "run" // snapshot_YYYYMMDD Snapshot are built nightly.
// stable_# Stables are built at the discretion of the MCP team.
// the mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD snapshot are built nightly.
// stable_# stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not always work. // Use non-default mappings at your own risk. they may not always work.
// simply re-run your setup task after changing the mappings to update your workspace. // Simply re-run your setup task after changing the mappings to update your workspace.
mappings = "stable_39" mappings channel: 'snapshot', version: '20200514-1.15.1'
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable. // makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment (SCAN,REGISTRIES,REGISTRYDUMP)
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
effortlessbuilding {
source sourceSets.main
}
}
} }
repositories { server {
flatDir { dirs 'libs' } workingDirectory project.file('run')
// Recommended logging data for a userdev environment (SCAN,REGISTRIES,REGISTRYDUMP)
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
mods {
effortlessbuilding {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment (SCAN,REGISTRIES,REGISTRYDUMP)
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'
args '--mod', 'effortlessbuilding', '--all', '--output', file('src/generated/resources/')
mods {
effortlessbuilding {
source sourceSets.main
}
}
}
}
} }
dependencies { dependencies {
// you may put jars on which you depend on in ./libs // Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed
// or you may define them like so.. // that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.15.2-31.2.0'
// You may put jars on which you depend on in ./libs or you may define them like so..
// compile "some.group:artifact:version:classifier" // compile "some.group:artifact:version:classifier"
// compile "some.group:artifact:version" // compile "some.group:artifact:version"
// real examples // Real examples
// compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env // compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
// compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env // compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// the 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime. // The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
// provided 'com.mod-buildcraft:buildcraft:6.0.8:dev' // provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// the deobf configurations: 'deobfCompile' and 'deobfProvided' are the same as the normal compile and provided, // These dependencies get remapped to your current MCP mappings
// except that these dependencies get remapped to your current MCP mappings // deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev'
//deobfCompile 'com.mod-buildcraft:buildcraft:6.0.8:dev'
//deobfProvided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
provided 'mod.chiselsandbits:chiselsandbits:14.30'
// for more info... // For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html // http://www.gradle.org/docs/current/userguide/dependency_management.html
} }
processResources { // Example for how to get properties into the manifest for reading by the runtime..
// this will ensure that this task is redone when the versions change. jar {
inputs.property "version", project.version manifest {
inputs.property "mcversion", project.minecraft.version attributes([
"Specification-Title": "effortlessbuilding",
// replace stuff in mcmod.info, nothing else "Specification-Vendor": "requios",
from(sourceSets.main.resources.srcDirs) { "Specification-Version": "1", // We are version 1 of ourselves
include 'mcmod.info' "Implementation-Title": project.name,
"Implementation-Version": "${version}",
// replace version and mcversion "Implementation-Vendor" :"requios",
expand 'version':project.version, 'mcversion':project.minecraft.version "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
} ])
}
// copy everything else except the mcmod.info }
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info' // Example configuration to allow publishing using the maven-publish task
// This is the preferred method to reobfuscate your jar file
jar.finalizedBy('reobfJar')
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing
//publish.dependsOn('reobfJar')
publishing {
publications {
mavenJava(MavenPublication) {
artifact jar
}
}
repositories {
maven {
url "file:///${project.projectDir}/mcmodsrepo"
}
} }
} }

4
gradle.properties Normal file
View File

@@ -0,0 +1,4 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false

Binary file not shown.

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip

Binary file not shown.

View File

@@ -1,89 +1,134 @@
package nl.requios.effortlessbuilding; package nl.requios.effortlessbuilding;
import net.minecraftforge.common.config.Config; import net.minecraftforge.common.ForgeConfigSpec;
import static net.minecraftforge.common.config.Config.*;
@Config(modid = EffortlessBuilding.MODID, name = "EffortlessBuilding", type = Type.INSTANCE, category = "")
public class BuildConfig { public class BuildConfig {
public static Reach reach = new Reach(); private static final ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder();
public static SurvivalBalancers survivalBalancers = new SurvivalBalancers(); public static final Reach reach = new Reach(builder);
public static Visuals visuals = new Visuals(); public static final SurvivalBalancers survivalBalancers = new SurvivalBalancers(builder);
public static final Visuals visuals = new Visuals(builder);
public static final ForgeConfigSpec spec = builder.build();
public static class Reach { public static class Reach {
@Comment({"Reach: how far away the player can place blocks using mirror/array etc.", public final ForgeConfigSpec.ConfigValue<Boolean> enableReachUpgrades;
public final ForgeConfigSpec.ConfigValue<Integer> maxReachCreative;
public final ForgeConfigSpec.ConfigValue<Integer> maxReachLevel0;
public final ForgeConfigSpec.ConfigValue<Integer> maxReachLevel1;
public final ForgeConfigSpec.ConfigValue<Integer> maxReachLevel2;
public final ForgeConfigSpec.ConfigValue<Integer> maxReachLevel3;
public Reach(ForgeConfigSpec.Builder builder) {
builder.push("Reach");
enableReachUpgrades = builder
.comment("Reach: how far away the player can place blocks using mirror/array etc.",
"Enable the crafting of reach upgrades to increase reach.", "Enable the crafting of reach upgrades to increase reach.",
"If disabled, reach is set to level 3 for survival players."}) "If disabled, reach is set to level 3 for survival players.")
public boolean enableReachUpgrades = true; .define("enableReachUpgrades", true);
@Comment({"Maximum reach in creative", maxReachCreative = builder
"Keep in mind that chunks need to be loaded to be able to place blocks inside."}) .comment("Maximum reach in creative",
public int maxReachCreative = 200; "Keep in mind that chunks need to be loaded to be able to place blocks inside.")
.define("maxReachCreative", 200);
@Comment({"Maximum reach in survival without upgrades", maxReachLevel0 = builder
.comment("Maximum reach in survival without upgrades",
"Reach upgrades are craftable consumables that permanently increase reach.", "Reach upgrades are craftable consumables that permanently increase reach.",
"Set to 0 to disable Effortless Building until the player has consumed a reach upgrade."}) "Set to 0 to disable Effortless Building until the player has consumed a reach upgrade.")
public int maxReachLevel0 = 20; .define("maxReachLevel0", 20);
@Comment("Maximum reach in survival with one upgrade") maxReachLevel1 = builder
public int maxReachLevel1 = 50; .comment("Maximum reach in survival with one upgrade")
.define("maxReachLevel1", 50);
@Comment("Maximum reach in survival with two upgrades") maxReachLevel2 = builder
public int maxReachLevel2 = 100; .comment("Maximum reach in survival with two upgrades")
.define("maxReachLevel2", 100);
@Comment("Maximum reach in survival with three upgrades") maxReachLevel3 = builder
public int maxReachLevel3 = 200; .comment("Maximum reach in survival with three upgrades")
.define("maxReachLevel3", 200);
builder.pop();
}
} }
public static class SurvivalBalancers { public static class SurvivalBalancers {
@Comment({"Allows a survival player to break blocks that are far away, in addition to placing blocks.", public final ForgeConfigSpec.ConfigValue<Boolean> breakFar;
"Note: this allows insta-breaking of blocks in survival."}) public final ForgeConfigSpec.ConfigValue<Boolean> increasedMiningTime;
public boolean breakFar = false; public final ForgeConfigSpec.ConfigValue<Integer> miningTimePercentage;
public final ForgeConfigSpec.ConfigValue<Integer> quickReplaceMiningLevel;
public final ForgeConfigSpec.ConfigValue<Integer> undoStackSize;
@Comment({"Increases the time to mine a block when breaking multiple at once.", public SurvivalBalancers(ForgeConfigSpec.Builder builder) {
builder.push("SurvivalBalancers");
breakFar = builder
.comment("Allows a survival player to break blocks that are far away, in addition to placing blocks.",
"Note: this allows insta-breaking of blocks in survival.")
.define("breakFar", false);
increasedMiningTime = builder
.comment("Increases the time to mine a block when breaking multiple at once.",
"Mining time depends on how many blocks, what type of blocks, and the percentage below.", "Mining time depends on how many blocks, what type of blocks, and the percentage below.",
"Example: breaking 1 dirt + 1 obsidian takes the time of breaking 1 dirt + 1 obsidian."}) "Example: breaking 1 dirt + 1 obsidian takes the time of breaking 1 dirt + 1 obsidian.")
public boolean increasedMiningTime = true; .define("increasedMiningTime", true);
@Comment({"How much the mining time of each additional block counts towards an increased mining time.", miningTimePercentage = builder
.comment("How much the mining time of each additional block counts towards an increased mining time.",
"A percentage between 0% and 100%, where 0% is the same as disabling it,", "A percentage between 0% and 100%, where 0% is the same as disabling it,",
"and 100% takes as much time as breaking each block individually.", "and 100% takes as much time as breaking each block individually.",
"The block in front of you always counts as 100%."}) "The block in front of you always counts as 100%.")
@RangeInt(min = 0, max = 200) .defineInRange("miningTimePercentage", 50, 0, 200);
public int miningTimePercentage = 50;
@Comment({"Determines what blocks can be replaced in survival.", quickReplaceMiningLevel = builder
.comment("Determines what blocks can be replaced in survival.",
"-1: only blocks that can be harvested by hand (default)", "-1: only blocks that can be harvested by hand (default)",
"0: blocks that can be harvested with wooden or gold tools", "0: blocks that can be harvested with wooden or gold tools",
"1: blocks that can be harvested with stone tools", "1: blocks that can be harvested with stone tools",
"2: blocks that can be harvested with iron tools", "2: blocks that can be harvested with iron tools",
"3: blocks that can be harvested with diamond tools", "3: blocks that can be harvested with diamond tools")
}) .defineInRange("quickReplaceMiningLevel", -1, -1, 3);
@RangeInt(min = -1, max = 3)
public int quickReplaceMiningLevel = -1;
@Comment({"How many placements are remembered for the undo functionality."}) undoStackSize = builder
@RequiresMcRestart .comment("How many placements are remembered for the undo functionality.")
public int undoStackSize = 10; .worldRestart()
.define("undoStackSize", 10);
builder.pop();
}
} }
public static class Visuals { public static class Visuals {
@Comment({"Show a block preview if you have a block in hand on build mode NORMAL"}) public final ForgeConfigSpec.ConfigValue<Boolean> alwaysShowBlockPreview;
public boolean alwaysShowBlockPreview = false; public final ForgeConfigSpec.ConfigValue<Double> dissolveTimeMultiplier;
public final ForgeConfigSpec.ConfigValue<Integer> shaderTreshold;
public final ForgeConfigSpec.ConfigValue<Boolean> useShaders;
@Comment({"How long the dissolve effect takes when placing blocks.", public Visuals(ForgeConfigSpec.Builder builder) {
builder.push("Visuals");
alwaysShowBlockPreview = builder
.comment("Show a block preview if you have a block in hand even in the 'Normal' build mode")
.define("alwaysShowBlockPreview", false);
dissolveTimeMultiplier = builder
.comment("How long the dissolve effect takes when placing blocks.",
"Default between 30 and 60 ticks, you can multiply that here.", "Default between 30 and 60 ticks, you can multiply that here.",
"Recommended values:", "Recommended values:",
"Snappy: 0.7", "Snappy: 0.7",
"Relaxing: 1.5"}) "Relaxing: 1.5")
public double dissolveTimeMultiplier = 1.0; .define("dissolveTimeMultiplier", 1.0);
@Comment({"Switch to using the simple performance shader when placing more than this many blocks."}) shaderTreshold = builder
public int shaderTreshold = 1500; .comment("Switch to using the simple performance shader when placing more than this many blocks.")
.define("shaderTreshold", 1500);
@Comment({"Use fancy shaders while placing blocks"}) useShaders = builder
public boolean useShaders = true; .comment("Use fancy shaders while placing blocks")
.define("useShaders", true);
builder.pop();
}
} }
} }

View File

@@ -1,58 +1,58 @@
package nl.requios.effortlessbuilding; package nl.requios.effortlessbuilding;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent; import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.config.Config; import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.capability.ModeCapabilityManager; import nl.requios.effortlessbuilding.capability.ModeCapabilityManager;
import nl.requios.effortlessbuilding.capability.ModifierCapabilityManager; import nl.requios.effortlessbuilding.capability.ModifierCapabilityManager;
import nl.requios.effortlessbuilding.command.CommandReach; import nl.requios.effortlessbuilding.command.CommandReach;
import nl.requios.effortlessbuilding.compatibility.CompatHelper; import nl.requios.effortlessbuilding.compatibility.CompatHelper;
import nl.requios.effortlessbuilding.gui.RandomizerBagGuiHandler; import nl.requios.effortlessbuilding.gui.RandomizerBagContainer;
import nl.requios.effortlessbuilding.item.ItemRandomizerBag; import nl.requios.effortlessbuilding.item.ItemRandomizerBag;
import nl.requios.effortlessbuilding.item.ItemReachUpgrade1; import nl.requios.effortlessbuilding.item.ItemReachUpgrade1;
import nl.requios.effortlessbuilding.item.ItemReachUpgrade2; import nl.requios.effortlessbuilding.item.ItemReachUpgrade2;
import nl.requios.effortlessbuilding.item.ItemReachUpgrade3; import nl.requios.effortlessbuilding.item.ItemReachUpgrade3;
import nl.requios.effortlessbuilding.network.*; import nl.requios.effortlessbuilding.network.PacketHandler;
import nl.requios.effortlessbuilding.proxy.ClientProxy;
import nl.requios.effortlessbuilding.proxy.IProxy; import nl.requios.effortlessbuilding.proxy.IProxy;
import nl.requios.effortlessbuilding.proxy.ServerProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@Mod(modid = EffortlessBuilding.MODID, name = EffortlessBuilding.NAME, version = EffortlessBuilding.VERSION) // The value here should match an entry in the META-INF/mods.toml file
@Mod.EventBusSubscriber @Mod(EffortlessBuilding.MODID)
@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
public class EffortlessBuilding public class EffortlessBuilding
{ {
public static final String MODID = "effortlessbuilding"; public static final String MODID = "effortlessbuilding";
public static final String NAME = "Effortless Building"; public static final String NAME = "Effortless Building";
public static final String VERSION = "1.12.2-2.16"; public static final String VERSION = "1.15.2-2.21";
@Mod.Instance(EffortlessBuilding.MODID)
public static EffortlessBuilding instance; public static EffortlessBuilding instance;
public static Logger logger; public static final Logger logger = LogManager.getLogger();
@SidedProxy( public static IProxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> ServerProxy::new);
clientSide="nl.requios.effortlessbuilding.proxy.ClientProxy",
serverSide="nl.requios.effortlessbuilding.proxy.ServerProxy"
)
public static IProxy proxy;
public static final SimpleNetworkWrapper packetHandler = NetworkRegistry.INSTANCE.newSimpleChannel(EffortlessBuilding.MODID);
public static final ItemRandomizerBag ITEM_RANDOMIZER_BAG = new ItemRandomizerBag(); public static final ItemRandomizerBag ITEM_RANDOMIZER_BAG = new ItemRandomizerBag();
public static final ItemReachUpgrade1 ITEM_REACH_UPGRADE_1 = new ItemReachUpgrade1(); public static final ItemReachUpgrade1 ITEM_REACH_UPGRADE_1 = new ItemReachUpgrade1();
@@ -69,82 +69,89 @@ public class EffortlessBuilding
ITEM_REACH_UPGRADE_3 ITEM_REACH_UPGRADE_3
}; };
public static final int RANDOMIZER_BAG_GUI = 0; public static final ContainerType<RandomizerBagContainer> RANDOMIZER_BAG_CONTAINER = register("randomizer_bag", RandomizerBagContainer::new);
public static final ResourceLocation RANDOMIZER_BAG_GUI = new ResourceLocation(EffortlessBuilding.MODID, "randomizer_bag");
@EventHandler public EffortlessBuilding() {
// preInit "Run before anything else. Read your config, create blocks, items, etc, and register them with the GameRegistry." instance = this;
public void preInit(FMLPreInitializationEvent event)
{
logger = event.getModLog();
CapabilityManager.INSTANCE.register(ModifierCapabilityManager.IModifierCapability.class, new ModifierCapabilityManager.Storage(), ModifierCapabilityManager.ModifierCapability.class); // Register the setup method for modloading
CapabilityManager.INSTANCE.register(ModeCapabilityManager.IModeCapability.class, new ModeCapabilityManager.Storage(), ModeCapabilityManager.ModeCapability.class); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
// Register the enqueueIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
// Register the processIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
// Register the clientSetup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientSetup);
EffortlessBuilding.packetHandler.registerMessage(ModifierSettingsMessage.MessageHandler.class, ModifierSettingsMessage.class, 0, Side.SERVER); //Register config
EffortlessBuilding.packetHandler.registerMessage(ModifierSettingsMessage.MessageHandler.class, ModifierSettingsMessage.class, 0, Side.CLIENT); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, BuildConfig.spec);
EffortlessBuilding.packetHandler.registerMessage(ModeSettingsMessage.MessageHandler.class, ModeSettingsMessage.class, 1, Side.SERVER); // Register ourselves for server and other game events we are interested in
EffortlessBuilding.packetHandler.registerMessage(ModeSettingsMessage.MessageHandler.class, ModeSettingsMessage.class, 1, Side.CLIENT); MinecraftForge.EVENT_BUS.register(this);
EffortlessBuilding.packetHandler.registerMessage(ModeActionMessage.MessageHandler.class, ModeActionMessage.class, 2, Side.SERVER);
EffortlessBuilding.packetHandler.registerMessage(ModeActionMessage.MessageHandler.class, ModeActionMessage.class, 2, Side.CLIENT);
EffortlessBuilding.packetHandler.registerMessage(BlockPlacedMessage.MessageHandler.class, BlockPlacedMessage.class, 3, Side.SERVER);
EffortlessBuilding.packetHandler.registerMessage(BlockPlacedMessage.MessageHandler.class, BlockPlacedMessage.class, 3, Side.CLIENT);
EffortlessBuilding.packetHandler.registerMessage(BlockBrokenMessage.MessageHandler.class, BlockBrokenMessage.class, 4, Side.SERVER);
EffortlessBuilding.packetHandler.registerMessage(BlockBrokenMessage.MessageHandler.class, BlockBrokenMessage.class, 4, Side.CLIENT);
EffortlessBuilding.packetHandler.registerMessage(CancelModeMessage.MessageHandler.class, CancelModeMessage.class, 5, Side.SERVER);
EffortlessBuilding.packetHandler.registerMessage(CancelModeMessage.MessageHandler.class, CancelModeMessage.class, 5, Side.CLIENT);
EffortlessBuilding.packetHandler.registerMessage(RequestLookAtMessage.MessageHandler.class, RequestLookAtMessage.class, 6, Side.SERVER);
EffortlessBuilding.packetHandler.registerMessage(RequestLookAtMessage.MessageHandler.class, RequestLookAtMessage.class, 6, Side.CLIENT);
EffortlessBuilding.packetHandler.registerMessage(AddUndoMessage.MessageHandler.class, AddUndoMessage.class, 7, Side.SERVER);
EffortlessBuilding.packetHandler.registerMessage(AddUndoMessage.MessageHandler.class, AddUndoMessage.class, 7, Side.CLIENT);
EffortlessBuilding.packetHandler.registerMessage(ClearUndoMessage.MessageHandler.class, ClearUndoMessage.class, 8, Side.SERVER);
EffortlessBuilding.packetHandler.registerMessage(ClearUndoMessage.MessageHandler.class, ClearUndoMessage.class, 8, Side.CLIENT);
proxy.preInit(event);
} }
@EventHandler @SubscribeEvent
// Do your mod setup. Build whatever data structures you care about. public void setup(final FMLCommonSetupEvent event)
// Register network handlers
public void init(FMLInitializationEvent event)
{ {
ConfigManager.sync(MODID, Config.Type.INSTANCE); CapabilityManager.INSTANCE.register(ModifierCapabilityManager.IModifierCapability.class, new ModifierCapabilityManager.Storage(), ModifierCapabilityManager.ModifierCapability::new);
NetworkRegistry.INSTANCE.registerGuiHandler(EffortlessBuilding.instance, new RandomizerBagGuiHandler()); CapabilityManager.INSTANCE.register(ModeCapabilityManager.IModeCapability.class, new ModeCapabilityManager.Storage(), ModeCapabilityManager.ModeCapability::new);
proxy.init(event); PacketHandler.register();
//TODO 1.13 config
// ConfigManager.sync(MODID, Config.Type.INSTANCE);
proxy.setup(event);
CompatHelper.setup();
} }
@EventHandler @SubscribeEvent
// postInit "Handle interaction with other mods, complete your setup based on this." public void clientSetup(final FMLClientSetupEvent event) {
public void postInit(FMLPostInitializationEvent event)
{ proxy.clientSetup(event);
proxy.postInit(event);
CompatHelper.postInit();
} }
@EventHandler @SubscribeEvent
public void serverStarting(FMLServerStartingEvent event) public void enqueueIMC(final InterModEnqueueEvent event) {
{
event.registerServerCommand(new CommandReach()); // some example code to dispatch IMC to another mod
proxy.serverStarting(event); // InterModComms.sendTo("examplemod", "helloworld", () -> { logger.info("Hello world from the MDK"); return "Hello world";});
}
@SubscribeEvent
public void processIMC(final InterModProcessEvent event) {
// some example code to receive and process InterModComms from other mods
// logger.info("Got IMC {}", event.getIMCStream().
// map(m->m.getMessageSupplier().get()).
// collect(Collectors.toList()));
}
@SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event) {
CommandReach.register(event.getCommandDispatcher());
}
private static <T extends Container> ContainerType<T> register(String key, ContainerType.IFactory<T> factory) {
return Registry.register(Registry.MENU, key, new ContainerType<>(factory));
} }
public static void log(String msg){ public static void log(String msg){
logger.info(msg); logger.info(msg);
} }
public static void log(EntityPlayer player, String msg){ public static void log(PlayerEntity player, String msg){
log(player, msg, false); log(player, msg, false);
} }
public static void log(EntityPlayer player, String msg, boolean actionBar){ public static void log(PlayerEntity player, String msg, boolean actionBar){
player.sendStatusMessage(new TextComponentString(msg), actionBar); player.sendStatusMessage(new StringTextComponent(msg), actionBar);
}
//Log with translation supported, call either on client or server (which then sends a message)
public static void logTranslate(PlayerEntity player, String prefix, String translationKey, String suffix, boolean actionBar){
proxy.logTranslate(player, prefix, translationKey, suffix, actionBar);
} }
} }

View File

@@ -1,29 +1,22 @@
package nl.requios.effortlessbuilding; package nl.requios.effortlessbuilding;
import net.minecraft.block.Block; import net.minecraft.block.BlockState;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.Blocks;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraftforge.common.config.Config; import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.network.PacketDistributor;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager; import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.BlockSet;
import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers; import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.UndoRedo; import nl.requios.effortlessbuilding.buildmodifier.UndoRedo;
@@ -32,53 +25,33 @@ import nl.requios.effortlessbuilding.capability.ModifierCapabilityManager;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import nl.requios.effortlessbuilding.helper.SurvivalHelper; import nl.requios.effortlessbuilding.helper.SurvivalHelper;
import nl.requios.effortlessbuilding.network.AddUndoMessage; import nl.requios.effortlessbuilding.network.AddUndoMessage;
import nl.requios.effortlessbuilding.network.BlockBrokenMessage;
import nl.requios.effortlessbuilding.network.ClearUndoMessage; import nl.requios.effortlessbuilding.network.ClearUndoMessage;
import nl.requios.effortlessbuilding.network.PacketHandler;
import nl.requios.effortlessbuilding.network.RequestLookAtMessage; import nl.requios.effortlessbuilding.network.RequestLookAtMessage;
import scala.actors.threadpool.Arrays;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import static net.minecraftforge.fml.common.gameevent.PlayerEvent.*;
@Mod.EventBusSubscriber @Mod.EventBusSubscriber
public class EventHandler public class EventHandler
{ {
@SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event)
{
event.getRegistry().registerAll(EffortlessBuilding.BLOCKS);
}
@SubscribeEvent
public static void registerItems(RegistryEvent.Register<Item> event)
{
event.getRegistry().registerAll(EffortlessBuilding.ITEMS);
for (Block block : EffortlessBuilding.BLOCKS)
{
event.getRegistry().register(new ItemBlock(block).setRegistryName(block.getRegistryName()));
}
}
@SubscribeEvent @SubscribeEvent
public static void attachCapabilities(AttachCapabilitiesEvent<Entity> event) { public static void attachCapabilities(AttachCapabilitiesEvent<Entity> event) {
if (event.getObject() instanceof EntityPlayer) { if (event.getObject() instanceof PlayerEntity) {
event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "BuildModifier"), new ModifierCapabilityManager.Provider()); event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "build_modifier"), new ModifierCapabilityManager.Provider());
event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "BuildMode"), new ModeCapabilityManager.Provider()); event.addCapability(new ResourceLocation(EffortlessBuilding.MODID, "build_mode"), new ModeCapabilityManager.Provider());
} }
} }
@SubscribeEvent //TODO 1.13 config
public static void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) // @SubscribeEvent
{ // public static void onConfigChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event)
if (event.getModID().equals(EffortlessBuilding.MODID)) // {
{ // if (event.getModID().equals(EffortlessBuilding.MODID))
ConfigManager.sync(EffortlessBuilding.MODID, Config.Type.INSTANCE); // {
} // ConfigManager.sync(EffortlessBuilding.MODID, Config.Type.INSTANCE);
} // }
// }
// @SubscribeEvent // @SubscribeEvent
// public static void onServerTick(TickEvent.ServerTickEvent event) { // public static void onServerTick(TickEvent.ServerTickEvent event) {
@@ -87,11 +60,13 @@ public class EventHandler
@SubscribeEvent @SubscribeEvent
//Only called serverside (except with lilypads...) //Only called serverside (except with lilypads...)
public static void onBlockPlaced(BlockEvent.PlaceEvent event) { public static void onBlockPlaced(BlockEvent.EntityPlaceEvent event) {
if (event.getWorld().isRemote) return; if (event.getWorld().isRemote()) return;
if (!(event.getEntity() instanceof PlayerEntity)) return;
//Cancel event if necessary //Cancel event if necessary
EntityPlayer player = event.getPlayer(); ServerPlayerEntity player = ((ServerPlayerEntity) event.getEntity());
BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode(); BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode();
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
@@ -100,21 +75,26 @@ public class EventHandler
} else if (modifierSettings.doQuickReplace()) { } else if (modifierSettings.doQuickReplace()) {
//Cancel event and send message if QuickReplace //Cancel event and send message if QuickReplace
event.setCanceled(true); event.setCanceled(true);
EffortlessBuilding.packetHandler.sendTo(new RequestLookAtMessage(true), (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new RequestLookAtMessage(true));
EffortlessBuilding.packetHandler.sendTo(new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState()), (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState()));
} else { } else {
//NORMAL mode, let vanilla handle block placing //NORMAL mode, let vanilla handle block placing
//But modifiers should still work //But modifiers should still work
//Send message to client, which sends message back with raytrace info //Send message to client, which sends message back with raytrace info
EffortlessBuilding.packetHandler.sendTo(new RequestLookAtMessage(false), (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new RequestLookAtMessage(false));
EffortlessBuilding.packetHandler.sendTo(new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState()), (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new AddUndoMessage(event.getPos(), event.getBlockSnapshot().getReplacedBlock(), event.getState()));
} }
// Stat<ResourceLocation> blocksPlacedStat = StatList.CUSTOM.get(new ResourceLocation(EffortlessBuilding.MODID, "blocks_placed"));
// player.getStats().increment(player, blocksPlacedStat, 1);
//
// System.out.println(player.getStats().getValue(blocksPlacedStat));
} }
@SubscribeEvent @SubscribeEvent
public static void onBlockBroken(BlockEvent.BreakEvent event) { public static void onBlockBroken(BlockEvent.BreakEvent event) {
if (event.getWorld().isRemote) return; if (event.getWorld().isRemote()) return;
//Cancel event if necessary //Cancel event if necessary
//If cant break far then dont cancel event ever //If cant break far then dont cancel event ever
@@ -123,21 +103,21 @@ public class EventHandler
event.setCanceled(true); event.setCanceled(true);
} else { } else {
//NORMAL mode, let vanilla handle block breaking //NORMAL mode, let vanilla handle block breaking
//But modifiers should still work //But modifiers and QuickReplace should still work
//Dont break the original block yourself, otherwise Tinkers Hammer and Veinminer won't work //Dont break the original block yourself, otherwise Tinkers Hammer and Veinminer won't work
BuildModes.onBlockBroken(event.getPlayer(), event.getPos(), false); BuildModes.onBlockBroken(event.getPlayer(), event.getPos(), false);
//Add to undo stack in client //Add to undo stack in client
EffortlessBuilding.packetHandler.sendTo(new AddUndoMessage(event.getPos(), event.getState(), Blocks.AIR.getDefaultState()), (EntityPlayerMP) event.getPlayer()); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) event.getPlayer()), new AddUndoMessage(event.getPos(), event.getState(), Blocks.AIR.getDefaultState()));
} }
} }
@SubscribeEvent @SubscribeEvent
public static void breakSpeed(PlayerEvent.BreakSpeed event) { public static void breakSpeed(PlayerEvent.BreakSpeed event) {
//Disable if config says so //Disable if config says so
if (!BuildConfig.survivalBalancers.increasedMiningTime) return; if (!BuildConfig.survivalBalancers.increasedMiningTime.get()) return;
EntityPlayer player = event.getEntityPlayer(); PlayerEntity player = event.getPlayer();
World world = player.world; World world = player.world;
BlockPos pos = event.getPos(); BlockPos pos = event.getPos();
@@ -151,14 +131,14 @@ public class EventHandler
for (int i = 1; i < coordinates.size(); i++) { for (int i = 1; i < coordinates.size(); i++) {
BlockPos coordinate = coordinates.get(i); BlockPos coordinate = coordinates.get(i);
//get existing blockstates at those coordinates //get existing blockstates at those coordinates
IBlockState blockState = world.getBlockState(coordinate); BlockState blockState = world.getBlockState(coordinate);
//add hardness for each blockstate, if can break //add hardness for each blockstate, if can break
if (SurvivalHelper.canBreak(world, player, coordinate)) if (SurvivalHelper.canBreak(world, player, coordinate))
totalBlockHardness += blockState.getBlockHardness(world, coordinate); totalBlockHardness += blockState.getBlockHardness(world, coordinate);
} }
//Grabbing percentage from config //Grabbing percentage from config
float percentage = (float) BuildConfig.survivalBalancers.miningTimePercentage / 100; float percentage = (float) BuildConfig.survivalBalancers.miningTimePercentage.get() / 100;
totalBlockHardness *= percentage; totalBlockHardness *= percentage;
totalBlockHardness += originalBlockHardness; totalBlockHardness += originalBlockHardness;
@@ -170,37 +150,60 @@ public class EventHandler
} }
@SubscribeEvent @SubscribeEvent
public static void onPlayerLoggedIn(PlayerLoggedInEvent event) { public static void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
EntityPlayer player = event.player; PlayerEntity player = event.getPlayer();
ModifierSettingsManager.handleNewPlayer(player); ModifierSettingsManager.handleNewPlayer(player);
ModeSettingsManager.handleNewPlayer(player); ModeSettingsManager.handleNewPlayer(player);
} }
@SubscribeEvent @SubscribeEvent
public static void onPlayerLoggedOut(PlayerLoggedOutEvent event) { public static void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) {
EntityPlayer player = event.player; PlayerEntity player = event.getPlayer();
if (player.getEntityWorld().isRemote) return; if (player.getEntityWorld().isRemote) return;
UndoRedo.clear(player); UndoRedo.clear(player);
EffortlessBuilding.packetHandler.sendTo(new ClearUndoMessage(), (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new ClearUndoMessage());
} }
@SubscribeEvent @SubscribeEvent
public static void onPlayerRespawn(PlayerRespawnEvent event) { public static void onPlayerRespawn(PlayerEvent.PlayerRespawnEvent event) {
EntityPlayer player = event.player; PlayerEntity player = event.getPlayer();
ModifierSettingsManager.handleNewPlayer(player); ModifierSettingsManager.handleNewPlayer(player);
ModeSettingsManager.handleNewPlayer(player); ModeSettingsManager.handleNewPlayer(player);
} }
@SubscribeEvent @SubscribeEvent
public static void onPlayerChangedDimension(PlayerChangedDimensionEvent event) { public static void onPlayerChangedDimension(PlayerEvent.PlayerChangedDimensionEvent event) {
EntityPlayer player = event.player; PlayerEntity player = event.getPlayer();
if (player.getEntityWorld().isRemote) return; if (player.getEntityWorld().isRemote) return;
//Set build mode to normal
ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player);
modeSettings.setBuildMode(BuildModes.BuildModeEnum.NORMAL);
ModeSettingsManager.setModeSettings(player, modeSettings);
//Disable modifiers
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
modifierSettings.getMirrorSettings().enabled = false;
modifierSettings.getRadialMirrorSettings().enabled = false;
modifierSettings.getArraySettings().enabled = false;
ModifierSettingsManager.setModifierSettings(player, modifierSettings);
ModifierSettingsManager.handleNewPlayer(player); ModifierSettingsManager.handleNewPlayer(player);
ModeSettingsManager.handleNewPlayer(player); ModeSettingsManager.handleNewPlayer(player);
UndoRedo.clear(player); UndoRedo.clear(player);
EffortlessBuilding.packetHandler.sendTo(new ClearUndoMessage(), (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new ClearUndoMessage());
}
@SubscribeEvent
public static void onPlayerClone(PlayerEvent.Clone event) {
//Attach capabilities on death, otherwise crash
PlayerEntity oldPlayer = event.getOriginal();
oldPlayer.revive();
PlayerEntity newPlayer = event.getPlayer();
ModifierSettingsManager.setModifierSettings(newPlayer, ModifierSettingsManager.getModifierSettings(oldPlayer));
ModeSettingsManager.setModeSettings(newPlayer, ModeSettingsManager.getModeSettings(oldPlayer));
} }
} }

View File

@@ -0,0 +1,48 @@
package nl.requios.effortlessbuilding;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.AtlasTexture;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.ModeOptions;
import java.util.HashMap;
@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD, value = {Dist.CLIENT})
public class ModClientEventHandler {
private static final HashMap<BuildModes.BuildModeEnum, ResourceLocation> buildModeIcons = new HashMap<>();
private static final HashMap<ModeOptions.ActionEnum, ResourceLocation> modeOptionIcons = new HashMap<>();
@SubscribeEvent
public static void onTextureStitch(final TextureStitchEvent.Pre event) {
EffortlessBuilding.log("Stitching textures");
//register icon textures
for (final BuildModes.BuildModeEnum mode : BuildModes.BuildModeEnum.values())
{
final ResourceLocation spriteLocation = new ResourceLocation(EffortlessBuilding.MODID, "icons/" + mode.name().toLowerCase());
event.addSprite(spriteLocation);
buildModeIcons.put(mode, spriteLocation);
}
for (final ModeOptions.ActionEnum action : ModeOptions.ActionEnum.values())
{
final ResourceLocation spriteLocation = new ResourceLocation(EffortlessBuilding.MODID, "icons/" + action.name().toLowerCase());
event.addSprite(spriteLocation);
modeOptionIcons.put(action, spriteLocation);
}
}
public static TextureAtlasSprite getBuildModeIcon(BuildModes.BuildModeEnum mode) {
return Minecraft.getInstance().getModelManager().getAtlasTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).getSprite(buildModeIcons.get(mode));
}
public static TextureAtlasSprite getModeOptionIcon(ModeOptions.ActionEnum action) {
return Minecraft.getInstance().getModelManager().getAtlasTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).getSprite(modeOptionIcons.get(action));
}
}

View File

@@ -0,0 +1,45 @@
package nl.requios.effortlessbuilding;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.ModeOptions;
import java.util.HashMap;
// You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
// Event bus for receiving Registry Events)
@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
public class ModEventHandler {
@SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event) {
event.getRegistry().registerAll(EffortlessBuilding.BLOCKS);
}
@SubscribeEvent
public static void registerItems(RegistryEvent.Register<Item> event) {
event.getRegistry().registerAll(EffortlessBuilding.ITEMS);
for (Block block : EffortlessBuilding.BLOCKS)
{
event.getRegistry().register(new BlockItem(block, new Item.Properties()).setRegistryName(block.getRegistryName()));
}
}
// @SubscribeEvent
// public static void registerContainerTypes(RegistryEvent.Register<ContainerType<?>> event) {
// event.getRegistry().register()
// }
}

View File

@@ -1,13 +1,12 @@
package nl.requios.effortlessbuilding.buildmode; package nl.requios.effortlessbuilding.buildmode;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import java.util.Dictionary; import java.util.Dictionary;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List;
import java.util.UUID; import java.util.UUID;
public abstract class BaseBuildMode implements IBuildMode { public abstract class BaseBuildMode implements IBuildMode {
@@ -16,25 +15,25 @@ public abstract class BaseBuildMode implements IBuildMode {
protected Dictionary<UUID, Integer> rightClickClientTable = new Hashtable<>(); protected Dictionary<UUID, Integer> rightClickClientTable = new Hashtable<>();
protected Dictionary<UUID, Integer> rightClickServerTable = new Hashtable<>(); protected Dictionary<UUID, Integer> rightClickServerTable = new Hashtable<>();
protected Dictionary<UUID, BlockPos> firstPosTable = new Hashtable<>(); protected Dictionary<UUID, BlockPos> firstPosTable = new Hashtable<>();
protected Dictionary<UUID, EnumFacing> sideHitTable = new Hashtable<>(); protected Dictionary<UUID, Direction> sideHitTable = new Hashtable<>();
protected Dictionary<UUID, Vec3d> hitVecTable = new Hashtable<>(); protected Dictionary<UUID, Vec3d> hitVecTable = new Hashtable<>();
@Override @Override
public void initialize(EntityPlayer player) { public void initialize(PlayerEntity player) {
rightClickClientTable.put(player.getUniqueID(), 0); rightClickClientTable.put(player.getUniqueID(), 0);
rightClickServerTable.put(player.getUniqueID(), 0); rightClickServerTable.put(player.getUniqueID(), 0);
firstPosTable.put(player.getUniqueID(), BlockPos.ORIGIN); firstPosTable.put(player.getUniqueID(), BlockPos.ZERO);
sideHitTable.put(player.getUniqueID(), EnumFacing.UP); sideHitTable.put(player.getUniqueID(), Direction.UP);
hitVecTable.put(player.getUniqueID(), Vec3d.ZERO); hitVecTable.put(player.getUniqueID(), Vec3d.ZERO);
} }
@Override @Override
public EnumFacing getSideHit(EntityPlayer player) { public Direction getSideHit(PlayerEntity player) {
return sideHitTable.get(player.getUniqueID()); return sideHitTable.get(player.getUniqueID());
} }
@Override @Override
public Vec3d getHitVec(EntityPlayer player) { public Vec3d getHitVec(PlayerEntity player) {
return hitVecTable.get(player.getUniqueID()); return hitVecTable.get(player.getUniqueID());
} }
} }

View File

@@ -1,17 +1,15 @@
package nl.requios.effortlessbuilding.buildmode; package nl.requios.effortlessbuilding.buildmode;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceContext;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.buildmodes.*; import nl.requios.effortlessbuilding.buildmode.buildmodes.*;
import nl.requios.effortlessbuilding.buildmode.buildmodes.Circle; import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers;
import nl.requios.effortlessbuilding.buildmode.buildmodes.Cylinder; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.buildmode.buildmodes.Sphere;
import nl.requios.effortlessbuilding.buildmodifier.*;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import nl.requios.effortlessbuilding.helper.SurvivalHelper; import nl.requios.effortlessbuilding.helper.SurvivalHelper;
import nl.requios.effortlessbuilding.network.BlockBrokenMessage; import nl.requios.effortlessbuilding.network.BlockBrokenMessage;
@@ -28,8 +26,8 @@ public class BuildModes {
//Static variables are shared between client and server in singleplayer //Static variables are shared between client and server in singleplayer
//We need them separate //We need them separate
public static Dictionary<EntityPlayer, Boolean> currentlyBreakingClient = new Hashtable<>(); public static Dictionary<PlayerEntity, Boolean> currentlyBreakingClient = new Hashtable<>();
public static Dictionary<EntityPlayer, Boolean> currentlyBreakingServer = new Hashtable<>(); public static Dictionary<PlayerEntity, Boolean> currentlyBreakingServer = new Hashtable<>();
public enum BuildModeEnum { public enum BuildModeEnum {
NORMAL("effortlessbuilding.mode.normal", new Normal()), NORMAL("effortlessbuilding.mode.normal", new Normal()),
@@ -59,10 +57,10 @@ public class BuildModes {
//Uses a network message to get the previous raytraceresult from the player //Uses a network message to get the previous raytraceresult from the player
//The server could keep track of all raytraceresults but this might lag with many players //The server could keep track of all raytraceresults but this might lag with many players
//Raytraceresult is needed for sideHit and hitVec //Raytraceresult is needed for sideHit and hitVec
public static void onBlockPlacedMessage(EntityPlayer player, BlockPlacedMessage message) { public static void onBlockPlacedMessage(PlayerEntity player, BlockPlacedMessage message) {
//Check if not in the middle of breaking //Check if not in the middle of breaking
Dictionary<EntityPlayer, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; Dictionary<PlayerEntity, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer;
if (currentlyBreaking.get(player) != null && currentlyBreaking.get(player)) { if (currentlyBreaking.get(player) != null && currentlyBreaking.get(player)) {
//Cancel breaking //Cancel breaking
initializeMode(player); initializeMode(player);
@@ -79,7 +77,8 @@ public class BuildModes {
startPos = message.getBlockPos(); startPos = message.getBlockPos();
//Offset in direction of sidehit if not quickreplace and not replaceable //Offset in direction of sidehit if not quickreplace and not replaceable
boolean replaceable = player.world.getBlockState(startPos).getBlock().isReplaceable(player.world, startPos); //TODO 1.13 replaceable
boolean replaceable = player.world.getBlockState(startPos).getMaterial().isReplaceable();
boolean becomesDoubleSlab = SurvivalHelper.doesBecomeDoubleSlab(player, startPos, message.getSideHit()); boolean becomesDoubleSlab = SurvivalHelper.doesBecomeDoubleSlab(player, startPos, message.getSideHit());
if (!modifierSettings.doQuickReplace() && !replaceable && !becomesDoubleSlab) { if (!modifierSettings.doQuickReplace() && !replaceable && !becomesDoubleSlab) {
startPos = startPos.offset(message.getSideHit()); startPos = startPos.offset(message.getSideHit());
@@ -113,7 +112,7 @@ public class BuildModes {
coordinates = coordinates.subList(0, limit); coordinates = coordinates.subList(0, limit);
} }
EnumFacing sideHit = buildMode.instance.getSideHit(player); Direction sideHit = buildMode.instance.getSideHit(player);
if (sideHit == null) sideHit = message.getSideHit(); if (sideHit == null) sideHit = message.getSideHit();
Vec3d hitVec = buildMode.instance.getHitVec(player); Vec3d hitVec = buildMode.instance.getHitVec(player);
@@ -128,15 +127,15 @@ public class BuildModes {
} }
//Use a network message to break blocks in the distance using clientside mouse input //Use a network message to break blocks in the distance using clientside mouse input
public static void onBlockBrokenMessage(EntityPlayer player, BlockBrokenMessage message) { public static void onBlockBrokenMessage(PlayerEntity player, BlockBrokenMessage message) {
BlockPos startPos = message.isBlockHit() ? message.getBlockPos() : null; BlockPos startPos = message.isBlockHit() ? message.getBlockPos() : null;
onBlockBroken(player, startPos, true); onBlockBroken(player, startPos, true);
} }
public static void onBlockBroken(EntityPlayer player, BlockPos startPos, boolean breakStartPos) { public static void onBlockBroken(PlayerEntity player, BlockPos startPos, boolean breakStartPos) {
//Check if not in the middle of placing //Check if not in the middle of placing
Dictionary<EntityPlayer, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; Dictionary<PlayerEntity, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer;
if (currentlyBreaking.get(player) != null && !currentlyBreaking.get(player)) { if (currentlyBreaking.get(player) != null && !currentlyBreaking.get(player)) {
//Cancel placing //Cancel placing
initializeMode(player); initializeMode(player);
@@ -154,7 +153,7 @@ public class BuildModes {
//Get coordinates //Get coordinates
BuildModeEnum buildMode = modeSettings.getBuildMode(); BuildModeEnum buildMode = modeSettings.getBuildMode();
List<BlockPos> coordinates = buildMode.instance.onRightClick(player, startPos, EnumFacing.UP, Vec3d.ZERO, true); List<BlockPos> coordinates = buildMode.instance.onRightClick(player, startPos, Direction.UP, Vec3d.ZERO, true);
if (coordinates.isEmpty()) { if (coordinates.isEmpty()) {
currentlyBreaking.put(player, true); currentlyBreaking.put(player, true);
@@ -169,7 +168,7 @@ public class BuildModes {
currentlyBreaking.remove(player); currentlyBreaking.remove(player);
} }
public static List<BlockPos> findCoordinates(EntityPlayer player, BlockPos startPos, boolean skipRaytrace) { public static List<BlockPos> findCoordinates(PlayerEntity player, BlockPos startPos, boolean skipRaytrace) {
List<BlockPos> coordinates = new ArrayList<>(); List<BlockPos> coordinates = new ArrayList<>();
ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player);
@@ -178,31 +177,33 @@ public class BuildModes {
return coordinates; return coordinates;
} }
public static void initializeMode(EntityPlayer player) { public static void initializeMode(PlayerEntity player) {
//Resetting mode, so not placing or breaking //Resetting mode, so not placing or breaking
Dictionary<EntityPlayer, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; Dictionary<PlayerEntity, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer;
currentlyBreaking.remove(player); currentlyBreaking.remove(player);
ModeSettingsManager.getModeSettings(player).getBuildMode().instance.initialize(player); ModeSettingsManager.getModeSettings(player).getBuildMode().instance.initialize(player);
} }
public static boolean isCurrentlyPlacing(EntityPlayer player) { public static boolean isCurrentlyPlacing(PlayerEntity player) {
Dictionary<EntityPlayer, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; Dictionary<PlayerEntity, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer;
return currentlyBreaking.get(player) != null && !currentlyBreaking.get(player); return currentlyBreaking.get(player) != null && !currentlyBreaking.get(player);
} }
public static boolean isCurrentlyBreaking(EntityPlayer player) { public static boolean isCurrentlyBreaking(PlayerEntity player) {
Dictionary<EntityPlayer, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; Dictionary<PlayerEntity, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer;
return currentlyBreaking.get(player) != null && currentlyBreaking.get(player); return currentlyBreaking.get(player) != null && currentlyBreaking.get(player);
} }
//Either placing or breaking //Either placing or breaking
public static boolean isActive(EntityPlayer player) { public static boolean isActive(PlayerEntity player) {
Dictionary<EntityPlayer, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer; Dictionary<PlayerEntity, Boolean> currentlyBreaking = player.world.isRemote ? currentlyBreakingClient : currentlyBreakingServer;
return currentlyBreaking.get(player) != null; return currentlyBreaking.get(player) != null;
} }
//-- Common build mode functionality --//
//Find coordinates on a line bound by a plane //Find coordinates on a line bound by a plane
public static Vec3d findXBound(double x, Vec3d start, Vec3d look) { public static Vec3d findXBound(double x, Vec3d start, Vec3d look) {
//then y and z are //then y and z are
@@ -228,18 +229,43 @@ public class BuildModes {
return new Vec3d(x, y, z); return new Vec3d(x, y, z);
} }
public static boolean isCriteriaValid(Vec3d start, Vec3d look, int reach, EntityPlayer player, boolean skipRaytrace, Vec3d lineBound, Vec3d planeBound, double distToPlayerSq) { //Use this instead of player.getLookVec() in any buildmodes code
public static Vec3d getPlayerLookVec(PlayerEntity player){
Vec3d lookVec = player.getLookVec();
double x = lookVec.x;
double y = lookVec.y;
double z = lookVec.z;
//Further calculations (findXBound etc) don't like any component being 0 or 1 (e.g. dividing by 0)
//isCriteriaValid below will take up to 2 minutes to raytrace blocks towards infinity if that is the case
//So make sure they are close to but never exactly 0 or 1
if (Math.abs(x) < 0.0001) x = 0.0001;
if (Math.abs(x - 1.0) < 0.0001) x = 0.9999;
if (Math.abs(x + 1.0) < 0.0001) x = -0.9999;
if (Math.abs(y) < 0.0001) y = 0.0001;
if (Math.abs(y - 1.0) < 0.0001) y = 0.9999;
if (Math.abs(y + 1.0) < 0.0001) y = -0.9999;
if (Math.abs(z) < 0.0001) z = 0.0001;
if (Math.abs(z - 1.0) < 0.0001) z = 0.9999;
if (Math.abs(z + 1.0) < 0.0001) z = -0.9999;
return new Vec3d(x, y, z);
}
public static boolean isCriteriaValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace, Vec3d lineBound, Vec3d planeBound, double distToPlayerSq) {
boolean intersects = false; boolean intersects = false;
if (!skipRaytrace) { if (!skipRaytrace) {
//collision within a 1 block radius to selected is fine //collision within a 1 block radius to selected is fine
RayTraceResult rayTraceResult = player.world.rayTraceBlocks(start, lineBound, false, true, false); RayTraceContext rayTraceContext = new RayTraceContext(start, lineBound, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, player);
intersects = rayTraceResult != null && rayTraceResult.typeOfHit == RayTraceResult.Type.BLOCK && RayTraceResult rayTraceResult = player.world.rayTraceBlocks(rayTraceContext);
planeBound.subtract(rayTraceResult.hitVec).lengthSquared() > 4; intersects = rayTraceResult != null && rayTraceResult.getType() == RayTraceResult.Type.BLOCK &&
planeBound.subtract(rayTraceResult.getHitVec()).lengthSquared() > 4;
} }
return planeBound.subtract(start).dotProduct(look) > 0 && return planeBound.subtract(start).dotProduct(look) > 0 &&
distToPlayerSq > 2 && distToPlayerSq < reach * reach && distToPlayerSq > 2 && distToPlayerSq < reach * reach &&
!intersects; !intersects;
} }
} }

View File

@@ -1,7 +1,7 @@
package nl.requios.effortlessbuilding.buildmode; package nl.requios.effortlessbuilding.buildmode;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -10,16 +10,16 @@ import java.util.List;
public interface IBuildMode { public interface IBuildMode {
//Fired when a player selects a buildmode and when it needs to initializeMode //Fired when a player selects a buildmode and when it needs to initializeMode
void initialize(EntityPlayer player); void initialize(PlayerEntity player);
//Fired when a block would be placed //Fired when a block would be placed
//Return a list of coordinates where you want to place blocks //Return a list of coordinates where you want to place blocks
List<BlockPos> onRightClick(EntityPlayer player, BlockPos blockPos, EnumFacing sideHit, Vec3d hitVec, boolean skipRaytrace); List<BlockPos> onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace);
//Fired continuously for visualization purposes //Fired continuously for visualization purposes
List<BlockPos> findCoordinates(EntityPlayer player, BlockPos blockPos, boolean skipRaytrace); List<BlockPos> findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace);
EnumFacing getSideHit(EntityPlayer player); Direction getSideHit(PlayerEntity player);
Vec3d getHitVec(EntityPlayer player); Vec3d getHitVec(PlayerEntity player);
} }

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmode; package nl.requios.effortlessbuilding.buildmode;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
@@ -14,6 +14,7 @@ public class ModeOptions {
REDO("effortlessbuilding.action.redo"), REDO("effortlessbuilding.action.redo"),
REPLACE("effortlessbuilding.action.replace"), REPLACE("effortlessbuilding.action.replace"),
OPEN_MODIFIER_SETTINGS("effortlessbuilding.action.open_modifier_settings"), OPEN_MODIFIER_SETTINGS("effortlessbuilding.action.open_modifier_settings"),
OPEN_PLAYER_SETTINGS("effortlessbuilding.action.open_player_settings"),
NORMAL_SPEED("effortlessbuilding.action.normal_speed"), NORMAL_SPEED("effortlessbuilding.action.normal_speed"),
FAST_SPEED("effortlessbuilding.action.fast_speed"), FAST_SPEED("effortlessbuilding.action.fast_speed"),
@@ -110,7 +111,7 @@ public class ModeOptions {
} }
//Called on both client and server //Called on both client and server
public static void performAction(EntityPlayer player, ActionEnum action) { public static void performAction(PlayerEntity player, ActionEnum action) {
if (action == null) return; if (action == null) return;
switch (action) { switch (action) {
@@ -130,6 +131,10 @@ public class ModeOptions {
if (player.world.isRemote) if (player.world.isRemote)
ClientProxy.openModifierSettings(); ClientProxy.openModifierSettings();
break; break;
case OPEN_PLAYER_SETTINGS:
if (player.world.isRemote)
ClientProxy.openPlayerSettings();
break;
case NORMAL_SPEED: case NORMAL_SPEED:
buildSpeed = ActionEnum.NORMAL_SPEED; buildSpeed = ActionEnum.NORMAL_SPEED;
@@ -175,8 +180,12 @@ public class ModeOptions {
break; break;
} }
if (player.world.isRemote && action != ActionEnum.REPLACE && action != ActionEnum.OPEN_MODIFIER_SETTINGS) { if (player.world.isRemote &&
ClientProxy.logTranslate(action.name); action != ActionEnum.REPLACE &&
action != ActionEnum.OPEN_MODIFIER_SETTINGS &&
action != ActionEnum.OPEN_PLAYER_SETTINGS) {
EffortlessBuilding.logTranslate(player, "", action.name, "", true);
} }
} }
} }

View File

@@ -1,49 +1,62 @@
package nl.requios.effortlessbuilding.buildmode; package nl.requios.effortlessbuilding.buildmode;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.network.PacketDistributor;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.capability.ModeCapabilityManager; import nl.requios.effortlessbuilding.capability.ModeCapabilityManager;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import nl.requios.effortlessbuilding.network.ModeSettingsMessage; import nl.requios.effortlessbuilding.network.ModeSettingsMessage;
import nl.requios.effortlessbuilding.network.PacketHandler;
import javax.annotation.Nonnull;
@Mod.EventBusSubscriber @Mod.EventBusSubscriber
public class ModeSettingsManager { public class ModeSettingsManager {
//Retrieves the buildsettings of a player through the modifierCapability capability //Retrieves the buildsettings of a player through the modifierCapability capability
//Never returns null //Never returns null
public static ModeSettings getModeSettings(EntityPlayer player) { @Nonnull
if (player.hasCapability(ModeCapabilityManager.modeCapability, null)) { public static ModeSettings getModeSettings(PlayerEntity player) {
ModeCapabilityManager.IModeCapability capability = player.getCapability( LazyOptional<ModeCapabilityManager.IModeCapability> modeCapability =
ModeCapabilityManager.modeCapability, null); player.getCapability(ModeCapabilityManager.modeCapability, null);
if (modeCapability.isPresent()) {
ModeCapabilityManager.IModeCapability capability = modeCapability.orElse(null);
if (capability.getModeData() == null) { if (capability.getModeData() == null) {
capability.setModeData(new ModeSettings()); capability.setModeData(new ModeSettings());
} }
return capability.getModeData(); return capability.getModeData();
} }
throw new IllegalArgumentException("Player does not have modeCapability capability");
//Player does not have modeCapability capability
//Return dummy settings
return new ModeSettings();
// throw new IllegalArgumentException("Player does not have modeCapability capability");
} }
public static void setModeSettings(EntityPlayer player, ModeSettings modeSettings) { public static void setModeSettings(PlayerEntity player, ModeSettings modeSettings) {
if (player == null) { if (player == null) {
EffortlessBuilding.log("Cannot set buildsettings, player is null"); EffortlessBuilding.log("Cannot set buildmode settings, player is null");
return; return;
} }
if (player.hasCapability(ModeCapabilityManager.modeCapability, null)) { LazyOptional<ModeCapabilityManager.IModeCapability> modeCapability =
ModeCapabilityManager.IModeCapability capability = player.getCapability( player.getCapability(ModeCapabilityManager.modeCapability, null);
ModeCapabilityManager.modeCapability, null);
modeCapability.ifPresent((capability) -> {
capability.setModeData(modeSettings); capability.setModeData(modeSettings);
//Initialize new mode
BuildModes.initializeMode(player); BuildModes.initializeMode(player);
} else { });
EffortlessBuilding.log(player, "Saving buildsettings failed.");
if (!modeCapability.isPresent()) {
EffortlessBuilding.log(player, "Saving buildmode settings failed.");
} }
} }
public static String sanitize(ModeSettings modeSettings, EntityPlayer player) { public static String sanitize(ModeSettings modeSettings, PlayerEntity player) {
int maxReach = ReachHelper.getMaxReach(player); int maxReach = ReachHelper.getMaxReach(player);
String error = ""; String error = "";
@@ -71,16 +84,15 @@ public class ModeSettingsManager {
} }
} }
public static void handleNewPlayer(EntityPlayer player){ public static void handleNewPlayer(PlayerEntity player){
if (getModeSettings(player) == null) { //Makes sure player has mode settings (if it doesnt it will create it)
setModeSettings(player, new ModeSettings()); getModeSettings(player);
}
//Only on server //Only on server
if (!player.world.isRemote) { if (!player.world.isRemote) {
//Send to client //Send to client
ModeSettingsMessage msg = new ModeSettingsMessage(getModeSettings(player)); ModeSettingsMessage msg = new ModeSettingsMessage(getModeSettings(player));
EffortlessBuilding.packetHandler.sendTo(msg, (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), msg);
} }
} }
} }

View File

@@ -1,11 +1,9 @@
package nl.requios.effortlessbuilding.buildmode; package nl.requios.effortlessbuilding.buildmode;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.buildmode.buildmodes.DiagonalLine;
import nl.requios.effortlessbuilding.buildmode.buildmodes.Floor;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.util.*; import java.util.*;
@@ -34,20 +32,20 @@ public abstract class ThreeClicksBuildMode extends BaseBuildMode {
//check if its not behind the player and its not too close and not too far //check if its not behind the player and its not too close and not too far
//also check if raytrace from player to block does not intersect blocks //also check if raytrace from player to block does not intersect blocks
public boolean isValid(Vec3d start, Vec3d look, int reach, EntityPlayer player, boolean skipRaytrace) { public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) {
return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq); return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq);
} }
} }
@Override @Override
public void initialize(EntityPlayer player) { public void initialize(PlayerEntity player) {
super.initialize(player); super.initialize(player);
secondPosTable.put(player.getUniqueID(), BlockPos.ORIGIN); secondPosTable.put(player.getUniqueID(), BlockPos.ZERO);
} }
@Override @Override
public List<BlockPos> onRightClick(EntityPlayer player, BlockPos blockPos, EnumFacing sideHit, Vec3d hitVec, boolean skipRaytrace) { public List<BlockPos> onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable;
@@ -89,7 +87,7 @@ public abstract class ThreeClicksBuildMode extends BaseBuildMode {
} }
@Override @Override
public List<BlockPos> findCoordinates(EntityPlayer player, BlockPos blockPos, boolean skipRaytrace) { public List<BlockPos> findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable;
int rightClickNr = rightClickTable.get(player.getUniqueID()); int rightClickNr = rightClickTable.get(player.getUniqueID());
@@ -158,21 +156,21 @@ public abstract class ThreeClicksBuildMode extends BaseBuildMode {
} }
//Finds the place of the second block pos //Finds the place of the second block pos
protected abstract BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace); protected abstract BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace);
//Finds the place of the third block pos //Finds the place of the third block pos
protected abstract BlockPos findThirdPos(EntityPlayer player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace); protected abstract BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace);
//After first and second pos are known, we want to visualize the blocks in a way (like floor for cube) //After first and second pos are known, we want to visualize the blocks in a way (like floor for cube)
protected abstract List<BlockPos> getIntermediateBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2); protected abstract List<BlockPos> getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2);
//After first, second and third pos are known, we want all the blocks //After first, second and third pos are known, we want all the blocks
protected abstract List<BlockPos> getFinalBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3); protected abstract List<BlockPos> getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3);
//Finds height after floor has been chosen in buildmodes with 3 clicks //Finds height after floor has been chosen in buildmodes with 3 clicks
public static BlockPos findHeight(EntityPlayer player, BlockPos secondPos, boolean skipRaytrace) { public static BlockPos findHeight(PlayerEntity player, BlockPos secondPos, boolean skipRaytrace) {
Vec3d look = player.getLookVec(); Vec3d look = BuildModes.getPlayerLookVec(player);
Vec3d start = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ());
List<HeightCriteria> criteriaList = new ArrayList<>(3); List<HeightCriteria> criteriaList = new ArrayList<>(3);

View File

@@ -1,9 +1,10 @@
package nl.requios.effortlessbuilding.buildmode; package nl.requios.effortlessbuilding.buildmode;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.util.ArrayList; import java.util.ArrayList;
@@ -14,7 +15,7 @@ import java.util.UUID;
public abstract class TwoClicksBuildMode extends BaseBuildMode { public abstract class TwoClicksBuildMode extends BaseBuildMode {
@Override @Override
public List<BlockPos> onRightClick(EntityPlayer player, BlockPos blockPos, EnumFacing sideHit, Vec3d hitVec, boolean skipRaytrace) { public List<BlockPos> onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable;
@@ -44,7 +45,7 @@ public abstract class TwoClicksBuildMode extends BaseBuildMode {
} }
@Override @Override
public List<BlockPos> findCoordinates(EntityPlayer player, BlockPos blockPos, boolean skipRaytrace) { public List<BlockPos> findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable; Dictionary<UUID, Integer> rightClickTable = player.world.isRemote ? rightClickClientTable : rightClickServerTable;
int rightClickNr = rightClickTable.get(player.getUniqueID()); int rightClickNr = rightClickTable.get(player.getUniqueID());
@@ -79,8 +80,8 @@ public abstract class TwoClicksBuildMode extends BaseBuildMode {
} }
//Finds the place of the second block pos based on criteria (floor must be on same height as first click, wall on same plane etc) //Finds the place of the second block pos based on criteria (floor must be on same height as first click, wall on same plane etc)
protected abstract BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace); protected abstract BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace);
//After first and second pos are known, we want all the blocks //After first and second pos are known, we want all the blocks
protected abstract List<BlockPos> getAllBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2); protected abstract List<BlockPos> getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2);
} }

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode;
@@ -11,16 +11,16 @@ import java.util.*;
public class Circle extends TwoClicksBuildMode { public class Circle extends TwoClicksBuildMode {
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return Floor.findFloor(player, firstPos, skipRaytrace); return Floor.findFloor(player, firstPos, skipRaytrace);
} }
@Override @Override
protected List<BlockPos> getAllBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return getCircleBlocks(player, x1, y1, z1, x2, y2, z2); return getCircleBlocks(player, x1, y1, z1, x2, y2, z2);
} }
public static List<BlockPos> getCircleBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public static List<BlockPos> getCircleBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
float centerX = x1; float centerX = x1;

View File

@@ -1,39 +1,35 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.buildmode.IBuildMode;
import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.buildmode.ModeOptions;
import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode;
import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.util.*; import java.util.*;
public class Cube extends ThreeClicksBuildMode { public class Cube extends ThreeClicksBuildMode {
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return Floor.findFloor(player, firstPos, skipRaytrace); return Floor.findFloor(player, firstPos, skipRaytrace);
} }
@Override @Override
protected BlockPos findThirdPos(EntityPlayer player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) {
return findHeight(player, secondPos, skipRaytrace); return findHeight(player, secondPos, skipRaytrace);
} }
@Override @Override
protected List<BlockPos> getIntermediateBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return getFloorBlocksUsingCubeFill(player, x1, y1, z1, x2, y2, z2); return getFloorBlocksUsingCubeFill(player, x1, y1, z1, x2, y2, z2);
} }
@Override @Override
protected List<BlockPos> getFinalBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { protected List<BlockPos> getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
return getCubeBlocks(player, x1, y1, z1, x3, y3, z3); return getCubeBlocks(player, x1, y1, z1, x3, y3, z3);
} }
public static List<BlockPos> getFloorBlocksUsingCubeFill(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public static List<BlockPos> getFloorBlocksUsingCubeFill(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (ModeOptions.getCubeFill() == ModeOptions.ActionEnum.CUBE_SKELETON) if (ModeOptions.getCubeFill() == ModeOptions.ActionEnum.CUBE_SKELETON)
@@ -44,7 +40,7 @@ public class Cube extends ThreeClicksBuildMode {
return list; return list;
} }
public static List<BlockPos> getCubeBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public static List<BlockPos> getCubeBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
switch (ModeOptions.getCubeFill()) { switch (ModeOptions.getCubeFill()) {

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode;
@@ -10,26 +10,26 @@ import java.util.List;
public class Cylinder extends ThreeClicksBuildMode { public class Cylinder extends ThreeClicksBuildMode {
@Override @Override
public BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { public BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return Floor.findFloor(player, firstPos, skipRaytrace); return Floor.findFloor(player, firstPos, skipRaytrace);
} }
@Override @Override
public BlockPos findThirdPos(EntityPlayer player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { public BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) {
return findHeight(player, secondPos, skipRaytrace); return findHeight(player, secondPos, skipRaytrace);
} }
@Override @Override
public List<BlockPos> getIntermediateBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public List<BlockPos> getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2);
} }
@Override @Override
public List<BlockPos> getFinalBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { public List<BlockPos> getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
return getCylinderBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); return getCylinderBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3);
} }
public static List<BlockPos> getCylinderBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { public static List<BlockPos> getCylinderBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
//Get circle blocks (using CIRCLE_START and FILL options built-in) //Get circle blocks (using CIRCLE_START and FILL options built-in)

View File

@@ -1,10 +1,9 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode;
import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -12,29 +11,29 @@ import java.util.List;
public class DiagonalLine extends ThreeClicksBuildMode { public class DiagonalLine extends ThreeClicksBuildMode {
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return Floor.findFloor(player, firstPos, skipRaytrace); return Floor.findFloor(player, firstPos, skipRaytrace);
} }
@Override @Override
protected BlockPos findThirdPos(EntityPlayer player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) {
return findHeight(player, secondPos, skipRaytrace); return findHeight(player, secondPos, skipRaytrace);
} }
@Override @Override
protected List<BlockPos> getIntermediateBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
//Add diagonal line from first to second //Add diagonal line from first to second
return getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 10); return getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 10);
} }
@Override @Override
protected List<BlockPos> getFinalBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { protected List<BlockPos> getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
//Add diagonal line from first to third //Add diagonal line from first to third
return getDiagonalLineBlocks(player, x1, y1, z1, x3, y3, z3, 10); return getDiagonalLineBlocks(player, x1, y1, z1, x3, y3, z3, 10);
} }
//Add diagonal line from first to second //Add diagonal line from first to second
public static List<BlockPos> getDiagonalLineBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, float sampleMultiplier) { public static List<BlockPos> getDiagonalLineBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, float sampleMultiplier) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
Vec3d first = new Vec3d(x1, y1, z1).add(0.5, 0.5, 0.5); Vec3d first = new Vec3d(x1, y1, z1).add(0.5, 0.5, 0.5);

View File

@@ -1,9 +1,8 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode;
import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -11,27 +10,27 @@ import java.util.List;
public class DiagonalWall extends ThreeClicksBuildMode { public class DiagonalWall extends ThreeClicksBuildMode {
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return Floor.findFloor(player, firstPos, skipRaytrace); return Floor.findFloor(player, firstPos, skipRaytrace);
} }
@Override @Override
protected BlockPos findThirdPos(EntityPlayer player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) {
return findHeight(player, secondPos, skipRaytrace); return findHeight(player, secondPos, skipRaytrace);
} }
@Override @Override
protected List<BlockPos> getIntermediateBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 1); return DiagonalLine.getDiagonalLineBlocks(player, x1, y1, z1, x2, y2, z2, 1);
} }
@Override @Override
protected List<BlockPos> getFinalBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { protected List<BlockPos> getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
return getDiagonalWallBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); return getDiagonalWallBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3);
} }
//Add diagonal wall from first to second //Add diagonal wall from first to second
public static List<BlockPos> getDiagonalWallBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { public static List<BlockPos> getDiagonalWallBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
//Get diagonal line blocks //Get diagonal line blocks

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
@@ -23,20 +23,20 @@ public class Floor extends TwoClicksBuildMode {
//check if its not behind the player and its not too close and not too far //check if its not behind the player and its not too close and not too far
//also check if raytrace from player to block does not intersect blocks //also check if raytrace from player to block does not intersect blocks
public boolean isValid(Vec3d start, Vec3d look, int reach, EntityPlayer player, boolean skipRaytrace) { public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) {
return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq); return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq);
} }
} }
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return findFloor(player, firstPos, skipRaytrace); return findFloor(player, firstPos, skipRaytrace);
} }
public static BlockPos findFloor(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { public static BlockPos findFloor(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
Vec3d look = player.getLookVec(); Vec3d look = BuildModes.getPlayerLookVec(player);
Vec3d start = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ());
List<Criteria> criteriaList = new ArrayList<>(3); List<Criteria> criteriaList = new ArrayList<>(3);
@@ -58,11 +58,11 @@ public class Floor extends TwoClicksBuildMode {
} }
@Override @Override
protected List<BlockPos> getAllBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return getFloorBlocks(player, x1, y1, z1, x2, y2, z2); return getFloorBlocks(player, x1, y1, z1, x2, y2, z2);
} }
public static List<BlockPos> getFloorBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public static List<BlockPos> getFloorBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL) if (ModeOptions.getFill() == ModeOptions.ActionEnum.FULL)

View File

@@ -1,8 +1,9 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.TwoClicksBuildMode;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
@@ -47,7 +48,7 @@ public class Line extends TwoClicksBuildMode {
//check if its not behind the player and its not too close and not too far //check if its not behind the player and its not too close and not too far
//also check if raytrace from player to block does not intersect blocks //also check if raytrace from player to block does not intersect blocks
public boolean isValid(Vec3d start, Vec3d look, int reach, EntityPlayer player, boolean skipRaytrace) { public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) {
return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq); return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, lineBound, planeBound, distToPlayerSq);
} }
@@ -55,13 +56,13 @@ public class Line extends TwoClicksBuildMode {
} }
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return findLine(player, firstPos, skipRaytrace); return findLine(player, firstPos, skipRaytrace);
} }
public static BlockPos findLine(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { public static BlockPos findLine(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
Vec3d look = player.getLookVec(); Vec3d look = BuildModes.getPlayerLookVec(player);
Vec3d start = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ());
List<Criteria> criteriaList = new ArrayList<>(3); List<Criteria> criteriaList = new ArrayList<>(3);
@@ -109,11 +110,11 @@ public class Line extends TwoClicksBuildMode {
} }
@Override @Override
protected List<BlockPos> getAllBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return getLineBlocks(player, x1, y1, z1, x2, y2, z2); return getLineBlocks(player, x1, y1, z1, x2, y2, z2);
} }
public static List<BlockPos> getLineBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public static List<BlockPos> getLineBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (x1 != x2) { if (x1 != x2) {

View File

@@ -1,7 +1,7 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.buildmode.IBuildMode; import nl.requios.effortlessbuilding.buildmode.IBuildMode;
@@ -11,31 +11,31 @@ import java.util.List;
public class Normal implements IBuildMode { public class Normal implements IBuildMode {
@Override @Override
public void initialize(EntityPlayer player) { public void initialize(PlayerEntity player) {
} }
@Override @Override
public List<BlockPos> onRightClick(EntityPlayer player, BlockPos blockPos, EnumFacing sideHit, Vec3d hitVec, boolean skipRaytrace) { public List<BlockPos> onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (blockPos != null) list.add(blockPos); if (blockPos != null) list.add(blockPos);
return list; return list;
} }
@Override @Override
public List<BlockPos> findCoordinates(EntityPlayer player, BlockPos blockPos, boolean skipRaytrace) { public List<BlockPos> findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (blockPos != null) list.add(blockPos); if (blockPos != null) list.add(blockPos);
return list; return list;
} }
@Override @Override
public EnumFacing getSideHit(EntityPlayer player) { public Direction getSideHit(PlayerEntity player) {
return null; return null;
} }
@Override @Override
public Vec3d getHitVec(EntityPlayer player) { public Vec3d getHitVec(PlayerEntity player) {
return null; return null;
} }
} }

View File

@@ -1,7 +1,7 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.buildmode.IBuildMode; import nl.requios.effortlessbuilding.buildmode.IBuildMode;
@@ -11,31 +11,31 @@ import java.util.List;
public class NormalPlus implements IBuildMode { public class NormalPlus implements IBuildMode {
@Override @Override
public void initialize(EntityPlayer player) { public void initialize(PlayerEntity player) {
} }
@Override @Override
public List<BlockPos> onRightClick(EntityPlayer player, BlockPos blockPos, EnumFacing sideHit, Vec3d hitVec, boolean skipRaytrace) { public List<BlockPos> onRightClick(PlayerEntity player, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (blockPos != null) list.add(blockPos); if (blockPos != null) list.add(blockPos);
return list; return list;
} }
@Override @Override
public List<BlockPos> findCoordinates(EntityPlayer player, BlockPos blockPos, boolean skipRaytrace) { public List<BlockPos> findCoordinates(PlayerEntity player, BlockPos blockPos, boolean skipRaytrace) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (blockPos != null) list.add(blockPos); if (blockPos != null) list.add(blockPos);
return list; return list;
} }
@Override @Override
public EnumFacing getSideHit(EntityPlayer player) { public Direction getSideHit(PlayerEntity player) {
return null; return null;
} }
@Override @Override
public Vec3d getHitVec(EntityPlayer player) { public Vec3d getHitVec(PlayerEntity player) {
return null; return null;
} }
} }

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.buildmode.ModeOptions;
import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode; import nl.requios.effortlessbuilding.buildmode.ThreeClicksBuildMode;
@@ -12,27 +12,27 @@ import java.util.List;
public class SlopeFloor extends ThreeClicksBuildMode { public class SlopeFloor extends ThreeClicksBuildMode {
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return Floor.findFloor(player, firstPos, skipRaytrace); return Floor.findFloor(player, firstPos, skipRaytrace);
} }
@Override @Override
protected BlockPos findThirdPos(EntityPlayer player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { protected BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) {
return findHeight(player, secondPos, skipRaytrace); return findHeight(player, secondPos, skipRaytrace);
} }
@Override @Override
protected List<BlockPos> getIntermediateBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return Floor.getFloorBlocks(player, x1, y1, z1, x2, y2, z2); return Floor.getFloorBlocks(player, x1, y1, z1, x2, y2, z2);
} }
@Override @Override
protected List<BlockPos> getFinalBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { protected List<BlockPos> getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
return getSlopeFloorBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); return getSlopeFloorBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3);
} }
//Add slope floor from first to second //Add slope floor from first to second
public static List<BlockPos> getSlopeFloorBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { public static List<BlockPos> getSlopeFloorBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
int axisLimit = ReachHelper.getMaxBlocksPerAxis(player); int axisLimit = ReachHelper.getMaxBlocksPerAxis(player);

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.buildmode.ModeOptions;
@@ -12,26 +12,26 @@ import java.util.List;
public class Sphere extends ThreeClicksBuildMode { public class Sphere extends ThreeClicksBuildMode {
@Override @Override
public BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { public BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return Floor.findFloor(player, firstPos, skipRaytrace); return Floor.findFloor(player, firstPos, skipRaytrace);
} }
@Override @Override
public BlockPos findThirdPos(EntityPlayer player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) { public BlockPos findThirdPos(PlayerEntity player, BlockPos firstPos, BlockPos secondPos, boolean skipRaytrace) {
return findHeight(player, secondPos, skipRaytrace); return findHeight(player, secondPos, skipRaytrace);
} }
@Override @Override
public List<BlockPos> getIntermediateBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public List<BlockPos> getIntermediateBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2); return Circle.getCircleBlocks(player, x1, y1, z1, x2, y2, z2);
} }
@Override @Override
public List<BlockPos> getFinalBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { public List<BlockPos> getFinalBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
return getSphereBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3); return getSphereBlocks(player, x1, y1, z1, x2, y2, z2, x3, y3, z3);
} }
public static List<BlockPos> getSphereBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { public static List<BlockPos> getSphereBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
float centerX = x1; float centerX = x1;

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmode.buildmodes; package nl.requios.effortlessbuilding.buildmode.buildmodes;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
@@ -26,20 +26,20 @@ public class Wall extends TwoClicksBuildMode {
//check if its not behind the player and its not too close and not too far //check if its not behind the player and its not too close and not too far
//also check if raytrace from player to block does not intersect blocks //also check if raytrace from player to block does not intersect blocks
public boolean isValid(Vec3d start, Vec3d look, int reach, EntityPlayer player, boolean skipRaytrace) { public boolean isValid(Vec3d start, Vec3d look, int reach, PlayerEntity player, boolean skipRaytrace) {
return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq); return BuildModes.isCriteriaValid(start, look, reach, player, skipRaytrace, planeBound, planeBound, distToPlayerSq);
} }
} }
@Override @Override
protected BlockPos findSecondPos(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { protected BlockPos findSecondPos(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
return findWall(player, firstPos, skipRaytrace); return findWall(player, firstPos, skipRaytrace);
} }
public static BlockPos findWall(EntityPlayer player, BlockPos firstPos, boolean skipRaytrace) { public static BlockPos findWall(PlayerEntity player, BlockPos firstPos, boolean skipRaytrace) {
Vec3d look = player.getLookVec(); Vec3d look = BuildModes.getPlayerLookVec(player);
Vec3d start = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ());
List<Criteria> criteriaList = new ArrayList<>(3); List<Criteria> criteriaList = new ArrayList<>(3);
@@ -76,11 +76,11 @@ public class Wall extends TwoClicksBuildMode {
} }
@Override @Override
protected List<BlockPos> getAllBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { protected List<BlockPos> getAllBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
return getWallBlocks(player, x1, y1, z1, x2, y2, z2); return getWallBlocks(player, x1, y1, z1, x2, y2, z2);
} }
public static List<BlockPos> getWallBlocks(EntityPlayer player, int x1, int y1, int z1, int x2, int y2, int z2) { public static List<BlockPos> getWallBlocks(PlayerEntity player, int x1, int y1, int z1, int x2, int y2, int z2) {
List<BlockPos> list = new ArrayList<>(); List<BlockPos> list = new ArrayList<>();
if (x1 == x2) { if (x1 == x2) {

View File

@@ -1,10 +1,10 @@
package nl.requios.effortlessbuilding.buildmodifier; package nl.requios.effortlessbuilding.buildmodifier;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.EnumHand; import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -18,7 +18,7 @@ public class Array {
public static class ArraySettings{ public static class ArraySettings{
public boolean enabled = false; public boolean enabled = false;
public BlockPos offset = BlockPos.ORIGIN; public BlockPos offset = BlockPos.ZERO;
public int count = 5; public int count = 5;
public ArraySettings() { public ArraySettings() {
@@ -41,7 +41,7 @@ public class Array {
} }
} }
public static List<BlockPos> findCoordinates(EntityPlayer player, BlockPos startPos) { public static List<BlockPos> findCoordinates(PlayerEntity player, BlockPos startPos) {
List<BlockPos> coordinates = new ArrayList<>(); List<BlockPos> coordinates = new ArrayList<>();
//find arraysettings for the player //find arraysettings for the player
@@ -59,8 +59,8 @@ public class Array {
return coordinates; return coordinates;
} }
public static List<IBlockState> findBlockStates(EntityPlayer player, BlockPos startPos, IBlockState blockState, ItemStack itemStack, List<ItemStack> itemStacks) { public static List<BlockState> findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List<ItemStack> itemStacks) {
List<IBlockState> blockStates = new ArrayList<>(); List<BlockState> blockStates = new ArrayList<>();
//find arraysettings for the player that placed the block //find arraysettings for the player that placed the block
ArraySettings a = ModifierSettingsManager.getModifierSettings(player).getArraySettings(); ArraySettings a = ModifierSettingsManager.getModifierSettings(player).getArraySettings();
@@ -82,7 +82,7 @@ public class Array {
if (bagInventory != null) { if (bagInventory != null) {
itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); itemStack = ItemRandomizerBag.pickRandomStack(bagInventory);
blockState = BuildModifiers blockState = BuildModifiers
.getBlockStateFromItem(itemStack, player, startPos, EnumFacing.UP, new Vec3d(0, 0, 0), EnumHand.MAIN_HAND); .getBlockStateFromItem(itemStack, player, startPos, Direction.UP, new Vec3d(0, 0, 0), Hand.MAIN_HAND);
} }
//blockState = blockState.getBlock().getStateForPlacement(player.world, pos, ) //blockState = blockState.getBlock().getStateForPlacement(player.world, pos, )

View File

@@ -1,6 +1,6 @@
package nl.requios.effortlessbuilding.buildmodifier; package nl.requios.effortlessbuilding.buildmodifier;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -8,13 +8,13 @@ import java.util.List;
public class BlockSet { public class BlockSet {
private List<BlockPos> coordinates; private List<BlockPos> coordinates;
private List<IBlockState> previousBlockStates; private List<BlockState> previousBlockStates;
private List<IBlockState> newBlockStates; private List<BlockState> newBlockStates;
private Vec3d hitVec; private Vec3d hitVec;
private BlockPos firstPos; private BlockPos firstPos;
private BlockPos secondPos; private BlockPos secondPos;
public BlockSet(List<BlockPos> coordinates, List<IBlockState> previousBlockStates, List<IBlockState> newBlockStates, Vec3d hitVec, public BlockSet(List<BlockPos> coordinates, List<BlockState> previousBlockStates, List<BlockState> newBlockStates, Vec3d hitVec,
BlockPos firstPos, BlockPos secondPos) { BlockPos firstPos, BlockPos secondPos) {
this.coordinates = coordinates; this.coordinates = coordinates;
this.previousBlockStates = previousBlockStates; this.previousBlockStates = previousBlockStates;
@@ -28,11 +28,11 @@ public class BlockSet {
return coordinates; return coordinates;
} }
public List<IBlockState> getPreviousBlockStates() { public List<BlockState> getPreviousBlockStates() {
return previousBlockStates; return previousBlockStates;
} }
public List<IBlockState> getNewBlockStates() { public List<BlockState> getNewBlockStates() {
return newBlockStates; return newBlockStates;
} }

View File

@@ -1,14 +1,17 @@
package nl.requios.effortlessbuilding.buildmodifier; package nl.requios.effortlessbuilding.buildmodifier;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.item.ItemBlock; import net.minecraft.item.BlockItem;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.item.ItemUseContext;
import net.minecraft.util.EnumHand; import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World; import net.minecraft.world.World;
import nl.requios.effortlessbuilding.compatibility.CompatHelper; import nl.requios.effortlessbuilding.compatibility.CompatHelper;
@@ -22,7 +25,7 @@ import java.util.*;
public class BuildModifiers { public class BuildModifiers {
//Called from BuildModes //Called from BuildModes
public static void onBlockPlaced(EntityPlayer player, List<BlockPos> startCoordinates, EnumFacing sideHit, Vec3d hitVec, boolean placeStartPos) { public static void onBlockPlaced(PlayerEntity player, List<BlockPos> startCoordinates, Direction sideHit, Vec3d hitVec, boolean placeStartPos) {
World world = player.world; World world = player.world;
ItemRandomizerBag.renewRandomness(); ItemRandomizerBag.renewRandomness();
@@ -32,14 +35,14 @@ public class BuildModifiers {
//find coordinates and blockstates //find coordinates and blockstates
List<BlockPos> coordinates = findCoordinates(player, startCoordinates); List<BlockPos> coordinates = findCoordinates(player, startCoordinates);
List<ItemStack> itemStacks = new ArrayList<>(); List<ItemStack> itemStacks = new ArrayList<>();
List<IBlockState> blockStates = findBlockStates(player, startCoordinates, hitVec, sideHit, itemStacks); List<BlockState> blockStates = findBlockStates(player, startCoordinates, hitVec, sideHit, itemStacks);
//check if valid blockstates //check if valid blockstates
if (blockStates.size() == 0 || coordinates.size() != blockStates.size()) return; if (blockStates.size() == 0 || coordinates.size() != blockStates.size()) return;
//remember previous blockstates for undo //remember previous blockstates for undo
List<IBlockState> previousBlockStates = new ArrayList<>(coordinates.size()); List<BlockState> previousBlockStates = new ArrayList<>(coordinates.size());
List<IBlockState> newBlockStates = new ArrayList<>(coordinates.size()); List<BlockState> newBlockStates = new ArrayList<>(coordinates.size());
for (BlockPos coordinate : coordinates) { for (BlockPos coordinate : coordinates) {
previousBlockStates.add(world.getBlockState(coordinate)); previousBlockStates.add(world.getBlockState(coordinate));
} }
@@ -55,17 +58,17 @@ public class BuildModifiers {
//place blocks //place blocks
for (int i = placeStartPos ? 0 : 1; i < coordinates.size(); i++) { for (int i = placeStartPos ? 0 : 1; i < coordinates.size(); i++) {
BlockPos blockPos = coordinates.get(i); BlockPos blockPos = coordinates.get(i);
IBlockState blockState = blockStates.get(i); BlockState blockState = blockStates.get(i);
ItemStack itemStack = itemStacks.get(i); ItemStack itemStack = itemStacks.get(i);
if (world.isBlockLoaded(blockPos, true)) { if (world.isBlockPresent(blockPos)) {
//check itemstack empty //check itemstack empty
if (itemStack.isEmpty()) { if (itemStack.isEmpty()) {
//try to find new stack, otherwise continue //try to find new stack, otherwise continue
itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock()); itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock());
if (itemStack.isEmpty()) continue; if (itemStack.isEmpty()) continue;
} }
SurvivalHelper.placeBlock(world, player, blockPos, blockState, itemStack, EnumFacing.UP, hitVec, false, false, false); SurvivalHelper.placeBlock(world, player, blockPos, blockState, itemStack, Direction.UP, hitVec, false, false, false);
} }
} }
@@ -87,10 +90,9 @@ public class BuildModifiers {
BlockPos secondPos = startCoordinates.get(startCoordinates.size() - 1); BlockPos secondPos = startCoordinates.get(startCoordinates.size() - 1);
UndoRedo.addUndo(player, new BlockSet(coordinates, previousBlockStates, newBlockStates, hitVec, firstPos, secondPos)); UndoRedo.addUndo(player, new BlockSet(coordinates, previousBlockStates, newBlockStates, hitVec, firstPos, secondPos));
} }
} }
public static void onBlockBroken(EntityPlayer player, List<BlockPos> startCoordinates, boolean breakStartPos) { public static void onBlockBroken(PlayerEntity player, List<BlockPos> startCoordinates, boolean breakStartPos) {
World world = player.world; World world = player.world;
List<BlockPos> coordinates = findCoordinates(player, startCoordinates); List<BlockPos> coordinates = findCoordinates(player, startCoordinates);
@@ -98,8 +100,8 @@ public class BuildModifiers {
if (coordinates.isEmpty()) return; if (coordinates.isEmpty()) return;
//remember previous blockstates for undo //remember previous blockstates for undo
List<IBlockState> previousBlockStates = new ArrayList<>(coordinates.size()); List<BlockState> previousBlockStates = new ArrayList<>(coordinates.size());
List<IBlockState> newBlockStates = new ArrayList<>(coordinates.size()); List<BlockState> newBlockStates = new ArrayList<>(coordinates.size());
for (BlockPos coordinate : coordinates) { for (BlockPos coordinate : coordinates) {
previousBlockStates.add(world.getBlockState(coordinate)); previousBlockStates.add(world.getBlockState(coordinate));
} }
@@ -108,7 +110,7 @@ public class BuildModifiers {
BlockPreviewRenderer.onBlocksBroken(); BlockPreviewRenderer.onBlocksBroken();
//list of air blockstates //list of air blockstates
for (BlockPos coordinate : coordinates) { for (int i = 0; i < coordinates.size(); i++) {
newBlockStates.add(Blocks.AIR.getDefaultState()); newBlockStates.add(Blocks.AIR.getDefaultState());
} }
@@ -121,7 +123,7 @@ public class BuildModifiers {
//break all those blocks //break all those blocks
for (int i = breakStartPos ? 0 : 1; i < coordinates.size(); i++) { for (int i = breakStartPos ? 0 : 1; i < coordinates.size(); i++) {
BlockPos coordinate = coordinates.get(i); BlockPos coordinate = coordinates.get(i);
if (world.isBlockLoaded(coordinate, false)) { if (world.isBlockPresent(coordinate) && !world.isAirBlock(coordinate)) {
if (!onlyInstaBreaking || world.getBlockState(coordinate).getBlockHardness(world, coordinate) == 0f) { if (!onlyInstaBreaking || world.getBlockState(coordinate).getBlockHardness(world, coordinate) == 0f) {
SurvivalHelper.breakBlock(world, player, coordinate, false); SurvivalHelper.breakBlock(world, player, coordinate, false);
} }
@@ -146,7 +148,7 @@ public class BuildModifiers {
} }
public static List<BlockPos> findCoordinates(EntityPlayer player, List<BlockPos> posList) { public static List<BlockPos> findCoordinates(PlayerEntity player, List<BlockPos> posList) {
List<BlockPos> coordinates = new ArrayList<>(); List<BlockPos> coordinates = new ArrayList<>();
//Add current blocks being placed too //Add current blocks being placed too
coordinates.addAll(posList); coordinates.addAll(posList);
@@ -167,18 +169,18 @@ public class BuildModifiers {
return coordinates; return coordinates;
} }
public static List<BlockPos> findCoordinates(EntityPlayer player, BlockPos blockPos) { public static List<BlockPos> findCoordinates(PlayerEntity player, BlockPos blockPos) {
return findCoordinates(player, new ArrayList<>(Arrays.asList(blockPos))); return findCoordinates(player, new ArrayList<>(Arrays.asList(blockPos)));
} }
public static List<IBlockState> findBlockStates(EntityPlayer player, List<BlockPos> posList, Vec3d hitVec, EnumFacing facing, List<ItemStack> itemStacks) { public static List<BlockState> findBlockStates(PlayerEntity player, List<BlockPos> posList, Vec3d hitVec, Direction facing, List<ItemStack> itemStacks) {
List<IBlockState> blockStates = new ArrayList<>(); List<BlockState> blockStates = new ArrayList<>();
itemStacks.clear(); itemStacks.clear();
//Get itemstack //Get itemstack
ItemStack itemStack = player.getHeldItem(EnumHand.MAIN_HAND); ItemStack itemStack = player.getHeldItem(Hand.MAIN_HAND);
if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) { if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) {
itemStack = player.getHeldItem(EnumHand.OFF_HAND); itemStack = player.getHeldItem(Hand.OFF_HAND);
} }
if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) { if (itemStack.isEmpty() || !CompatHelper.isItemBlockProxy(itemStack)) {
return blockStates; return blockStates;
@@ -186,22 +188,22 @@ public class BuildModifiers {
//Get ItemBlock stack //Get ItemBlock stack
ItemStack itemBlock = ItemStack.EMPTY; ItemStack itemBlock = ItemStack.EMPTY;
if (itemStack.getItem() instanceof ItemBlock) itemBlock = itemStack; if (itemStack.getItem() instanceof BlockItem) itemBlock = itemStack;
else itemBlock = CompatHelper.getItemBlockFromStack(itemStack); else itemBlock = CompatHelper.getItemBlockFromStack(itemStack);
ItemRandomizerBag.resetRandomness(); ItemRandomizerBag.resetRandomness();
//Add blocks in posList first //Add blocks in posList first
for (BlockPos blockPos : posList) { for (BlockPos blockPos : posList) {
if (!(itemStack.getItem() instanceof ItemBlock)) itemBlock = CompatHelper.getItemBlockFromStack(itemStack); if (!(itemStack.getItem() instanceof BlockItem)) itemBlock = CompatHelper.getItemBlockFromStack(itemStack);
IBlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, EnumHand.MAIN_HAND); BlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, Hand.MAIN_HAND);
blockStates.add(blockState); blockStates.add(blockState);
itemStacks.add(itemBlock); itemStacks.add(itemBlock);
} }
for (BlockPos blockPos : posList) { for (BlockPos blockPos : posList) {
IBlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, EnumHand.MAIN_HAND); BlockState blockState = getBlockStateFromItem(itemBlock, player, blockPos, facing, hitVec, Hand.MAIN_HAND);
List<IBlockState> arrayBlockStates = Array.findBlockStates(player, blockPos, blockState, itemStack, itemStacks); List<BlockState> arrayBlockStates = Array.findBlockStates(player, blockPos, blockState, itemStack, itemStacks);
blockStates.addAll(arrayBlockStates); blockStates.addAll(arrayBlockStates);
blockStates.addAll(Mirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks)); blockStates.addAll(Mirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks));
blockStates.addAll(RadialMirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks)); blockStates.addAll(RadialMirror.findBlockStates(player, blockPos, blockState, itemStack, itemStacks));
@@ -209,7 +211,7 @@ public class BuildModifiers {
List<BlockPos> arrayCoordinates = Array.findCoordinates(player, blockPos); List<BlockPos> arrayCoordinates = Array.findCoordinates(player, blockPos);
for (int i = 0; i < arrayCoordinates.size(); i++) { for (int i = 0; i < arrayCoordinates.size(); i++) {
BlockPos coordinate = arrayCoordinates.get(i); BlockPos coordinate = arrayCoordinates.get(i);
IBlockState blockState1 = arrayBlockStates.get(i); BlockState blockState1 = arrayBlockStates.get(i);
blockStates.addAll(Mirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks)); blockStates.addAll(Mirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks));
blockStates.addAll(RadialMirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks)); blockStates.addAll(RadialMirror.findBlockStates(player, coordinate, blockState1, itemStack, itemStacks));
} }
@@ -234,9 +236,8 @@ public class BuildModifiers {
modifierSettings.doQuickReplace(); modifierSettings.doQuickReplace();
} }
public static IBlockState getBlockStateFromItem(ItemStack itemStack, EntityPlayer player, BlockPos blockPos, EnumFacing facing, Vec3d hitVec, EnumHand hand) { public static BlockState getBlockStateFromItem(ItemStack itemStack, PlayerEntity player, BlockPos blockPos, Direction facing, Vec3d hitVec, Hand hand) {
return Block.getBlockFromItem(itemStack.getItem()).getStateForPlacement(player.world, blockPos, facing, return Block.getBlockFromItem(itemStack.getItem()).getStateForPlacement(new BlockItemUseContext(new ItemUseContext(player, hand, new BlockRayTraceResult(hitVec, facing, blockPos, false))));
((float) hitVec.x), ((float) hitVec.y), ((float) hitVec.z), itemStack.getMetadata(), player, hand);
} }
//Returns true if equal (or both null) //Returns true if equal (or both null)

View File

@@ -1,14 +1,16 @@
package nl.requios.effortlessbuilding.buildmodifier; package nl.requios.effortlessbuilding.buildmodifier;
import net.minecraft.block.BlockDirectional; import net.minecraft.block.*;
import net.minecraft.block.BlockDispenser; import net.minecraft.block.StairsBlock;
import net.minecraft.block.BlockSlab; import net.minecraft.block.DirectionalBlock;
import net.minecraft.block.BlockStairs; import net.minecraft.block.SlabBlock;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.state.properties.Half;
import net.minecraft.util.EnumHand; import net.minecraft.state.properties.SlabType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
@@ -45,7 +47,7 @@ public class Mirror {
} }
} }
public static List<BlockPos> findCoordinates(EntityPlayer player, BlockPos startPos) { public static List<BlockPos> findCoordinates(PlayerEntity player, BlockPos startPos) {
List<BlockPos> coordinates = new ArrayList<>(); List<BlockPos> coordinates = new ArrayList<>();
//find mirrorsettings for the player //find mirrorsettings for the player
@@ -85,8 +87,8 @@ public class Mirror {
coordinates.add(newBlockPos); coordinates.add(newBlockPos);
} }
public static List<IBlockState> findBlockStates(EntityPlayer player, BlockPos startPos, IBlockState blockState, ItemStack itemStack, List<ItemStack> itemStacks) { public static List<BlockState> findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List<ItemStack> itemStacks) {
List<IBlockState> blockStates = new ArrayList<>(); List<BlockState> blockStates = new ArrayList<>();
//find mirrorsettings for the player //find mirrorsettings for the player
MirrorSettings m = ModifierSettingsManager.getModifierSettings(player).getMirrorSettings(); MirrorSettings m = ModifierSettingsManager.getModifierSettings(player).getMirrorSettings();
@@ -98,15 +100,15 @@ public class Mirror {
bagInventory = ItemRandomizerBag.getBagInventory(itemStack); bagInventory = ItemRandomizerBag.getBagInventory(itemStack);
} }
if (m.mirrorX) blockStateMirrorX(player, m, startPos, blockState, bagInventory, itemStack, EnumHand.MAIN_HAND, blockStates, itemStacks); if (m.mirrorX) blockStateMirrorX(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks);
if (m.mirrorY) blockStateMirrorY(player, m, startPos, blockState, bagInventory, itemStack, EnumHand.MAIN_HAND, blockStates, itemStacks); if (m.mirrorY) blockStateMirrorY(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks);
if (m.mirrorZ) blockStateMirrorZ(player, m, startPos, blockState, bagInventory, itemStack, EnumHand.MAIN_HAND, blockStates, itemStacks); if (m.mirrorZ) blockStateMirrorZ(player, m, startPos, blockState, bagInventory, itemStack, Hand.MAIN_HAND, blockStates, itemStacks);
return blockStates; return blockStates;
} }
private static void blockStateMirrorX(EntityPlayer player, MirrorSettings m, BlockPos oldBlockPos, IBlockState oldBlockState, private static void blockStateMirrorX(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState,
IItemHandler bagInventory, ItemStack itemStack, EnumHand hand, List<IBlockState> blockStates, List<ItemStack> itemStacks) { IItemHandler bagInventory, ItemStack itemStack, Hand hand, List<BlockState> blockStates, List<ItemStack> itemStacks) {
//find mirror position //find mirror position
double x = m.position.x + (m.position.x - oldBlockPos.getX() - 0.5); double x = m.position.x + (m.position.x - oldBlockPos.getX() - 0.5);
BlockPos newBlockPos = new BlockPos(x, oldBlockPos.getY(), oldBlockPos.getZ()); BlockPos newBlockPos = new BlockPos(x, oldBlockPos.getY(), oldBlockPos.getZ());
@@ -114,11 +116,11 @@ public class Mirror {
//Randomizer bag synergy //Randomizer bag synergy
if (bagInventory != null) { if (bagInventory != null) {
itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); itemStack = ItemRandomizerBag.pickRandomStack(bagInventory);
oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, EnumFacing.UP, new Vec3d(0, 0, 0), hand); oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vec3d(0, 0, 0), hand);
} }
//Find blockstate //Find blockstate
IBlockState newBlockState = oldBlockState == null ? null : oldBlockState.withMirror(net.minecraft.util.Mirror.FRONT_BACK); BlockState newBlockState = oldBlockState == null ? null : oldBlockState.mirror(net.minecraft.util.Mirror.FRONT_BACK);
//Store blockstate and itemstack //Store blockstate and itemstack
blockStates.add(newBlockState); blockStates.add(newBlockState);
@@ -128,8 +130,8 @@ public class Mirror {
if (m.mirrorZ) blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); if (m.mirrorZ) blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks);
} }
private static void blockStateMirrorY(EntityPlayer player, MirrorSettings m, BlockPos oldBlockPos, IBlockState oldBlockState, private static void blockStateMirrorY(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState,
IItemHandler bagInventory, ItemStack itemStack, EnumHand hand, List<IBlockState> blockStates, List<ItemStack> itemStacks) { IItemHandler bagInventory, ItemStack itemStack, Hand hand, List<BlockState> blockStates, List<ItemStack> itemStacks) {
//find mirror position //find mirror position
double y = m.position.y + (m.position.y - oldBlockPos.getY() - 0.5); double y = m.position.y + (m.position.y - oldBlockPos.getY() - 0.5);
BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), y, oldBlockPos.getZ()); BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), y, oldBlockPos.getZ());
@@ -137,11 +139,11 @@ public class Mirror {
//Randomizer bag synergy //Randomizer bag synergy
if (bagInventory != null) { if (bagInventory != null) {
itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); itemStack = ItemRandomizerBag.pickRandomStack(bagInventory);
oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, EnumFacing.UP, new Vec3d(0, 0, 0), hand); oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vec3d(0, 0, 0), hand);
} }
//Find blockstate //Find blockstate
IBlockState newBlockState = oldBlockState == null ? null : getVerticalMirror(oldBlockState); BlockState newBlockState = oldBlockState == null ? null : getVerticalMirror(oldBlockState);
//Store blockstate and itemstack //Store blockstate and itemstack
blockStates.add(newBlockState); blockStates.add(newBlockState);
@@ -150,8 +152,8 @@ public class Mirror {
if (m.mirrorZ) blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks); if (m.mirrorZ) blockStateMirrorZ(player, m, newBlockPos, newBlockState, bagInventory, itemStack, hand, blockStates, itemStacks);
} }
private static void blockStateMirrorZ(EntityPlayer player, MirrorSettings m, BlockPos oldBlockPos, IBlockState oldBlockState, private static void blockStateMirrorZ(PlayerEntity player, MirrorSettings m, BlockPos oldBlockPos, BlockState oldBlockState,
IItemHandler bagInventory, ItemStack itemStack, EnumHand hand, List<IBlockState> blockStates, List<ItemStack> itemStacks) { IItemHandler bagInventory, ItemStack itemStack, Hand hand, List<BlockState> blockStates, List<ItemStack> itemStacks) {
//find mirror position //find mirror position
double z = m.position.z + (m.position.z - oldBlockPos.getZ() - 0.5); double z = m.position.z + (m.position.z - oldBlockPos.getZ() - 0.5);
BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), oldBlockPos.getY(), z); BlockPos newBlockPos = new BlockPos(oldBlockPos.getX(), oldBlockPos.getY(), z);
@@ -159,11 +161,11 @@ public class Mirror {
//Randomizer bag synergy //Randomizer bag synergy
if (bagInventory != null) { if (bagInventory != null) {
itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); itemStack = ItemRandomizerBag.pickRandomStack(bagInventory);
oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, EnumFacing.UP, new Vec3d(0, 0, 0), hand); oldBlockState = BuildModifiers.getBlockStateFromItem(itemStack, player, oldBlockPos, Direction.UP, new Vec3d(0, 0, 0), hand);
} }
//Find blockstate //Find blockstate
IBlockState newBlockState = oldBlockState == null ? null : oldBlockState.withMirror(net.minecraft.util.Mirror.LEFT_RIGHT); BlockState newBlockState = oldBlockState == null ? null : oldBlockState.mirror(net.minecraft.util.Mirror.LEFT_RIGHT);
//Store blockstate and itemstack //Store blockstate and itemstack
blockStates.add(newBlockState); blockStates.add(newBlockState);
@@ -182,41 +184,42 @@ public class Mirror {
return true; return true;
} }
private static IBlockState getVerticalMirror(IBlockState blockState) { private static BlockState getVerticalMirror(BlockState blockState) {
//Stairs //Stairs
if (blockState.getBlock() instanceof BlockStairs) { if (blockState.getBlock() instanceof StairsBlock) {
if (blockState.getValue(BlockStairs.HALF) == BlockStairs.EnumHalf.BOTTOM) { if (blockState.get(StairsBlock.HALF) == Half.BOTTOM) {
return blockState.withProperty(BlockStairs.HALF, BlockStairs.EnumHalf.TOP); return blockState.with(StairsBlock.HALF, Half.TOP);
} else { } else {
return blockState.withProperty(BlockStairs.HALF, BlockStairs.EnumHalf.BOTTOM); return blockState.with(StairsBlock.HALF, Half.BOTTOM);
} }
} }
//Slabs //Slabs
if (blockState.getBlock() instanceof BlockSlab) { if (blockState.getBlock() instanceof SlabBlock) {
if (((BlockSlab) blockState.getBlock()).isDouble()) return blockState; if (blockState.get(SlabBlock.TYPE) == SlabType.DOUBLE) {
if (blockState.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM) { return blockState;
return blockState.withProperty(BlockSlab.HALF, BlockSlab.EnumBlockHalf.TOP); } else if (blockState.get(SlabBlock.TYPE) == SlabType.BOTTOM) {
return blockState.with(SlabBlock.TYPE, SlabType.TOP);
} else { } else {
return blockState.withProperty(BlockSlab.HALF, BlockSlab.EnumBlockHalf.BOTTOM); return blockState.with(SlabBlock.TYPE, SlabType.BOTTOM);
} }
} }
//Buttons, endrod, observer, piston //Buttons, endrod, observer, piston
if (blockState.getBlock() instanceof BlockDirectional) { if (blockState.getBlock() instanceof DirectionalBlock) {
if (blockState.getValue(BlockDirectional.FACING) == EnumFacing.DOWN) { if (blockState.get(DirectionalBlock.FACING) == Direction.DOWN) {
return blockState.withProperty(BlockDirectional.FACING, EnumFacing.UP); return blockState.with(DirectionalBlock.FACING, Direction.UP);
} else if (blockState.getValue(BlockDirectional.FACING) == EnumFacing.UP) { } else if (blockState.get(DirectionalBlock.FACING) == Direction.UP) {
return blockState.withProperty(BlockDirectional.FACING, EnumFacing.DOWN); return blockState.with(DirectionalBlock.FACING, Direction.DOWN);
} }
} }
//Dispenser, dropper //Dispenser, dropper
if (blockState.getBlock() instanceof BlockDispenser) { if (blockState.getBlock() instanceof DispenserBlock) {
if (blockState.getValue(BlockDispenser.FACING) == EnumFacing.DOWN) { if (blockState.get(DispenserBlock.FACING) == Direction.DOWN) {
return blockState.withProperty(BlockDispenser.FACING, EnumFacing.UP); return blockState.with(DispenserBlock.FACING, Direction.UP);
} else if (blockState.getValue(BlockDispenser.FACING) == EnumFacing.UP) { } else if (blockState.get(DispenserBlock.FACING) == Direction.UP) {
return blockState.withProperty(BlockDispenser.FACING, EnumFacing.DOWN); return blockState.with(DispenserBlock.FACING, Direction.DOWN);
} }
} }

View File

@@ -1,46 +1,62 @@
package nl.requios.effortlessbuilding.buildmodifier; package nl.requios.effortlessbuilding.buildmodifier;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.network.PacketDistributor;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.capability.ModifierCapabilityManager; import nl.requios.effortlessbuilding.capability.ModifierCapabilityManager;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import nl.requios.effortlessbuilding.network.ModifierSettingsMessage; import nl.requios.effortlessbuilding.network.ModifierSettingsMessage;
import nl.requios.effortlessbuilding.network.PacketHandler;
import javax.annotation.Nonnull;
@Mod.EventBusSubscriber @Mod.EventBusSubscriber
public class ModifierSettingsManager { public class ModifierSettingsManager {
//Retrieves the buildsettings of a player through the modifierCapability capability //Retrieves the buildsettings of a player through the modifierCapability capability
//Never returns null //Never returns null
public static ModifierSettings getModifierSettings(EntityPlayer player){ @Nonnull
if (player.hasCapability(ModifierCapabilityManager.modifierCapability, null)) { public static ModifierSettings getModifierSettings(PlayerEntity player){
ModifierCapabilityManager.IModifierCapability capability = player.getCapability( LazyOptional<ModifierCapabilityManager.IModifierCapability> modifierCapability =
ModifierCapabilityManager.modifierCapability, null); player.getCapability(ModifierCapabilityManager.modifierCapability, null);
if (modifierCapability.isPresent()) {
ModifierCapabilityManager.IModifierCapability capability = modifierCapability.orElse(null);
if (capability.getModifierData() == null) { if (capability.getModifierData() == null) {
capability.setModifierData(new ModifierSettings()); capability.setModifierData(new ModifierSettings());
} }
return capability.getModifierData(); return capability.getModifierData();
} }
throw new IllegalArgumentException("Player does not have modifierCapability capability");
//Player does not have modifierCapability capability
//Return dummy settings
return new ModifierSettings();
// throw new IllegalArgumentException("Player does not have modifierCapability capability");
} }
public static void setModifierSettings(EntityPlayer player, ModifierSettings modifierSettings) { public static void setModifierSettings(PlayerEntity player, ModifierSettings modifierSettings) {
if (player == null) { if (player == null) {
EffortlessBuilding.log("Cannot set buildsettings, player is null"); EffortlessBuilding.log("Cannot set buildsettings, player is null");
return; return;
} }
if (player.hasCapability(ModifierCapabilityManager.modifierCapability, null)) {
ModifierCapabilityManager.IModifierCapability capability = player.getCapability( LazyOptional<ModifierCapabilityManager.IModifierCapability> modifierCapability =
ModifierCapabilityManager.modifierCapability, null); player.getCapability(ModifierCapabilityManager.modifierCapability, null);
modifierCapability.ifPresent((capability) -> {
capability.setModifierData(modifierSettings); capability.setModifierData(modifierSettings);
} else { });
if (!modifierCapability.isPresent()) {
EffortlessBuilding.log(player, "Saving buildsettings failed."); EffortlessBuilding.log(player, "Saving buildsettings failed.");
} }
} }
public static String sanitize(ModifierSettings modifierSettings, EntityPlayer player) { public static String sanitize(ModifierSettings modifierSettings, PlayerEntity player) {
int maxReach = ReachHelper.getMaxReach(player); int maxReach = ReachHelper.getMaxReach(player);
String error = ""; String error = "";
@@ -163,33 +179,28 @@ public class ModifierSettingsManager {
//Set mirror radius to max //Set mirror radius to max
int reach = 10; int reach = 10;
switch (reachUpgrade) { switch (reachUpgrade) {
case 0: reach = BuildConfig.reach.maxReachLevel0; break; case 0: reach = BuildConfig.reach.maxReachLevel0.get(); break;
case 1: reach = BuildConfig.reach.maxReachLevel1; break; case 1: reach = BuildConfig.reach.maxReachLevel1.get(); break;
case 2: reach = BuildConfig.reach.maxReachLevel2; break; case 2: reach = BuildConfig.reach.maxReachLevel2.get(); break;
case 3: reach = BuildConfig.reach.maxReachLevel3; break; case 3: reach = BuildConfig.reach.maxReachLevel3.get(); break;
} }
EffortlessBuilding.log("before "+this.mirrorSettings.radius);
if (this.mirrorSettings != null) if (this.mirrorSettings != null)
this.mirrorSettings.radius = reach / 2; this.mirrorSettings.radius = reach / 2;
if (this.radialMirrorSettings != null) if (this.radialMirrorSettings != null)
this.radialMirrorSettings.radius = reach / 2; this.radialMirrorSettings.radius = reach / 2;
EffortlessBuilding.log("after "+this.mirrorSettings.radius);
} }
} }
public static void handleNewPlayer(EntityPlayer player){ public static void handleNewPlayer(PlayerEntity player){
if (getModifierSettings(player) == null) { //Makes sure player has modifier settings (if it doesnt it will create it)
setModifierSettings(player, new ModifierSettings()); getModifierSettings(player);
}
//Only on server //Only on server
if (!player.world.isRemote) { if (!player.world.isRemote) {
//Send to client //Send to client
ModifierSettingsMessage msg = new ModifierSettingsMessage(getModifierSettings(player)); ModifierSettingsMessage msg = new ModifierSettingsMessage(getModifierSettings(player));
EffortlessBuilding.packetHandler.sendTo(msg, (EntityPlayerMP) player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), msg);
} }
} }
} }

View File

@@ -1,10 +1,10 @@
package nl.requios.effortlessbuilding.buildmodifier; package nl.requios.effortlessbuilding.buildmodifier;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.EnumHand; import net.minecraft.util.Hand;
import net.minecraft.util.Mirror; import net.minecraft.util.Mirror;
import net.minecraft.util.Rotation; import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -44,7 +44,7 @@ public class RadialMirror {
} }
} }
public static List<BlockPos> findCoordinates(EntityPlayer player, BlockPos startPos) { public static List<BlockPos> findCoordinates(PlayerEntity player, BlockPos startPos) {
List<BlockPos> coordinates = new ArrayList<>(); List<BlockPos> coordinates = new ArrayList<>();
//find radial mirror settings for the player //find radial mirror settings for the player
@@ -77,8 +77,8 @@ public class RadialMirror {
return coordinates; return coordinates;
} }
public static List<IBlockState> findBlockStates(EntityPlayer player, BlockPos startPos, IBlockState blockState, ItemStack itemStack, List<ItemStack> itemStacks) { public static List<BlockState> findBlockStates(PlayerEntity player, BlockPos startPos, BlockState blockState, ItemStack itemStack, List<ItemStack> itemStacks) {
List<IBlockState> blockStates = new ArrayList<>(); List<BlockState> blockStates = new ArrayList<>();
List<BlockPos> coordinates = new ArrayList<>(); //to keep track of duplicates List<BlockPos> coordinates = new ArrayList<>(); //to keep track of duplicates
//find radial mirror settings for the player that placed the block //find radial mirror settings for the player that placed the block
@@ -105,7 +105,7 @@ public class RadialMirror {
bagInventory = ItemRandomizerBag.getBagInventory(itemStack); bagInventory = ItemRandomizerBag.getBagInventory(itemStack);
} }
IBlockState newBlockState; BlockState newBlockState;
for (int i = 1; i < r.slices; i++) { for (int i = 1; i < r.slices; i++) {
newBlockState = blockState; newBlockState = blockState;
double curAngle = sliceAngle * i; double curAngle = sliceAngle * i;
@@ -124,7 +124,7 @@ public class RadialMirror {
if (bagInventory != null) { if (bagInventory != null) {
itemStack = ItemRandomizerBag.pickRandomStack(bagInventory); itemStack = ItemRandomizerBag.pickRandomStack(bagInventory);
newBlockState = BuildModifiers newBlockState = BuildModifiers
.getBlockStateFromItem(itemStack, player, startPos, EnumFacing.UP, new Vec3d(0, 0, 0), EnumHand.MAIN_HAND); .getBlockStateFromItem(itemStack, player, startPos, Direction.UP, new Vec3d(0, 0, 0), Hand.MAIN_HAND);
newBlockState = rotateOriginalBlockState(startAngleToCenter, newBlockState); newBlockState = rotateOriginalBlockState(startAngleToCenter, newBlockState);
} }
@@ -139,43 +139,43 @@ public class RadialMirror {
return blockStates; return blockStates;
} }
private static IBlockState rotateOriginalBlockState(double startAngleToCenter, IBlockState blockState) { private static BlockState rotateOriginalBlockState(double startAngleToCenter, BlockState blockState) {
IBlockState newBlockState = blockState; BlockState newBlockState = blockState;
if (startAngleToCenter < -0.751 * Math.PI || startAngleToCenter > 0.749 * Math.PI) { if (startAngleToCenter < -0.751 * Math.PI || startAngleToCenter > 0.749 * Math.PI) {
newBlockState = blockState.withRotation(Rotation.CLOCKWISE_180); newBlockState = blockState.rotate(Rotation.CLOCKWISE_180);
} else if (startAngleToCenter < -0.251 * Math.PI) { } else if (startAngleToCenter < -0.251 * Math.PI) {
newBlockState = blockState.withRotation(Rotation.COUNTERCLOCKWISE_90); newBlockState = blockState.rotate(Rotation.COUNTERCLOCKWISE_90);
} else if (startAngleToCenter > 0.249 * Math.PI) { } else if (startAngleToCenter > 0.249 * Math.PI) {
newBlockState = blockState.withRotation(Rotation.CLOCKWISE_90); newBlockState = blockState.rotate(Rotation.CLOCKWISE_90);
} }
return newBlockState; return newBlockState;
} }
private static IBlockState rotateBlockState(Vec3d relVec, IBlockState blockState, boolean alternate) { private static BlockState rotateBlockState(Vec3d relVec, BlockState blockState, boolean alternate) {
IBlockState newBlockState; BlockState newBlockState;
double angleToCenter = MathHelper.atan2(relVec.x, relVec.z); //between -PI and PI double angleToCenter = MathHelper.atan2(relVec.x, relVec.z); //between -PI and PI
if (angleToCenter < -0.751 * Math.PI || angleToCenter > 0.749 * Math.PI) { if (angleToCenter < -0.751 * Math.PI || angleToCenter > 0.749 * Math.PI) {
newBlockState = blockState.withRotation(Rotation.CLOCKWISE_180); newBlockState = blockState.rotate(Rotation.CLOCKWISE_180);
if (alternate) { if (alternate) {
newBlockState = newBlockState.withMirror(Mirror.FRONT_BACK); newBlockState = newBlockState.mirror(Mirror.FRONT_BACK);
} }
} else if (angleToCenter < -0.251 * Math.PI) { } else if (angleToCenter < -0.251 * Math.PI) {
newBlockState = blockState.withRotation(Rotation.CLOCKWISE_90); newBlockState = blockState.rotate(Rotation.CLOCKWISE_90);
if (alternate) { if (alternate) {
newBlockState = newBlockState.withMirror(Mirror.LEFT_RIGHT); newBlockState = newBlockState.mirror(Mirror.LEFT_RIGHT);
} }
} else if (angleToCenter > 0.249 * Math.PI) { } else if (angleToCenter > 0.249 * Math.PI) {
newBlockState = blockState.withRotation(Rotation.COUNTERCLOCKWISE_90); newBlockState = blockState.rotate(Rotation.COUNTERCLOCKWISE_90);
if (alternate) { if (alternate) {
newBlockState = newBlockState.withMirror(Mirror.LEFT_RIGHT); newBlockState = newBlockState.mirror(Mirror.LEFT_RIGHT);
} }
} else { } else {
newBlockState = blockState; newBlockState = blockState;
if (alternate) { if (alternate) {
newBlockState = newBlockState.withMirror(Mirror.FRONT_BACK); newBlockState = newBlockState.mirror(Mirror.FRONT_BACK);
} }
} }

View File

@@ -1,15 +1,18 @@
package nl.requios.effortlessbuilding.buildmodifier; package nl.requios.effortlessbuilding.buildmodifier;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.block.Blocks;
import net.minecraft.init.Blocks; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootParameterSet;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.helper.FixedStack; import nl.requios.effortlessbuilding.helper.FixedStack;
@@ -29,7 +32,7 @@ public class UndoRedo {
private static Map<UUID, FixedStack<BlockSet>> redoStacksServer = new HashMap<>(); private static Map<UUID, FixedStack<BlockSet>> redoStacksServer = new HashMap<>();
//add to undo stack //add to undo stack
public static void addUndo(EntityPlayer player, BlockSet blockSet) { public static void addUndo(PlayerEntity player, BlockSet blockSet) {
Map<UUID, FixedStack<BlockSet>> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; Map<UUID, FixedStack<BlockSet>> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer;
//Assert coordinates is as long as previous and new blockstate lists //Assert coordinates is as long as previous and new blockstate lists
@@ -50,27 +53,26 @@ public class UndoRedo {
//If no stack exists, make one //If no stack exists, make one
if (!undoStacks.containsKey(player.getUniqueID())) { if (!undoStacks.containsKey(player.getUniqueID())) {
undoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize])); undoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize.get()]));
} }
undoStacks.get(player.getUniqueID()).push(blockSet); undoStacks.get(player.getUniqueID()).push(blockSet);
} }
private static void addRedo(EntityPlayer player, BlockSet blockSet) { private static void addRedo(PlayerEntity player, BlockSet blockSet) {
Map<UUID, FixedStack<BlockSet>> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; Map<UUID, FixedStack<BlockSet>> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer;
//(No asserts necessary, it's private) //(No asserts necessary, it's private)
//If no stack exists, make one //If no stack exists, make one
if (!redoStacks.containsKey(player.getUniqueID())) { if (!redoStacks.containsKey(player.getUniqueID())) {
redoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize])); redoStacks.put(player.getUniqueID(), new FixedStack<>(new BlockSet[BuildConfig.survivalBalancers.undoStackSize.get()]));
} }
redoStacks.get(player.getUniqueID()).push(blockSet); redoStacks.get(player.getUniqueID()).push(blockSet);
} }
public static boolean undo(EntityPlayer player) { public static boolean undo(PlayerEntity player) {
Map<UUID, FixedStack<BlockSet>> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; Map<UUID, FixedStack<BlockSet>> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer;
if (!undoStacks.containsKey(player.getUniqueID())) return false; if (!undoStacks.containsKey(player.getUniqueID())) return false;
@@ -81,8 +83,8 @@ public class UndoRedo {
BlockSet blockSet = undoStack.pop(); BlockSet blockSet = undoStack.pop();
List<BlockPos> coordinates = blockSet.getCoordinates(); List<BlockPos> coordinates = blockSet.getCoordinates();
List<IBlockState> previousBlockStates = blockSet.getPreviousBlockStates(); List<BlockState> previousBlockStates = blockSet.getPreviousBlockStates();
List<IBlockState> newBlockStates = blockSet.getNewBlockStates(); List<BlockState> newBlockStates = blockSet.getNewBlockStates();
Vec3d hitVec = blockSet.getHitVec(); Vec3d hitVec = blockSet.getHitVec();
//Find up to date itemstacks in player inventory //Find up to date itemstacks in player inventory
@@ -99,25 +101,27 @@ public class UndoRedo {
if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue; if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue;
//get blockstate from itemstack //get blockstate from itemstack
IBlockState previousBlockState = Blocks.AIR.getDefaultState(); BlockState previousBlockState = Blocks.AIR.getDefaultState();
if (itemStack.getItem() instanceof ItemBlock) { if (itemStack.getItem() instanceof BlockItem) {
previousBlockState = previousBlockStates.get(i);//((ItemBlock) itemStack.getItem()).getBlock().getDefaultState(); previousBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState();
} }
if (player.world.isBlockLoaded(coordinate, true)) { if (player.world.isBlockPresent(coordinate)) {
//check itemstack empty //check itemstack empty
if (itemStack.isEmpty()) { if (itemStack.isEmpty()) {
itemStack = findItemStackInInventory(player, previousBlockStates.get(i)); itemStack = findItemStackInInventory(player, previousBlockStates.get(i));
//get blockstate from new itemstack //get blockstate from new itemstack
if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemBlock) { if (!itemStack.isEmpty() && itemStack.getItem() instanceof BlockItem) {
previousBlockState = previousBlockStates.get(i);//((ItemBlock) itemStack.getItem()).getBlock().getDefaultState(); previousBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState();
} else { } else {
if (previousBlockStates.get(i).getBlock() != Blocks.AIR)
EffortlessBuilding.logTranslate(player, "", previousBlockStates.get(i).getBlock().getTranslationKey(), " not found in inventory", true);
previousBlockState = Blocks.AIR.getDefaultState(); previousBlockState = Blocks.AIR.getDefaultState();
} }
} }
if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true); if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true);
//if previousBlockState is air, placeBlock will set it to air //if previousBlockState is air, placeBlock will set it to air
SurvivalHelper.placeBlock(player.world, player, coordinate, previousBlockState, itemStack, EnumFacing.UP, hitVec, true, false, false); SurvivalHelper.placeBlock(player.world, player, coordinate, previousBlockState, itemStack, Direction.UP, hitVec, true, false, false);
} }
} }
} }
@@ -128,7 +132,7 @@ public class UndoRedo {
return true; return true;
} }
public static boolean redo(EntityPlayer player) { public static boolean redo(PlayerEntity player) {
Map<UUID, FixedStack<BlockSet>> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; Map<UUID, FixedStack<BlockSet>> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer;
if (!redoStacks.containsKey(player.getUniqueID())) return false; if (!redoStacks.containsKey(player.getUniqueID())) return false;
@@ -139,8 +143,8 @@ public class UndoRedo {
BlockSet blockSet = redoStack.pop(); BlockSet blockSet = redoStack.pop();
List<BlockPos> coordinates = blockSet.getCoordinates(); List<BlockPos> coordinates = blockSet.getCoordinates();
List<IBlockState> previousBlockStates = blockSet.getPreviousBlockStates(); List<BlockState> previousBlockStates = blockSet.getPreviousBlockStates();
List<IBlockState> newBlockStates = blockSet.getNewBlockStates(); List<BlockState> newBlockStates = blockSet.getNewBlockStates();
Vec3d hitVec = blockSet.getHitVec(); Vec3d hitVec = blockSet.getHitVec();
//Find up to date itemstacks in player inventory //Find up to date itemstacks in player inventory
@@ -157,24 +161,26 @@ public class UndoRedo {
if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue; if (previousBlockStates.get(i).equals(newBlockStates.get(i))) continue;
//get blockstate from itemstack //get blockstate from itemstack
IBlockState newBlockState = Blocks.AIR.getDefaultState(); BlockState newBlockState = Blocks.AIR.getDefaultState();
if (itemStack.getItem() instanceof ItemBlock) { if (itemStack.getItem() instanceof BlockItem) {
newBlockState = newBlockStates.get(i);//((ItemBlock) itemStack.getItem()).getBlock().getDefaultState(); newBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState();
} }
if (player.world.isBlockLoaded(coordinate, true)) { if (player.world.isBlockPresent(coordinate)) {
//check itemstack empty //check itemstack empty
if (itemStack.isEmpty()) { if (itemStack.isEmpty()) {
itemStack = findItemStackInInventory(player, newBlockStates.get(i)); itemStack = findItemStackInInventory(player, newBlockStates.get(i));
//get blockstate from new itemstack //get blockstate from new itemstack
if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemBlock) { if (!itemStack.isEmpty() && itemStack.getItem() instanceof BlockItem) {
newBlockState = newBlockStates.get(i);//((ItemBlock) itemStack.getItem()).getBlock().getDefaultState(); newBlockState = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState();
} else { } else {
if (newBlockStates.get(i).getBlock() != Blocks.AIR)
EffortlessBuilding.logTranslate(player, "", newBlockStates.get(i).getBlock().getTranslationKey(), " not found in inventory", true);
newBlockState = Blocks.AIR.getDefaultState(); newBlockState = Blocks.AIR.getDefaultState();
} }
} }
if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true); if (itemStack.isEmpty()) SurvivalHelper.breakBlock(player.world, player, coordinate, true);
SurvivalHelper.placeBlock(player.world, player, coordinate, newBlockState, itemStack, EnumFacing.UP, hitVec, true, false, false); SurvivalHelper.placeBlock(player.world, player, coordinate, newBlockState, itemStack, Direction.UP, hitVec, true, false, false);
} }
} }
} }
@@ -185,7 +191,7 @@ public class UndoRedo {
return true; return true;
} }
public static void clear(EntityPlayer player) { public static void clear(PlayerEntity player) {
Map<UUID, FixedStack<BlockSet>> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer; Map<UUID, FixedStack<BlockSet>> undoStacks = player.world.isRemote ? undoStacksClient : undoStacksServer;
Map<UUID, FixedStack<BlockSet>> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer; Map<UUID, FixedStack<BlockSet>> redoStacks = player.world.isRemote ? redoStacksClient : redoStacksServer;
if (undoStacks.containsKey(player.getUniqueID())) { if (undoStacks.containsKey(player.getUniqueID())) {
@@ -196,15 +202,15 @@ public class UndoRedo {
} }
} }
private static List<ItemStack> findItemStacksInInventory(EntityPlayer player, List<IBlockState> blockStates) { private static List<ItemStack> findItemStacksInInventory(PlayerEntity player, List<BlockState> blockStates) {
List<ItemStack> itemStacks = new ArrayList<>(blockStates.size()); List<ItemStack> itemStacks = new ArrayList<>(blockStates.size());
for (IBlockState blockState : blockStates) { for (BlockState blockState : blockStates) {
itemStacks.add(findItemStackInInventory(player, blockState)); itemStacks.add(findItemStackInInventory(player, blockState));
} }
return itemStacks; return itemStacks;
} }
private static ItemStack findItemStackInInventory(EntityPlayer player, IBlockState blockState) { private static ItemStack findItemStackInInventory(PlayerEntity player, BlockState blockState) {
ItemStack itemStack = ItemStack.EMPTY; ItemStack itemStack = ItemStack.EMPTY;
if (blockState == null) return itemStack; if (blockState == null) return itemStack;
@@ -213,14 +219,21 @@ public class UndoRedo {
// then change line 103 back (get state from item) // then change line 103 back (get state from item)
itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock()); itemStack = InventoryHelper.findItemStackInInventory(player, blockState.getBlock());
//then anything it drops //then anything it drops
if (itemStack.isEmpty()) { if (itemStack.isEmpty()) {
Item itemDropped = blockState.getBlock().getItemDropped(blockState, player.world.rand, 10); //Cannot check drops on clientside because loot tables are server only
if (itemDropped instanceof ItemBlock) { if (!player.world.isRemote)
Block block = ((ItemBlock) itemDropped).getBlock(); {
List<ItemStack> itemsDropped = Block.getDrops(blockState, (ServerWorld) player.world, BlockPos.ZERO, null);
for (ItemStack itemStackDropped : itemsDropped) {
if (itemStackDropped.getItem() instanceof BlockItem) {
Block block = ((BlockItem) itemStackDropped.getItem()).getBlock();
itemStack = InventoryHelper.findItemStackInInventory(player, block); itemStack = InventoryHelper.findItemStackInInventory(player, block);
} }
} }
}
}
//then air //then air
//(already empty) //(already empty)

View File

@@ -1,9 +1,10 @@
package nl.requios.effortlessbuilding.capability; package nl.requios.effortlessbuilding.capability;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler; import net.minecraftforge.items.ItemStackHandler;
@@ -12,31 +13,22 @@ import nl.requios.effortlessbuilding.item.ItemRandomizerBag;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class ItemHandlerCapabilityProvider implements ICapabilitySerializable<NBTTagCompound> { public class ItemHandlerCapabilityProvider implements ICapabilitySerializable<CompoundNBT> {
IItemHandler itemHandler = new ItemStackHandler(ItemRandomizerBag.INV_SIZE); IItemHandler itemHandler = new ItemStackHandler(ItemRandomizerBag.INV_SIZE);
@Nonnull
@Override @Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) { public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.orEmpty(cap, LazyOptional.of(() -> itemHandler));
return true;
return false;
}
@Nullable
@Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
return (T) itemHandler;
return null;
} }
@Override @Override
public NBTTagCompound serializeNBT() { public CompoundNBT serializeNBT() {
return ((ItemStackHandler) itemHandler).serializeNBT(); return ((ItemStackHandler) itemHandler).serializeNBT();
} }
@Override @Override
public void deserializeNBT(NBTTagCompound nbt) { public void deserializeNBT(CompoundNBT nbt) {
((ItemStackHandler) itemHandler).deserializeNBT(nbt); ((ItemStackHandler) itemHandler).deserializeNBT(nbt);
} }
} }

View File

@@ -1,20 +1,21 @@
package nl.requios.effortlessbuilding.capability; package nl.requios.effortlessbuilding.capability;
import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.INBT;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static nl.requios.effortlessbuilding.buildmode.ModeSettingsManager.*; import static nl.requios.effortlessbuilding.buildmode.ModeSettingsManager.ModeSettings;
@Mod.EventBusSubscriber @Mod.EventBusSubscriber
public class ModeCapabilityManager { public class ModeCapabilityManager {
@@ -44,12 +45,12 @@ public class ModeCapabilityManager {
public static class Storage implements Capability.IStorage<IModeCapability> { public static class Storage implements Capability.IStorage<IModeCapability> {
@Override @Override
public NBTBase writeNBT(Capability<IModeCapability> capability, IModeCapability instance, EnumFacing side) { public INBT writeNBT(Capability<IModeCapability> capability, IModeCapability instance, Direction side) {
NBTTagCompound compound = new NBTTagCompound(); CompoundNBT compound = new CompoundNBT();
ModeSettings modeSettings = instance.getModeData(); ModeSettings modeSettings = instance.getModeData();
if (modeSettings == null) modeSettings = new ModeSettings(); if (modeSettings == null) modeSettings = new ModeSettings();
//compound.setInteger("buildMode", modeSettings.getBuildMode().ordinal()); //compound.putInteger("buildMode", modeSettings.getBuildMode().ordinal());
//TODO add mode settings //TODO add mode settings
@@ -57,8 +58,8 @@ public class ModeCapabilityManager {
} }
@Override @Override
public void readNBT(Capability<IModeCapability> capability, IModeCapability instance, EnumFacing side, NBTBase nbt) { public void readNBT(Capability<IModeCapability> capability, IModeCapability instance, Direction side, INBT nbt) {
NBTTagCompound compound = (NBTTagCompound) nbt; CompoundNBT compound = (CompoundNBT) nbt;
//BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.values()[compound.getInteger("buildMode")]; //BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.values()[compound.getInteger("buildMode")];
@@ -69,36 +70,34 @@ public class ModeCapabilityManager {
} }
} }
public static class Provider implements ICapabilitySerializable<NBTBase> { public static class Provider implements ICapabilitySerializable<INBT> {
IModeCapability inst = modeCapability.getDefaultInstance(); IModeCapability inst = modeCapability.getDefaultInstance();
@Nonnull
@Override @Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) { public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
return capability == modeCapability; return modeCapability.orEmpty(cap, LazyOptional.of(() -> inst));
} }
@Override @Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) { public INBT serializeNBT() {
if (capability == modeCapability) return modeCapability.<T>cast(inst);
return null;
}
@Override
public NBTBase serializeNBT() {
return modeCapability.getStorage().writeNBT(modeCapability, inst, null); return modeCapability.getStorage().writeNBT(modeCapability, inst, null);
} }
@Override @Override
public void deserializeNBT(NBTBase nbt) { public void deserializeNBT(INBT nbt) {
modeCapability.getStorage().readNBT(modeCapability, inst, null, nbt); modeCapability.getStorage().readNBT(modeCapability, inst, null, nbt);
} }
} }
// Allows for the capability to persist after death. // Allows for the capability to persist after death.
@SubscribeEvent @SubscribeEvent
public static void clonePlayer(PlayerEvent.Clone event) { public static void clonePlayer(PlayerEvent.Clone event) {
IModeCapability original = event.getOriginal().getCapability(modeCapability, null); LazyOptional<IModeCapability> original = event.getOriginal().getCapability(modeCapability, null);
IModeCapability clone = event.getEntity().getCapability(modeCapability, null); LazyOptional<IModeCapability> clone = event.getEntity().getCapability(modeCapability, null);
clone.setModeData(original.getModeData()); clone.ifPresent(cloneModeCapability ->
original.ifPresent(originalModeCapability ->
cloneModeCapability.setModeData(originalModeCapability.getModeData())));
} }
} }

View File

@@ -1,16 +1,17 @@
package nl.requios.effortlessbuilding.capability; package nl.requios.effortlessbuilding.capability;
import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.INBT;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import nl.requios.effortlessbuilding.buildmodifier.Array; import nl.requios.effortlessbuilding.buildmodifier.Array;
import nl.requios.effortlessbuilding.buildmodifier.Mirror; import nl.requios.effortlessbuilding.buildmodifier.Mirror;
import nl.requios.effortlessbuilding.buildmodifier.RadialMirror; import nl.requios.effortlessbuilding.buildmodifier.RadialMirror;
@@ -48,57 +49,57 @@ public class ModifierCapabilityManager {
public static class Storage implements Capability.IStorage<IModifierCapability> { public static class Storage implements Capability.IStorage<IModifierCapability> {
@Override @Override
public NBTBase writeNBT(Capability<IModifierCapability> capability, IModifierCapability instance, EnumFacing side) { public INBT writeNBT(Capability<IModifierCapability> capability, IModifierCapability instance, Direction side) {
NBTTagCompound compound = new NBTTagCompound(); CompoundNBT compound = new CompoundNBT();
ModifierSettings modifierSettings = instance.getModifierData(); ModifierSettings modifierSettings = instance.getModifierData();
if (modifierSettings == null) modifierSettings = new ModifierSettings(); if (modifierSettings == null) modifierSettings = new ModifierSettings();
//MIRROR //MIRROR
Mirror.MirrorSettings m = modifierSettings.getMirrorSettings(); Mirror.MirrorSettings m = modifierSettings.getMirrorSettings();
if (m == null) m = new Mirror.MirrorSettings(); if (m == null) m = new Mirror.MirrorSettings();
compound.setBoolean("mirrorEnabled", m.enabled); compound.putBoolean("mirrorEnabled", m.enabled);
compound.setDouble("mirrorPosX", m.position.x); compound.putDouble("mirrorPosX", m.position.x);
compound.setDouble("mirrorPosY", m.position.y); compound.putDouble("mirrorPosY", m.position.y);
compound.setDouble("mirrorPosZ", m.position.z); compound.putDouble("mirrorPosZ", m.position.z);
compound.setBoolean("mirrorX", m.mirrorX); compound.putBoolean("mirrorX", m.mirrorX);
compound.setBoolean("mirrorY", m.mirrorY); compound.putBoolean("mirrorY", m.mirrorY);
compound.setBoolean("mirrorZ", m.mirrorZ); compound.putBoolean("mirrorZ", m.mirrorZ);
compound.setInteger("mirrorRadius", m.radius); compound.putInt("mirrorRadius", m.radius);
compound.setBoolean("mirrorDrawLines", m.drawLines); compound.putBoolean("mirrorDrawLines", m.drawLines);
compound.setBoolean("mirrorDrawPlanes", m.drawPlanes); compound.putBoolean("mirrorDrawPlanes", m.drawPlanes);
//ARRAY //ARRAY
Array.ArraySettings a = modifierSettings.getArraySettings(); Array.ArraySettings a = modifierSettings.getArraySettings();
if (a == null) a = new Array.ArraySettings(); if (a == null) a = new Array.ArraySettings();
compound.setBoolean("arrayEnabled", a.enabled); compound.putBoolean("arrayEnabled", a.enabled);
compound.setInteger("arrayOffsetX", a.offset.getX()); compound.putInt("arrayOffsetX", a.offset.getX());
compound.setInteger("arrayOffsetY", a.offset.getY()); compound.putInt("arrayOffsetY", a.offset.getY());
compound.setInteger("arrayOffsetZ", a.offset.getZ()); compound.putInt("arrayOffsetZ", a.offset.getZ());
compound.setInteger("arrayCount", a.count); compound.putInt("arrayCount", a.count);
compound.setInteger("reachUpgrade", modifierSettings.getReachUpgrade()); compound.putInt("reachUpgrade", modifierSettings.getReachUpgrade());
//compound.setBoolean("quickReplace", buildSettings.doQuickReplace()); dont save quickreplace //compound.putBoolean("quickReplace", buildSettings.doQuickReplace()); dont save quickreplace
//RADIAL MIRROR //RADIAL MIRROR
RadialMirror.RadialMirrorSettings r = modifierSettings.getRadialMirrorSettings(); RadialMirror.RadialMirrorSettings r = modifierSettings.getRadialMirrorSettings();
if (r == null) r = new RadialMirror.RadialMirrorSettings(); if (r == null) r = new RadialMirror.RadialMirrorSettings();
compound.setBoolean("radialMirrorEnabled", r.enabled); compound.putBoolean("radialMirrorEnabled", r.enabled);
compound.setDouble("radialMirrorPosX", r.position.x); compound.putDouble("radialMirrorPosX", r.position.x);
compound.setDouble("radialMirrorPosY", r.position.y); compound.putDouble("radialMirrorPosY", r.position.y);
compound.setDouble("radialMirrorPosZ", r.position.z); compound.putDouble("radialMirrorPosZ", r.position.z);
compound.setInteger("radialMirrorSlices", r.slices); compound.putInt("radialMirrorSlices", r.slices);
compound.setBoolean("radialMirrorAlternate", r.alternate); compound.putBoolean("radialMirrorAlternate", r.alternate);
compound.setInteger("radialMirrorRadius", r.radius); compound.putInt("radialMirrorRadius", r.radius);
compound.setBoolean("radialMirrorDrawLines", r.drawLines); compound.putBoolean("radialMirrorDrawLines", r.drawLines);
compound.setBoolean("radialMirrorDrawPlanes", r.drawPlanes); compound.putBoolean("radialMirrorDrawPlanes", r.drawPlanes);
return compound; return compound;
} }
@Override @Override
public void readNBT(Capability<IModifierCapability> capability, IModifierCapability instance, EnumFacing side, NBTBase nbt) { public void readNBT(Capability<IModifierCapability> capability, IModifierCapability instance, Direction side, INBT nbt) {
NBTTagCompound compound = (NBTTagCompound) nbt; CompoundNBT compound = (CompoundNBT) nbt;
//MIRROR //MIRROR
boolean mirrorEnabled = compound.getBoolean("mirrorEnabled"); boolean mirrorEnabled = compound.getBoolean("mirrorEnabled");
@@ -109,7 +110,7 @@ public class ModifierCapabilityManager {
boolean mirrorX = compound.getBoolean("mirrorX"); boolean mirrorX = compound.getBoolean("mirrorX");
boolean mirrorY = compound.getBoolean("mirrorY"); boolean mirrorY = compound.getBoolean("mirrorY");
boolean mirrorZ = compound.getBoolean("mirrorZ"); boolean mirrorZ = compound.getBoolean("mirrorZ");
int mirrorRadius = compound.getInteger("mirrorRadius"); int mirrorRadius = compound.getInt("mirrorRadius");
boolean mirrorDrawLines = compound.getBoolean("mirrorDrawLines"); boolean mirrorDrawLines = compound.getBoolean("mirrorDrawLines");
boolean mirrorDrawPlanes = compound.getBoolean("mirrorDrawPlanes"); boolean mirrorDrawPlanes = compound.getBoolean("mirrorDrawPlanes");
Mirror.MirrorSettings mirrorSettings = new Mirror.MirrorSettings(mirrorEnabled, mirrorPosition, mirrorX, mirrorY, mirrorZ, mirrorRadius, mirrorDrawLines, mirrorDrawPlanes); Mirror.MirrorSettings mirrorSettings = new Mirror.MirrorSettings(mirrorEnabled, mirrorPosition, mirrorX, mirrorY, mirrorZ, mirrorRadius, mirrorDrawLines, mirrorDrawPlanes);
@@ -117,13 +118,13 @@ public class ModifierCapabilityManager {
//ARRAY //ARRAY
boolean arrayEnabled = compound.getBoolean("arrayEnabled"); boolean arrayEnabled = compound.getBoolean("arrayEnabled");
BlockPos arrayOffset = new BlockPos( BlockPos arrayOffset = new BlockPos(
compound.getInteger("arrayOffsetX"), compound.getInt("arrayOffsetX"),
compound.getInteger("arrayOffsetY"), compound.getInt("arrayOffsetY"),
compound.getInteger("arrayOffsetZ")); compound.getInt("arrayOffsetZ"));
int arrayCount = compound.getInteger("arrayCount"); int arrayCount = compound.getInt("arrayCount");
Array.ArraySettings arraySettings = new Array.ArraySettings(arrayEnabled, arrayOffset, arrayCount); Array.ArraySettings arraySettings = new Array.ArraySettings(arrayEnabled, arrayOffset, arrayCount);
int reachUpgrade = compound.getInteger("reachUpgrade"); int reachUpgrade = compound.getInt("reachUpgrade");
//boolean quickReplace = compound.getBoolean("quickReplace"); //dont load quickreplace //boolean quickReplace = compound.getBoolean("quickReplace"); //dont load quickreplace
@@ -133,9 +134,9 @@ public class ModifierCapabilityManager {
compound.getDouble("radialMirrorPosX"), compound.getDouble("radialMirrorPosX"),
compound.getDouble("radialMirrorPosY"), compound.getDouble("radialMirrorPosY"),
compound.getDouble("radialMirrorPosZ")); compound.getDouble("radialMirrorPosZ"));
int radialMirrorSlices = compound.getInteger("radialMirrorSlices"); int radialMirrorSlices = compound.getInt("radialMirrorSlices");
boolean radialMirrorAlternate = compound.getBoolean("radialMirrorAlternate"); boolean radialMirrorAlternate = compound.getBoolean("radialMirrorAlternate");
int radialMirrorRadius = compound.getInteger("radialMirrorRadius"); int radialMirrorRadius = compound.getInt("radialMirrorRadius");
boolean radialMirrorDrawLines = compound.getBoolean("radialMirrorDrawLines"); boolean radialMirrorDrawLines = compound.getBoolean("radialMirrorDrawLines");
boolean radialMirrorDrawPlanes = compound.getBoolean("radialMirrorDrawPlanes"); boolean radialMirrorDrawPlanes = compound.getBoolean("radialMirrorDrawPlanes");
RadialMirror.RadialMirrorSettings radialMirrorSettings = new RadialMirror.RadialMirrorSettings(radialMirrorEnabled, radialMirrorPosition, RadialMirror.RadialMirrorSettings radialMirrorSettings = new RadialMirror.RadialMirrorSettings(radialMirrorEnabled, radialMirrorPosition,
@@ -146,36 +147,36 @@ public class ModifierCapabilityManager {
} }
} }
public static class Provider implements ICapabilitySerializable<NBTBase> { public static class Provider implements ICapabilitySerializable<INBT> {
IModifierCapability inst = modifierCapability.getDefaultInstance(); IModifierCapability inst = modifierCapability.getDefaultInstance();
@Nonnull
@Override @Override
public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) { public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
return capability == modifierCapability; return modifierCapability.orEmpty(cap, LazyOptional.of(() -> inst));
} }
@Override @Override
public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) { public INBT serializeNBT() {
if (capability == modifierCapability) return modifierCapability.<T>cast(inst);
return null;
}
@Override
public NBTBase serializeNBT() {
return modifierCapability.getStorage().writeNBT(modifierCapability, inst, null); return modifierCapability.getStorage().writeNBT(modifierCapability, inst, null);
} }
@Override @Override
public void deserializeNBT(NBTBase nbt) { public void deserializeNBT(INBT nbt) {
modifierCapability.getStorage().readNBT(modifierCapability, inst, null, nbt); modifierCapability.getStorage().readNBT(modifierCapability, inst, null, nbt);
} }
} }
// Allows for the capability to persist after death. // Allows for the capability to persist after death.
@SubscribeEvent @SubscribeEvent
public static void clonePlayer(PlayerEvent.Clone event) { public static void clonePlayer(PlayerEvent.Clone event) {
IModifierCapability original = event.getOriginal().getCapability(modifierCapability, null); LazyOptional<IModifierCapability> original = event.getOriginal().getCapability(modifierCapability, null);
IModifierCapability clone = event.getEntity().getCapability(modifierCapability, null); LazyOptional<IModifierCapability> clone = event.getEntity().getCapability(modifierCapability, null);
clone.setModifierData(original.getModifierData()); clone.ifPresent(cloneModifierCapability ->
original.ifPresent(originalModifierCapability ->
cloneModifierCapability.setModifierData(originalModifierCapability.getModifierData())));
} }
} }

View File

@@ -1,46 +1,43 @@
package nl.requios.effortlessbuilding.command; package nl.requios.effortlessbuilding.command;
import net.minecraft.command.CommandBase; import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.command.CommandException; import com.mojang.brigadier.arguments.IntegerArgumentType;
import net.minecraft.command.ICommandSender; import net.minecraft.command.CommandSource;
import net.minecraft.command.WrongUsageException; import net.minecraft.command.Commands;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraftforge.fml.network.PacketDistributor;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.network.ModifierSettingsMessage; import nl.requios.effortlessbuilding.network.ModifierSettingsMessage;
import nl.requios.effortlessbuilding.network.PacketHandler;
public class CommandReach extends CommandBase { public class CommandReach {
@Override
public String getName() { public static void register(CommandDispatcher<CommandSource> dispatcher) {
return "reach"; dispatcher.register(Commands.literal("reach").then(Commands.literal("set").then(Commands.argument("level", IntegerArgumentType.integer(0, 3)).executes((context) -> {
return setReachLevel(context.getSource().asPlayer(), IntegerArgumentType.getInteger(context, "level"));
}))).then(Commands.literal("get").executes((context -> {
return getReachLevel(context.getSource().asPlayer());
}))));
} }
@Override private static int setReachLevel(ServerPlayerEntity player, int level){
public String getUsage(ICommandSender sender) {
return "commands.reach.usage";
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
EntityPlayerMP player = (EntityPlayerMP) sender;
if (args.length != 1) {
int reachUpgrade = ModifierSettingsManager.getModifierSettings(player).getReachUpgrade();
EffortlessBuilding.log(player, "Current reach: level "+reachUpgrade);
throw new WrongUsageException("commands.reach.usage");
}
if (sender instanceof EntityPlayerMP) {
//Set reach level to args[0]
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
modifierSettings.setReachUpgrade(Integer.valueOf(args[0])); modifierSettings.setReachUpgrade(level);
ModifierSettingsManager.setModifierSettings(player, modifierSettings); ModifierSettingsManager.setModifierSettings(player, modifierSettings);
//Send to client //Send to client
EffortlessBuilding.packetHandler.sendTo(new ModifierSettingsMessage(modifierSettings), player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new ModifierSettingsMessage(modifierSettings));
sender.sendMessage(new TextComponentString("Reach level of " + sender.getName() + " set to " + modifierSettings player.sendMessage(new StringTextComponent("Reach level of " + player.getName().getString() + " set to " + modifierSettings.getReachUpgrade()));
.getReachUpgrade()));
} return 1;
}
private static int getReachLevel(ServerPlayerEntity player){
int reachUpgrade = ModifierSettingsManager.getModifierSettings(player).getReachUpgrade();
EffortlessBuilding.log(player, "Current reach: level "+reachUpgrade);
return 1;
} }
} }

View File

@@ -1,13 +0,0 @@
package nl.requios.effortlessbuilding.compatibility;
import mod.chiselsandbits.core.ClientSide;
import mod.chiselsandbits.helpers.ChiselToolType;
import net.minecraft.util.EnumHand;
public class ActiveChiselsAndBitsProxy implements IChiselsAndBitsProxy {
@Override
public boolean isHoldingChiselTool(EnumHand hand) {
ChiselToolType toolType = ClientSide.instance.getHeldToolType(hand);
return toolType != null && toolType.hasMenu();
}
}

View File

@@ -1,48 +1,50 @@
package nl.requios.effortlessbuilding.compatibility; package nl.requios.effortlessbuilding.compatibility;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand; import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.item.ItemRandomizerBag; import nl.requios.effortlessbuilding.item.ItemRandomizerBag;
public class CompatHelper { public class CompatHelper {
// Get a handle to the dank null item instance. This will remain null if the mod doesn't load //TODO 1.13 compatibility
// and all checks will fail, so it works. // // Get a handle to the dank null item instance. This will remain null if the mod doesn't load
@GameRegistry.ObjectHolder("danknull:dank_null") // // and all checks will fail, so it works.
public static final Item dankNullItem = null; // @GameRegistry.ObjectHolder("danknull:dank_null")
// public static final Item dankNullItem = null;
public static IChiselsAndBitsProxy chiselsAndBitsProxy; //
// public static IChiselsAndBitsProxy chiselsAndBitsProxy;
public static void postInit() { //
if (Loader.isModLoaded("chiselsandbits")) { public static void setup() {
// reflection to avoid hard dependency //TODO 1.13 compatibility
try { // if (Loader.isModLoaded("chiselsandbits")) {
chiselsAndBitsProxy = Class.forName("nl.requios.effortlessbuilding.compatibility.ActiveChiselsAndBitsProxy").asSubclass(ActiveChiselsAndBitsProxy.class).newInstance(); // // reflection to avoid hard dependency
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { // try {
e.printStackTrace(); // chiselsAndBitsProxy = Class.forName("nl.requios.effortlessbuilding.compatibility.ActiveChiselsAndBitsProxy").asSubclass(ActiveChiselsAndBitsProxy.class).newInstance();
} // } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
} else { // e.printStackTrace();
chiselsAndBitsProxy = new DummyChiselsAndBitsProxy(); // }
} // } else {
// chiselsAndBitsProxy = new DummyChiselsAndBitsProxy();
// }
} }
// Check if the item given is a proxy for blocks. For now, we check for the randomizer bag, // Check if the item given is a proxy for blocks. For now, we check for the randomizer bag,
// /dank/null, or plain old blocks. // /dank/null, or plain old blocks.
public static boolean isItemBlockProxy(ItemStack stack) { public static boolean isItemBlockProxy(ItemStack stack) {
Item item = stack.getItem(); Item item = stack.getItem();
if (item instanceof ItemBlock) if (item instanceof BlockItem)
return true; return true;
if ((item instanceof ItemRandomizerBag)) if ((item instanceof ItemRandomizerBag))
return true; return true;
if (item == dankNullItem) //TODO 1.13 compatibility
return true; // if (item == dankNullItem)
// return true;
return false; return false;
} }
@@ -51,63 +53,76 @@ public class CompatHelper {
public static ItemStack getItemBlockFromStack(ItemStack proxy) { public static ItemStack getItemBlockFromStack(ItemStack proxy) {
Item proxyItem = proxy.getItem(); Item proxyItem = proxy.getItem();
if (proxyItem instanceof ItemBlock) if (proxyItem instanceof BlockItem)
return proxy; return proxy;
//Randomizer Bag //Randomizer Bag
if (proxyItem instanceof ItemRandomizerBag) { if (proxyItem instanceof ItemRandomizerBag) {
ItemStack itemStack = proxy; ItemStack itemStack = proxy;
while (!(itemStack.getItem() instanceof ItemBlock || itemStack.isEmpty())) { while (!(itemStack.getItem() instanceof BlockItem || itemStack.isEmpty())) {
if (itemStack.getItem() instanceof ItemRandomizerBag) if (itemStack.getItem() instanceof ItemRandomizerBag)
itemStack = ItemRandomizerBag.pickRandomStack(ItemRandomizerBag.getBagInventory(itemStack)); itemStack = ItemRandomizerBag.pickRandomStack(ItemRandomizerBag.getBagInventory(itemStack));
} }
return itemStack; return itemStack;
} }
//TODO 1.13 compatibility
//Dank Null //Dank Null
if (proxyItem == dankNullItem) { // if (proxyItem == dankNullItem) {
int index = 0; // int index = 0;
if (proxy.hasTagCompound() && proxy.getTagCompound().hasKey("selectedIndex")) // if (proxy.hasTagCompound() && proxy.getTagCompound().hasKey("selectedIndex"))
index = proxy.getTagCompound().getInteger("selectedIndex"); // index = proxy.getTagCompound().getInteger("selectedIndex");
return proxy.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).getStackInSlot(index); // return proxy.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).getStackInSlot(index);
} // }
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
public static ItemStack getItemBlockByState(ItemStack stack, IBlockState state) { public static ItemStack getItemBlockByState(ItemStack stack, BlockState state) {
if (state == null) return ItemStack.EMPTY;
Item blockItem = Item.getItemFromBlock(state.getBlock()); Item blockItem = Item.getItemFromBlock(state.getBlock());
if (stack.getItem() instanceof ItemBlock) if (stack.getItem() instanceof BlockItem)
return stack; return stack;
else if (stack.getItem() instanceof ItemRandomizerBag) { else if (stack.getItem() instanceof ItemRandomizerBag) {
IItemHandler bagInventory = ItemRandomizerBag.getBagInventory(stack); IItemHandler bagInventory = ItemRandomizerBag.getBagInventory(stack);
return ItemRandomizerBag.findStack(bagInventory, blockItem); return ItemRandomizerBag.findStack(bagInventory, blockItem);
} else if (stack.getItem() == dankNullItem) {
int index = itemHandlerSlotForItem(stack, blockItem);
if (index >= 0)
return stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).getStackInSlot(index);
} }
//TODO 1.13 compatibility
// else if (stack.getItem() == dankNullItem) {
// int index = itemHandlerSlotForItem(stack, blockItem);
// if (index >= 0)
// return stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).getStackInSlot(index);
// }
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
// Handle IItemHandler slot stacks not being modifiable. We must call IItemHandler#extractItem, // Handle IItemHandler slot stacks not being modifiable. We must call IItemHandler#extractItem,
// because the ItemStack returned by IItemHandler#getStackInSlot isn't modifiable. // because the ItemStack returned by IItemHandler#getStackInSlot isn't modifiable.
public static void shrinkStack(ItemStack origStack, ItemStack curStack, EntityPlayer player) { public static void shrinkStack(ItemStack origStack, ItemStack curStack, PlayerEntity player) {
//Hacky way to get the origstack, because given origStack is itemblock stack and never a proxy //TODO 1.13 compatibility, offhand support
origStack = player.getHeldItem(EnumHand.MAIN_HAND); //Hacky way to get the origstack, because given origStack is itemblock stack and never proxy
// origStack = player.getHeldItem(EnumHand.MAIN_HAND);
if (origStack.getItem() == dankNullItem) { // if (origStack.getItem() == dankNullItem) {
int index = itemHandlerSlotForItem(origStack, curStack.getItem()); // int index = itemHandlerSlotForItem(origStack, curStack.getItem());
origStack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).extractItem(index, 1, false); // origStack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).extractItem(index, 1, false);
} else // } else
curStack.shrink(1); curStack.shrink(1);
} }
private static int itemHandlerSlotForItem(ItemStack stack, Item blockItem) { private static int itemHandlerSlotForItem(ItemStack stack, Item blockItem) {
IItemHandler handler = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); LazyOptional<IItemHandler> itemHandlerLazyOptional = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
IItemHandler handler = itemHandlerLazyOptional.orElse(null);
if (handler == null) {
EffortlessBuilding.logger.warn("Itemblock proxy has no item handler capability!");
return -1;
}
for (int i = 0; i < handler.getSlots(); i++) { for (int i = 0; i < handler.getSlots(); i++) {
ItemStack ref = handler.getStackInSlot(i); ItemStack ref = handler.getStackInSlot(i);
if (ref.getItem() instanceof ItemBlock) if (ref.getItem() instanceof BlockItem)
if (ref.getItem() == blockItem) if (ref.getItem() == blockItem)
return i; return i;
} }

View File

@@ -1,10 +0,0 @@
package nl.requios.effortlessbuilding.compatibility;
import net.minecraft.util.EnumHand;
public class DummyChiselsAndBitsProxy implements IChiselsAndBitsProxy {
@Override
public boolean isHoldingChiselTool(EnumHand hand) {
return false;
}
}

View File

@@ -1,7 +0,0 @@
package nl.requios.effortlessbuilding.compatibility;
import net.minecraft.util.EnumHand;
public interface IChiselsAndBitsProxy {
boolean isHoldingChiselTool(EnumHand hand);
}

View File

@@ -1,47 +1,55 @@
package nl.requios.effortlessbuilding.gui; package nl.requios.effortlessbuilding.gui;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.ClickType; import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Container; import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.Slot; import net.minecraft.inventory.container.ClickType;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand; import net.minecraft.util.Hand;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import net.minecraftforge.items.SlotItemHandler; import net.minecraftforge.items.SlotItemHandler;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.item.ItemRandomizerBag; import nl.requios.effortlessbuilding.item.ItemRandomizerBag;
public class RandomizerBagContainer extends Container { public class RandomizerBagContainer extends Container {
private final IItemHandler bagInventory; private final IItemHandler bagInventory;
private final int sizeInventory;
private static final int INV_START = ItemRandomizerBag.INV_SIZE, INV_END = INV_START + 26, private static final int INV_START = ItemRandomizerBag.INV_SIZE, INV_END = INV_START + 26,
HOTBAR_START = INV_END + 1, HOTBAR_END = HOTBAR_START + 8; HOTBAR_START = INV_END + 1, HOTBAR_END = HOTBAR_START + 8;
public RandomizerBagContainer(InventoryPlayer parInventoryPlayer, IItemHandler parIInventory) { public RandomizerBagContainer(int containerId, PlayerInventory playerInventory) {
bagInventory = parIInventory; this(containerId, playerInventory, new ItemStackHandler(ItemRandomizerBag.INV_SIZE));
sizeInventory = bagInventory.getSlots(); }
for (int i = 0; i < sizeInventory; ++i) {
this.addSlotToContainer(new SlotItemHandler(bagInventory, i, 44 + (18 * i), 20)); public RandomizerBagContainer(int containerId, PlayerInventory playerInventory, IItemHandler inventory) {
super(EffortlessBuilding.RANDOMIZER_BAG_CONTAINER, containerId);
bagInventory = inventory;
for (int i = 0; i < ItemRandomizerBag.INV_SIZE; ++i) {
this.addSlot(new SlotItemHandler(bagInventory, i, 44 + (18 * i), 20));
} }
// add player inventory slots // add player inventory slots
int i; int i;
for (i = 0; i < 3; ++i) { for (i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) { for (int j = 0; j < 9; ++j) {
addSlotToContainer(new Slot(parInventoryPlayer, j + i * 9 + 9, 8 + j * 18, 51 + i * 18)); addSlot(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 51 + i * 18));
} }
} }
// add hotbar slots // add hotbar slots
for (i = 0; i < 9; ++i) { for (i = 0; i < 9; ++i) {
addSlotToContainer(new Slot(parInventoryPlayer, i, 8 + i * 18, 109)); addSlot(new Slot(playerInventory, i, 8 + i * 18, 109));
} }
} }
@Override @Override
public boolean canInteractWith(EntityPlayer playerIn) { public boolean canInteractWith(PlayerEntity playerIn) {
return true; return true;
} }
@@ -54,7 +62,7 @@ public class RandomizerBagContainer extends Container {
} }
@Override @Override
public ItemStack transferStackInSlot(EntityPlayer playerIn, int slotIndex) { public ItemStack transferStackInSlot(PlayerEntity playerIn, int slotIndex) {
ItemStack itemstack = ItemStack.EMPTY; ItemStack itemstack = ItemStack.EMPTY;
Slot slot = this.inventorySlots.get(slotIndex); Slot slot = this.inventorySlots.get(slotIndex);
@@ -107,9 +115,9 @@ public class RandomizerBagContainer extends Container {
* be able to save properly * be able to save properly
*/ */
@Override @Override
public ItemStack slotClick(int slot, int dragType, ClickType clickTypeIn, EntityPlayer player) { public ItemStack slotClick(int slot, int dragType, ClickType clickTypeIn, PlayerEntity player) {
// this will prevent the player from interacting with the item that opened the inventory: // this will prevent the player from interacting with the item that opened the inventory:
if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack().equals(player.getHeldItem(EnumHand.MAIN_HAND))) { if (slot >= 0 && getSlot(slot) != null && getSlot(slot).getStack().equals(player.getHeldItem(Hand.MAIN_HAND))) {
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
return super.slotClick(slot, dragType, clickTypeIn, player); return super.slotClick(slot, dragType, clickTypeIn, player);
@@ -119,7 +127,7 @@ public class RandomizerBagContainer extends Container {
* Callback for when the crafting gui is closed. * Callback for when the crafting gui is closed.
*/ */
@Override @Override
public void onContainerClosed(EntityPlayer player) public void onContainerClosed(PlayerEntity player)
{ {
super.onContainerClosed(player); super.onContainerClosed(player);
if(!player.world.isRemote) if(!player.world.isRemote)

View File

@@ -1,49 +0,0 @@
package nl.requios.effortlessbuilding.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.items.IItemHandler;
import nl.requios.effortlessbuilding.EffortlessBuilding;
@SideOnly(Side.CLIENT)
public class RandomizerBagGuiContainer extends GuiContainer {
private static final ResourceLocation guiTextures =
new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/container/randomizerbag.png");
private final InventoryPlayer inventoryPlayer;
private final IItemHandler inventoryBag;
public RandomizerBagGuiContainer(InventoryPlayer inventoryPlayer, IItemHandler inventoryBag) {
super(new RandomizerBagContainer(inventoryPlayer, inventoryBag));
this.inventoryPlayer = inventoryPlayer;
this.inventoryBag = inventoryBag;
ySize = 134;
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
drawDefaultBackground();
super.drawScreen(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
String s = "Randomizer Bag";
fontRenderer.drawString(s, 8, 6, 0x404040);
fontRenderer.drawString(inventoryPlayer.getDisplayName().getUnformattedText(), 8, ySize - 96 + 2, 0x404040);
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(guiTextures);
int marginHorizontal = (width - xSize) / 2;
int marginVertical = (height - ySize) / 2;
drawTexturedModalRect(marginHorizontal, marginVertical, 0, 0, xSize, ySize);
}
}

View File

@@ -1,41 +0,0 @@
package nl.requios.effortlessbuilding.gui;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import javax.annotation.Nullable;
public class RandomizerBagGuiHandler implements IGuiHandler {
@Nullable
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
if (ID == EffortlessBuilding.RANDOMIZER_BAG_GUI) {
// Use the player's held item to create the container
IItemHandler capability = player.getHeldItemMainhand().hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null) ?
player.getHeldItemMainhand().getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null) :
player.getHeldItemOffhand().getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
return new RandomizerBagContainer(player.inventory, capability);
}
return null;
}
@Nullable
@Override
@SideOnly(Side.CLIENT)
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
if (ID == EffortlessBuilding.RANDOMIZER_BAG_GUI) {
// Use the player's held item to create the client-side gui container
IItemHandler capability = player.getHeldItemMainhand().hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null) ?
player.getHeldItemMainhand().getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null) :
player.getHeldItemOffhand().getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
return new RandomizerBagGuiContainer(player.inventory, capability);
}
return null;
}
}

View File

@@ -0,0 +1,46 @@
package nl.requios.effortlessbuilding.gui;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.items.IItemHandler;
import nl.requios.effortlessbuilding.EffortlessBuilding;
@OnlyIn(Dist.CLIENT)
public class RandomizerBagScreen extends ContainerScreen<RandomizerBagContainer> {
private static final ResourceLocation guiTextures =
new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/container/randomizerbag.png");
public RandomizerBagScreen(RandomizerBagContainer randomizerBagContainer, PlayerInventory playerInventory, ITextComponent title) {
super(randomizerBagContainer, playerInventory, title);//new TranslationTextComponent("effortlessbuilding.screen.randomizer_bag"));
ySize = 134;
}
@Override
public void render(int mouseX, int mouseY, float partialTicks) {
renderBackground();
super.render(mouseX, mouseY, partialTicks);
this.renderHoveredToolTip(mouseX, mouseY);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
font.drawString(this.title.getFormattedText(), 8, 6, 0x404040);
font.drawString(playerInventory.getDisplayName().getFormattedText(), 8, ySize - 96 + 2, 0x404040);
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
RenderSystem.color3f(1.0F, 1.0F, 1.0F);
minecraft.getTextureManager().bindTexture(guiTextures);
int marginHorizontal = (width - xSize) / 2;
int marginVertical = (height - ySize) / 2;
blit(marginHorizontal, marginVertical, 0, 0, xSize, ySize);
}
}

View File

@@ -0,0 +1,304 @@
package nl.requios.effortlessbuilding.gui.buildmode;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.SimpleSound;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.gui.IGuiEventListener;
import net.minecraft.client.gui.screen.LanguageScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.widget.list.ExtendedList;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.client.gui.widget.ExtendedButton;
import net.minecraftforge.fml.client.gui.widget.Slider;
import nl.requios.effortlessbuilding.EffortlessBuilding;
public class PlayerSettingsGui extends Screen {
protected int left, right, top, bottom;
private Button shaderTypeButton;
private ShaderTypeList shaderTypeList;
private Button closeButton;
protected boolean showShaderList = false;
public enum ShaderType {
DISSOLVE_BLUE("Dissolve Blue"),
DISSOLVE_ORANGE("Dissolve Orange");
public String name;
ShaderType(String name) {
this.name = name;
}
}
public PlayerSettingsGui() {
super(new TranslationTextComponent("effortlessbuilding.screen.player_settings"));
}
@Override
protected void init() {
left = this.width / 2 - 140;
right = this.width / 2 + 140;
top = this.height / 2 - 100;
bottom = this.height / 2 + 100;
int yy = top;
shaderTypeList = new ShaderTypeList(this.minecraft);
this.children.add(shaderTypeList);
//TODO set selected name
String currentShaderName = ShaderType.DISSOLVE_BLUE.name;
shaderTypeButton = new ExtendedButton(right - 180, yy, 180, 20, currentShaderName, (button) -> {
showShaderList = !showShaderList;
});
addButton(shaderTypeButton);
yy += 50;
Slider slider = new Slider(right - 200, yy, 200, 20, "", "", 0.5, 2.0, 1.0, true, true, (button) -> {
});
addButton(slider);
closeButton = new ExtendedButton(left + 50, bottom - 20, 180, 20, "Done", (button) -> {
this.minecraft.player.closeScreen();
});
addButton(closeButton);
}
@Override
public void tick() {
super.tick();
}
@Override
public void render(int mouseX, int mouseY, float partialTicks) {
this.renderBackground();
int yy = top;
font.drawString("Shader type", left, yy + 5, 0xFFFFFF);
yy += 50;
font.drawString("Shader speed", left, yy + 5, 0xFFFFFF);
super.render(mouseX, mouseY, partialTicks);
if (showShaderList)
this.shaderTypeList.render(mouseX, mouseY, partialTicks);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
super.mouseClicked(mouseX, mouseY, mouseButton);
if (showShaderList) {
if (!shaderTypeList.isMouseOver(mouseX, mouseY) && !shaderTypeButton.isMouseOver(mouseX, mouseY))
showShaderList = false;
}
return true;
}
@Override
public void removed() {
ShaderTypeList.ShaderTypeEntry selectedShader = shaderTypeList.getSelected();
//TODO save
}
//Inspired by LanguageScreen
@OnlyIn(Dist.CLIENT)
class ShaderTypeList extends ExtendedList<PlayerSettingsGui.ShaderTypeList.ShaderTypeEntry> {
public ShaderTypeList(Minecraft mcIn) {
super(mcIn, 180, 140, top + 20, top + 100, 18);
this.setLeftPos(right - width);
for (int i = 0; i < 40; i++) {
for (ShaderType shaderType : ShaderType.values()) {
ShaderTypeEntry shaderTypeEntry = new ShaderTypeEntry(shaderType);
addEntry(shaderTypeEntry);
//TODO setSelected to this if appropriate
}
}
if (this.getSelected() != null) {
this.centerScrollOn(this.getSelected());
}
}
@Override
public int getRowWidth() {
return width;
}
@Override
public void setSelected(PlayerSettingsGui.ShaderTypeList.ShaderTypeEntry selected) {
super.setSelected(selected);
Minecraft.getInstance().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1.0F));
EffortlessBuilding.log("Selected shader " + selected.shaderType.name);
shaderTypeButton.setMessage(selected.shaderType.name);
// showShaderList = false;
}
@Override
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) {
if (!showShaderList) return false;
return super.mouseClicked(p_mouseClicked_1_, p_mouseClicked_3_, p_mouseClicked_5_);
}
@Override
public boolean mouseReleased(double p_mouseReleased_1_, double p_mouseReleased_3_, int p_mouseReleased_5_) {
if (!showShaderList) return false;
return super.mouseReleased(p_mouseReleased_1_, p_mouseReleased_3_, p_mouseReleased_5_);
}
@Override
public boolean mouseDragged(double p_mouseDragged_1_, double p_mouseDragged_3_, int p_mouseDragged_5_, double p_mouseDragged_6_, double p_mouseDragged_8_) {
if (!showShaderList) return false;
return super.mouseDragged(p_mouseDragged_1_, p_mouseDragged_3_, p_mouseDragged_5_, p_mouseDragged_6_, p_mouseDragged_8_);
}
@Override
public boolean mouseScrolled(double p_mouseScrolled_1_, double p_mouseScrolled_3_, double p_mouseScrolled_5_) {
if (!showShaderList) return false;
return super.mouseScrolled(p_mouseScrolled_1_, p_mouseScrolled_3_, p_mouseScrolled_5_);
}
@Override
public boolean isMouseOver(double p_isMouseOver_1_, double p_isMouseOver_3_) {
if (!showShaderList) return false;
return super.isMouseOver(p_isMouseOver_1_, p_isMouseOver_3_);
}
protected boolean isFocused() {
return PlayerSettingsGui.this.getFocused() == this;
}
@Override
protected int getScrollbarPosition() {
return right - 6;
}
@OnlyIn(Dist.CLIENT)
public class ShaderTypeEntry extends ExtendedList.AbstractListEntry<ShaderTypeEntry> {
private final ShaderType shaderType;
public ShaderTypeEntry(ShaderType shaderType) {
this.shaderType = shaderType;
}
public void render(int itemIndex, int rowTop, int rowLeft, int rowWidth, int rowHeight, int mouseX, int mouseY, boolean hovered, float partialTicks) {
if (rowTop + 10 > ShaderTypeList.this.y0 && rowTop + rowHeight - 5 < ShaderTypeList.this.y1)
drawString(font, shaderType.name, ShaderTypeList.this.x0 + 8, rowTop + 4, 0xFFFFFF);
}
@Override
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) {
if (p_mouseClicked_5_ == 0) {
setSelected(this);
return true;
} else {
return false;
}
}
}
//From AbstractList, disabled parts
public void render(int p_render_1_, int p_render_2_, float p_render_3_) {
this.renderBackground();
int i = this.getScrollbarPosition();
int j = i + 6;
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferbuilder = tessellator.getBuffer();
// this.minecraft.getTextureManager().bindTexture(AbstractGui.BACKGROUND_LOCATION);
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE);
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
float f = 32.0F;
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_COLOR);
bufferbuilder.pos((double)this.x0, (double)this.y1, 0.0D).color(20, 20, 20, 180).endVertex();
bufferbuilder.pos((double)this.x1, (double)this.y1, 0.0D).color(20, 20, 20, 180).endVertex();
bufferbuilder.pos((double)this.x1, (double)this.y0, 0.0D).color(20, 20, 20, 180).endVertex();
bufferbuilder.pos((double)this.x0, (double)this.y0, 0.0D).color(20, 20, 20, 180).endVertex();
tessellator.draw();
int k = this.getRowLeft();
int l = this.y0 + 4 - (int)this.getScrollAmount();
if (this.renderHeader) {
this.renderHeader(k, l, tessellator);
}
this.renderList(k, l, p_render_1_, p_render_2_, p_render_3_);
RenderSystem.disableDepthTest();
// this.renderHoleBackground(0, this.y0, 255, 255);
// this.renderHoleBackground(this.y1, this.height, 255, 255);
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE);
RenderSystem.disableAlphaTest();
RenderSystem.shadeModel(7425);
RenderSystem.disableTexture();
// int i1 = 4;
// bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
// bufferbuilder.pos((double)this.x0, (double)(this.y0 + 4), 0.0D).tex(0.0F, 1.0F).color(0, 0, 0, 0).endVertex();
// bufferbuilder.pos((double)this.x1, (double)(this.y0 + 4), 0.0D).tex(1.0F, 1.0F).color(0, 0, 0, 0).endVertex();
// bufferbuilder.pos((double)this.x1, (double)this.y0, 0.0D).tex(1.0F, 0.0F).color(0, 0, 0, 255).endVertex();
// bufferbuilder.pos((double)this.x0, (double)this.y0, 0.0D).tex(0.0F, 0.0F).color(0, 0, 0, 255).endVertex();
// tessellator.draw();
// bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
// bufferbuilder.pos((double)this.x0, (double)this.y1, 0.0D).tex(0.0F, 1.0F).color(0, 0, 0, 255).endVertex();
// bufferbuilder.pos((double)this.x1, (double)this.y1, 0.0D).tex(1.0F, 1.0F).color(0, 0, 0, 255).endVertex();
// bufferbuilder.pos((double)this.x1, (double)(this.y1 - 4), 0.0D).tex(1.0F, 0.0F).color(0, 0, 0, 0).endVertex();
// bufferbuilder.pos((double)this.x0, (double)(this.y1 - 4), 0.0D).tex(0.0F, 0.0F).color(0, 0, 0, 0).endVertex();
// tessellator.draw();
//SCROLLBAR
int j1 = this.getMaxScroll();
if (j1 > 0) {
int k1 = (int)((float)((this.y1 - this.y0) * (this.y1 - this.y0)) / (float)this.getMaxPosition());
k1 = MathHelper.clamp(k1, 32, this.y1 - this.y0 - 8);
int l1 = (int)this.getScrollAmount() * (this.y1 - this.y0 - k1) / j1 + this.y0;
if (l1 < this.y0) {
l1 = this.y0;
}
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
bufferbuilder.pos((double)i, (double)this.y1, 0.0D).tex(0.0F, 1.0F).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)j, (double)this.y1, 0.0D).tex(1.0F, 1.0F).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)j, (double)this.y0, 0.0D).tex(1.0F, 0.0F).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)i, (double)this.y0, 0.0D).tex(0.0F, 0.0F).color(0, 0, 0, 255).endVertex();
tessellator.draw();
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
bufferbuilder.pos((double)i, (double)(l1 + k1), 0.0D).tex(0.0F, 1.0F).color(128, 128, 128, 255).endVertex();
bufferbuilder.pos((double)j, (double)(l1 + k1), 0.0D).tex(1.0F, 1.0F).color(128, 128, 128, 255).endVertex();
bufferbuilder.pos((double)j, (double)l1, 0.0D).tex(1.0F, 0.0F).color(128, 128, 128, 255).endVertex();
bufferbuilder.pos((double)i, (double)l1, 0.0D).tex(0.0F, 0.0F).color(128, 128, 128, 255).endVertex();
tessellator.draw();
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
bufferbuilder.pos((double)i, (double)(l1 + k1 - 1), 0.0D).tex(0.0F, 1.0F).color(192, 192, 192, 255).endVertex();
bufferbuilder.pos((double)(j - 1), (double)(l1 + k1 - 1), 0.0D).tex(1.0F, 1.0F).color(192, 192, 192, 255).endVertex();
bufferbuilder.pos((double)(j - 1), (double)l1, 0.0D).tex(1.0F, 0.0F).color(192, 192, 192, 255).endVertex();
bufferbuilder.pos((double)i, (double)l1, 0.0D).tex(0.0F, 0.0F).color(192, 192, 192, 255).endVertex();
tessellator.draw();
}
// this.renderDecorations(p_render_1_, p_render_2_);
RenderSystem.enableTexture();
RenderSystem.shadeModel(7424);
RenderSystem.enableAlphaTest();
RenderSystem.disableBlend();
}
private int getMaxScroll() {
return Math.max(0, this.getMaxPosition() - (this.y1 - this.y0 - 4));
}
}
}

View File

@@ -3,11 +3,18 @@ package nl.requios.effortlessbuilding.gui.buildmode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.renderer.texture.AtlasTexture;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import net.minecraft.util.Direction;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.ModClientEventHandler;
import nl.requios.effortlessbuilding.ModEventHandler;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager; import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager;
import nl.requios.effortlessbuilding.proxy.ClientProxy; import nl.requios.effortlessbuilding.proxy.ClientProxy;
import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.lang3.text.WordUtils;
@@ -16,14 +23,10 @@ import org.lwjgl.opengl.GL11;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.ModelLoader;
import static nl.requios.effortlessbuilding.buildmode.BuildModes.*; import static nl.requios.effortlessbuilding.buildmode.BuildModes.*;
import static nl.requios.effortlessbuilding.buildmode.ModeOptions.*; import static nl.requios.effortlessbuilding.buildmode.ModeOptions.*;
@@ -32,7 +35,7 @@ import static nl.requios.effortlessbuilding.buildmode.ModeOptions.*;
* From Chisels and Bits by AlgorithmX2 * From Chisels and Bits by AlgorithmX2
* https://github.com/AlgorithmX2/Chisels-and-Bits/blob/1.12/src/main/java/mod/chiselsandbits/client/gui/ChiselsAndBitsMenu.java * https://github.com/AlgorithmX2/Chisels-and-Bits/blob/1.12/src/main/java/mod/chiselsandbits/client/gui/ChiselsAndBitsMenu.java
*/ */
public class RadialMenu extends GuiScreen { public class RadialMenu extends Screen {
private final float TIME_SCALE = 0.01f; private final float TIME_SCALE = 0.01f;
public static final RadialMenu instance = new RadialMenu(); public static final RadialMenu instance = new RadialMenu();
@@ -43,6 +46,10 @@ public class RadialMenu extends GuiScreen {
public ActionEnum doAction = null; public ActionEnum doAction = null;
public boolean actionUsed = false; public boolean actionUsed = false;
public RadialMenu() {
super(new TranslationTextComponent("effortlessbuilding.screen.radial_menu"));
}
private float clampVis(final float f) { private float clampVis(final float f) {
return Math.max( 0.0f, Math.min( 1.0f, f ) ); return Math.max( 0.0f, Math.min( 1.0f, f ) );
} }
@@ -66,8 +73,8 @@ public class RadialMenu extends GuiScreen {
} }
public void configure(final int scaledWidth, final int scaledHeight ) { public void configure(final int scaledWidth, final int scaledHeight ) {
mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getInstance();
fontRenderer = mc.fontRenderer; font = mc.fontRenderer;
width = scaledWidth; width = scaledWidth;
height = scaledHeight; height = scaledHeight;
} }
@@ -80,10 +87,10 @@ public class RadialMenu extends GuiScreen {
public final ActionEnum action; public final ActionEnum action;
public String name; public String name;
public EnumFacing textSide; public Direction textSide;
public MenuButton(final String name, final ActionEnum action, final double x, final double y, public MenuButton(final String name, final ActionEnum action, final double x, final double y,
final EnumFacing textSide) { final Direction textSide) {
this.name = I18n.format(name); this.name = I18n.format(name);
this.action = action; this.action = action;
x1 = x - 10; x1 = x - 10;
@@ -109,24 +116,24 @@ public class RadialMenu extends GuiScreen {
} }
@Override @Override
public void drawScreen(final int mouseX, final int mouseY, final float partialTicks) { public void render(final int mouseX, final int mouseY, final float partialTicks) {
if (!isVisible()) return; if (!isVisible()) return;
BuildModeEnum currentBuildMode = ModeSettingsManager.getModeSettings(Minecraft.getMinecraft().player).getBuildMode(); BuildModeEnum currentBuildMode = ModeSettingsManager.getModeSettings(Minecraft.getInstance().player).getBuildMode();
GlStateManager.pushMatrix(); RenderSystem.pushMatrix();
GlStateManager.translate( 0.0F, 0.0F, 200.0F ); RenderSystem.translatef( 0.0F, 0.0F, 200.0F );
final int startColor = (int) ( visibility * 98 ) << 24; final int startColor = (int) ( visibility * 98 ) << 24;
final int endColor = (int) ( visibility * 128 ) << 24; final int endColor = (int) ( visibility * 128 ) << 24;
drawGradientRect(0, 0, width, height, startColor, endColor); fillGradient(0, 0, width, height, startColor, endColor);
GlStateManager.disableTexture2D(); RenderSystem.disableTexture();
GlStateManager.enableBlend(); RenderSystem.enableBlend();
GlStateManager.disableAlpha(); RenderSystem.disableAlphaTest();
GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); RenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0);
GlStateManager.shadeModel(GL11.GL_SMOOTH); RenderSystem.shadeModel(GL11.GL_SMOOTH);
final Tessellator tessellator = Tessellator.getInstance(); final Tessellator tessellator = Tessellator.getInstance();
final BufferBuilder buffer = tessellator.getBuffer(); final BufferBuilder buffer = tessellator.getBuffer();
@@ -135,8 +142,14 @@ public class RadialMenu extends GuiScreen {
final double middleX = width / 2.0; final double middleX = width / 2.0;
final double middleY = height / 2.0; final double middleY = height / 2.0;
final double mouseXCenter = mouseX - middleX; //Fix for high def (retina) displays: use custom mouse coordinates
final double mouseYCenter = mouseY - middleY; //Borrowed from GameRenderer::updateCameraAndRender
Minecraft mc = Minecraft.getInstance();
int mouseXX = (int)(mc.mouseHelper.getMouseX() * (double)mc.getMainWindow().getScaledWidth() / (double)mc.getMainWindow().getWidth());
int mouseYY = (int)(mc.mouseHelper.getMouseY() * (double)mc.getMainWindow().getScaledHeight() / (double)mc.getMainWindow().getHeight());
final double mouseXCenter = mouseXX - middleX;
final double mouseYCenter = mouseYY - middleY;
double mouseRadians = Math.atan2(mouseYCenter, mouseXCenter); double mouseRadians = Math.atan2(mouseYCenter, mouseXCenter);
final double ringInnerEdge = 30; final double ringInnerEdge = 30;
@@ -158,17 +171,18 @@ public class RadialMenu extends GuiScreen {
} }
//Add actions //Add actions
buttons.add(new MenuButton(ActionEnum.UNDO.name, ActionEnum.UNDO, -buttonDistance - 26, -13, EnumFacing.UP)); buttons.add(new MenuButton(ActionEnum.UNDO.name, ActionEnum.UNDO, -buttonDistance - 26, -13, Direction.UP));
buttons.add(new MenuButton(ActionEnum.REDO.name, ActionEnum.REDO, -buttonDistance, -13, EnumFacing.UP)); buttons.add(new MenuButton(ActionEnum.REDO.name, ActionEnum.REDO, -buttonDistance, -13, Direction.UP));
buttons.add(new MenuButton(ActionEnum.OPEN_MODIFIER_SETTINGS.name, ActionEnum.OPEN_MODIFIER_SETTINGS, -buttonDistance - 26, 13, EnumFacing.DOWN)); buttons.add(new MenuButton(ActionEnum.OPEN_PLAYER_SETTINGS.name, ActionEnum.OPEN_PLAYER_SETTINGS, -buttonDistance - 26 - 13, 13, Direction.DOWN));
buttons.add(new MenuButton(ActionEnum.REPLACE.name, ActionEnum.REPLACE, -buttonDistance, 13, EnumFacing.DOWN)); buttons.add(new MenuButton(ActionEnum.OPEN_MODIFIER_SETTINGS.name, ActionEnum.OPEN_MODIFIER_SETTINGS, -buttonDistance - 13, 13, Direction.DOWN));
buttons.add(new MenuButton(ActionEnum.REPLACE.name, ActionEnum.REPLACE, -buttonDistance + 13, 13, Direction.DOWN));
//Add buildmode dependent options //Add buildmode dependent options
OptionEnum[] options = currentBuildMode.options; OptionEnum[] options = currentBuildMode.options;
for (int i = 0; i < options.length; i++) { for (int i = 0; i < options.length; i++) {
for (int j = 0; j < options[i].actions.length; j++) { for (int j = 0; j < options[i].actions.length; j++) {
ActionEnum action = options[i].actions[j]; ActionEnum action = options[i].actions[j];
buttons.add(new MenuButton(action.name, action, buttonDistance + j * 26, -13 + i * 39, EnumFacing.DOWN)); buttons.add(new MenuButton(action.name, action, buttonDistance + j * 26, -13 + i * 39, Direction.DOWN));
} }
} }
@@ -231,10 +245,10 @@ public class RadialMenu extends GuiScreen {
switchTo = menuRegion.mode; switchTo = menuRegion.mode;
} }
buffer.pos(middleX + x1m1, middleY + y1m1, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + x1m1, middleY + y1m1, getBlitOffset()).color(r, g, b, a).endVertex();
buffer.pos(middleX + x2m1, middleY + y2m1, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + x2m1, middleY + y2m1, getBlitOffset()).color(r, g, b, a).endVertex();
buffer.pos(middleX + x2m2, middleY + y2m2, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + x2m2, middleY + y2m2, getBlitOffset()).color(r, g, b, a).endVertex();
buffer.pos(middleX + x1m2, middleY + y1m2, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + x1m2, middleY + y1m2, getBlitOffset()).color(r, g, b, a).endVertex();
currentMode++; currentMode++;
} }
@@ -270,22 +284,22 @@ public class RadialMenu extends GuiScreen {
doAction = btn.action; doAction = btn.action;
} }
buffer.pos(middleX + btn.x1, middleY + btn.y1, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + btn.x1, middleY + btn.y1, getBlitOffset()).color(r, g, b, a).endVertex();
buffer.pos(middleX + btn.x1, middleY + btn.y2, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + btn.x1, middleY + btn.y2, getBlitOffset()).color(r, g, b, a).endVertex();
buffer.pos(middleX + btn.x2, middleY + btn.y2, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + btn.x2, middleY + btn.y2, getBlitOffset()).color(r, g, b, a).endVertex();
buffer.pos(middleX + btn.x2, middleY + btn.y1, zLevel).color(r, g, b, a).endVertex(); buffer.pos(middleX + btn.x2, middleY + btn.y1, getBlitOffset()).color(r, g, b, a).endVertex();
} }
tessellator.draw(); tessellator.draw();
GlStateManager.shadeModel(GL11.GL_FLAT); RenderSystem.shadeModel(GL11.GL_FLAT);
GlStateManager.translate(0f, 0f, 5f); RenderSystem.translatef(0f, 0f, 5f);
GlStateManager.enableTexture2D(); RenderSystem.enableTexture();
GlStateManager.color(1f, 1f, 1f, 1f); RenderSystem.color3f(1f, 1f, 1f);
GlStateManager.disableBlend(); RenderSystem.disableBlend();
GlStateManager.enableAlpha(); RenderSystem.enableAlphaTest();
GlStateManager.bindTexture(Minecraft.getMinecraft().getTextureMapBlocks().getGlTextureId()); mc.getTextureManager().bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE);
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
@@ -295,7 +309,7 @@ public class RadialMenu extends GuiScreen {
final double x = (menuRegion.x1 + menuRegion.x2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge); final double x = (menuRegion.x1 + menuRegion.x2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge);
final double y = (menuRegion.y1 + menuRegion.y2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge); final double y = (menuRegion.y1 + menuRegion.y2) * 0.5 * (ringOuterEdge * 0.6 + 0.4 * ringInnerEdge);
final TextureAtlasSprite sprite = ClientProxy.getBuildModeIcon(menuRegion.mode); final TextureAtlasSprite sprite = ModClientEventHandler.getBuildModeIcon(menuRegion.mode);
final double x1 = x - 8; final double x1 = x - 8;
final double x2 = x + 8; final double x2 = x + 8;
@@ -310,10 +324,10 @@ public class RadialMenu extends GuiScreen {
final double v1 = 0; final double v1 = 0;
final double v2 = 16; final double v2 = 16;
buffer.pos(middleX + x1, middleY + y1, zLevel).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); buffer.pos(middleX + x1, middleY + y1, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex();
buffer.pos(middleX + x1, middleY + y2, zLevel).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); buffer.pos(middleX + x1, middleY + y2, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex();
buffer.pos(middleX + x2, middleY + y2, zLevel).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); buffer.pos(middleX + x2, middleY + y2, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex();
buffer.pos(middleX + x2, middleY + y1, zLevel).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); buffer.pos(middleX + x2, middleY + y1, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex();
} }
//Draw action icons //Draw action icons
@@ -327,7 +341,7 @@ public class RadialMenu extends GuiScreen {
final double v1 = 0; final double v1 = 0;
final double v2 = 16; final double v2 = 16;
final TextureAtlasSprite sprite = ClientProxy.getModeOptionIcon(button.action); final TextureAtlasSprite sprite = ModClientEventHandler.getModeOptionIcon(button.action);
final double btnmiddleX = (button.x1 + button.x2) / 2 + 0.01; final double btnmiddleX = (button.x1 + button.x2) / 2 + 0.01;
final double btnmiddleY = (button.y1 + button.y2) / 2 + 0.01; final double btnmiddleY = (button.y1 + button.y2) / 2 + 0.01;
@@ -336,25 +350,25 @@ public class RadialMenu extends GuiScreen {
final double btny1 = btnmiddleY - 8; final double btny1 = btnmiddleY - 8;
final double btny2 = btnmiddleY + 8; final double btny2 = btnmiddleY + 8;
buffer.pos(middleX + btnx1, middleY + btny1, zLevel).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); buffer.pos(middleX + btnx1, middleY + btny1, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex();
buffer.pos(middleX + btnx1, middleY + btny2, zLevel).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); buffer.pos(middleX + btnx1, middleY + btny2, getBlitOffset()).tex(sprite.getInterpolatedU(u1), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex();
buffer.pos(middleX + btnx2, middleY + btny2, zLevel).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex(); buffer.pos(middleX + btnx2, middleY + btny2, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v2)).color(f, f, f, a).endVertex();
buffer.pos(middleX + btnx2, middleY + btny1, zLevel).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex(); buffer.pos(middleX + btnx2, middleY + btny1, getBlitOffset()).tex(sprite.getInterpolatedU(u2), sprite.getInterpolatedV(v1)).color(f, f, f, a).endVertex();
} }
tessellator.draw(); tessellator.draw();
//Draw strings //Draw strings
//fontRenderer.drawStringWithShadow("Actions", (int) (middleX - buttonDistance - 13) - fontRenderer.getStringWidth("Actions") * 0.5f, (int) middleY - 38, 0xffffffff); //font.drawStringWithShadow("Actions", (int) (middleX - buttonDistance - 13) - font.getStringWidth("Actions") * 0.5f, (int) middleY - 38, 0xffffffff);
//Draw option strings //Draw option strings
for (int i = 0; i < currentBuildMode.options.length; i++) { for (int i = 0; i < currentBuildMode.options.length; i++) {
OptionEnum option = options[i]; OptionEnum option = options[i];
fontRenderer.drawStringWithShadow(I18n.format(option.name), (int) (middleX + buttonDistance - 9), (int) middleY - 37 + i * 39, 0xeeeeeeff); font.drawStringWithShadow(I18n.format(option.name), (int) (middleX + buttonDistance - 9), (int) middleY - 37 + i * 39, 0xeeeeeeff);
} }
String credits = "Effortless Building"; String credits = "Effortless Building";
fontRenderer.drawStringWithShadow(credits, width - fontRenderer.getStringWidth(credits) - 4, height - 10, 0x88888888); font.drawStringWithShadow(credits, width - font.getStringWidth(credits) - 4, height - 10, 0x88888888);
//Draw buildmode text //Draw buildmode text
for (final MenuRegion menuRegion : modes) { for (final MenuRegion menuRegion : modes) {
@@ -364,16 +378,16 @@ public class RadialMenu extends GuiScreen {
final double y = (menuRegion.y1 + menuRegion.y2) * 0.5; final double y = (menuRegion.y1 + menuRegion.y2) * 0.5;
int fixed_x = (int) (x * textDistance); int fixed_x = (int) (x * textDistance);
final int fixed_y = (int) (y * textDistance) - fontRenderer.FONT_HEIGHT / 2; final int fixed_y = (int) (y * textDistance) - font.FONT_HEIGHT / 2;
final String text = I18n.format(menuRegion.mode.name); final String text = I18n.format(menuRegion.mode.name);
if ( x <= -0.2 ) { if ( x <= -0.2 ) {
fixed_x -= fontRenderer.getStringWidth(text); fixed_x -= font.getStringWidth(text);
} else if ( -0.2 <= x && x <= 0.2 ) { } else if ( -0.2 <= x && x <= 0.2 ) {
fixed_x -= fontRenderer.getStringWidth(text) / 2; fixed_x -= font.getStringWidth(text) / 2;
} }
fontRenderer.drawStringWithShadow(text, (int) middleX + fixed_x, (int) middleY + fixed_y, 0xffffffff); font.drawStringWithShadow(text, (int) middleX + fixed_x, (int) middleY + fixed_y, 0xffffffff);
} }
} }
@@ -387,51 +401,51 @@ public class RadialMenu extends GuiScreen {
//Add keybind in brackets //Add keybind in brackets
if (button.action == ActionEnum.UNDO) { if (button.action == ActionEnum.UNDO) {
keybind = ClientProxy.keyBindings[4].getDisplayName(); keybind = ClientProxy.keyBindings[4].getLocalizedName();
} }
if (button.action == ActionEnum.REDO) { if (button.action == ActionEnum.REDO) {
keybind = ClientProxy.keyBindings[5].getDisplayName(); keybind = ClientProxy.keyBindings[5].getLocalizedName();
} }
if (button.action == ActionEnum.REPLACE) { if (button.action == ActionEnum.REPLACE) {
keybind = ClientProxy.keyBindings[1].getDisplayName(); keybind = ClientProxy.keyBindings[1].getLocalizedName();
} }
if (button.action == ActionEnum.OPEN_MODIFIER_SETTINGS) { if (button.action == ActionEnum.OPEN_MODIFIER_SETTINGS) {
keybind = ClientProxy.keyBindings[0].getDisplayName(); keybind = ClientProxy.keyBindings[0].getLocalizedName();
} }
if (currentBuildMode.options.length > 0) { if (currentBuildMode.options.length > 0) {
//Add (ctrl) to first two actions of first option //Add (ctrl) to first two actions of first option
if (button.action == currentBuildMode.options[0].actions[0] if (button.action == currentBuildMode.options[0].actions[0]
|| button.action == currentBuildMode.options[0].actions[1]) { || button.action == currentBuildMode.options[0].actions[1]) {
keybind = ClientProxy.keyBindings[6].getDisplayName(); keybind = ClientProxy.keyBindings[6].getLocalizedName();
if (keybind.equals("LCONTROL")) keybind = "Ctrl"; if (keybind.equals("Left Control")) keybind = "Ctrl";
} }
} }
if (!keybind.isEmpty()) keybindFormatted = TextFormatting.GRAY + "(" + WordUtils.capitalizeFully(keybind) + ")"; if (!keybind.isEmpty()) keybindFormatted = TextFormatting.GRAY + "(" + WordUtils.capitalizeFully(keybind) + ")";
if (button.textSide == EnumFacing.WEST) { if (button.textSide == Direction.WEST) {
fontRenderer.drawSplitString( text, (int) (middleX + button.x1 - 8 ) - fontRenderer.getStringWidth(text), font.drawSplitString( text, (int) (middleX + button.x1 - 8 ) - font.getStringWidth(text),
(int) (middleY + button.y1 + 6), wrap, 0xffffffff); (int) (middleY + button.y1 + 6), wrap, 0xffffffff);
} else if (button.textSide == EnumFacing.EAST) { } else if (button.textSide == Direction.EAST) {
fontRenderer.drawSplitString(text, (int) (middleX + button.x2 + 8), font.drawSplitString(text, (int) (middleX + button.x2 + 8),
(int) (middleY + button.y1 + 6 ), wrap, 0xffffffff); (int) (middleY + button.y1 + 6 ), wrap, 0xffffffff);
} else if (button.textSide == EnumFacing.UP || button.textSide == EnumFacing.NORTH) { } else if (button.textSide == Direction.UP || button.textSide == Direction.NORTH) {
fontRenderer.drawSplitString( keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - fontRenderer.getStringWidth(keybindFormatted) * 0.5), font.drawSplitString( keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(keybindFormatted) * 0.5),
(int) (middleY + button.y1 - 26), wrap,0xffffffff); (int) (middleY + button.y1 - 26), wrap,0xffffffff);
fontRenderer.drawSplitString( text, (int) (middleX + (button.x1 + button.x2) * 0.5 - fontRenderer.getStringWidth(text) * 0.5), font.drawSplitString( text, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(text) * 0.5),
(int) (middleY + button.y1 - 14), wrap,0xffffffff); (int) (middleY + button.y1 - 14), wrap,0xffffffff);
} else if (button.textSide == EnumFacing.DOWN || button.textSide == EnumFacing.SOUTH) { } else if (button.textSide == Direction.DOWN || button.textSide == Direction.SOUTH) {
fontRenderer.drawSplitString(text, (int) (middleX + (button.x1 + button.x2) * 0.5 - fontRenderer.getStringWidth(text) * 0.5), font.drawSplitString(text, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(text) * 0.5),
(int) (middleY + button.y1 + 26), wrap, 0xffffffff); (int) (middleY + button.y1 + 26), wrap, 0xffffffff);
fontRenderer.drawSplitString(keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - fontRenderer.getStringWidth(keybindFormatted) * 0.5), font.drawSplitString(keybindFormatted, (int) (middleX + (button.x1 + button.x2) * 0.5 - font.getStringWidth(keybindFormatted) * 0.5),
(int) (middleY + button.y1 + 38), wrap, 0xffffffff); (int) (middleY + button.y1 + 38), wrap, 0xffffffff);
} }
@@ -439,7 +453,7 @@ public class RadialMenu extends GuiScreen {
} }
} }
GlStateManager.popMatrix(); RenderSystem.popMatrix();
} }
private boolean inTriangle(final double x1, final double y1, final double x2, final double y2, private boolean inTriangle(final double x1, final double y1, final double x2, final double y2,
@@ -458,19 +472,21 @@ public class RadialMenu extends GuiScreen {
* Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton * Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton
*/ */
@Override @Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton ) { public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
EffortlessBuilding.log("mouse clicked"); EffortlessBuilding.log("mouse clicked");
// KeyBinding.updateKeyBindState(); KeyBinding.updateKeyBindState();
// KeyBinding.setKeyBindState(ClientProxy.keyBindings[3].getKeyCode(), true); KeyBinding.setKeyBindState(ClientProxy.keyBindings[3].getKey(), true);
// if (mouseButton == 0) { if (mouseButton == 0) {
// this.mc.displayGuiScreen(null); this.minecraft.displayGuiScreen(null);
//
// if (this.mc.currentScreen == null) { if (this.minecraft.currentScreen == null) {
// this.mc.setIngameFocus(); this.minecraft.setGameFocused(true);
// }
// }
} }
} }
return super.mouseClicked(mouseX, mouseY, mouseButton);
}
}

View File

@@ -1,27 +1,30 @@
package nl.requios.effortlessbuilding.gui.buildmodifier; package nl.requios.effortlessbuilding.gui.buildmodifier;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.client.config.GuiCheckBox; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.Array; import nl.requios.effortlessbuilding.buildmodifier.Array;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.gui.elements.GuiCheckBoxFixed;
import nl.requios.effortlessbuilding.gui.elements.GuiCollapsibleScrollEntry; import nl.requios.effortlessbuilding.gui.elements.GuiCollapsibleScrollEntry;
import nl.requios.effortlessbuilding.gui.elements.GuiNumberField; import nl.requios.effortlessbuilding.gui.elements.GuiNumberField;
import nl.requios.effortlessbuilding.gui.elements.GuiScrollPane; import nl.requios.effortlessbuilding.gui.elements.GuiScrollPane;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@OnlyIn(Dist.CLIENT)
public class ArraySettingsGui extends GuiCollapsibleScrollEntry { public class ArraySettingsGui extends GuiCollapsibleScrollEntry {
protected List<GuiNumberField> arrayNumberFieldList = new ArrayList<>(); protected List<GuiNumberField> arrayNumberFieldList = new ArrayList<>();
private GuiCheckBox buttonArrayEnabled; private GuiCheckBoxFixed buttonArrayEnabled;
private GuiNumberField textArrayOffsetX, textArrayOffsetY, textArrayOffsetZ, textArrayCount; private GuiNumberField textArrayOffsetX, textArrayOffsetY, textArrayOffsetZ, textArrayCount;
public ArraySettingsGui(GuiScrollPane scrollPane) { public ArraySettingsGui(GuiScrollPane scrollPane) {
@@ -29,31 +32,37 @@ public class ArraySettingsGui extends GuiCollapsibleScrollEntry {
} }
@Override @Override
public int initGui(int id, List<GuiButton> buttonList) { public void init(List<Widget> buttons) {
id = super.initGui(id, buttonList); super.init(buttons);
int y = top; int y = top;
buttonArrayEnabled = new GuiCheckBox(id++, left - 15 + 8, y, "", false); buttonArrayEnabled = new GuiCheckBoxFixed(left - 15 + 8, y, "", false) {
buttonList.add(buttonArrayEnabled); @Override
public void onClick(double mouseX, double mouseY) {
super.onClick(mouseX, mouseY);
setCollapsed(!buttonArrayEnabled.isChecked());
}
};
buttons.add(buttonArrayEnabled);
y = top + 20; y = top + 20;
textArrayOffsetX = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 70, y, 50, 18); textArrayOffsetX = new GuiNumberField(font, buttons, left + 70, y, 50, 18);
textArrayOffsetX.setNumber(0); textArrayOffsetX.setNumber(0);
textArrayOffsetX.setTooltip("How much each copy is shifted."); textArrayOffsetX.setTooltip("How much each copy is shifted.");
arrayNumberFieldList.add(textArrayOffsetX); arrayNumberFieldList.add(textArrayOffsetX);
textArrayOffsetY = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 140, y, 50, 18); textArrayOffsetY = new GuiNumberField(font, buttons, left + 140, y, 50, 18);
textArrayOffsetY.setNumber(0); textArrayOffsetY.setNumber(0);
textArrayOffsetY.setTooltip("How much each copy is shifted."); textArrayOffsetY.setTooltip("How much each copy is shifted.");
arrayNumberFieldList.add(textArrayOffsetY); arrayNumberFieldList.add(textArrayOffsetY);
textArrayOffsetZ = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 210, y, 50, 18); textArrayOffsetZ = new GuiNumberField(font, buttons, left + 210, y, 50, 18);
textArrayOffsetZ.setNumber(0); textArrayOffsetZ.setNumber(0);
textArrayOffsetZ.setTooltip("How much each copy is shifted."); textArrayOffsetZ.setTooltip("How much each copy is shifted.");
arrayNumberFieldList.add(textArrayOffsetZ); arrayNumberFieldList.add(textArrayOffsetZ);
y = top + 50; y = top + 50;
textArrayCount = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 55, y, 50, 18); textArrayCount = new GuiNumberField(font, buttons, left + 55, y, 50, 18);
textArrayCount.setNumber(5); textArrayCount.setNumber(5);
textArrayCount.setTooltip("How many copies should be made."); textArrayCount.setTooltip("How many copies should be made.");
arrayNumberFieldList.add(textArrayCount); arrayNumberFieldList.add(textArrayCount);
@@ -69,57 +78,51 @@ public class ArraySettingsGui extends GuiCollapsibleScrollEntry {
} }
setCollapsed(!buttonArrayEnabled.isChecked()); setCollapsed(!buttonArrayEnabled.isChecked());
return id;
} }
@Override
public void updateScreen() { public void updateScreen() {
super.updateScreen();
arrayNumberFieldList.forEach(GuiNumberField::update); arrayNumberFieldList.forEach(GuiNumberField::update);
} }
@Override @Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY,
boolean isSelected, float partialTicks) { boolean isSelected, float partialTicks) {
super.drawEntry(slotIndex, x, y, listWidth, slotHeight, mouseX, mouseY, isSelected, partialTicks);
int yy = y; int yy = y;
int offset = 8; int offset = 8;
buttonArrayEnabled.drawButton(this.mc, mouseX, mouseY, partialTicks); buttonArrayEnabled.render(mouseX, mouseY, partialTicks);
if (buttonArrayEnabled.isChecked()) { if (buttonArrayEnabled.isChecked()) {
buttonArrayEnabled.y = yy; buttonArrayEnabled.y = yy;
fontRenderer.drawString("Array enabled", left + offset, yy + 2, 0xFFFFFF, true); font.drawString("Array enabled", left + offset, yy + 2, 0xFFFFFF);
yy = y + 20; yy = y + 20;
fontRenderer.drawString("Offset", left + offset, yy + 5, 0xFFFFFF, true); font.drawString("Offset", left + offset, yy + 5, 0xFFFFFF);
fontRenderer.drawString("X", left + 50 + offset, yy + 5, 0xFFFFFF, true); font.drawString("X", left + 50 + offset, yy + 5, 0xFFFFFF);
textArrayOffsetX.y = yy; textArrayOffsetX.y = yy;
fontRenderer.drawString("Y", left + 120 + offset, yy + 5, 0xFFFFFF, true); font.drawString("Y", left + 120 + offset, yy + 5, 0xFFFFFF);
textArrayOffsetY.y = yy; textArrayOffsetY.y = yy;
fontRenderer.drawString("Z", left + 190 + offset, yy + 5, 0xFFFFFF, true); font.drawString("Z", left + 190 + offset, yy + 5, 0xFFFFFF);
textArrayOffsetZ.y = yy; textArrayOffsetZ.y = yy;
yy = y + 50; yy = y + 50;
fontRenderer.drawString("Count", left + offset, yy + 5, 0xFFFFFF, true); font.drawString("Count", left + offset, yy + 5, 0xFFFFFF);
textArrayCount.y = yy; textArrayCount.y = yy;
int currentReach = Math.max(-1, getArrayReach()); int currentReach = Math.max(-1, getArrayReach());
int maxReach = ReachHelper.getMaxReach(mc.player); int maxReach = ReachHelper.getMaxReach(mc.player);
TextFormatting reachColor = isCurrentReachValid(currentReach, maxReach) ? TextFormatting.GRAY : TextFormatting.RED; TextFormatting reachColor = isCurrentReachValid(currentReach, maxReach) ? TextFormatting.GRAY : TextFormatting.RED;
String reachText = "Reach: " + reachColor + currentReach + TextFormatting.GRAY + "/" + TextFormatting.GRAY + maxReach; String reachText = "Reach: " + reachColor + currentReach + TextFormatting.GRAY + "/" + TextFormatting.GRAY + maxReach;
fontRenderer.drawString(reachText, left + 176 + offset, yy + 5, 0xFFFFFF, true); font.drawString(reachText, left + 176 + offset, yy + 5, 0xFFFFFF);
arrayNumberFieldList.forEach(numberField -> numberField.drawNumberField(this.mc, mouseX, mouseY, partialTicks)); arrayNumberFieldList.forEach(numberField -> numberField.drawNumberField(mouseX, mouseY, partialTicks));
} else { } else {
buttonArrayEnabled.y = yy; buttonArrayEnabled.y = yy;
fontRenderer.drawString("Array disabled", left + offset, yy + 2, 0x999999, true); font.drawString("Array disabled", left + offset, yy + 2, 0x999999);
} }
} }
public void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY) { public void drawTooltip(Screen guiScreen, int mouseX, int mouseY) {
//Draw tooltips last //Draw tooltips last
if (buttonArrayEnabled.isChecked()) if (buttonArrayEnabled.isChecked())
{ {
@@ -128,43 +131,28 @@ public class ArraySettingsGui extends GuiCollapsibleScrollEntry {
} }
@Override @Override
public void updatePosition(int slotIndex, int x, int y, float partialTicks) { public boolean charTyped(char typedChar, int keyCode) {
super.updatePosition(slotIndex, x, y, partialTicks); super.charTyped(typedChar, keyCode);
}
@Override
public void keyTyped(char typedChar, int keyCode) throws IOException {
super.keyTyped(typedChar, keyCode);
for (GuiNumberField numberField : arrayNumberFieldList) { for (GuiNumberField numberField : arrayNumberFieldList) {
numberField.keyTyped(typedChar, keyCode); numberField.charTyped(typedChar, keyCode);
} }
return true;
} }
@Override @Override
public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) { public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) {
super.mousePressed(slotIndex, mouseX, mouseY, mouseEvent, relativeX, relativeY);
arrayNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent)); arrayNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent));
boolean insideArrayEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12; boolean insideArrayEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12;
if (insideArrayEnabledLabel) { if (insideArrayEnabledLabel) {
buttonArrayEnabled.setIsChecked(!buttonArrayEnabled.isChecked()); buttonArrayEnabled.playDownSound(this.mc.getSoundHandler());
buttonArrayEnabled.playPressSound(this.mc.getSoundHandler()); buttonArrayEnabled.onClick(mouseX, mouseY);
actionPerformed(buttonArrayEnabled);
} }
return true; return true;
} }
@Override
public void actionPerformed(GuiButton button) {
super.actionPerformed(button);
if (button == buttonArrayEnabled) {
setCollapsed(!buttonArrayEnabled.isChecked());
}
arrayNumberFieldList.forEach(numberField -> numberField.actionPerformed(button));
}
public Array.ArraySettings getArraySettings() { public Array.ArraySettings getArraySettings() {
boolean arrayEnabled = buttonArrayEnabled.isChecked(); boolean arrayEnabled = buttonArrayEnabled.isChecked();
BlockPos arrayOffset = new BlockPos(0, 0, 0); BlockPos arrayOffset = new BlockPos(0, 0, 0);

View File

@@ -1,35 +1,35 @@
package nl.requios.effortlessbuilding.gui.buildmodifier; package nl.requios.effortlessbuilding.gui.buildmodifier;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.client.config.GuiCheckBox; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.Mirror; import nl.requios.effortlessbuilding.buildmodifier.Mirror;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.gui.elements.GuiCollapsibleScrollEntry; import nl.requios.effortlessbuilding.gui.elements.*;
import nl.requios.effortlessbuilding.gui.elements.GuiIconButton;
import nl.requios.effortlessbuilding.gui.elements.GuiNumberField;
import nl.requios.effortlessbuilding.gui.elements.GuiScrollPane;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@SuppressWarnings("Duplicates")
@OnlyIn(Dist.CLIENT)
public class MirrorSettingsGui extends GuiCollapsibleScrollEntry { public class MirrorSettingsGui extends GuiCollapsibleScrollEntry {
protected static final ResourceLocation BUILDING_ICONS = new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/building_icons.png"); protected static final ResourceLocation BUILDING_ICONS = new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/building_icons.png");
protected List<GuiButton> mirrorButtonList = new ArrayList<>(); protected List<Button> mirrorButtonList = new ArrayList<>();
protected List<GuiIconButton> mirrorIconButtonList = new ArrayList<>(); protected List<GuiIconButton> mirrorIconButtonList = new ArrayList<>();
protected List<GuiNumberField> mirrorNumberFieldList = new ArrayList<>(); protected List<GuiNumberField> mirrorNumberFieldList = new ArrayList<>();
private GuiNumberField textMirrorPosX, textMirrorPosY, textMirrorPosZ, textMirrorRadius; private GuiNumberField textMirrorPosX, textMirrorPosY, textMirrorPosZ, textMirrorRadius;
private GuiCheckBox buttonMirrorEnabled, buttonMirrorX, buttonMirrorY, buttonMirrorZ; private GuiCheckBoxFixed buttonMirrorEnabled, buttonMirrorX, buttonMirrorY, buttonMirrorZ;
private GuiIconButton buttonCurrentPosition, buttonToggleOdd, buttonDrawPlanes, buttonDrawLines; private GuiIconButton buttonCurrentPosition, buttonToggleOdd, buttonDrawPlanes, buttonDrawLines;
private boolean drawPlanes, drawLines, toggleOdd; private boolean drawPlanes, drawLines, toggleOdd;
@@ -38,42 +38,48 @@ public class MirrorSettingsGui extends GuiCollapsibleScrollEntry {
} }
@Override @Override
public int initGui(int id, List<GuiButton> buttonList) { public void init(List<Widget> buttonList) {
id = super.initGui(id, buttonList); super.init(buttonList);
int y = top - 2; int y = top - 2;
buttonMirrorEnabled = new GuiCheckBox(id++, left - 15 + 8, y, "", false); buttonMirrorEnabled = new GuiCheckBoxFixed(left - 15 + 8, y, "", false) {
@Override
public void onClick(double mouseX, double mouseY) {
super.onClick(mouseX, mouseY);
setCollapsed(!buttonMirrorEnabled.isChecked());
}
};
buttonList.add(buttonMirrorEnabled); buttonList.add(buttonMirrorEnabled);
y = top + 18; y = top + 18;
textMirrorPosX = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 58, y, 62, 18); textMirrorPosX = new GuiNumberField(font, buttonList, left + 58, y, 62, 18);
textMirrorPosX.setNumber(0); textMirrorPosX.setNumber(0);
textMirrorPosX.setTooltip( textMirrorPosX.setTooltip(
Arrays.asList("The position of the mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5.")); Arrays.asList("The position of the mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5."));
mirrorNumberFieldList.add(textMirrorPosX); mirrorNumberFieldList.add(textMirrorPosX);
textMirrorPosY = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 138, y, 62, 18); textMirrorPosY = new GuiNumberField(font, buttonList, left + 138, y, 62, 18);
textMirrorPosY.setNumber(64); textMirrorPosY.setNumber(64);
textMirrorPosY.setTooltip(Arrays.asList("The position of the mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5.")); textMirrorPosY.setTooltip(Arrays.asList("The position of the mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5."));
mirrorNumberFieldList.add(textMirrorPosY); mirrorNumberFieldList.add(textMirrorPosY);
textMirrorPosZ = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 218, y, 62, 18); textMirrorPosZ = new GuiNumberField(font, buttonList, left + 218, y, 62, 18);
textMirrorPosZ.setNumber(0); textMirrorPosZ.setNumber(0);
textMirrorPosZ.setTooltip(Arrays.asList("The position of the mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5.")); textMirrorPosZ.setTooltip(Arrays.asList("The position of the mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5."));
mirrorNumberFieldList.add(textMirrorPosZ); mirrorNumberFieldList.add(textMirrorPosZ);
y = top + 50; y = top + 50;
buttonMirrorX = new GuiCheckBox(id++, left + 60, y, " X", true); buttonMirrorX = new GuiCheckBoxFixed(left + 60, y, " X", true);
mirrorButtonList.add(buttonMirrorX); mirrorButtonList.add(buttonMirrorX);
buttonMirrorY = new GuiCheckBox(id++, left + 100, y, " Y", false); buttonMirrorY = new GuiCheckBoxFixed(left + 100, y, " Y", false);
mirrorButtonList.add(buttonMirrorY); mirrorButtonList.add(buttonMirrorY);
buttonMirrorZ = new GuiCheckBox(id++, left + 140, y, " Z", false); buttonMirrorZ = new GuiCheckBoxFixed(left + 140, y, " Z", false);
mirrorButtonList.add(buttonMirrorZ); mirrorButtonList.add(buttonMirrorZ);
y = top + 47; y = top + 47;
textMirrorRadius = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 218, y, 62, 18); textMirrorRadius = new GuiNumberField(font, buttonList, left + 218, y, 62, 18);
textMirrorRadius.setNumber(50); textMirrorRadius.setNumber(50);
//TODO change to diameter (remove /2) //TODO change to diameter (remove /2)
textMirrorRadius.setTooltip(Arrays.asList("How far the mirror reaches in any direction.", textMirrorRadius.setTooltip(Arrays.asList("How far the mirror reaches in any direction.",
@@ -82,19 +88,46 @@ public class MirrorSettingsGui extends GuiCollapsibleScrollEntry {
mirrorNumberFieldList.add(textMirrorRadius); mirrorNumberFieldList.add(textMirrorRadius);
y = top + 72; y = top + 72;
buttonCurrentPosition = new GuiIconButton(id++, left + 5, y, 0, 0, BUILDING_ICONS); buttonCurrentPosition = new GuiIconButton(left + 5, y, 0, 0, BUILDING_ICONS, button -> {
Vec3d pos = new Vec3d(Math.floor(mc.player.getPosX()) + 0.5, Math.floor(mc.player.getPosY()) + 0.5, Math.floor(mc.player.getPosZ()) + 0.5);
textMirrorPosX.setNumber(pos.x);
textMirrorPosY.setNumber(pos.y);
textMirrorPosZ.setNumber(pos.z);
});
buttonCurrentPosition.setTooltip("Set mirror position to current player position"); buttonCurrentPosition.setTooltip("Set mirror position to current player position");
mirrorIconButtonList.add(buttonCurrentPosition); mirrorIconButtonList.add(buttonCurrentPosition);
buttonToggleOdd = new GuiIconButton(id++, left + 35, y, 0, 20, BUILDING_ICONS); buttonToggleOdd = new GuiIconButton(left + 35, y, 0, 20, BUILDING_ICONS, button -> {
toggleOdd = !toggleOdd;
buttonToggleOdd.setUseAlternateIcon(toggleOdd);
if (toggleOdd) {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to corner of block", "for even numbered builds"));
textMirrorPosX.setNumber(textMirrorPosX.getNumber() + 0.5);
textMirrorPosY.setNumber(textMirrorPosY.getNumber() + 0.5);
textMirrorPosZ.setNumber(textMirrorPosZ.getNumber() + 0.5);
} else {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to middle of block", "for odd numbered builds"));
textMirrorPosX.setNumber(Math.floor(textMirrorPosX.getNumber()));
textMirrorPosY.setNumber(Math.floor(textMirrorPosY.getNumber()));
textMirrorPosZ.setNumber(Math.floor(textMirrorPosZ.getNumber()));
}
});
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to middle of block", "for odd numbered builds")); buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to middle of block", "for odd numbered builds"));
mirrorIconButtonList.add(buttonToggleOdd); mirrorIconButtonList.add(buttonToggleOdd);
buttonDrawLines = new GuiIconButton(id++, left + 65, y, 0, 40, BUILDING_ICONS); buttonDrawLines = new GuiIconButton(left + 65, y, 0, 40, BUILDING_ICONS, button -> {
drawLines = !drawLines;
buttonDrawLines.setUseAlternateIcon(drawLines);
buttonDrawLines.setTooltip(drawLines ? "Hide lines" : "Show lines");
});
buttonDrawLines.setTooltip("Show lines"); buttonDrawLines.setTooltip("Show lines");
mirrorIconButtonList.add(buttonDrawLines); mirrorIconButtonList.add(buttonDrawLines);
buttonDrawPlanes = new GuiIconButton(id++, left + 95, y, 0, 60, BUILDING_ICONS); buttonDrawPlanes = new GuiIconButton(left + 95, y, 0, 60, BUILDING_ICONS, button -> {
drawPlanes = !drawPlanes;
buttonDrawPlanes.setUseAlternateIcon(drawPlanes);
buttonDrawPlanes.setTooltip(drawPlanes ? "Hide area" : "Show area");
});
buttonDrawPlanes.setTooltip("Show area"); buttonDrawPlanes.setTooltip("Show area");
mirrorIconButtonList.add(buttonDrawPlanes); mirrorIconButtonList.add(buttonDrawPlanes);
@@ -129,8 +162,6 @@ public class MirrorSettingsGui extends GuiCollapsibleScrollEntry {
buttonList.addAll(mirrorIconButtonList); buttonList.addAll(mirrorIconButtonList);
setCollapsed(!buttonMirrorEnabled.isChecked()); setCollapsed(!buttonMirrorEnabled.isChecked());
return id;
} }
@Override @Override
@@ -142,31 +173,30 @@ public class MirrorSettingsGui extends GuiCollapsibleScrollEntry {
@Override @Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY,
boolean isSelected, float partialTicks) { boolean isSelected, float partialTicks) {
super.drawEntry(slotIndex, x, y, listWidth, slotHeight, mouseX, mouseY, isSelected, partialTicks);
int yy = y; int yy = y;
int offset = 8; int offset = 8;
buttonMirrorEnabled.drawButton(this.mc, mouseX, mouseY, partialTicks); buttonMirrorEnabled.render(mouseX, mouseY, partialTicks);
if (buttonMirrorEnabled.isChecked()) { if (buttonMirrorEnabled.isChecked()) {
buttonMirrorEnabled.y = yy; buttonMirrorEnabled.y = yy;
fontRenderer.drawString("Mirror enabled", left + offset, yy + 2, 0xFFFFFF, true); font.drawString("Mirror enabled", left + offset, yy + 2, 0xFFFFFF);
yy = y + 18; yy = y + 18;
fontRenderer.drawString("Position", left + offset, yy + 5, 0xFFFFFF, true); font.drawString("Position", left + offset, yy + 5, 0xFFFFFF);
fontRenderer.drawString("X", left + 40 + offset, yy + 5, 0xFFFFFF, true); font.drawString("X", left + 40 + offset, yy + 5, 0xFFFFFF);
textMirrorPosX.y = yy; textMirrorPosX.y = yy;
fontRenderer.drawString("Y", left + 120 + offset, yy + 5, 0xFFFFFF, true); font.drawString("Y", left + 120 + offset, yy + 5, 0xFFFFFF);
textMirrorPosY.y = yy; textMirrorPosY.y = yy;
fontRenderer.drawString("Z", left + 200 + offset, yy + 5, 0xFFFFFF, true); font.drawString("Z", left + 200 + offset, yy + 5, 0xFFFFFF);
textMirrorPosZ.y = yy; textMirrorPosZ.y = yy;
yy = y + 50; yy = y + 50;
fontRenderer.drawString("Direction", left + offset, yy + 2, 0xFFFFFF, true); font.drawString("Direction", left + offset, yy + 2, 0xFFFFFF);
buttonMirrorX.y = yy; buttonMirrorX.y = yy;
buttonMirrorY.y = yy; buttonMirrorY.y = yy;
buttonMirrorZ.y = yy; buttonMirrorZ.y = yy;
fontRenderer.drawString("Radius", left + 176 + offset, yy + 2, 0xFFFFFF, true); font.drawString("Radius", left + 176 + offset, yy + 2, 0xFFFFFF);
textMirrorRadius.y = yy - 3; textMirrorRadius.y = yy - 3;
yy = y + 72; yy = y + 72;
@@ -175,17 +205,17 @@ public class MirrorSettingsGui extends GuiCollapsibleScrollEntry {
buttonDrawLines.y = yy; buttonDrawLines.y = yy;
buttonDrawPlanes.y = yy; buttonDrawPlanes.y = yy;
mirrorButtonList.forEach(button -> button.drawButton(this.mc, mouseX, mouseY, partialTicks)); mirrorButtonList.forEach(button -> button.render(mouseX, mouseY, partialTicks));
mirrorIconButtonList.forEach(button -> button.drawButton(this.mc, mouseX, mouseY, partialTicks)); mirrorIconButtonList.forEach(button -> button.render(mouseX, mouseY, partialTicks));
mirrorNumberFieldList.forEach(numberField -> numberField.drawNumberField(this.mc, mouseX, mouseY, partialTicks)); mirrorNumberFieldList.forEach(numberField -> numberField.drawNumberField(mouseX, mouseY, partialTicks));
} else { } else {
buttonMirrorEnabled.y = yy; buttonMirrorEnabled.y = yy;
fontRenderer.drawString("Mirror disabled", left + offset, yy + 2, 0x999999, true); font.drawString("Mirror disabled", left + offset, yy + 2, 0x999999);
} }
} }
public void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY) { public void drawTooltip(Screen guiScreen, int mouseX, int mouseY) {
//Draw tooltips last //Draw tooltips last
if (buttonMirrorEnabled.isChecked()) if (buttonMirrorEnabled.isChecked())
{ {
@@ -195,74 +225,28 @@ public class MirrorSettingsGui extends GuiCollapsibleScrollEntry {
} }
@Override @Override
public void updatePosition(int slotIndex, int x, int y, float partialTicks) { public boolean charTyped(char typedChar, int keyCode) {
super.updatePosition(slotIndex, x, y, partialTicks); super.charTyped(typedChar, keyCode);
}
@Override
public void keyTyped(char typedChar, int keyCode) throws IOException {
super.keyTyped(typedChar, keyCode);
for (GuiNumberField numberField : mirrorNumberFieldList) { for (GuiNumberField numberField : mirrorNumberFieldList) {
numberField.keyTyped(typedChar, keyCode); numberField.charTyped(typedChar, keyCode);
} }
return true;
} }
@Override @Override
public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) { public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) {
super.mousePressed(slotIndex, mouseX, mouseY, mouseEvent, relativeX, relativeY);
mirrorNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent)); mirrorNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent));
boolean insideMirrorEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12; boolean insideMirrorEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12;
if (insideMirrorEnabledLabel) { if (insideMirrorEnabledLabel) {
buttonMirrorEnabled.setIsChecked(!buttonMirrorEnabled.isChecked()); buttonMirrorEnabled.playDownSound(this.mc.getSoundHandler());
buttonMirrorEnabled.playPressSound(this.mc.getSoundHandler()); buttonMirrorEnabled.onClick(mouseX, mouseY);
actionPerformed(buttonMirrorEnabled);
} }
return true; return true;
} }
@Override
public void actionPerformed(GuiButton button) {
super.actionPerformed(button);
if (button == buttonMirrorEnabled) {
setCollapsed(!buttonMirrorEnabled.isChecked());
}
if (button == buttonCurrentPosition) {
Vec3d pos = new Vec3d(Math.floor(mc.player.posX) + 0.5, Math.floor(mc.player.posY) + 0.5, Math.floor(mc.player.posZ) + 0.5);
textMirrorPosX.setNumber(pos.x);
textMirrorPosY.setNumber(pos.y);
textMirrorPosZ.setNumber(pos.z);
}
if (button == buttonToggleOdd) {
toggleOdd = !toggleOdd;
buttonToggleOdd.setUseAlternateIcon(toggleOdd);
if (toggleOdd) {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to corner of block", "for even numbered builds"));
textMirrorPosX.setNumber(textMirrorPosX.getNumber() + 0.5);
textMirrorPosY.setNumber(textMirrorPosY.getNumber() + 0.5);
textMirrorPosZ.setNumber(textMirrorPosZ.getNumber() + 0.5);
} else {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to middle of block", "for odd numbered builds"));
textMirrorPosX.setNumber(Math.floor(textMirrorPosX.getNumber()));
textMirrorPosY.setNumber(Math.floor(textMirrorPosY.getNumber()));
textMirrorPosZ.setNumber(Math.floor(textMirrorPosZ.getNumber()));
}
}
if (button == buttonDrawLines) {
drawLines = !drawLines;
buttonDrawLines.setUseAlternateIcon(drawLines);
buttonDrawLines.setTooltip(drawLines ? "Hide lines" : "Show lines");
}
if (button == buttonDrawPlanes) {
drawPlanes = !drawPlanes;
buttonDrawPlanes.setUseAlternateIcon(drawPlanes);
buttonDrawPlanes.setTooltip(drawPlanes ? "Hide area" : "Show area");
}
mirrorNumberFieldList.forEach(numberField -> numberField.actionPerformed(button));
}
public Mirror.MirrorSettings getMirrorSettings() { public Mirror.MirrorSettings getMirrorSettings() {
boolean mirrorEnabled = buttonMirrorEnabled.isChecked(); boolean mirrorEnabled = buttonMirrorEnabled.isChecked();

View File

@@ -1,7 +1,12 @@
package nl.requios.effortlessbuilding.gui.buildmodifier; package nl.requios.effortlessbuilding.gui.buildmodifier;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.Array; import nl.requios.effortlessbuilding.buildmodifier.Array;
import nl.requios.effortlessbuilding.buildmodifier.Mirror; import nl.requios.effortlessbuilding.buildmodifier.Mirror;
@@ -9,89 +14,97 @@ import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.RadialMirror; import nl.requios.effortlessbuilding.buildmodifier.RadialMirror;
import nl.requios.effortlessbuilding.gui.elements.GuiScrollPane; import nl.requios.effortlessbuilding.gui.elements.GuiScrollPane;
import nl.requios.effortlessbuilding.network.ModifierSettingsMessage; import nl.requios.effortlessbuilding.network.ModifierSettingsMessage;
import nl.requios.effortlessbuilding.network.PacketHandler;
import nl.requios.effortlessbuilding.proxy.ClientProxy; import nl.requios.effortlessbuilding.proxy.ClientProxy;
import java.io.IOException; @OnlyIn(Dist.CLIENT)
public class ModifierSettingsGui extends Screen {
public class ModifierSettingsGui extends GuiScreen {
private GuiScrollPane scrollPane; private GuiScrollPane scrollPane;
private GuiButton buttonClose; private Button buttonClose;
private MirrorSettingsGui mirrorSettingsGui; private MirrorSettingsGui mirrorSettingsGui;
private ArraySettingsGui arraySettingsGui; private ArraySettingsGui arraySettingsGui;
private RadialMirrorSettingsGui radialMirrorSettingsGui; private RadialMirrorSettingsGui radialMirrorSettingsGui;
public ModifierSettingsGui() {
super(new TranslationTextComponent("effortlessbuilding.screen.modifier_settings"));
}
@Override @Override
//Create buttons and labels and add them to buttonList/labelList //Create buttons and labels and add them to buttonList/labelList
public void initGui() { protected void init() {
int id = 0; scrollPane = new GuiScrollPane(this, font, 8, height - 30);
scrollPane = new GuiScrollPane(this, fontRenderer, 8, height - 30);
mirrorSettingsGui = new MirrorSettingsGui(scrollPane); mirrorSettingsGui = new MirrorSettingsGui(scrollPane);
scrollPane.listEntries.add(mirrorSettingsGui); scrollPane.AddListEntry(mirrorSettingsGui);
arraySettingsGui = new ArraySettingsGui(scrollPane); arraySettingsGui = new ArraySettingsGui(scrollPane);
scrollPane.listEntries.add(arraySettingsGui); scrollPane.AddListEntry(arraySettingsGui);
radialMirrorSettingsGui = new RadialMirrorSettingsGui(scrollPane); radialMirrorSettingsGui = new RadialMirrorSettingsGui(scrollPane);
scrollPane.listEntries.add(radialMirrorSettingsGui); scrollPane.AddListEntry(radialMirrorSettingsGui);
id = scrollPane.initGui(id, buttonList); scrollPane.init(buttons);
//Close button //Close button
int y = height - 26; int y = height - 26;
buttonClose = new GuiButton(id++, width / 2 - 100, y, "Close"); buttonClose = new Button(width / 2 - 100, y, 200, 20, "Close", (button) -> {
buttonList.add(buttonClose); Minecraft.getInstance().player.closeScreen();
});
buttons.add(buttonClose);
} }
@Override @Override
//Process general logic, i.e. hide buttons //Process general logic, i.e. hide buttons
public void updateScreen() { public void tick() {
scrollPane.updateScreen(); scrollPane.updateScreen();
handleMouseInput();
} }
@Override @Override
//Set colors using GL11, use the fontRendererObj field to display text //Set colors using GL11, use the fontObj field to display text
//Use drawTexturedModalRect() to transfers areas of a texture resource to the screen //Use drawTexturedModalRect() to transfers areas of a texture resource to the screen
public void drawScreen(int mouseX, int mouseY, float partialTicks) { public void render(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground(); this.renderBackground();
scrollPane.drawScreen(mouseX, mouseY, partialTicks); scrollPane.render(mouseX, mouseY, partialTicks);
buttonClose.drawButton(this.mc, mouseX, mouseY, partialTicks); buttonClose.render(mouseX, mouseY, partialTicks);
scrollPane.drawTooltip(this, mouseX, mouseY); scrollPane.drawTooltip(this, mouseX, mouseY);
} }
@Override @Override
protected void keyTyped(char typedChar, int keyCode) throws IOException { public boolean charTyped(char typedChar, int keyCode) {
super.keyTyped(typedChar, keyCode); super.charTyped(typedChar, keyCode);
scrollPane.keyTyped(typedChar, keyCode); scrollPane.charTyped(typedChar, keyCode);
if (keyCode == ClientProxy.keyBindings[0].getKeyCode()) { if (keyCode == ClientProxy.keyBindings[0].getKey().getKeyCode()) {
mc.player.closeScreen(); minecraft.player.closeScreen();
} }
return false;
} }
@Override @Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
super.mouseClicked(mouseX, mouseY, mouseButton); super.mouseClicked(mouseX, mouseY, mouseButton);
scrollPane.mouseClicked(mouseX, mouseY, mouseButton); buttons.forEach(button -> button.mouseClicked(mouseX, mouseY, mouseButton));
return scrollPane.mouseClicked(mouseX, mouseY, mouseButton);
} }
@Override @Override
protected void mouseReleased(int mouseX, int mouseY, int state) { public boolean mouseReleased(double mouseX, double mouseY, int state) {
if (state != 0 || !scrollPane.mouseReleased(mouseX, mouseY, state)) if (state != 0 || !scrollPane.mouseReleased(mouseX, mouseY, state))
{ {
super.mouseReleased(mouseX, mouseY, state); return super.mouseReleased(mouseX, mouseY, state);
} }
return false;
} }
@Override public void handleMouseInput() {
public void handleMouseInput() throws IOException { //super.handleMouseInput();
super.handleMouseInput();
scrollPane.handleMouseInput(); scrollPane.handleMouseInput();
//Scrolling numbers //Scrolling numbers
@@ -101,16 +114,7 @@ public class ModifierSettingsGui extends GuiScreen {
} }
@Override @Override
protected void actionPerformed(GuiButton button) { public void removed() {
//check what button and action type (left/right click)
if (button == buttonClose) {
mc.player.closeScreen();
}
scrollPane.actionPerformed(button);
}
@Override
public void onGuiClosed() {
scrollPane.onGuiClosed(); scrollPane.onGuiClosed();
//save everything //save everything
@@ -118,20 +122,22 @@ public class ModifierSettingsGui extends GuiScreen {
Array.ArraySettings a = arraySettingsGui.getArraySettings(); Array.ArraySettings a = arraySettingsGui.getArraySettings();
RadialMirror.RadialMirrorSettings r = radialMirrorSettingsGui.getRadialMirrorSettings(); RadialMirror.RadialMirrorSettings r = radialMirrorSettingsGui.getRadialMirrorSettings();
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(mc.player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(minecraft.player);
if (modifierSettings == null) modifierSettings = new ModifierSettingsManager.ModifierSettings(); if (modifierSettings == null) modifierSettings = new ModifierSettingsManager.ModifierSettings();
modifierSettings.setMirrorSettings(m); modifierSettings.setMirrorSettings(m);
modifierSettings.setArraySettings(a); modifierSettings.setArraySettings(a);
modifierSettings.setRadialMirrorSettings(r); modifierSettings.setRadialMirrorSettings(r);
//Sanitize //Sanitize
String error = ModifierSettingsManager.sanitize(modifierSettings, mc.player); String error = ModifierSettingsManager.sanitize(modifierSettings, minecraft.player);
if (!error.isEmpty()) EffortlessBuilding.log(mc.player, error); if (!error.isEmpty()) EffortlessBuilding.log(minecraft.player, error);
ModifierSettingsManager.setModifierSettings(mc.player, modifierSettings); ModifierSettingsManager.setModifierSettings(minecraft.player, modifierSettings);
//Send to server //Send to server
EffortlessBuilding.packetHandler.sendToServer(new ModifierSettingsMessage(modifierSettings)); PacketHandler.INSTANCE.sendToServer(new ModifierSettingsMessage(modifierSettings));
Minecraft.getInstance().mouseHelper.grabMouse();
} }
} }

View File

@@ -1,35 +1,35 @@
package nl.requios.effortlessbuilding.gui.buildmodifier; package nl.requios.effortlessbuilding.gui.buildmodifier;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.client.config.GuiCheckBox; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.RadialMirror; import nl.requios.effortlessbuilding.buildmodifier.RadialMirror;
import nl.requios.effortlessbuilding.gui.elements.GuiCollapsibleScrollEntry; import nl.requios.effortlessbuilding.gui.elements.*;
import nl.requios.effortlessbuilding.gui.elements.GuiIconButton;
import nl.requios.effortlessbuilding.gui.elements.GuiNumberField;
import nl.requios.effortlessbuilding.gui.elements.GuiScrollPane;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@SuppressWarnings("Duplicates")
@OnlyIn(Dist.CLIENT)
public class RadialMirrorSettingsGui extends GuiCollapsibleScrollEntry { public class RadialMirrorSettingsGui extends GuiCollapsibleScrollEntry {
protected static final ResourceLocation BUILDING_ICONS = new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/building_icons.png"); protected static final ResourceLocation BUILDING_ICONS = new ResourceLocation(EffortlessBuilding.MODID, "textures/gui/building_icons.png");
protected List<GuiButton> radialMirrorButtonList = new ArrayList<>(); protected List<Button> radialMirrorButtonList = new ArrayList<>();
protected List<GuiIconButton> radialMirrorIconButtonList = new ArrayList<>(); protected List<GuiIconButton> radialMirrorIconButtonList = new ArrayList<>();
protected List<GuiNumberField> radialMirrorNumberFieldList = new ArrayList<>(); protected List<GuiNumberField> radialMirrorNumberFieldList = new ArrayList<>();
private GuiNumberField textRadialMirrorPosX, textRadialMirrorPosY, textRadialMirrorPosZ, textRadialMirrorSlices, textRadialMirrorRadius; private GuiNumberField textRadialMirrorPosX, textRadialMirrorPosY, textRadialMirrorPosZ, textRadialMirrorSlices, textRadialMirrorRadius;
private GuiCheckBox buttonRadialMirrorEnabled, buttonRadialMirrorAlternate; private GuiCheckBoxFixed buttonRadialMirrorEnabled, buttonRadialMirrorAlternate;
private GuiIconButton buttonCurrentPosition, buttonToggleOdd, buttonDrawPlanes, buttonDrawLines; private GuiIconButton buttonCurrentPosition, buttonToggleOdd, buttonDrawPlanes, buttonDrawLines;
private boolean drawPlanes, drawLines, toggleOdd; private boolean drawPlanes, drawLines, toggleOdd;
@@ -38,37 +38,43 @@ public class RadialMirrorSettingsGui extends GuiCollapsibleScrollEntry {
} }
@Override @Override
public int initGui(int id, List<GuiButton> buttonList) { public void init(List<Widget> buttonList) {
id = super.initGui(id, buttonList); super.init(buttonList);
int y = top - 2; int y = top - 2;
buttonRadialMirrorEnabled = new GuiCheckBox(id++, left - 15 + 8, y, "", false); buttonRadialMirrorEnabled = new GuiCheckBoxFixed(left - 15 + 8, y, "", false) {
@Override
public void onClick(double mouseX, double mouseY) {
super.onClick(mouseX, mouseY);
setCollapsed(!buttonRadialMirrorEnabled.isChecked());
}
};
buttonList.add(buttonRadialMirrorEnabled); buttonList.add(buttonRadialMirrorEnabled);
y = top + 18; y = top + 18;
textRadialMirrorPosX = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 58, y, 62, 18); textRadialMirrorPosX = new GuiNumberField(font, buttonList, left + 58, y, 62, 18);
textRadialMirrorPosX.setNumber(0); textRadialMirrorPosX.setNumber(0);
textRadialMirrorPosX.setTooltip( textRadialMirrorPosX.setTooltip(
Arrays.asList("The position of the radial mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5.")); Arrays.asList("The position of the radial mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5."));
radialMirrorNumberFieldList.add(textRadialMirrorPosX); radialMirrorNumberFieldList.add(textRadialMirrorPosX);
textRadialMirrorPosY = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 138, y, 62, 18); textRadialMirrorPosY = new GuiNumberField(font, buttonList, left + 138, y, 62, 18);
textRadialMirrorPosY.setNumber(64); textRadialMirrorPosY.setNumber(64);
textRadialMirrorPosY.setTooltip(Arrays.asList("The position of the radial mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5.")); textRadialMirrorPosY.setTooltip(Arrays.asList("The position of the radial mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5."));
radialMirrorNumberFieldList.add(textRadialMirrorPosY); radialMirrorNumberFieldList.add(textRadialMirrorPosY);
textRadialMirrorPosZ = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 218, y, 62, 18); textRadialMirrorPosZ = new GuiNumberField(font, buttonList, left + 218, y, 62, 18);
textRadialMirrorPosZ.setNumber(0); textRadialMirrorPosZ.setNumber(0);
textRadialMirrorPosZ.setTooltip(Arrays.asList("The position of the radial mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5.")); textRadialMirrorPosZ.setTooltip(Arrays.asList("The position of the radial mirror.", TextFormatting.GRAY + "For odd numbered builds add 0.5."));
radialMirrorNumberFieldList.add(textRadialMirrorPosZ); radialMirrorNumberFieldList.add(textRadialMirrorPosZ);
y = top + 47; y = top + 47;
textRadialMirrorSlices = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 55, y, 50, 18); textRadialMirrorSlices = new GuiNumberField(font, buttonList, left + 55, y, 50, 18);
textRadialMirrorSlices.setNumber(4); textRadialMirrorSlices.setNumber(4);
textRadialMirrorSlices.setTooltip(Arrays.asList("The number of repeating slices.", TextFormatting.GRAY + "Minimally 2.")); textRadialMirrorSlices.setTooltip(Arrays.asList("The number of repeating slices.", TextFormatting.GRAY + "Minimally 2."));
radialMirrorNumberFieldList.add(textRadialMirrorSlices); radialMirrorNumberFieldList.add(textRadialMirrorSlices);
textRadialMirrorRadius = new GuiNumberField(id++, id++, id++, fontRenderer, buttonList, left + 218, y, 62, 18); textRadialMirrorRadius = new GuiNumberField(font, buttonList, left + 218, y, 62, 18);
textRadialMirrorRadius.setNumber(50); textRadialMirrorRadius.setNumber(50);
//TODO change to diameter (remove /2) //TODO change to diameter (remove /2)
textRadialMirrorRadius.setTooltip(Arrays.asList("How far the radial mirror reaches from its center position.", textRadialMirrorRadius.setTooltip(Arrays.asList("How far the radial mirror reaches from its center position.",
@@ -76,26 +82,52 @@ public class RadialMirrorSettingsGui extends GuiCollapsibleScrollEntry {
TextFormatting.GRAY + "Upgradeable in survival with reach upgrades.")); TextFormatting.GRAY + "Upgradeable in survival with reach upgrades."));
radialMirrorNumberFieldList.add(textRadialMirrorRadius); radialMirrorNumberFieldList.add(textRadialMirrorRadius);
y = top + 72; y = top + 72;
buttonCurrentPosition = new GuiIconButton(id++, left + 5, y, 0, 0, BUILDING_ICONS); buttonCurrentPosition = new GuiIconButton(left + 5, y, 0, 0, BUILDING_ICONS, button -> {
Vec3d pos = new Vec3d(Math.floor(mc.player.getPosX()) + 0.5, Math.floor(mc.player.getPosY()) + 0.5, Math.floor(mc.player.getPosZ()) + 0.5);
textRadialMirrorPosX.setNumber(pos.x);
textRadialMirrorPosY.setNumber(pos.y);
textRadialMirrorPosZ.setNumber(pos.z);
});
buttonCurrentPosition.setTooltip("Set radial mirror position to current player position"); buttonCurrentPosition.setTooltip("Set radial mirror position to current player position");
radialMirrorIconButtonList.add(buttonCurrentPosition); radialMirrorIconButtonList.add(buttonCurrentPosition);
buttonToggleOdd = new GuiIconButton(id++, left + 35, y, 0, 20, BUILDING_ICONS); buttonToggleOdd = new GuiIconButton(left + 35, y, 0, 20, BUILDING_ICONS, button -> {
toggleOdd = !toggleOdd;
buttonToggleOdd.setUseAlternateIcon(toggleOdd);
if (toggleOdd) {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to corner of block", "for even numbered builds"));
textRadialMirrorPosX.setNumber(textRadialMirrorPosX.getNumber() + 0.5);
textRadialMirrorPosY.setNumber(textRadialMirrorPosY.getNumber() + 0.5);
textRadialMirrorPosZ.setNumber(textRadialMirrorPosZ.getNumber() + 0.5);
} else {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to middle of block", "for odd numbered builds"));
textRadialMirrorPosX.setNumber(Math.floor(textRadialMirrorPosX.getNumber()));
textRadialMirrorPosY.setNumber(Math.floor(textRadialMirrorPosY.getNumber()));
textRadialMirrorPosZ.setNumber(Math.floor(textRadialMirrorPosZ.getNumber()));
}
});
buttonToggleOdd.setTooltip(Arrays.asList("Set radial mirror position to middle of block", "for odd numbered builds")); buttonToggleOdd.setTooltip(Arrays.asList("Set radial mirror position to middle of block", "for odd numbered builds"));
radialMirrorIconButtonList.add(buttonToggleOdd); radialMirrorIconButtonList.add(buttonToggleOdd);
buttonDrawLines = new GuiIconButton(id++, left + 65, y, 0, 40, BUILDING_ICONS); buttonDrawLines = new GuiIconButton(left + 65, y, 0, 40, BUILDING_ICONS, button -> {
drawLines = !drawLines;
buttonDrawLines.setUseAlternateIcon(drawLines);
buttonDrawLines.setTooltip(drawLines ? "Hide lines" : "Show lines");
});
buttonDrawLines.setTooltip("Show lines"); buttonDrawLines.setTooltip("Show lines");
radialMirrorIconButtonList.add(buttonDrawLines); radialMirrorIconButtonList.add(buttonDrawLines);
buttonDrawPlanes = new GuiIconButton(id++, left + 95, y, 0, 60, BUILDING_ICONS); buttonDrawPlanes = new GuiIconButton(left + 95, y, 0, 60, BUILDING_ICONS, button -> {
drawPlanes = !drawPlanes;
buttonDrawPlanes.setUseAlternateIcon(drawPlanes);
buttonDrawPlanes.setTooltip(drawPlanes ? "Hide area" : "Show area");
});
buttonDrawPlanes.setTooltip("Show area"); buttonDrawPlanes.setTooltip("Show area");
radialMirrorIconButtonList.add(buttonDrawPlanes); radialMirrorIconButtonList.add(buttonDrawPlanes);
y = top + 76; y = top + 76;
buttonRadialMirrorAlternate = new GuiCheckBox(id++, left + 140, y, " Alternate", false); buttonRadialMirrorAlternate = new GuiCheckBoxFixed(left + 140, y, " Alternate", false);
radialMirrorButtonList.add(buttonRadialMirrorAlternate); radialMirrorButtonList.add(buttonRadialMirrorAlternate);
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(mc.player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(mc.player);
@@ -128,42 +160,38 @@ public class RadialMirrorSettingsGui extends GuiCollapsibleScrollEntry {
buttonList.addAll(radialMirrorIconButtonList); buttonList.addAll(radialMirrorIconButtonList);
setCollapsed(!buttonRadialMirrorEnabled.isChecked()); setCollapsed(!buttonRadialMirrorEnabled.isChecked());
return id;
} }
@Override
public void updateScreen() { public void updateScreen() {
super.updateScreen();
radialMirrorNumberFieldList.forEach(GuiNumberField::update); radialMirrorNumberFieldList.forEach(GuiNumberField::update);
} }
@Override @Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY,
boolean isSelected, float partialTicks) { boolean isSelected, float partialTicks) {
super.drawEntry(slotIndex, x, y, listWidth, slotHeight, mouseX, mouseY, isSelected, partialTicks);
int yy = y; int yy = y;
int offset = 8; int offset = 8;
buttonRadialMirrorEnabled.drawButton(this.mc, mouseX, mouseY, partialTicks); buttonRadialMirrorEnabled.render(mouseX, mouseY, partialTicks);
if (buttonRadialMirrorEnabled.isChecked()) { if (buttonRadialMirrorEnabled.isChecked()) {
buttonRadialMirrorEnabled.y = yy; buttonRadialMirrorEnabled.y = yy;
fontRenderer.drawString("Radial mirror enabled", left + offset, yy + 2, 0xFFFFFF, true); font.drawString("Radial mirror enabled", left + offset, yy + 2, 0xFFFFFF);
yy = y + 18; yy = y + 18;
fontRenderer.drawString("Position", left + offset, yy + 5, 0xFFFFFF, true); font.drawString("Position", left + offset, yy + 5, 0xFFFFFF);
fontRenderer.drawString("X", left + 40 + offset, yy + 5, 0xFFFFFF, true); font.drawString("X", left + 40 + offset, yy + 5, 0xFFFFFF);
textRadialMirrorPosX.y = yy; textRadialMirrorPosX.y = yy;
fontRenderer.drawString("Y", left + 120 + offset, yy + 5, 0xFFFFFF, true); font.drawString("Y", left + 120 + offset, yy + 5, 0xFFFFFF);
textRadialMirrorPosY.y = yy; textRadialMirrorPosY.y = yy;
fontRenderer.drawString("Z", left + 200 + offset, yy + 5, 0xFFFFFF, true); font.drawString("Z", left + 200 + offset, yy + 5, 0xFFFFFF);
textRadialMirrorPosZ.y = yy; textRadialMirrorPosZ.y = yy;
yy = y + 50; yy = y + 50;
fontRenderer.drawString("Slices", left + offset, yy + 2, 0xFFFFFF, true); font.drawString("Slices", left + offset, yy + 2, 0xFFFFFF);
textRadialMirrorSlices.y = yy - 3; textRadialMirrorSlices.y = yy - 3;
fontRenderer.drawString("Radius", left + 176 + offset, yy + 2, 0xFFFFFF, true); font.drawString("Radius", left + 176 + offset, yy + 2, 0xFFFFFF);
textRadialMirrorRadius.y = yy - 3; textRadialMirrorRadius.y = yy - 3;
yy = y + 72; yy = y + 72;
@@ -175,18 +203,18 @@ public class RadialMirrorSettingsGui extends GuiCollapsibleScrollEntry {
yy = y + 76; yy = y + 76;
buttonRadialMirrorAlternate.y = yy; buttonRadialMirrorAlternate.y = yy;
radialMirrorButtonList.forEach(button -> button.drawButton(this.mc, mouseX, mouseY, partialTicks)); radialMirrorButtonList.forEach(button -> button.render(mouseX, mouseY, partialTicks));
radialMirrorIconButtonList.forEach(button -> button.drawButton(this.mc, mouseX, mouseY, partialTicks)); radialMirrorIconButtonList.forEach(button -> button.render(mouseX, mouseY, partialTicks));
radialMirrorNumberFieldList radialMirrorNumberFieldList
.forEach(numberField -> numberField.drawNumberField(this.mc, mouseX, mouseY, partialTicks)); .forEach(numberField -> numberField.drawNumberField(mouseX, mouseY, partialTicks));
} else { } else {
buttonRadialMirrorEnabled.y = yy; buttonRadialMirrorEnabled.y = yy;
fontRenderer.drawString("Radial mirror disabled", left + offset, yy + 2, 0x999999, true); font.drawString("Radial mirror disabled", left + offset, yy + 2, 0x999999);
} }
} }
public void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY) { public void drawTooltip(Screen guiScreen, int mouseX, int mouseY) {
//Draw tooltips last //Draw tooltips last
if (buttonRadialMirrorEnabled.isChecked()) if (buttonRadialMirrorEnabled.isChecked())
{ {
@@ -196,74 +224,28 @@ public class RadialMirrorSettingsGui extends GuiCollapsibleScrollEntry {
} }
@Override @Override
public void updatePosition(int slotIndex, int x, int y, float partialTicks) { public boolean charTyped(char typedChar, int keyCode) {
super.updatePosition(slotIndex, x, y, partialTicks); super.charTyped(typedChar, keyCode);
}
@Override
public void keyTyped(char typedChar, int keyCode) throws IOException {
super.keyTyped(typedChar, keyCode);
for (GuiNumberField numberField : radialMirrorNumberFieldList) { for (GuiNumberField numberField : radialMirrorNumberFieldList) {
numberField.keyTyped(typedChar, keyCode); numberField.charTyped(typedChar, keyCode);
} }
return true;
} }
@Override @Override
public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) { public boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY) {
super.mousePressed(slotIndex, mouseX, mouseY, mouseEvent, relativeX, relativeY);
radialMirrorNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent)); radialMirrorNumberFieldList.forEach(numberField -> numberField.mouseClicked(mouseX, mouseY, mouseEvent));
boolean insideRadialMirrorEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12; boolean insideRadialMirrorEnabledLabel = mouseX >= left && mouseX < right && relativeY >= -2 && relativeY < 12;
if (insideRadialMirrorEnabledLabel) { if (insideRadialMirrorEnabledLabel) {
buttonRadialMirrorEnabled.setIsChecked(!buttonRadialMirrorEnabled.isChecked()); buttonRadialMirrorEnabled.playDownSound(this.mc.getSoundHandler());
buttonRadialMirrorEnabled.playPressSound(this.mc.getSoundHandler()); buttonRadialMirrorEnabled.onClick(mouseX, mouseY);
actionPerformed(buttonRadialMirrorEnabled);
} }
return true; return true;
} }
@Override
public void actionPerformed(GuiButton button) {
super.actionPerformed(button);
if (button == buttonRadialMirrorEnabled) {
setCollapsed(!buttonRadialMirrorEnabled.isChecked());
}
if (button == buttonCurrentPosition) {
Vec3d pos = new Vec3d(Math.floor(mc.player.posX) + 0.5, Math.floor(mc.player.posY) + 0.5, Math.floor(mc.player.posZ) + 0.5);
textRadialMirrorPosX.setNumber(pos.x);
textRadialMirrorPosY.setNumber(pos.y);
textRadialMirrorPosZ.setNumber(pos.z);
}
if (button == buttonToggleOdd) {
toggleOdd = !toggleOdd;
buttonToggleOdd.setUseAlternateIcon(toggleOdd);
if (toggleOdd) {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to corner of block", "for even numbered builds"));
textRadialMirrorPosX.setNumber(textRadialMirrorPosX.getNumber() + 0.5);
textRadialMirrorPosY.setNumber(textRadialMirrorPosY.getNumber() + 0.5);
textRadialMirrorPosZ.setNumber(textRadialMirrorPosZ.getNumber() + 0.5);
} else {
buttonToggleOdd.setTooltip(Arrays.asList("Set mirror position to middle of block", "for odd numbered builds"));
textRadialMirrorPosX.setNumber(Math.floor(textRadialMirrorPosX.getNumber()));
textRadialMirrorPosY.setNumber(Math.floor(textRadialMirrorPosY.getNumber()));
textRadialMirrorPosZ.setNumber(Math.floor(textRadialMirrorPosZ.getNumber()));
}
}
if (button == buttonDrawLines) {
drawLines = !drawLines;
buttonDrawLines.setUseAlternateIcon(drawLines);
buttonDrawLines.setTooltip(drawLines ? "Hide lines" : "Show lines");
}
if (button == buttonDrawPlanes) {
drawPlanes = !drawPlanes;
buttonDrawPlanes.setUseAlternateIcon(drawPlanes);
buttonDrawPlanes.setTooltip(drawPlanes ? "Hide area" : "Show area");
}
radialMirrorNumberFieldList.forEach(numberField -> numberField.actionPerformed(button));
}
public RadialMirror.RadialMirrorSettings getRadialMirrorSettings() { public RadialMirror.RadialMirrorSettings getRadialMirrorSettings() {
boolean radialMirrorEnabled = buttonRadialMirrorEnabled.isChecked(); boolean radialMirrorEnabled = buttonRadialMirrorEnabled.isChecked();

View File

@@ -0,0 +1,66 @@
package nl.requios.effortlessbuilding.gui.elements;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraftforge.fml.client.gui.GuiUtils;
/**
* This class provides a checkbox style control.
*/
public class GuiCheckBoxFixed extends Button
{
private boolean isChecked;
private int boxWidth;
public GuiCheckBoxFixed(int xPos, int yPos, String displayString, boolean isChecked)
{
super(xPos, yPos, Minecraft.getInstance().fontRenderer.getStringWidth(displayString) + 2 + 11, 11, displayString, b -> {});
this.isChecked = isChecked;
this.boxWidth = 11;
this.height = 11;
this.width = this.boxWidth + 2 + Minecraft.getInstance().fontRenderer.getStringWidth(displayString);
}
@Override
public void renderButton(int mouseX, int mouseY, float partial)
{
if (this.visible)
{
Minecraft mc = Minecraft.getInstance();
this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.boxWidth && mouseY < this.y + this.height;
GuiUtils.drawContinuousTexturedBox(WIDGETS_LOCATION, this.x, this.y, 0, 46, this.boxWidth, this.height, 200, 20, 2, 3, 2, 2, this.getBlitOffset());
this.renderBg(mc, mouseX, mouseY);
int color = 14737632;
if (packedFGColor != 0)
{
color = packedFGColor;
}
else if (!this.active)
{
color = 10526880;
}
if (this.isChecked)
this.drawCenteredString(mc.fontRenderer, "x", this.x + this.boxWidth / 2 + 1, this.y + 1, 14737632);
this.drawString(mc.fontRenderer, getMessage(), this.x + this.boxWidth + 2, this.y + 2, color);
}
}
@Override
public void onPress()
{
this.isChecked = !this.isChecked;
}
public boolean isChecked()
{
return this.isChecked;
}
public void setIsChecked(boolean isChecked)
{
this.isChecked = isChecked;
}
}

View File

@@ -2,16 +2,19 @@ package nl.requios.effortlessbuilding.gui.elements;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.screen.Screen;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.io.IOException;
import java.util.List; import java.util.List;
@OnlyIn(Dist.CLIENT)
public abstract class GuiCollapsibleScrollEntry implements GuiScrollPane.IScrollEntry { public abstract class GuiCollapsibleScrollEntry implements GuiScrollPane.IScrollEntry {
public GuiScrollPane scrollPane; public GuiScrollPane scrollPane;
protected FontRenderer fontRenderer; protected FontRenderer font;
protected Minecraft mc; protected Minecraft mc;
protected boolean isCollapsed = true; protected boolean isCollapsed = true;
@@ -19,35 +22,24 @@ public abstract class GuiCollapsibleScrollEntry implements GuiScrollPane.IScroll
public GuiCollapsibleScrollEntry(GuiScrollPane scrollPane) { public GuiCollapsibleScrollEntry(GuiScrollPane scrollPane) {
this.scrollPane = scrollPane; this.scrollPane = scrollPane;
this.fontRenderer = scrollPane.fontRenderer; this.font = scrollPane.font;
this.mc = scrollPane.parent.mc; this.mc = Minecraft.getInstance();
} }
@Override @Override
public int initGui(int id, List<GuiButton> buttonList) { public void init(List<Widget> buttonList) {
left = scrollPane.getWidth() / 2 - 140;
left = scrollPane.width / 2 - 140; right = scrollPane.getWidth() / 2 + 140;
right = scrollPane.width / 2 + 140; top = scrollPane.getHeight() / 2 - 100;
top = scrollPane.height / 2 - 100; bottom = scrollPane.getHeight() / 2 + 100;
bottom = scrollPane.height / 2 + 100;
return id;
} }
@Override @Override
public void updateScreen() { public void updateScreen() {
} }
@Override @Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, public void drawTooltip(Screen guiScreen, int mouseX, int mouseY) {
boolean isSelected, float partialTicks) {
}
@Override
public void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY) {
} }
@Override @Override
@@ -56,8 +48,8 @@ public abstract class GuiCollapsibleScrollEntry implements GuiScrollPane.IScroll
} }
@Override @Override
public void keyTyped(char eventChar, int eventKey) throws IOException { public boolean charTyped(char eventChar, int eventKey) {
return false;
} }
@Override @Override
@@ -70,14 +62,8 @@ public abstract class GuiCollapsibleScrollEntry implements GuiScrollPane.IScroll
} }
@Override
public void actionPerformed(GuiButton button) {
}
@Override @Override
public void onGuiClosed() { public void onGuiClosed() {
} }
@Override @Override

View File

@@ -1,27 +1,30 @@
package nl.requios.effortlessbuilding.gui.elements; package nl.requios.effortlessbuilding.gui.elements;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class GuiIconButton extends GuiButton { @OnlyIn(Dist.CLIENT)
public class GuiIconButton extends Button {
private final ResourceLocation resourceLocation; private final ResourceLocation resourceLocation;
private final int iconX, iconY, iconWidth, iconHeight, iconAltX, iconAltY; private final int iconX, iconY, iconWidth, iconHeight, iconAltX, iconAltY;
List<String> tooltip = new ArrayList<>(); List<String> tooltip = new ArrayList<>();
private boolean useAltIcon = false; private boolean useAltIcon = false;
public GuiIconButton(int buttonId, int x, int y, int iconX, int iconY, ResourceLocation resourceLocation) { public GuiIconButton(int x, int y, int iconX, int iconY, ResourceLocation resourceLocation, Button.IPressable onPress) {
this(buttonId, x, y, 20, 20, iconX, iconY, 20, 20, 20, 0, resourceLocation); this(x, y, 20, 20, iconX, iconY, 20, 20, 20, 0, resourceLocation, onPress);
} }
public GuiIconButton(int buttonId, int x, int y, int width, int height, int iconX, int iconY, int iconWidth, int iconHeight, int iconAltX, int iconAltY, ResourceLocation resourceLocation) { public GuiIconButton(int x, int y, int width, int height, int iconX, int iconY, int iconWidth, int iconHeight, int iconAltX, int iconAltY, ResourceLocation resourceLocation, Button.IPressable onPress) {
super(buttonId, x, y, width, height, ""); super(x, y, width, height, "", onPress);
this.iconX = iconX; this.iconX = iconX;
this.iconY = iconY; this.iconY = iconY;
this.iconWidth = iconWidth; this.iconWidth = iconWidth;
@@ -44,12 +47,12 @@ public class GuiIconButton extends GuiButton {
} }
@Override @Override
public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks) { public void render(int mouseX, int mouseY, float partialTicks) {
super.drawButton(mc, mouseX, mouseY, partialTicks); super.render(mouseX, mouseY, partialTicks);
if (this.visible) if (this.visible)
{ {
this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height; this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
mc.getTextureManager().bindTexture(this.resourceLocation); Minecraft.getInstance().getTextureManager().bindTexture(this.resourceLocation);
int currentIconX = this.iconX; int currentIconX = this.iconX;
int currentIconY = this.iconY; int currentIconY = this.iconY;
@@ -59,17 +62,18 @@ public class GuiIconButton extends GuiButton {
currentIconY += iconAltY; currentIconY += iconAltY;
} }
this.drawTexturedModalRect(this.x, this.y, currentIconX, currentIconY, this.iconWidth, this.iconHeight); //Draws a textured rectangle at the current z-value. Used to be drawTexturedModalRect in Gui.
this.blit(this.x, this.y, currentIconX, currentIconY, this.iconWidth, this.iconHeight);
} }
} }
public void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY) { public void drawTooltip(Screen screen, int mouseX, int mouseY) {
boolean flag = mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height; boolean flag = mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height;
if (flag) { if (flag) {
List<String> textLines = new ArrayList<>(); List<String> textLines = new ArrayList<>();
textLines.addAll(tooltip); textLines.addAll(tooltip);
guiScreen.drawHoveringText(textLines, mouseX - 10, mouseY + 25); screen.renderTooltip(textLines, mouseX - 10, mouseY + 25);
} }
} }
} }

View File

@@ -1,48 +1,68 @@
package nl.requios.effortlessbuilding.gui.elements; package nl.requios.effortlessbuilding.gui.elements;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.*; import net.minecraft.client.gui.*;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.io.IOException;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
public class GuiNumberField extends Gui { @OnlyIn(Dist.CLIENT)
public class GuiNumberField extends AbstractGui {
public int x, y, width, height; public int x, y, width, height;
public int buttonWidth = 10; public int buttonWidth = 10;
protected GuiTextField textField; protected TextFieldWidget textField;
protected GuiButton minusButton, plusButton; protected Button minusButton, plusButton;
List<String> tooltip = new ArrayList<>(); List<String> tooltip = new ArrayList<>();
public GuiNumberField(int id1, int id2, int id3, FontRenderer fontRenderer, public GuiNumberField(FontRenderer font, List<Widget> buttonList, int x, int y, int width, int height) {
List<GuiButton> buttonList, int x, int y, int width, int height) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.width = width; this.width = width;
this.height = height; this.height = height;
textField = new GuiTextField(id1, fontRenderer, x + buttonWidth + 1, y + 1, width - 2 * buttonWidth - 2, height - 2); textField = new TextFieldWidget(font, x + buttonWidth + 1, y + 1, width - 2 * buttonWidth - 2, height - 2, "");
minusButton = new GuiButton(id2, x, y - 1, buttonWidth, height + 2, "-"); minusButton = new Button(x, y - 1, buttonWidth, height + 2, "-", button -> {
plusButton = new GuiButton(id3, x + width - buttonWidth, y - 1, buttonWidth, height + 2, "+"); float valueChanged = 1f;
if (Screen.hasControlDown()) valueChanged = 5f;
if (Screen.hasShiftDown()) valueChanged = 10f;
setNumber(getNumber() - valueChanged);
});
plusButton = new Button(x + width - buttonWidth, y - 1, buttonWidth, height + 2, "+", button -> {
float valueChanged = 1f;
if (Screen.hasControlDown()) valueChanged = 5f;
if (Screen.hasShiftDown()) valueChanged = 10f;
setNumber(getNumber() + valueChanged);
});
buttonList.add(minusButton); buttonList.add(minusButton);
buttonList.add(plusButton); buttonList.add(plusButton);
} }
public void setNumber(double number) { public void setNumber(double number) {
DecimalFormat format = new DecimalFormat("0.#"); textField.setText(DecimalFormat.getInstance().format(number));
textField.setText(format.format(number));
} }
public double getNumber() { public double getNumber() {
if (textField.getText().isEmpty()) return 0; if (textField.getText().isEmpty()) return 0;
return Double.parseDouble(textField.getText()); try {
return DecimalFormat.getInstance().parse(textField.getText()).doubleValue();
} catch (ParseException e) {
return 0;
}
} }
public void setTooltip(String tooltip) { public void setTooltip(String tooltip) {
@@ -53,7 +73,7 @@ public class GuiNumberField extends Gui {
this.tooltip = tooltip; this.tooltip = tooltip;
} }
public boolean mouseClicked(int mouseX, int mouseY, int mouseButton) { public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
boolean result = textField.mouseClicked(mouseX, mouseY, mouseButton); boolean result = textField.mouseClicked(mouseX, mouseY, mouseButton);
//Check if clicked inside textfield //Check if clicked inside textfield
@@ -62,24 +82,24 @@ public class GuiNumberField extends Gui {
//Rightclicked inside textfield //Rightclicked inside textfield
if (flag && mouseButton == 1) { if (flag && mouseButton == 1) {
textField.setText(""); textField.setText("");
textField.setFocused(true); textField.setFocused2(true);
result = true; result = true;
} }
return result; return result;
} }
public void drawNumberField(Minecraft mc, int mouseX, int mouseY, float partialTicks) { public void drawNumberField(int mouseX, int mouseY, float partialTicks) {
textField.y = y + 1; textField.y = y + 1;
minusButton.y = y - 1; minusButton.y = y - 1;
plusButton.y = y - 1; plusButton.y = y - 1;
textField.drawTextBox(); textField.render(mouseX, mouseY, partialTicks);
minusButton.drawButton(mc, mouseX, mouseY, partialTicks); minusButton.render(mouseX, mouseY, partialTicks);
plusButton.drawButton(mc, mouseX, mouseY, partialTicks); plusButton.render(mouseX, mouseY, partialTicks);
} }
public void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY) { public void drawTooltip(Screen screen, int mouseX, int mouseY) {
boolean insideTextField = mouseX >= x + buttonWidth && mouseX < x + width - buttonWidth && mouseY >= y && mouseY < y + height; boolean insideTextField = mouseX >= x + buttonWidth && mouseX < x + width - buttonWidth && mouseY >= y && mouseY < y + height;
boolean insideMinusButton = mouseX >= x && mouseX < x + buttonWidth && mouseY >= y && mouseY < y + height; boolean insideMinusButton = mouseX >= x && mouseX < x + buttonWidth && mouseY >= y && mouseY < y + height;
boolean insidePlusButton = mouseX >= x + width - buttonWidth && mouseX < x + width && mouseY >= y && mouseY < y + height; boolean insidePlusButton = mouseX >= x + width - buttonWidth && mouseX < x + width && mouseY >= y && mouseY < y + height;
@@ -102,37 +122,25 @@ public class GuiNumberField extends Gui {
textLines.add("Hold " + TextFormatting.AQUA + "ctrl " + TextFormatting.RESET + "for " + TextFormatting.DARK_GREEN + "5"); textLines.add("Hold " + TextFormatting.AQUA + "ctrl " + TextFormatting.RESET + "for " + TextFormatting.DARK_GREEN + "5");
} }
guiScreen.drawHoveringText(textLines, mouseX - 10, mouseY + 25); screen.renderTooltip(textLines, mouseX - 10, mouseY + 25);
} }
public void actionPerformed(GuiButton button) {
float valueChanged = 1f;
if (GuiScreen.isCtrlKeyDown()) valueChanged = 5f;
if (GuiScreen.isShiftKeyDown()) valueChanged = 10f;
if (button == minusButton) {
setNumber(getNumber() - valueChanged);
}
if (button == plusButton) {
setNumber(getNumber() + valueChanged);
}
}
public void update() { public void update() {
textField.updateCursorCounter(); textField.tick();
} }
public void keyTyped(char typedChar, int keyCode) throws IOException { public boolean charTyped(char typedChar, int keyCode) {
if (!textField.isFocused()) return; if (!textField.isFocused()) return false;
// if (Character.isDigit(typedChar) || typedChar == '.' || typedChar == '-' || keyCode == Keyboard.KEY_BACK // if (Character.isDigit(typedChar) || typedChar == '.' || typedChar == '-' || keyCode == Keyboard.KEY_BACK
// || keyCode == Keyboard.KEY_DELETE || keyCode == Keyboard.KEY_LEFT || keyCode == Keyboard.KEY_RIGHT // || keyCode == Keyboard.KEY_DELETE || keyCode == Keyboard.KEY_LEFT || keyCode == Keyboard.KEY_RIGHT
// || keyCode == Keyboard.KEY_UP || keyCode == Keyboard.KEY_DOWN) { // || keyCode == Keyboard.KEY_UP || keyCode == Keyboard.KEY_DOWN) {
textField.textboxKeyTyped(typedChar, keyCode); return textField.charTyped(typedChar, keyCode);
// } // }
} }
//Scroll inside textfield to change number //Scroll inside textfield to change number
//Disabled because entire screen can be scrolled
// public void handleMouseInput(int mouseX, int mouseY) { // public void handleMouseInput(int mouseX, int mouseY) {
// boolean insideTextField = mouseX >= x + buttonWidth && mouseX < x + width - buttonWidth && mouseY >= y && mouseY < y + height; // boolean insideTextField = mouseX >= x + buttonWidth && mouseX < x + width - buttonWidth && mouseY >= y && mouseY < y + height;
// //

View File

@@ -1,186 +1,186 @@
package nl.requios.effortlessbuilding.gui.elements; package nl.requios.effortlessbuilding.gui.elements;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.*;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.GuiListExtended; import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Mouse;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@SideOnly(Side.CLIENT) @OnlyIn(Dist.CLIENT)
public class GuiScrollPane extends GuiListExtended { public class GuiScrollPane extends SlotGui {
public GuiScreen parent; public Screen parent;
public FontRenderer fontRenderer; public FontRenderer font;
public List<IScrollEntry> listEntries; private List<IScrollEntry> listEntries;
private float scrollMultiplier = 1f;
public GuiScrollPane(GuiScreen parent, FontRenderer fontRenderer, int top, int bottom) { private int mouseX;
super(parent.mc, parent.width, parent.height, top, bottom, 100); private int mouseY;
public GuiScrollPane(Screen parent, FontRenderer font, int top, int bottom) {
super(Minecraft.getInstance(), parent.width, parent.height, top, bottom, 100);
this.parent = parent; this.parent = parent;
this.fontRenderer = fontRenderer; this.font = font;
this.setShowSelectionBox(false); this.renderSelection = false;
listEntries = new ArrayList<>(); listEntries = new ArrayList<>();
MinecraftForge.EVENT_BUS.register(this);
} }
@Override public IScrollEntry getListEntry(int index) {
public IGuiListEntry getListEntry(int index) {
return listEntries.get(index); return listEntries.get(index);
} }
public void AddListEntry(IScrollEntry listEntry){
listEntries.add(listEntry);
}
@Override @Override
protected int getSize() { protected int getItemCount() {
return listEntries.size(); return listEntries.size();
} }
@Override @Override
protected int getScrollBarX() { protected boolean isSelectedItem(int slotIndex) {
return false;
}
@Override
protected int getScrollbarPosition() {
//return width / 2 + 140 + 10; //return width / 2 + 140 + 10;
return width - 15; return width - 15;
} }
@Override @Override
public int getListWidth() { public int getRowWidth() {
return 280; return 280;
} }
//Removed background //Removed background
@Override @Override
public void drawScreen(int mouseXIn, int mouseYIn, float partialTicks) public void render(int mouseXIn, int mouseYIn, float partialTicks)
{
if (this.visible)
{ {
if (this.visible) {
this.mouseX = mouseXIn; this.mouseX = mouseXIn;
this.mouseY = mouseYIn; this.mouseY = mouseYIn;
int scrollBarLeft = this.getScrollBarX(); this.renderBackground();
int scrollBarRight = scrollBarLeft + 6; int scrollbarLeft = this.getScrollbarPosition();
this.bindAmountScrolled(); int scrollbarRight = scrollbarLeft + 6;
GlStateManager.disableLighting(); this.capYPosition();
GlStateManager.disableFog();
Tessellator tessellator = Tessellator.getInstance(); Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferbuilder = tessellator.getBuffer(); BufferBuilder bufferbuilder = tessellator.getBuffer();
int insideLeft = this.left + this.width / 2 - this.getListWidth() / 2 + 2;
int insideTop = this.top + 4 - (int)this.amountScrolled;
if (this.hasListHeader) { int insideLeft = this.x0 + this.width / 2 - this.getRowWidth() / 2 + 2;
this.drawListHeader(insideLeft, insideTop, tessellator); int insideTop = this.y0 + 4 - (int) this.yo;
if (this.renderHeader) {
this.renderHeader(insideLeft, insideTop, tessellator);
} }
//All entries //All entries
this.drawSelectionBox(insideLeft, insideTop, mouseXIn, mouseYIn, partialTicks); this.renderList(insideLeft, insideTop, mouseXIn, mouseYIn, partialTicks);
GlStateManager.disableDepth(); RenderSystem.disableDepthTest();
//Dirt overlays on top and bottom //Dirt overlays on top and bottom
// this.overlayBackground(0, this.top, 255, 255); // this.renderHoleBackground(0, this.y0, 255, 255);
// this.overlayBackground(this.bottom, this.height, 255, 255); // this.renderHoleBackground(this.y1, this.height, 255, 255);
GlStateManager.enableBlend(); RenderSystem.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE); RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE);
GlStateManager.disableAlpha(); RenderSystem.disableAlphaTest();
GlStateManager.shadeModel(7425); RenderSystem.shadeModel(7425);
GlStateManager.disableTexture2D(); RenderSystem.disableTexture();
// //top fade //top
// bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); // bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
// bufferbuilder.pos((double)this.left, (double)(this.top + 5), 0.0D).tex(0.0D, 1.0D).color(100, 100, 100, 0).endVertex(); // bufferbuilder.pos((double)this.x0, (double)(this.y0 + 4), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 0).endVertex();
// bufferbuilder.pos((double)this.right, (double)(this.top + 5), 0.0D).tex(1.0D, 1.0D).color(100, 100, 100, 0).endVertex(); // bufferbuilder.pos((double)this.x1, (double)(this.y0 + 4), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 0).endVertex();
// bufferbuilder.pos((double)this.right, (double)this.top, 0.0D).tex(1.0D, 0.0D).color(100, 100, 100, 100).endVertex(); // bufferbuilder.pos((double)this.x1, (double)this.y0, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex();
// bufferbuilder.pos((double)this.left, (double)this.top, 0.0D).tex(0.0D, 0.0D).color(100, 100, 100, 100).endVertex(); // bufferbuilder.pos((double)this.x0, (double)this.y0, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex();
// tessellator.draw(); // tessellator.draw();
// //top line //bottom
// bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); // bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
// bufferbuilder.pos((double)this.left, (double)this.top, 0.0D).tex(0.0D, 1.0D).color(20, 20, 20, 255).endVertex(); // bufferbuilder.pos((double)this.x0, (double)this.y1, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex();
// bufferbuilder.pos((double)this.right, (double)this.top, 0.0D).tex(1.0D, 1.0D).color(20, 20, 20, 255).endVertex(); // bufferbuilder.pos((double)this.x1, (double)this.y1, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex();
// bufferbuilder.pos((double)this.right, (double)(this.top - 1), 0.0D).tex(1.0D, 0.0D).color(20, 20, 20, 255).endVertex(); // bufferbuilder.pos((double)this.x1, (double)(this.y1 - 4), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 0).endVertex();
// bufferbuilder.pos((double)this.left, (double)(this.top - 1), 0.0D).tex(0.0D, 0.0D).color(20, 20, 20, 255).endVertex(); // bufferbuilder.pos((double)this.x0, (double)(this.y1 - 4), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 0).endVertex();
// tessellator.draw();
// //bottom fade
// bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
// bufferbuilder.pos((double)this.left, (double)this.bottom, 0.0D).tex(0.0D, 1.0D).color(10, 10, 10, 100).endVertex();
// bufferbuilder.pos((double)this.right, (double)this.bottom, 0.0D).tex(1.0D, 1.0D).color(10, 10, 10, 100).endVertex();
// bufferbuilder.pos((double)this.right, (double)(this.bottom - 5), 0.0D).tex(1.0D, 0.0D).color(10, 10, 10, 0).endVertex();
// bufferbuilder.pos((double)this.left, (double)(this.bottom - 5), 0.0D).tex(0.0D, 0.0D).color(10, 10, 10, 0).endVertex();
// tessellator.draw();
// //bottom line
// bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
// bufferbuilder.pos((double)this.left, (double)(this.bottom + 1), 0.0D).tex(0.0D, 1.0D).color(20, 20, 20, 255).endVertex();
// bufferbuilder.pos((double)this.right, (double)(this.bottom + 1), 0.0D).tex(1.0D, 1.0D).color(20, 20, 20, 255).endVertex();
// bufferbuilder.pos((double)this.right, (double)this.bottom, 0.0D).tex(1.0D, 0.0D).color(20, 20, 20, 255).endVertex();
// bufferbuilder.pos((double)this.left, (double)this.bottom, 0.0D).tex(0.0D, 0.0D).color(20, 20, 20, 255).endVertex();
// tessellator.draw(); // tessellator.draw();
//Draw scrollbar //Draw scrollbar
int maxScroll = this.getMaxScroll(); int maxScroll = this.getMaxScroll();
if (maxScroll > 0) if (maxScroll > 0) {
{ int k1 = (int) ((float) ((this.y1 - this.y0) * (this.y1 - this.y0)) / (float) this.getMaxPosition());
int k1 = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); k1 = MathHelper.clamp(k1, 32, this.y1 - this.y0 - 8);
k1 = MathHelper.clamp(k1, 32, this.bottom - this.top - 8); int l1 = (int) this.yo * (this.y1 - this.y0 - k1) / maxScroll + this.y0;
int l1 = (int)this.amountScrolled * (this.bottom - this.top - k1) / maxScroll + this.top; if (l1 < this.y0) {
l1 = this.y0;
if (l1 < this.top)
{
l1 = this.top;
} }
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
bufferbuilder.pos((double)scrollBarLeft, (double)this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); bufferbuilder.pos((double) scrollbarLeft, (double) this.y1, 0.0F).tex(0.0F, 1.0F).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)scrollBarRight, (double)this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); bufferbuilder.pos((double) scrollbarRight, (double) this.y1, 0.0F).tex(1.0F, 1.0F).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)scrollBarRight, (double)this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); bufferbuilder.pos((double) scrollbarRight, (double) this.y0, 0.0F).tex(1.0F, 0.0F).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)scrollBarLeft, (double)this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); bufferbuilder.pos((double) scrollbarLeft, (double) this.y0, 0.0F).tex(0.0F, 0.0F).color(0, 0, 0, 255).endVertex();
tessellator.draw(); tessellator.draw();
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
bufferbuilder.pos((double)scrollBarLeft, (double)(l1 + k1), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double) scrollbarLeft, (double) (l1 + k1), 0.0F).tex(0.0F, 1.0F).color(128, 128, 128, 255).endVertex();
bufferbuilder.pos((double)scrollBarRight, (double)(l1 + k1), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double) scrollbarRight, (double) (l1 + k1), 0.0F).tex(1.0F, 1.0F).color(128, 128, 128, 255).endVertex();
bufferbuilder.pos((double)scrollBarRight, (double)l1, 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double) scrollbarRight, (double) l1, 0.0F).tex(1.0F, 0.0F).color(128, 128, 128, 255).endVertex();
bufferbuilder.pos((double)scrollBarLeft, (double)l1, 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double) scrollbarLeft, (double) l1, 0.0F).tex(0.0F, 0.0F).color(128, 128, 128, 255).endVertex();
tessellator.draw(); tessellator.draw();
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
bufferbuilder.pos((double)scrollBarLeft, (double)(l1 + k1 - 1), 0.0D).tex(0.0D, 1.0D).color(192, 192, 192, 255).endVertex(); bufferbuilder.pos((double) scrollbarLeft, (double) (l1 + k1 - 1), 0.0F).tex(0.0F, 1.0F).color(192, 192, 192, 255).endVertex();
bufferbuilder.pos((double)(scrollBarRight - 1), (double)(l1 + k1 - 1), 0.0D).tex(1.0D, 1.0D).color(192, 192, 192, 255).endVertex(); bufferbuilder.pos((double) (scrollbarRight - 1), (double) (l1 + k1 - 1), 0.0F).tex(1.0F, 1.0F).color(192, 192, 192, 255).endVertex();
bufferbuilder.pos((double)(scrollBarRight - 1), (double)l1, 0.0D).tex(1.0D, 0.0D).color(192, 192, 192, 255).endVertex(); bufferbuilder.pos((double) (scrollbarRight - 1), (double) l1, 0.0F).tex(1.0F, 0.0F).color(192, 192, 192, 255).endVertex();
bufferbuilder.pos((double)scrollBarLeft, (double)l1, 0.0D).tex(0.0D, 0.0D).color(192, 192, 192, 255).endVertex(); bufferbuilder.pos((double) scrollbarLeft, (double) l1, 0.0F).tex(0.0F, 0.0F).color(192, 192, 192, 255).endVertex();
tessellator.draw(); tessellator.draw();
} }
GlStateManager.enableTexture2D(); //this.renderDecorations(mouseXIn, mouseYIn);
GlStateManager.shadeModel(7424); RenderSystem.enableTexture();
GlStateManager.enableAlpha(); RenderSystem.shadeModel(7424);
GlStateManager.disableBlend(); RenderSystem.enableAlphaTest();
RenderSystem.disableBlend();
} }
} }
//SLOTHEIGHT MODIFICATIONS //SLOTHEIGHT MODIFICATIONS
//SlotHeight is still relied on for determining how much to scroll //SlotHeight is still relied on for determining how much to scroll
@Override @Override
protected int getContentHeight() { protected int getMaxPosition() {
//Add every entry height //Add every entry height
int height = this.headerPadding; int height = this.headerHeight;
for (IScrollEntry entry : listEntries) { for (IScrollEntry entry : listEntries) {
height += entry.getHeight(); height += entry.getHeight();
} }
return height; return height;
} }
public int getContentHeight(int count) { @Override
protected void renderBackground() {
}
@Override
protected void renderItem(int slotIndex, int xPos, int yPos, int heightIn, int mouseXIn, int mouseYIn, float partialTicks) {
this.getListEntry(slotIndex).drawEntry(slotIndex, xPos, yPos, this.getRowWidth(), heightIn, mouseXIn, mouseYIn,
this.getSlotIndexFromScreenCoords(mouseXIn, mouseYIn) == slotIndex, partialTicks);
}
public int getMaxPosition(int count) {
//Add all count entry heights //Add all count entry heights
int height = this.headerPadding; int height = this.headerHeight;
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
IScrollEntry entry = listEntries.get(i); IScrollEntry entry = listEntries.get(i);
height += entry.getHeight(); height += entry.getHeight();
@@ -188,33 +188,31 @@ public class GuiScrollPane extends GuiListExtended {
return height; return height;
} }
@Override public int getSlotIndexFromScreenCoords(double posX, double posY) {
public int getSlotIndexFromScreenCoords(int posX, int posY) { int left = this.x0 + (this.width - this.getRowWidth()) / 2;
int left = this.left + (this.width - this.getListWidth()) / 2; int right = this.x0 + (this.width + this.getRowWidth()) / 2;
int right = this.left + (this.width + this.getListWidth()) / 2; double relativeMouseY = getRelativeMouseY(mouseY, 0);
int relativeMouseY = getRelativeMouseY(mouseY, 0);
//Iterate over every entry until relativeMouseY falls within its height //Iterate over every entry until relativeMouseY falls within its height
for (int i = 0; i < listEntries.size(); i++) { for (int i = 0; i < listEntries.size(); i++) {
IScrollEntry entry = listEntries.get(i); IScrollEntry entry = listEntries.get(i);
if (relativeMouseY <= entry.getHeight()) if (relativeMouseY <= entry.getHeight())
return posX < this.getScrollBarX() && posX >= left && posX <= right && i >= 0 && return posX < this.getScrollbarPosition() && posX >= left && posX <= right && i >= 0 &&
relativeMouseY >= 0 && i < this.getSize() ? i : -1; relativeMouseY >= 0 && i < this.getItemCount() ? i : -1;
relativeMouseY -= entry.getHeight(); relativeMouseY -= entry.getHeight();
} }
return -1; return -1;
} }
@Override @Override
public boolean mouseClicked(int mouseX, int mouseY, int mouseEvent) public boolean mouseClicked(double mouseX, double mouseY, int button) {
{
int selectedSlot = this.getSlotIndexFromScreenCoords(mouseX, mouseY); int selectedSlot = this.getSlotIndexFromScreenCoords(mouseX, mouseY);
int relativeX = getRelativeMouseX(mouseX); double relativeX = getRelativeMouseX(mouseX);
//Always pass through mouseclicked, to be able to unfocus textfields //Always pass through mouseclicked, to be able to unfocus textfields
for (int i = 0; i < this.listEntries.size(); i++) { for (int i = 0; i < this.listEntries.size(); i++) {
int relativeY = getRelativeMouseY(mouseY, i); double relativeY = getRelativeMouseY(mouseY, i);
this.getListEntry(i).mousePressed(selectedSlot, mouseX, mouseY, mouseEvent, relativeX, relativeY); this.getListEntry(i).mousePressed(selectedSlot, (int) mouseX, (int) mouseY, button, (int) relativeX, (int) relativeY);
} }
@@ -239,60 +237,53 @@ public class GuiScrollPane extends GuiListExtended {
} }
@Override @Override
public boolean mouseReleased(int x, int y, int mouseEvent) public boolean mouseReleased(double mouseX, double mouseY, int button) {
for (int i = 0; i < this.getItemCount(); ++i)
{ {
for (int i = 0; i < this.getSize(); ++i) double relativeX = getRelativeMouseX(mouseX);
{ double relativeY = getRelativeMouseY(mouseY, i);
int relativeX = getRelativeMouseX(mouseX); this.getListEntry(i).mouseReleased(i, (int) mouseX, (int) mouseY, button, (int) relativeX, (int) relativeY);
int relativeY = getRelativeMouseY(mouseY, i);
this.getListEntry(i).mouseReleased(i, x, y, mouseEvent, relativeX, relativeY);
} }
this.setEnabled(true); this.visible = true;
return false; return false;
} }
@Override
public void handleMouseInput() { public void handleMouseInput() {
if (this.isMouseYWithinSlotBounds(this.mouseY)) { if (this.isMouseInList(this.mouseX, this.mouseY)) {
if (Mouse.getEventButton() == 0 && Mouse.getEventButtonState() && this.mouseY >= this.top && if (minecraft.mouseHelper.isLeftDown() && this.mouseY >= this.y0 &&
this.mouseY <= this.bottom) { this.mouseY <= this.y1) {
int i = this.left + (this.width - this.getListWidth()) / 2; int i = this.x0 + (this.width - this.getRowWidth()) / 2;
int j = this.left + (this.width + this.getListWidth()) / 2; int j = this.x0 + (this.width + this.getRowWidth()) / 2;
int slotIndex = getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); int slotIndex = getSlotIndexFromScreenCoords(this.mouseX, this.mouseY);
int relativeMouseY = getRelativeMouseY(mouseY, slotIndex); double relativeMouseY = getRelativeMouseY(mouseY, slotIndex);
if (slotIndex > -1) { if (slotIndex > -1) {
this.elementClicked(slotIndex, false, this.mouseX, this.mouseY); this.mouseClicked(this.mouseX, this.mouseY, 0);
this.selectedElement = slotIndex;
} else if (this.mouseX >= i && this.mouseX <= j && relativeMouseY < 0) { } else if (this.mouseX >= i && this.mouseX <= j && relativeMouseY < 0) {
this.clickedHeader(this.mouseX - i, this.mouseY - this.top + (int) this.amountScrolled - 4); this.clickedHeader(this.mouseX - i, this.mouseY - this.y0 + (int) this.yo - 4);
} }
} }
if (Mouse.isButtonDown(0) && this.getEnabled()) { if (minecraft.mouseHelper.isLeftDown() && this.isVisible()) {
if (this.initialClickY == -1) { if (this.yDrag == -1) {
boolean flag1 = true; boolean flag1 = true;
if (this.mouseY >= this.top && this.mouseY <= this.bottom) { if (this.mouseY >= this.y0 && this.mouseY <= this.y1) {
int i2 = this.left + (this.width - this.getListWidth()) / 2; int i2 = this.x0 + (this.width - this.getRowWidth()) / 2;
int j2 = this.left + (this.width + this.getListWidth()) / 2; int j2 = this.x0 + (this.width + this.getRowWidth()) / 2;
int slotIndex = getSlotIndexFromScreenCoords(this.mouseX, this.mouseY); int slotIndex = getSlotIndexFromScreenCoords(this.mouseX, this.mouseY);
int relativeMouseY = getRelativeMouseY(mouseY, slotIndex); double relativeMouseY = getRelativeMouseY(mouseY, slotIndex);
if (slotIndex > -1) { if (slotIndex > -1) {
boolean flag = slotIndex == this.selectedElement && this.mouseClicked(slotIndex, this.mouseX, this.mouseY);
Minecraft.getSystemTime() - this.lastClicked < 250L;
this.elementClicked(slotIndex, flag, this.mouseX, this.mouseY);
this.selectedElement = slotIndex;
this.lastClicked = Minecraft.getSystemTime();
} else if (this.mouseX >= i2 && this.mouseX <= j2 && relativeMouseY < 0) { } else if (this.mouseX >= i2 && this.mouseX <= j2 && relativeMouseY < 0) {
this.clickedHeader(this.mouseX - i2, this.clickedHeader(this.mouseX - i2,
this.mouseY - this.top + (int) this.amountScrolled - 4); this.mouseY - this.y0 + (int) this.yo - 4);
flag1 = false; flag1 = false;
} }
int i3 = this.getScrollBarX(); int i3 = this.getScrollbarPosition();
int j1 = i3 + 6; int j1 = i3 + 6;
if (this.mouseX >= i3 && this.mouseX <= j1) { if (this.mouseX >= i3 && this.mouseX <= j1) {
@@ -303,56 +294,45 @@ public class GuiScrollPane extends GuiListExtended {
maxScroll = 1; maxScroll = 1;
} }
int l1 = (int) ((float) ((this.bottom - this.top) * (this.bottom - this.top)) / int l1 = (int) ((float) ((this.y1 - this.y0) * (this.y1 - this.y0)) /
(float) this.getContentHeight()); (float) this.getMaxPosition());
l1 = MathHelper.clamp(l1, 32, this.bottom - this.top - 8); l1 = MathHelper.clamp(l1, 32, this.y1 - this.y0 - 8);
this.scrollMultiplier /= (float) (this.bottom - this.top - l1) / (float) maxScroll; this.scrollMultiplier /= (float) (this.y1 - this.y0 - l1) / (float) maxScroll;
} else { } else {
this.scrollMultiplier = 1.0F; this.scrollMultiplier = 1.0F;
} }
if (flag1) { if (flag1) {
this.initialClickY = this.mouseY; this.yDrag = this.mouseY;
} else { } else {
this.initialClickY = -2; this.yDrag = -2;
} }
} else { } else {
this.initialClickY = -2; this.yDrag = -2;
} }
} else if (this.initialClickY >= 0) { } else if (this.yDrag >= 0) {
this.amountScrolled -= (float) (this.mouseY - this.initialClickY) * this.scrollMultiplier; this.yo -= (float) (this.mouseY - this.yDrag) * this.scrollMultiplier;
this.initialClickY = this.mouseY; this.yDrag = this.mouseY;
} }
} else { } else {
this.initialClickY = -1; this.yDrag = -1;
} }
int i2 = Mouse.getEventDWheel();
if (i2 != 0) {
if (i2 > 0) {
i2 = -1;
} else if (i2 < 0) {
i2 = 1;
}
this.amountScrolled += (float) (i2 * this.slotHeight / 2);
}
} }
} }
//Draw in center if it fits //Draw in center if it fits
@Override @Override
protected void drawSelectionBox(int insideLeft, int insideTop, int mouseXIn, int mouseYIn, float partialTicks) protected void renderList(int insideLeft, int insideTop, int mouseXIn, int mouseYIn, float partialTicks)
{ {
int size = this.getSize(); int itemCount = this.getItemCount();
Tessellator tessellator = Tessellator.getInstance(); Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferbuilder = tessellator.getBuffer(); BufferBuilder bufferbuilder = tessellator.getBuffer();
//Find y to start with //Find y to start with
int y = this.headerPadding + insideTop; int y = this.headerHeight + insideTop;
int contentHeight = getContentHeight(); int contentHeight = getMaxPosition();
int insideHeight = this.bottom - this.top - 4; int insideHeight = this.y1 - this.y0 - 4;
if (contentHeight < insideHeight) { if (contentHeight < insideHeight) {
//it fits, so we can center it vertically //it fits, so we can center it vertically
@@ -360,67 +340,68 @@ public class GuiScrollPane extends GuiListExtended {
} }
//Draw all entries //Draw all entries
for (int i = 0; i < size; ++i) for (int i = 0; i < itemCount; ++i)
{ {
int entryHeight = listEntries.get(i).getHeight(); int entryHeight = listEntries.get(i).getHeight();
int entryHeight2 = entryHeight - 4; int entryHeight2 = entryHeight - 4;
if (y > this.bottom || y + entryHeight2 < this.top) if (y > this.y1 || y + entryHeight2 < this.y0)
{ {
this.updateItemPos(i, insideLeft, y, partialTicks); this.updateItemPosition(i, insideLeft, y, partialTicks);
} }
if (this.showSelectionBox && this.isSelected(i)) if (this.renderSelection && this.isSelectedItem(i)) {
{ int i1 = this.x0 + this.width / 2 - this.getRowWidth() / 2;
int i1 = this.left + this.width / 2 - this.getListWidth() / 2; int j1 = this.x0 + this.width / 2 + this.getRowWidth() / 2;
int j1 = this.left + this.width / 2 + this.getListWidth() / 2; RenderSystem.disableTexture();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); float f = this.isFocused() ? 1.0F : 0.5F;
GlStateManager.disableTexture2D(); RenderSystem.color4f(f, f, f, 1.0F);
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); bufferbuilder.begin(7, DefaultVertexFormats.POSITION);
bufferbuilder.pos((double)i1, (double)(y + entryHeight2 + 2), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double)i1, (double)(y + entryHeight2 + 2), 0.0D).endVertex();
bufferbuilder.pos((double)j1, (double)(y + entryHeight2 + 2), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double)j1, (double)(y + entryHeight2 + 2), 0.0D).endVertex();
bufferbuilder.pos((double)j1, (double)(y - 2), 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double)j1, (double)(y - 2), 0.0D).endVertex();
bufferbuilder.pos((double)i1, (double)(y - 2), 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); bufferbuilder.pos((double)i1, (double)(y - 2), 0.0D).endVertex();
bufferbuilder.pos((double)(i1 + 1), (double)(y + entryHeight2 + 1), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)(j1 - 1), (double)(y + entryHeight2 + 1), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)(j1 - 1), (double)(y - 1), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex();
bufferbuilder.pos((double)(i1 + 1), (double)(y - 1), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex();
tessellator.draw(); tessellator.draw();
GlStateManager.enableTexture2D(); RenderSystem.color4f(0.0F, 0.0F, 0.0F, 1.0F);
bufferbuilder.begin(7, DefaultVertexFormats.POSITION);
bufferbuilder.pos((double)(i1 + 1), (double)(y + entryHeight2 + 1), 0.0D).endVertex();
bufferbuilder.pos((double)(j1 - 1), (double)(y + entryHeight2 + 1), 0.0D).endVertex();
bufferbuilder.pos((double)(j1 - 1), (double)(y - 1), 0.0D).endVertex();
bufferbuilder.pos((double)(i1 + 1), (double)(y - 1), 0.0D).endVertex();
tessellator.draw();
RenderSystem.enableTexture();
} }
this.drawSlot(i, insideLeft, y, entryHeight2, mouseXIn, mouseYIn, partialTicks); this.renderItem(i, insideLeft, y, entryHeight2, mouseXIn, mouseYIn, partialTicks);
y += entryHeight; y += entryHeight;
} }
} }
private int getRelativeMouseX(int mouseX) { private double getRelativeMouseX(double mouseX) {
int j = this.left + this.width / 2 - this.getListWidth() / 2 + 2; int j = this.x0 + this.width / 2 - this.getRowWidth() / 2 + 2;
return mouseX - j; return mouseX - j;
} }
private int getRelativeMouseY(int mouseY, int contentIndex) { private double getRelativeMouseY(double mouseY, int contentIndex) {
int k = this.top + 4 - this.getAmountScrolled() + getContentHeight(contentIndex) + this.headerPadding; int k = this.y0 + 4 - this.getScroll() + getMaxPosition(contentIndex) + this.headerHeight;
int relativeMouseY = mouseY - k; double relativeMouseY = mouseY - k;
//Content might be centered, adjust relative mouse y accordingly //Content might be centered, adjust relative mouse y accordingly
int contentHeight = getContentHeight(); int contentHeight = getMaxPosition();
int insideHeight = this.bottom - this.top - 4; int insideHeight = this.y1 - this.y0 - 4;
if (contentHeight < insideHeight) { if (contentHeight < insideHeight) {
//it fits, so we can center it vertically //it fits, so we can center it vertically
relativeMouseY -= (insideHeight - contentHeight) / 2; relativeMouseY -= (insideHeight - contentHeight) / 2f;
} }
return relativeMouseY; return relativeMouseY;
} }
//PASSTHROUGHS //PASSTHROUGHS
public int initGui(int id, List<GuiButton> buttonList) { public void init(List<Widget> buttonList) {
for (IScrollEntry entry : this.listEntries) { for (IScrollEntry entry : this.listEntries) {
id = entry.initGui(id, buttonList); entry.init(buttonList);
} }
registerScrollButtons(id++, id++);
return id;
} }
public void updateScreen() { public void updateScreen() {
@@ -428,19 +409,16 @@ public class GuiScrollPane extends GuiListExtended {
entry.updateScreen(); entry.updateScreen();
} }
public void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY) { public void drawTooltip(Screen guiScreen, int mouseX, int mouseY) {
for (IScrollEntry entry : this.listEntries) for (IScrollEntry entry : this.listEntries)
entry.drawTooltip(guiScreen, mouseX, mouseY); entry.drawTooltip(guiScreen, mouseX, mouseY);
} }
public void keyTyped(char eventChar, int eventKey) throws IOException { @Override
public boolean charTyped(char eventChar, int eventKey) {
for (IScrollEntry entry : this.listEntries) for (IScrollEntry entry : this.listEntries)
entry.keyTyped(eventChar, eventKey); entry.charTyped(eventChar, eventKey);
} return false;
public void actionPerformed(GuiButton button) {
for (IScrollEntry entry : this.listEntries)
entry.actionPerformed(button);
} }
public void onGuiClosed() { public void onGuiClosed() {
@@ -448,19 +426,41 @@ public class GuiScrollPane extends GuiListExtended {
entry.onGuiClosed(); entry.onGuiClosed();
} }
public interface IScrollEntry extends GuiListExtended.IGuiListEntry { //Make protected values available
int initGui(int id, List<GuiButton> buttonList); public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public interface IScrollEntry {
void init(List<Widget> buttonList);
void updateScreen(); void updateScreen();
void drawTooltip(GuiScreen guiScreen, int mouseX, int mouseY); void drawTooltip(Screen guiScreen, int mouseX, int mouseY);
void keyTyped(char eventChar, int eventKey) throws IOException; boolean charTyped(char eventChar, int eventKey);
void actionPerformed(GuiButton button);
void onGuiClosed(); void onGuiClosed();
int getHeight(); int getHeight();
void updatePosition(int slotIndex, int x, int y, float partialTicks);
void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, boolean isSelected, float partialTicks);
/**
* Called when the mouse is clicked within this entry. Returning true means that something within this entry was
* clicked and the list should not be dragged.
*/
boolean mousePressed(int slotIndex, int mouseX, int mouseY, int mouseEvent, int relativeX, int relativeY);
/**
* Fired when the mouse button is released. Arguments: index, x, y, mouseEvent, relativeX, relativeY
*/
void mouseReleased(int slotIndex, int x, int y, int mouseEvent, int relativeX, int relativeY);
} }
} }

View File

@@ -1,28 +1,27 @@
package nl.requios.effortlessbuilding.helper; package nl.requios.effortlessbuilding.helper;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
public class InventoryHelper { public class InventoryHelper {
public static ItemStack findItemStackInInventory(EntityPlayer player, Block block) { public static ItemStack findItemStackInInventory(PlayerEntity player, Block block) {
for (ItemStack invStack : player.inventory.mainInventory) { for (ItemStack invStack : player.inventory.mainInventory) {
if (!invStack.isEmpty() && invStack.getItem() instanceof ItemBlock && if (!invStack.isEmpty() && invStack.getItem() instanceof BlockItem &&
((ItemBlock) invStack.getItem()).getBlock().equals(block)) { ((BlockItem) invStack.getItem()).getBlock().equals(block)) {
return invStack; return invStack;
} }
} }
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
public static int findTotalBlocksInInventory(EntityPlayer player, Block block) { public static int findTotalBlocksInInventory(PlayerEntity player, Block block) {
int total = 0; int total = 0;
for (ItemStack invStack : player.inventory.mainInventory) { for (ItemStack invStack : player.inventory.mainInventory) {
if (!invStack.isEmpty() && invStack.getItem() instanceof ItemBlock && if (!invStack.isEmpty() && invStack.getItem() instanceof BlockItem &&
((ItemBlock) invStack.getItem()).getBlock().equals(block)) { ((BlockItem) invStack.getItem()).getBlock().equals(block)) {
total += invStack.getCount(); total += invStack.getCount();
} }
} }

View File

@@ -1,15 +0,0 @@
package nl.requios.effortlessbuilding.helper;
import com.google.gson.JsonObject;
import net.minecraftforge.common.crafting.IConditionFactory;
import net.minecraftforge.common.crafting.JsonContext;
import nl.requios.effortlessbuilding.BuildConfig;
import java.util.function.BooleanSupplier;
public class ReachConditionFactory implements IConditionFactory {
@Override
public BooleanSupplier parse(JsonContext context, JsonObject json) {
return () -> BuildConfig.reach.enableReachUpgrades;
}
}

View File

@@ -1,32 +1,32 @@
package nl.requios.effortlessbuilding.helper; package nl.requios.effortlessbuilding.helper;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
public class ReachHelper { public class ReachHelper {
public static int getMaxReach(EntityPlayer player) { public static int getMaxReach(PlayerEntity player) {
if (player.isCreative()) return BuildConfig.reach.maxReachCreative; if (player.isCreative()) return BuildConfig.reach.maxReachCreative.get();
if (!BuildConfig.reach.enableReachUpgrades) return BuildConfig.reach.maxReachLevel3; if (!BuildConfig.reach.enableReachUpgrades.get()) return BuildConfig.reach.maxReachLevel3.get();
//Check buildsettings for reachUpgrade //Check buildsettings for reachUpgrade
int reachUpgrade = ModifierSettingsManager.getModifierSettings(player).getReachUpgrade(); int reachUpgrade = ModifierSettingsManager.getModifierSettings(player).getReachUpgrade();
switch (reachUpgrade) { switch (reachUpgrade) {
case 0: return BuildConfig.reach.maxReachLevel0; case 0: return BuildConfig.reach.maxReachLevel0.get();
case 1: return BuildConfig.reach.maxReachLevel1; case 1: return BuildConfig.reach.maxReachLevel1.get();
case 2: return BuildConfig.reach.maxReachLevel2; case 2: return BuildConfig.reach.maxReachLevel2.get();
case 3: return BuildConfig.reach.maxReachLevel3; case 3: return BuildConfig.reach.maxReachLevel3.get();
} }
return BuildConfig.reach.maxReachLevel0; return BuildConfig.reach.maxReachLevel0.get();
} }
public static int getPlacementReach(EntityPlayer player) { public static int getPlacementReach(PlayerEntity player) {
return getMaxReach(player) / 4; return getMaxReach(player) / 4;
} }
public static int getMaxBlocksPlacedAtOnce(EntityPlayer player) { public static int getMaxBlocksPlacedAtOnce(PlayerEntity player) {
if (player.isCreative()) return 1000000; if (player.isCreative()) return 1000000;
return MathHelper.ceil(Math.pow(getMaxReach(player), 1.6)); return MathHelper.ceil(Math.pow(getMaxReach(player), 1.6));
//Level 0: 121 //Level 0: 121
@@ -35,7 +35,7 @@ public class ReachHelper {
//Level 3: 4805 //Level 3: 4805
} }
public static int getMaxBlocksPerAxis(EntityPlayer player) { public static int getMaxBlocksPerAxis(PlayerEntity player) {
if (player.isCreative()) return 2000; if (player.isCreative()) return 2000;
return MathHelper.ceil(getMaxReach(player) * 0.3); return MathHelper.ceil(getMaxReach(player) * 0.3);
//Level 0: 6 //Level 0: 6
@@ -44,7 +44,7 @@ public class ReachHelper {
//Level 3: 60 //Level 3: 60
} }
public static boolean canBreakFar(EntityPlayer player) { public static boolean canBreakFar(PlayerEntity player) {
return player.isCreative() || BuildConfig.survivalBalancers.breakFar; return player.isCreative() || BuildConfig.survivalBalancers.breakFar.get();
} }
} }

View File

@@ -1,26 +1,25 @@
package nl.requios.effortlessbuilding.helper; package nl.requios.effortlessbuilding.helper;
import net.minecraft.block.Block; import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.block.BlockLiquid; import net.minecraft.block.*;
import net.minecraft.block.BlockSlab; import net.minecraft.block.SlabBlock;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material; import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.BlockItem;
import net.minecraft.util.*;
import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.block.Blocks;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemSlab;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.CachedBlockInfo;
import net.minecraft.util.EnumHand; import net.minecraft.util.Direction;
import net.minecraft.util.SoundCategory; import net.minecraft.util.Hand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess; import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraftforge.common.ToolType;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.compatibility.CompatHelper; import nl.requios.effortlessbuilding.compatibility.CompatHelper;
@@ -33,15 +32,15 @@ public class SurvivalHelper {
//Used for all placing of blocks in this mod. //Used for all placing of blocks in this mod.
//Checks if area is loaded, if player has the right permissions, if existing block can be replaced (drops it if so) and consumes an item from the stack. //Checks if area is loaded, if player has the right permissions, if existing block can be replaced (drops it if so) and consumes an item from the stack.
//Based on ItemBlock#onItemUse //Based on ItemBlock#onItemUse
public static boolean placeBlock(World world, EntityPlayer player, BlockPos pos, IBlockState blockState, public static boolean placeBlock(World world, PlayerEntity player, BlockPos pos, BlockState blockState,
ItemStack origstack, EnumFacing facing, Vec3d hitVec, boolean skipPlaceCheck, ItemStack origstack, Direction facing, Vec3d hitVec, boolean skipPlaceCheck,
boolean skipCollisionCheck, boolean playSound) { boolean skipCollisionCheck, boolean playSound) {
if (!world.isBlockLoaded(pos, true)) return false; if (!world.isBlockPresent(pos)) return false;
ItemStack itemstack = origstack; ItemStack itemstack = origstack;
if (blockState.getBlock().isAir(blockState, world, pos) || itemstack.isEmpty()) { if (blockState.getBlock().isAir(blockState, world, pos) || itemstack.isEmpty()) {
dropBlock(world, player, pos); dropBlock(world, player, pos);
world.setBlockToAir(pos); world.removeBlock(pos, false);
return true; return true;
} }
@@ -50,9 +49,9 @@ public class SurvivalHelper {
if (CompatHelper.isItemBlockProxy(itemstack)) if (CompatHelper.isItemBlockProxy(itemstack))
itemstack = CompatHelper.getItemBlockByState(itemstack, blockState); itemstack = CompatHelper.getItemBlockByState(itemstack, blockState);
if (!(itemstack.getItem() instanceof ItemBlock)) if (!(itemstack.getItem() instanceof BlockItem))
return false; return false;
Block block = ((ItemBlock) itemstack.getItem()).getBlock(); Block block = ((BlockItem) itemstack.getItem()).getBlock();
//More manual with ItemBlock#placeBlockAt //More manual with ItemBlock#placeBlockAt
@@ -60,10 +59,17 @@ public class SurvivalHelper {
//Drop existing block //Drop existing block
dropBlock(world, player, pos); dropBlock(world, player, pos);
boolean placed = ((ItemBlock) itemstack.getItem()).placeBlockAt(itemstack, player, world, pos, facing, (float) hitVec.x, (float) hitVec.y, (float) hitVec.z, blockState); //TryPlace sets block with offset and reduces itemstack count in creative, so we copy only parts of it
if (!placed) return false; // BlockItemUseContext blockItemUseContext = new BlockItemUseContext(world, player, itemstack, pos, facing, (float) hitVec.x, (float) hitVec.y, (float) hitVec.z);
// EnumActionResult result = ((ItemBlock) itemstack.getItem()).tryPlace(blockItemUseContext);
if (!world.setBlockState(pos, blockState, 3)) return false;
BlockItem.setTileEntityNBT(world, player, pos, itemstack); //Actually BlockItem::onBlockPlaced but that is protected
block.onBlockPlacedBy(world, pos, blockState, player, itemstack);
if (player instanceof ServerPlayerEntity) {
CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayerEntity)player, pos, itemstack);
}
IBlockState afterState = world.getBlockState(pos); BlockState afterState = world.getBlockState(pos);
if (playSound) { if (playSound) {
SoundType soundtype = afterState.getBlock().getSoundType(afterState, world, pos, player); SoundType soundtype = afterState.getBlock().getSoundType(afterState, world, pos, player);
@@ -105,8 +111,8 @@ public class SurvivalHelper {
//Used for all breaking of blocks in this mod. //Used for all breaking of blocks in this mod.
//Checks if area is loaded, if appropriate tool is used in survival mode, and drops the block directly into the players inventory //Checks if area is loaded, if appropriate tool is used in survival mode, and drops the block directly into the players inventory
public static boolean breakBlock(World world, EntityPlayer player, BlockPos pos, boolean skipChecks) { public static boolean breakBlock(World world, PlayerEntity player, BlockPos pos, boolean skipChecks) {
if (!world.isBlockLoaded(pos, false)) return false; if (!world.isBlockPresent(pos) && !world.isAirBlock(pos)) return false;
//Check if can break //Check if can break
if (skipChecks || canBreak(world, player, pos)) { if (skipChecks || canBreak(world, player, pos)) {
@@ -119,17 +125,17 @@ public class SurvivalHelper {
//Damage tool //Damage tool
player.getHeldItemMainhand().onBlockDestroyed(world, world.getBlockState(pos), pos, player); player.getHeldItemMainhand().onBlockDestroyed(world, world.getBlockState(pos), pos, player);
world.setBlockToAir(pos); world.removeBlock(pos, false);
return true; return true;
} }
return false; return false;
} }
//Gives items directly to player //Gives items directly to player
public static void dropBlock(World world, EntityPlayer player, BlockPos pos){ public static void dropBlock(World world, PlayerEntity player, BlockPos pos){
if (player.isCreative()) return; if (player.isCreative()) return;
IBlockState blockState = world.getBlockState(pos); BlockState blockState = world.getBlockState(pos);
Block block = blockState.getBlock(); Block block = blockState.getBlock();
block.harvestBlock(world, player, pos, blockState, world.getTileEntity(pos), player.getHeldItemMainhand()); block.harvestBlock(world, player, pos, blockState, world.getTileEntity(pos), player.getHeldItemMainhand());
@@ -176,17 +182,17 @@ public class SurvivalHelper {
* @param sidePlacedOn * @param sidePlacedOn
* @return Whether the player may place the block at pos with itemstack * @return Whether the player may place the block at pos with itemstack
*/ */
public static boolean canPlace(World world, EntityPlayer player, BlockPos pos, IBlockState newBlockState, ItemStack itemStack, boolean skipCollisionCheck, EnumFacing sidePlacedOn) { public static boolean canPlace(World world, PlayerEntity player, BlockPos pos, BlockState newBlockState, ItemStack itemStack, boolean skipCollisionCheck, Direction sidePlacedOn) {
//Check if itemstack is correct //Check if itemstack is correct
if (!(itemStack.getItem() instanceof ItemBlock) || Block.getBlockFromItem(itemStack.getItem()) != newBlockState.getBlock()) { if (!(itemStack.getItem() instanceof BlockItem) || Block.getBlockFromItem(itemStack.getItem()) != newBlockState.getBlock()) {
// EffortlessBuilding.log(player, "Cannot (re)place block", true); // EffortlessBuilding.log(player, "Cannot (re)place block", true);
// EffortlessBuilding.log("SurvivalHelper#canPlace: itemstack " + itemStack.toString() + " does not match blockstate " + newBlockState.toString()); // EffortlessBuilding.log("SurvivalHelper#canPlace: itemstack " + itemStack.toString() + " does not match blockstate " + newBlockState.toString());
//Happens when breaking blocks, no need to notify in that case //Happens when breaking blocks, no need to notify in that case
return false; return false;
} }
Block block = ((ItemBlock) itemStack.getItem()).getBlock(); Block block = ((BlockItem) itemStack.getItem()).getBlock();
return !itemStack.isEmpty() && canPlayerEdit(player, world, pos, itemStack) && return !itemStack.isEmpty() && canPlayerEdit(player, world, pos, itemStack) &&
mayPlace(world, block, newBlockState, pos, skipCollisionCheck, sidePlacedOn, player) && mayPlace(world, block, newBlockState, pos, skipCollisionCheck, sidePlacedOn, player) &&
@@ -194,13 +200,12 @@ public class SurvivalHelper {
} }
//Can be harvested with hand? (or in creative) //Can be harvested with hand? (or in creative)
private static boolean canReplace(World world, EntityPlayer player, BlockPos pos){ private static boolean canReplace(World world, PlayerEntity player, BlockPos pos){
if (player.isCreative()) return true; if (player.isCreative()) return true;
IBlockState state = world.getBlockState(pos); BlockState state = world.getBlockState(pos);
state = state.getBlock().getActualState(state, world, pos);
switch (BuildConfig.survivalBalancers.quickReplaceMiningLevel) { switch (BuildConfig.survivalBalancers.quickReplaceMiningLevel.get()) {
case -1: return state.getMaterial().isToolNotRequired(); case -1: return state.getMaterial().isToolNotRequired();
case 0: return state.getBlock().getHarvestLevel(state) <= 0; case 0: return state.getBlock().getHarvestLevel(state) <= 0;
case 1: return state.getBlock().getHarvestLevel(state) <= 1; case 1: return state.getBlock().getHarvestLevel(state) <= 1;
@@ -212,9 +217,11 @@ public class SurvivalHelper {
} }
//From EntityPlayer#canPlayerEdit //From EntityPlayer#canPlayerEdit
private static boolean canPlayerEdit(EntityPlayer player, World world, BlockPos pos, ItemStack stack) private static boolean canPlayerEdit(PlayerEntity player, World world, BlockPos pos, ItemStack stack)
{ {
if (player.capabilities.allowEdit) if (!world.isBlockModifiable(player, pos)) return false;
if (player.abilities.allowEdit)
{ {
//True in creative and survival mode //True in creative and survival mode
return true; return true;
@@ -222,24 +229,25 @@ public class SurvivalHelper {
else else
{ {
//Adventure mode //Adventure mode
Block block = world.getBlockState(pos).getBlock(); CachedBlockInfo blockworldstate = new CachedBlockInfo(world, pos, false);
return stack.canPlaceOn(block) || stack.canEditBlocks(); return stack.canPlaceOn(world.getTags(), blockworldstate);
} }
} }
//From World#mayPlace //From World#mayPlace
private static boolean mayPlace(World world, Block blockIn, IBlockState newBlockState, BlockPos pos, boolean skipCollisionCheck, EnumFacing sidePlacedOn, @Nullable Entity placer) private static boolean mayPlace(World world, Block blockIn, BlockState newBlockState, BlockPos pos, boolean skipCollisionCheck, Direction sidePlacedOn, @Nullable Entity placer)
{ {
IBlockState iblockstate1 = world.getBlockState(pos); BlockState iblockstate1 = world.getBlockState(pos);
AxisAlignedBB axisalignedbb = skipCollisionCheck ? Block.NULL_AABB : blockIn.getDefaultState().getCollisionBoundingBox(world, pos); VoxelShape voxelShape = skipCollisionCheck ? null : blockIn.getDefaultState().getCollisionShape(world, pos);
if (axisalignedbb != Block.NULL_AABB && !world.checkNoEntityCollision(axisalignedbb.offset(pos))) if (voxelShape != null && !world.checkNoEntityCollision(placer, voxelShape))
{ {
return false; return false;
} }
//Check if double slab //Check if double slab
if (placer != null && doesBecomeDoubleSlab(((EntityPlayer) placer), pos, sidePlacedOn)) { if (placer != null && doesBecomeDoubleSlab(((PlayerEntity) placer), pos, sidePlacedOn)) {
return true; return true;
} }
@@ -249,25 +257,27 @@ public class SurvivalHelper {
return false; return false;
} }
if (iblockstate1.getMaterial() == Material.CIRCUITS && blockIn == Blocks.ANVIL) //TODO 1.14 check what Material.CIRCUITS has become
if (iblockstate1.getMaterial() == Material.REDSTONE_LIGHT && blockIn == Blocks.ANVIL)
{ {
return true; return true;
} }
//Check quickreplace //Check quickreplace
if (placer instanceof EntityPlayer && ModifierSettingsManager.getModifierSettings(((EntityPlayer) placer)).doQuickReplace()) { if (placer instanceof PlayerEntity && ModifierSettingsManager.getModifierSettings(((PlayerEntity) placer)).doQuickReplace()) {
return true; return true;
} }
return iblockstate1.getBlock().isReplaceable(world, pos) && blockIn.canPlaceBlockOnSide(world, pos, sidePlacedOn); //TODO 1.13 replaceable
return iblockstate1.getMaterial().isReplaceable() /*&& canPlaceBlockOnSide(world, pos, sidePlacedOn)*/;
} }
//Can break using held tool? (or in creative) //Can break using held tool? (or in creative)
public static boolean canBreak(World world, EntityPlayer player, BlockPos pos) { public static boolean canBreak(World world, PlayerEntity player, BlockPos pos) {
IBlockState blockState = world.getBlockState(pos); BlockState blockState = world.getBlockState(pos);
if (blockState.getBlock() instanceof BlockLiquid) return false; if (!world.getFluidState(pos).isEmpty()) return false;
if (player.isCreative()) return true; if (player.isCreative()) return true;
@@ -275,13 +285,12 @@ public class SurvivalHelper {
} }
//From ForgeHooks#canHarvestBlock //From ForgeHooks#canHarvestBlock
public static boolean canHarvestBlock(@Nonnull Block block, @Nonnull EntityPlayer player, @Nonnull IBlockAccess world, @Nonnull BlockPos pos) public static boolean canHarvestBlock(@Nonnull Block block, @Nonnull PlayerEntity player, @Nonnull World world, @Nonnull BlockPos pos)
{ {
IBlockState state = world.getBlockState(pos); BlockState state = world.getBlockState(pos);
state = state.getBlock().getActualState(state, world, pos);
//Dont break bedrock //Dont break bedrock
if (state.getBlockHardness((World) world, pos) < 0) { if (state.getBlockHardness(world, pos) < 0) {
return false; return false;
} }
@@ -291,13 +300,13 @@ public class SurvivalHelper {
} }
ItemStack stack = player.getHeldItemMainhand(); ItemStack stack = player.getHeldItemMainhand();
String tool = block.getHarvestTool(state); ToolType tool = block.getHarvestTool(state);
if (stack.isEmpty() || tool == null) if (stack.isEmpty() || tool == null)
{ {
return player.canHarvestBlock(state); return player.canHarvestBlock(state);
} }
if (stack.getItemDamage() >= stack.getMaxDamage()) return false; if (stack.getDamage() >= stack.getMaxDamage()) return false;
int toolLevel = stack.getItem().getHarvestLevel(stack, tool, player, state); int toolLevel = stack.getItem().getHarvestLevel(stack, tool, player, state);
if (toolLevel < 0) if (toolLevel < 0)
@@ -308,27 +317,28 @@ public class SurvivalHelper {
return toolLevel >= block.getHarvestLevel(state); return toolLevel >= block.getHarvestLevel(state);
} }
public static boolean doesBecomeDoubleSlab(EntityPlayer player, BlockPos pos, EnumFacing facing) { public static boolean doesBecomeDoubleSlab(PlayerEntity player, BlockPos pos, Direction facing) {
IBlockState placedBlockState = player.world.getBlockState(pos); BlockState placedBlockState = player.world.getBlockState(pos);
ItemStack itemstack = player.getHeldItem(EnumHand.MAIN_HAND); ItemStack itemstack = player.getHeldItem(Hand.MAIN_HAND);
if (CompatHelper.isItemBlockProxy(itemstack)) if (CompatHelper.isItemBlockProxy(itemstack))
itemstack = CompatHelper.getItemBlockFromStack(itemstack); itemstack = CompatHelper.getItemBlockFromStack(itemstack);
if (itemstack.isEmpty() || !(itemstack.getItem() instanceof ItemSlab)) return false; if (itemstack.isEmpty() || !(itemstack.getItem() instanceof BlockItem) || !(((BlockItem) itemstack.getItem()).getBlock() instanceof SlabBlock)) return false;
BlockSlab heldSlab = (BlockSlab) ((ItemSlab) itemstack.getItem()).getBlock(); SlabBlock heldSlab = (SlabBlock) ((BlockItem) itemstack.getItem()).getBlock();
if (placedBlockState.getBlock() == heldSlab) { if (placedBlockState.getBlock() == heldSlab) {
IProperty<?> variantProperty = heldSlab.getVariantProperty(); //TODO 1.13
Comparable<?> placedVariant = placedBlockState.getValue(variantProperty); // IProperty<?> variantProperty = heldSlab.getVariantProperty();
BlockSlab.EnumBlockHalf placedHalf = placedBlockState.getValue(BlockSlab.HALF); // Comparable<?> placedVariant = placedBlockState.getValue(variantProperty);
// BlockSlab.EnumBlockHalf placedHalf = placedBlockState.getValue(BlockSlab.HALF);
Comparable<?> heldVariant = heldSlab.getTypeForItem(itemstack); //
// Comparable<?> heldVariant = heldSlab.getTypeForItem(itemstack);
if ((facing == EnumFacing.UP && placedHalf == BlockSlab.EnumBlockHalf.BOTTOM || facing == EnumFacing.DOWN && placedHalf == BlockSlab.EnumBlockHalf.TOP) && placedVariant == heldVariant) //
{ // if ((facing == EnumFacing.UP && placedHalf == BlockSlab.EnumBlockHalf.BOTTOM || facing == EnumFacing.DOWN && placedHalf == BlockSlab.EnumBlockHalf.TOP) && placedVariant == heldVariant)
return true; // {
} // return true;
// }
} }
return false; return false;
} }

View File

@@ -1,22 +1,28 @@
package nl.requios.effortlessbuilding.item; package nl.requios.effortlessbuilding.item;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.Item; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.ItemStack; import net.minecraft.inventory.container.Container;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.util.ActionResult; import net.minecraft.item.*;
import net.minecraft.util.EnumActionResult; import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.EnumFacing; import net.minecraft.util.*;
import net.minecraft.util.EnumHand; import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
@@ -24,6 +30,7 @@ import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager; import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.capability.ItemHandlerCapabilityProvider; import nl.requios.effortlessbuilding.capability.ItemHandlerCapabilityProvider;
import nl.requios.effortlessbuilding.gui.RandomizerBagContainer;
import nl.requios.effortlessbuilding.helper.SurvivalHelper; import nl.requios.effortlessbuilding.helper.SurvivalHelper;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@@ -39,52 +46,60 @@ public class ItemRandomizerBag extends Item {
private static Random rand = new Random(currentSeed); private static Random rand = new Random(currentSeed);
public ItemRandomizerBag() { public ItemRandomizerBag() {
this.setRegistryName(EffortlessBuilding.MODID, "randomizer_bag"); super(new Item.Properties().group(ItemGroup.TOOLS).maxStackSize(1));
this.setTranslationKey(this.getRegistryName().toString());
this.maxStackSize = 1; this.setRegistryName(EffortlessBuilding.MODID, "randomizer_bag");
this.setCreativeTab(CreativeTabs.TOOLS);
} }
@Override @Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { public ActionResultType onItemUse(ItemUseContext ctx) {
PlayerEntity player = ctx.getPlayer();
World world = ctx.getWorld();
BlockPos pos = ctx.getPos();
Direction facing = ctx.getFace();
ItemStack item = ctx.getItem();
Vec3d hitVec = ctx.getHitVec();
if (player.isSneaking()) { if (player == null) return ActionResultType.FAIL;
if (world.isRemote) return EnumActionResult.SUCCESS;
if (ctx.func_225518_g_()) { //ctx.isPlacerSneaking()
if (world.isRemote) return ActionResultType.SUCCESS;
//Open inventory //Open inventory
player.openGui(EffortlessBuilding.instance, EffortlessBuilding.RANDOMIZER_BAG_GUI, world, 0, 0, 0); NetworkHooks.openGui((ServerPlayerEntity) player, new ContainerProvider(item));
} else { } else {
if (world.isRemote) return EnumActionResult.SUCCESS; if (world.isRemote) return ActionResultType.SUCCESS;
//Only place manually if in normal vanilla mode //Only place manually if in normal vanilla mode
BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode(); BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode();
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
if (buildMode != BuildModes.BuildModeEnum.NORMAL || modifierSettings.doQuickReplace()) { if (buildMode != BuildModes.BuildModeEnum.NORMAL || modifierSettings.doQuickReplace()) {
return EnumActionResult.FAIL; return ActionResultType.FAIL;
} }
//Use item //Use item
//Get bag inventory //Get bag inventory
ItemStack bag = player.getHeldItem(hand); //TODO offhand support
ItemStack bag = player.getHeldItem(Hand.MAIN_HAND);
IItemHandler bagInventory = getBagInventory(bag); IItemHandler bagInventory = getBagInventory(bag);
if (bagInventory == null) if (bagInventory == null)
return EnumActionResult.FAIL; return ActionResultType.FAIL;
ItemStack toPlace = pickRandomStack(bagInventory); ItemStack toPlace = pickRandomStack(bagInventory);
if (toPlace.isEmpty()) return EnumActionResult.FAIL; if (toPlace.isEmpty()) return ActionResultType.FAIL;
//Previously: use onItemUse to place block (no synergy) //Previously: use onItemUse to place block (no synergy)
//bag.setItemDamage(toPlace.getMetadata()); //bag.setItemDamage(toPlace.getMetadata());
//toPlace.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); //toPlace.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ);
if (!world.getBlockState(pos).getBlock().isReplaceable(world, pos)) { //TODO replaceable
if (!world.getBlockState(pos).getBlock().getMaterial(world.getBlockState(pos)).isReplaceable()) {
pos = pos.offset(facing); pos = pos.offset(facing);
} }
IBlockState blockState = Block.getBlockFromItem(toPlace.getItem()).getStateForPlacement(world, pos, facing, BlockItemUseContext blockItemUseContext = new BlockItemUseContext(new ItemUseContext(player, Hand.MAIN_HAND, new BlockRayTraceResult(hitVec, facing, pos, false)));
hitX, hitY, hitZ, toPlace.getMetadata(), player, hand); BlockState blockState = Block.getBlockFromItem(toPlace.getItem()).getStateForPlacement(blockItemUseContext);
SurvivalHelper.placeBlock(world, player, pos, blockState, toPlace, facing, new Vec3d(hitX, hitY, hitZ), false, false, true); SurvivalHelper.placeBlock(world, player, pos, blockState, toPlace, facing, hitVec, false, false, true);
//Synergy //Synergy
//Works without calling //Works without calling
@@ -93,30 +108,30 @@ public class ItemRandomizerBag extends Item {
// Mirror.onBlockPlaced(placeEvent); // Mirror.onBlockPlaced(placeEvent);
// Array.onBlockPlaced(placeEvent); // Array.onBlockPlaced(placeEvent);
} }
return EnumActionResult.SUCCESS; return ActionResultType.SUCCESS;
} }
@Override @Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) { public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
ItemStack bag = player.getHeldItem(hand); ItemStack bag = player.getHeldItem(hand);
if (player.isSneaking()) { if (player.isSneaking()) {
if (world.isRemote) return new ActionResult<>(EnumActionResult.SUCCESS, bag); if (world.isRemote) return new ActionResult<>(ActionResultType.SUCCESS, bag);
//Open inventory //Open inventory
player.openGui(EffortlessBuilding.instance, EffortlessBuilding.RANDOMIZER_BAG_GUI, world, 0, 0, 0); NetworkHooks.openGui((ServerPlayerEntity) player, new ContainerProvider(bag));
} else { } else {
//Use item //Use item
//Get bag inventory //Get bag inventory
IItemHandler bagInventory = getBagInventory(bag); IItemHandler bagInventory = getBagInventory(bag);
if (bagInventory == null) if (bagInventory == null)
return new ActionResult<>(EnumActionResult.FAIL, bag); return new ActionResult<>(ActionResultType.FAIL, bag);
ItemStack toUse = pickRandomStack(bagInventory); ItemStack toUse = pickRandomStack(bagInventory);
if (toUse.isEmpty()) return new ActionResult<>(EnumActionResult.FAIL, bag); if (toUse.isEmpty()) return new ActionResult<>(ActionResultType.FAIL, bag);
return toUse.useItemRightClick(world, player, hand); return toUse.useItemRightClick(world, player, hand);
} }
return new ActionResult<>(EnumActionResult.PASS, bag); return new ActionResult<>(ActionResultType.PASS, bag);
} }
/** /**
@@ -126,8 +141,7 @@ public class ItemRandomizerBag extends Item {
* @return * @return
*/ */
public static IItemHandler getBagInventory(ItemStack bag) { public static IItemHandler getBagInventory(ItemStack bag) {
if (!bag.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null)) return null; return bag.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).orElse(null);
return bag.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
} }
/** /**
@@ -176,25 +190,28 @@ public class ItemRandomizerBag extends Item {
} }
@Override @Override
public int getMaxItemUseDuration(ItemStack stack) { public int getUseDuration(ItemStack p_77626_1_) {
return 1; return 1;
} }
@Nullable @Nullable
@Override @Override
public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
return new ItemHandlerCapabilityProvider(); return new ItemHandlerCapabilityProvider();
} }
@Override @Override
public void addInformation(ItemStack stack, @Nullable World world, List<String> tooltip, ITooltipFlag flag) { public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
tooltip.add(TextFormatting.BLUE + "Rightclick" + TextFormatting.GRAY + " to place a random block"); tooltip.add(new StringTextComponent(TextFormatting.BLUE + "Rightclick" + TextFormatting.GRAY + " to place a random block"));
tooltip.add(TextFormatting.BLUE + "Sneak + rightclick" + TextFormatting.GRAY + " to open inventory"); tooltip.add(new StringTextComponent(TextFormatting.BLUE + "Sneak + rightclick" + TextFormatting.GRAY + " to open inventory"));
if (world != null && world.getPlayers().size() > 1) {
tooltip.add(new StringTextComponent(TextFormatting.YELLOW + "Experimental on servers: may lose inventory"));
}
} }
@Override @Override
public String getTranslationKey() { public String getTranslationKey() {
return super.getTranslationKey(); return this.getRegistryName().toString();
} }
public static void resetRandomness() { public static void resetRandomness() {
@@ -205,4 +222,24 @@ public class ItemRandomizerBag extends Item {
currentSeed = Calendar.getInstance().getTimeInMillis(); currentSeed = Calendar.getInstance().getTimeInMillis();
rand.setSeed(currentSeed); rand.setSeed(currentSeed);
} }
public static class ContainerProvider implements INamedContainerProvider{
private ItemStack bag;
public ContainerProvider(ItemStack bag) {
this.bag = bag;
}
@Override
public ITextComponent getDisplayName() {
return new TranslationTextComponent("effortlessbuilding.screen.randomizer_bag");
}
@Nullable
@Override
public Container createMenu(int containerId, PlayerInventory playerInventory, PlayerEntity player) {
return new RandomizerBagContainer(containerId, playerInventory, ItemRandomizerBag.getBagInventory(bag));
}
}
} }

View File

@@ -1,12 +1,13 @@
package nl.requios.effortlessbuilding.item; package nl.requios.effortlessbuilding.item;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.*; import net.minecraft.util.*;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World; import net.minecraft.world.World;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
@@ -20,19 +21,16 @@ import java.util.List;
public class ItemReachUpgrade1 extends Item { public class ItemReachUpgrade1 extends Item {
public ItemReachUpgrade1() { public ItemReachUpgrade1() {
super(new Item.Properties().group(ItemGroup.TOOLS).maxStackSize(1));
this.setRegistryName(EffortlessBuilding.MODID, "reach_upgrade1"); this.setRegistryName(EffortlessBuilding.MODID, "reach_upgrade1");
this.setTranslationKey(this.getRegistryName().toString());
this.maxStackSize = 1;
this.setCreativeTab(CreativeTabs.TOOLS);
} }
@Override @Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) { public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
if (player.isCreative()) { if (player.isCreative()) {
if (world.isRemote) EffortlessBuilding.log(player, "Reach upgrades are not necessary in creative."); if (world.isRemote) EffortlessBuilding.log(player, "Reach upgrades are not necessary in creative.");
if (world.isRemote) EffortlessBuilding.log(player, "Still want increased reach? Use the config."); if (world.isRemote) EffortlessBuilding.log(player, "Still want increased reach? Use the config.");
return new ActionResult<>(EnumActionResult.PASS, player.getHeldItem(hand)); return new ActionResult<>(ActionResultType.PASS, player.getHeldItem(hand));
} }
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
@@ -52,16 +50,16 @@ public class ItemReachUpgrade1 extends Item {
SoundEvent soundEvent = new SoundEvent(new ResourceLocation("item.armor.equip_leather")); SoundEvent soundEvent = new SoundEvent(new ResourceLocation("item.armor.equip_leather"));
player.playSound(soundEvent, 1f, 1f); player.playSound(soundEvent, 1f, 1f);
} }
return new ActionResult<>(EnumActionResult.PASS, player.getHeldItem(hand)); return new ActionResult<>(ActionResultType.PASS, player.getHeldItem(hand));
} }
@Override @Override
public void addInformation(ItemStack stack, @Nullable World world, List<String> tooltip, ITooltipFlag flag) { public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
tooltip.add(TextFormatting.GRAY + "Consume to increase reach to " + TextFormatting.BLUE + BuildConfig.reach.maxReachLevel1); tooltip.add(new StringTextComponent(TextFormatting.GRAY + "Consume to increase reach to " + TextFormatting.BLUE + BuildConfig.reach.maxReachLevel1.get()));
} }
@Override @Override
public String getTranslationKey() { public String getTranslationKey() {
return super.getTranslationKey(); return this.getRegistryName().toString();
} }
} }

View File

@@ -1,11 +1,13 @@
package nl.requios.effortlessbuilding.item; package nl.requios.effortlessbuilding.item;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.*; import net.minecraft.util.*;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World; import net.minecraft.world.World;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
@@ -19,19 +21,16 @@ import java.util.List;
public class ItemReachUpgrade2 extends Item { public class ItemReachUpgrade2 extends Item {
public ItemReachUpgrade2() { public ItemReachUpgrade2() {
super(new Item.Properties().group(ItemGroup.TOOLS).maxStackSize(1));
this.setRegistryName(EffortlessBuilding.MODID, "reach_upgrade2"); this.setRegistryName(EffortlessBuilding.MODID, "reach_upgrade2");
this.setTranslationKey(this.getRegistryName().toString());
this.maxStackSize = 1;
this.setCreativeTab(CreativeTabs.TOOLS);
} }
@Override @Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) { public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
if (player.isCreative()) { if (player.isCreative()) {
if (world.isRemote) EffortlessBuilding.log(player, "Reach upgrades are not necessary in creative."); if (world.isRemote) EffortlessBuilding.log(player, "Reach upgrades are not necessary in creative.");
if (world.isRemote) EffortlessBuilding.log(player, "Still want increased reach? Use the config."); if (world.isRemote) EffortlessBuilding.log(player, "Still want increased reach? Use the config.");
return new ActionResult<>(EnumActionResult.PASS, player.getHeldItem(hand)); return new ActionResult<>(ActionResultType.PASS, player.getHeldItem(hand));
} }
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
@@ -55,17 +54,17 @@ public class ItemReachUpgrade2 extends Item {
SoundEvent soundEvent = new SoundEvent(new ResourceLocation("item.armor.equip_leather")); SoundEvent soundEvent = new SoundEvent(new ResourceLocation("item.armor.equip_leather"));
player.playSound(soundEvent, 1f, 1f); player.playSound(soundEvent, 1f, 1f);
} }
return new ActionResult<>(EnumActionResult.PASS, player.getHeldItem(hand)); return new ActionResult<>(ActionResultType.PASS, player.getHeldItem(hand));
} }
@Override @Override
public void addInformation(ItemStack stack, @Nullable World world, List<String> tooltip, ITooltipFlag flag) { public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
tooltip.add(TextFormatting.GRAY + "Consume to increase reach to " + TextFormatting.BLUE + BuildConfig.reach.maxReachLevel2); tooltip.add(new StringTextComponent(TextFormatting.GRAY + "Consume to increase reach to " + TextFormatting.BLUE + BuildConfig.reach.maxReachLevel2.get()));
tooltip.add(TextFormatting.GRAY + "Previous upgrades need to be consumed first"); tooltip.add(new StringTextComponent(TextFormatting.GRAY + "Previous upgrades need to be consumed first"));
} }
@Override @Override
public String getTranslationKey() { public String getTranslationKey() {
return super.getTranslationKey(); return this.getRegistryName().toString();
} }
} }

View File

@@ -1,11 +1,13 @@
package nl.requios.effortlessbuilding.item; package nl.requios.effortlessbuilding.item;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.*; import net.minecraft.util.*;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World; import net.minecraft.world.World;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
@@ -19,19 +21,16 @@ import java.util.List;
public class ItemReachUpgrade3 extends Item { public class ItemReachUpgrade3 extends Item {
public ItemReachUpgrade3() { public ItemReachUpgrade3() {
super(new Item.Properties().group(ItemGroup.TOOLS).maxStackSize(1));
this.setRegistryName(EffortlessBuilding.MODID, "reach_upgrade3"); this.setRegistryName(EffortlessBuilding.MODID, "reach_upgrade3");
this.setTranslationKey(this.getRegistryName().toString());
this.maxStackSize = 1;
this.setCreativeTab(CreativeTabs.TOOLS);
} }
@Override @Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) { public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
if (player.isCreative()) { if (player.isCreative()) {
if (world.isRemote) EffortlessBuilding.log(player, "Reach upgrades are not necessary in creative."); if (world.isRemote) EffortlessBuilding.log(player, "Reach upgrades are not necessary in creative.");
if (world.isRemote) EffortlessBuilding.log(player, "Still want increased reach? Use the config."); if (world.isRemote) EffortlessBuilding.log(player, "Still want increased reach? Use the config.");
return new ActionResult<>(EnumActionResult.PASS, player.getHeldItem(hand)); return new ActionResult<>(ActionResultType.PASS, player.getHeldItem(hand));
} }
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
@@ -58,17 +57,17 @@ public class ItemReachUpgrade3 extends Item {
SoundEvent soundEvent = new SoundEvent(new ResourceLocation("item.armor.equip_leather")); SoundEvent soundEvent = new SoundEvent(new ResourceLocation("item.armor.equip_leather"));
player.playSound(soundEvent, 1f, 1f); player.playSound(soundEvent, 1f, 1f);
} }
return new ActionResult<>(EnumActionResult.PASS, player.getHeldItem(hand)); return new ActionResult<>(ActionResultType.PASS, player.getHeldItem(hand));
} }
@Override @Override
public void addInformation(ItemStack stack, @Nullable World world, List<String> tooltip, ITooltipFlag flag) { public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
tooltip.add(TextFormatting.GRAY + "Consume to increase reach to " + TextFormatting.BLUE + BuildConfig.reach.maxReachLevel3); tooltip.add(new StringTextComponent(TextFormatting.GRAY + "Consume to increase reach to " + TextFormatting.BLUE + BuildConfig.reach.maxReachLevel3.get()));
tooltip.add(TextFormatting.GRAY + "Previous upgrades need to be consumed first"); tooltip.add(new StringTextComponent(TextFormatting.GRAY + "Previous upgrades need to be consumed first"));
} }
@Override @Override
public String getTranslationKey() { public String getTranslationKey() {
return super.getTranslationKey(); return this.getRegistryName().toString();
} }
} }

View File

@@ -1,37 +1,35 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.BlockSet; import nl.requios.effortlessbuilding.buildmodifier.BlockSet;
import nl.requios.effortlessbuilding.buildmodifier.UndoRedo; import nl.requios.effortlessbuilding.buildmodifier.UndoRedo;
import nl.requios.effortlessbuilding.proxy.ClientProxy;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.function.Supplier;
/*** /***
* Sends a message to the client asking to add a block to the undo stack. * Sends a message to the client asking to add a block to the undo stack.
*/ */
public class AddUndoMessage implements IMessage { public class AddUndoMessage {
private BlockPos coordinate; private BlockPos coordinate;
private IBlockState previousBlockState; private BlockState previousBlockState;
private IBlockState newBlockState; private BlockState newBlockState;
public AddUndoMessage() { public AddUndoMessage() {
coordinate = BlockPos.ORIGIN; coordinate = BlockPos.ZERO;
previousBlockState = null; previousBlockState = null;
newBlockState = null; newBlockState = null;
} }
public AddUndoMessage(BlockPos coordinate, IBlockState previousBlockState, IBlockState newBlockState) { public AddUndoMessage(BlockPos coordinate, BlockState previousBlockState, BlockState newBlockState) {
this.coordinate = coordinate; this.coordinate = coordinate;
this.previousBlockState = previousBlockState; this.previousBlockState = previousBlockState;
this.newBlockState = newBlockState; this.newBlockState = newBlockState;
@@ -41,54 +39,49 @@ public class AddUndoMessage implements IMessage {
return coordinate; return coordinate;
} }
public IBlockState getPreviousBlockState() { public BlockState getPreviousBlockState() {
return previousBlockState; return previousBlockState;
} }
public IBlockState getNewBlockState() { public BlockState getNewBlockState() {
return newBlockState; return newBlockState;
} }
@Override public static void encode(AddUndoMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) { buf.writeInt(message.coordinate.getX());
buf.writeInt(this.coordinate.getX()); buf.writeInt(message.coordinate.getY());
buf.writeInt(this.coordinate.getY()); buf.writeInt(message.coordinate.getZ());
buf.writeInt(this.coordinate.getZ()); buf.writeInt(Block.getStateId(message.previousBlockState));
buf.writeInt(Block.getStateId(this.previousBlockState)); buf.writeInt(Block.getStateId(message.newBlockState));
buf.writeInt(Block.getStateId(this.newBlockState));
} }
@Override public static AddUndoMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) { BlockPos coordinate = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt());
coordinate = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); BlockState previousBlockState = Block.getStateById(buf.readInt());
previousBlockState = Block.getStateById(buf.readInt()); BlockState newBlockState = Block.getStateById(buf.readInt());
newBlockState = Block.getStateById(buf.readInt()); return new AddUndoMessage(coordinate, previousBlockState, newBlockState);
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<AddUndoMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(AddUndoMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(AddUndoMessage message, MessageContext ctx) { if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
//EffortlessBuilding.log("message received on " + ctx.side + " side");
if (ctx.side == Side.CLIENT){
//Received clientside //Received clientside
EffortlessBuilding.proxy.getThreadListenerFromContext(ctx).addScheduledTask(() -> { PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
EntityPlayer player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
//Add to undo stack clientside //Add to undo stack clientside
//Only the appropriate player that needs to add this to the undo stack gets this message
UndoRedo.addUndo(player, new BlockSet( UndoRedo.addUndo(player, new BlockSet(
new ArrayList<BlockPos>() {{add(message.getCoordinate());}}, new ArrayList<BlockPos>() {{add(message.getCoordinate());}},
new ArrayList<IBlockState>() {{add(message.getPreviousBlockState());}}, new ArrayList<BlockState>() {{add(message.getPreviousBlockState());}},
new ArrayList<IBlockState>() {{add(message.getNewBlockState());}}, new ArrayList<BlockState>() {{add(message.getNewBlockState());}},
new Vec3d(0,0,0), new Vec3d(0,0,0),
message.getCoordinate(), message.getCoordinate())); message.getCoordinate(), message.getCoordinate()));
}
}); });
} ctx.get().setPacketHandled(true);
return null;
} }
} }
} }

View File

@@ -1,40 +1,47 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketBuffer;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers;
import java.util.function.Supplier;
/*** /***
* Sends a message to the server indicating that a player wants to break a block * Sends a message to the server indicating that a player wants to break a block
*/ */
public class BlockBrokenMessage implements IMessage { public class BlockBrokenMessage {
private boolean blockHit; private boolean blockHit;
private BlockPos blockPos; private BlockPos blockPos;
private EnumFacing sideHit; private Direction sideHit;
private Vec3d hitVec; private Vec3d hitVec;
public BlockBrokenMessage() { public BlockBrokenMessage() {
this.blockHit = false; this.blockHit = false;
this.blockPos = BlockPos.ORIGIN; this.blockPos = BlockPos.ZERO;
this.sideHit = EnumFacing.UP; this.sideHit = Direction.UP;
this.hitVec = new Vec3d(0, 0, 0); this.hitVec = new Vec3d(0, 0, 0);
} }
public BlockBrokenMessage(RayTraceResult result) { public BlockBrokenMessage(BlockRayTraceResult result) {
this.blockHit = result.typeOfHit == RayTraceResult.Type.BLOCK; this.blockHit = result.getType() == RayTraceResult.Type.BLOCK;
this.blockPos = result.getBlockPos(); this.blockPos = result.getPos();
this.sideHit = result.sideHit; this.sideHit = result.getFace();
this.hitVec = result.hitVec; this.hitVec = result.getHitVec();
}
public BlockBrokenMessage(boolean blockHit, BlockPos blockPos, Direction sideHit, Vec3d hitVec) {
this.blockHit = blockHit;
this.blockPos = blockPos;
this.sideHit = sideHit;
this.hitVec = hitVec;
} }
public boolean isBlockHit() { public boolean isBlockHit() {
@@ -45,7 +52,7 @@ public class BlockBrokenMessage implements IMessage {
return blockPos; return blockPos;
} }
public EnumFacing getSideHit() { public Direction getSideHit() {
return sideHit; return sideHit;
} }
@@ -53,43 +60,36 @@ public class BlockBrokenMessage implements IMessage {
return hitVec; return hitVec;
} }
@Override public static void encode(BlockBrokenMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) { buf.writeBoolean(message.blockHit);
buf.writeBoolean(blockHit); buf.writeInt(message.blockPos.getX());
buf.writeInt(blockPos.getX()); buf.writeInt(message.blockPos.getY());
buf.writeInt(blockPos.getY()); buf.writeInt(message.blockPos.getZ());
buf.writeInt(blockPos.getZ()); buf.writeInt(message.sideHit.getIndex());
buf.writeInt(sideHit.getIndex()); buf.writeDouble(message.hitVec.x);
buf.writeDouble(hitVec.x); buf.writeDouble(message.hitVec.y);
buf.writeDouble(hitVec.y); buf.writeDouble(message.hitVec.z);
buf.writeDouble(hitVec.z);
} }
@Override public static BlockBrokenMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) { boolean blockHit = buf.readBoolean();
blockHit = buf.readBoolean(); BlockPos blockPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt());
blockPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); Direction sideHit = Direction.byIndex(buf.readInt());
sideHit = EnumFacing.byIndex(buf.readInt()); Vec3d hitVec = new Vec3d(buf.readDouble(), buf.readDouble(), buf.readDouble());
hitVec = new Vec3d(buf.readDouble(), buf.readDouble(), buf.readDouble()); return new BlockBrokenMessage(blockHit, blockPos, sideHit, hitVec);
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<BlockBrokenMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(BlockBrokenMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(BlockBrokenMessage message, MessageContext ctx) { if (ctx.get().getDirection().getReceptionSide() == LogicalSide.SERVER) {
//EffortlessBuilding.log("message received on " + ctx.side + " side");
if (ctx.side == Side.SERVER) {
//Received serverside //Received serverside
EffortlessBuilding.proxy.getThreadListenerFromContext(ctx).addScheduledTask(() -> { BuildModes.onBlockBrokenMessage(ctx.get().getSender(), message);
BuildModes.onBlockBrokenMessage(ctx.getServerHandler().player, message); }
}); });
} ctx.get().setPacketHandled(true);
// No response packet
return null;
} }
} }
} }

View File

@@ -1,45 +1,52 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.util.Direction;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers;
import nl.requios.effortlessbuilding.proxy.ClientProxy;
import nl.requios.effortlessbuilding.render.BlockPreviewRenderer; import nl.requios.effortlessbuilding.render.BlockPreviewRenderer;
import java.util.function.Supplier;
/*** /***
* Sends a message to the server indicating that a player wants to place a block. * Sends a message to the server indicating that a player wants to place a block.
* Received clientside: server has placed blocks and its letting the client know. * Received clientside: server has placed blocks and its letting the client know.
*/ */
public class BlockPlacedMessage implements IMessage { public class BlockPlacedMessage {
private boolean blockHit; private boolean blockHit;
private BlockPos blockPos; private BlockPos blockPos;
private EnumFacing sideHit; private Direction sideHit;
private Vec3d hitVec; private Vec3d hitVec;
private boolean placeStartPos; //prevent double placing in normal mode private boolean placeStartPos; //prevent double placing in normal mode
public BlockPlacedMessage() { public BlockPlacedMessage() {
this.blockHit = false; this.blockHit = false;
this.blockPos = BlockPos.ORIGIN; this.blockPos = BlockPos.ZERO;
this.sideHit = EnumFacing.UP; this.sideHit = Direction.UP;
this.hitVec = new Vec3d(0, 0, 0); this.hitVec = new Vec3d(0, 0, 0);
this.placeStartPos = true; this.placeStartPos = true;
} }
public BlockPlacedMessage(RayTraceResult result, boolean placeStartPos) { public BlockPlacedMessage(BlockRayTraceResult result, boolean placeStartPos) {
this.blockHit = result.typeOfHit == RayTraceResult.Type.BLOCK; this.blockHit = result.getType() == RayTraceResult.Type.BLOCK;
this.blockPos = result.getBlockPos(); this.blockPos = result.getPos();
this.sideHit = result.sideHit; this.sideHit = result.getFace();
this.hitVec = result.hitVec; this.hitVec = result.getHitVec();
this.placeStartPos = placeStartPos;
}
public BlockPlacedMessage(boolean blockHit, BlockPos blockPos, Direction sideHit, Vec3d hitVec, boolean placeStartPos) {
this.blockHit = blockHit;
this.blockPos = blockPos;
this.sideHit = sideHit;
this.hitVec = hitVec;
this.placeStartPos = placeStartPos; this.placeStartPos = placeStartPos;
} }
@@ -51,7 +58,7 @@ public class BlockPlacedMessage implements IMessage {
return blockPos; return blockPos;
} }
public EnumFacing getSideHit() { public Direction getSideHit() {
return sideHit; return sideHit;
} }
@@ -63,51 +70,42 @@ public class BlockPlacedMessage implements IMessage {
return placeStartPos; return placeStartPos;
} }
@Override public static void encode(BlockPlacedMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) { buf.writeBoolean(message.blockHit);
buf.writeBoolean(blockHit); buf.writeInt(message.blockPos.getX());
buf.writeInt(blockPos.getX()); buf.writeInt(message.blockPos.getY());
buf.writeInt(blockPos.getY()); buf.writeInt(message.blockPos.getZ());
buf.writeInt(blockPos.getZ()); buf.writeInt(message.sideHit.getIndex());
buf.writeInt(sideHit.getIndex()); buf.writeDouble(message.hitVec.x);
buf.writeDouble(hitVec.x); buf.writeDouble(message.hitVec.y);
buf.writeDouble(hitVec.y); buf.writeDouble(message.hitVec.z);
buf.writeDouble(hitVec.z); buf.writeBoolean(message.placeStartPos);
buf.writeBoolean(placeStartPos);
} }
@Override public static BlockPlacedMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) { boolean blockHit = buf.readBoolean();
blockHit = buf.readBoolean(); BlockPos blockPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt());
blockPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); Direction sideHit = Direction.byIndex(buf.readInt());
sideHit = EnumFacing.byIndex(buf.readInt()); Vec3d hitVec = new Vec3d(buf.readDouble(), buf.readDouble(), buf.readDouble());
hitVec = new Vec3d(buf.readDouble(), buf.readDouble(), buf.readDouble()); boolean placeStartPos = buf.readBoolean();
placeStartPos = buf.readBoolean(); return new BlockPlacedMessage(blockHit, blockPos, sideHit, hitVec, placeStartPos);
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<BlockPlacedMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(BlockPlacedMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(BlockPlacedMessage message, MessageContext ctx) { if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
//EffortlessBuilding.log("message received on " + ctx.side + " side");
if (ctx.side == Side.CLIENT){
//Received clientside //Received clientside
EffortlessBuilding.proxy.getThreadListenerFromContext(ctx).addScheduledTask(() -> {
//Nod RenderHandler to do the dissolve shader effect //Nod RenderHandler to do the dissolve shader effect
BlockPreviewRenderer.onBlocksPlaced(); BlockPreviewRenderer.onBlocksPlaced();
});
return null;
} else { } else {
//Received serverside //Received serverside
EffortlessBuilding.proxy.getThreadListenerFromContext(ctx).addScheduledTask(() -> { BuildModes.onBlockPlacedMessage(ctx.get().getSender(), message);
BuildModes.onBlockPlacedMessage(ctx.getServerHandler().player, message); }
}); });
// No response packet ctx.get().setPacketHandled(true);
return null;
}
} }
} }
} }

View File

@@ -1,45 +1,35 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer;
import net.minecraft.util.IThreadListener; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import java.util.function.Supplier;
/** /**
* Sends a message to the server indicating that a buildmode needs to be canceled for a player * Sends a message to the server indicating that a buildmode needs to be canceled for a player
*/ */
public class CancelModeMessage implements IMessage { public class CancelModeMessage {
@Override
public void toBytes(ByteBuf buf) {
public static void encode(CancelModeMessage message, PacketBuffer buf) {
} }
@Override public static CancelModeMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) { return new CancelModeMessage();
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<CancelModeMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(CancelModeMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(CancelModeMessage message, MessageContext ctx) { PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
// Execute the action on the main server thread by adding it as a scheduled task
IThreadListener threadListener = EffortlessBuilding.proxy.getThreadListenerFromContext(ctx);
threadListener.addScheduledTask(() -> {
EntityPlayer player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
BuildModes.initializeMode(player); BuildModes.initializeMode(player);
}); });
// No response packet ctx.get().setPacketHandled(true);
return null;
} }
} }
} }

View File

@@ -1,57 +1,44 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.block.Block; import net.minecraft.network.PacketBuffer;
import net.minecraft.block.state.IBlockState; import net.minecraftforge.fml.LogicalSide;
import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.BlockSet;
import nl.requios.effortlessbuilding.buildmodifier.UndoRedo; import nl.requios.effortlessbuilding.buildmodifier.UndoRedo;
import nl.requios.effortlessbuilding.proxy.ClientProxy;
import java.util.ArrayList; import java.util.function.Supplier;
/*** /***
* Sends a message to the client asking to clear the undo and redo stacks. * Sends a message to the client asking to clear the undo and redo stacks.
*/ */
public class ClearUndoMessage implements IMessage { public class ClearUndoMessage {
public ClearUndoMessage() { public ClearUndoMessage() {
} }
@Override public static void encode(ClearUndoMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) {
} }
@Override public static ClearUndoMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) { return new ClearUndoMessage();
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<ClearUndoMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(ClearUndoMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(ClearUndoMessage message, MessageContext ctx) { if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
//EffortlessBuilding.log("message received on " + ctx.side + " side");
if (ctx.side == Side.CLIENT){
//Received clientside //Received clientside
PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
EffortlessBuilding.proxy.getThreadListenerFromContext(ctx).addScheduledTask(() -> {
EntityPlayer player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
//Add to undo stack clientside //Add to undo stack clientside
UndoRedo.clear(player); UndoRedo.clear(player);
}
}); });
} ctx.get().setPacketHandled(true);
return null;
} }
} }
} }

View File

@@ -1,22 +1,17 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer;
import net.minecraft.util.IThreadListener; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.buildmode.ModeOptions;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager;
import static nl.requios.effortlessbuilding.buildmode.ModeSettingsManager.*; import java.util.function.Supplier;
/** /**
* Shares mode settings (see ModeSettingsManager) between server and client * Shares mode settings (see ModeSettingsManager) between server and client
*/ */
public class ModeActionMessage implements IMessage { public class ModeActionMessage {
private ModeOptions.ActionEnum action; private ModeOptions.ActionEnum action;
@@ -27,36 +22,25 @@ public class ModeActionMessage implements IMessage {
this.action = action; this.action = action;
} }
@Override public static void encode(ModeActionMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) { buf.writeInt(message.action.ordinal());
buf.writeInt(action.ordinal());
} }
@Override public static ModeActionMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) { ModeOptions.ActionEnum action = ModeOptions.ActionEnum.values()[buf.readInt()];
action = ModeOptions.ActionEnum.values()[buf.readInt()]; return new ModeActionMessage(action);
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<ModeActionMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(ModeActionMessage message, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
@Override ModeOptions.performAction(player, message.action);
public IMessage onMessage(ModeActionMessage message, MessageContext ctx) {
//EffortlessBuilding.log("message received on " + ctx.side + " side");
// The value that was sent
ModeOptions.ActionEnum action = message.action;
// Execute the action on the main server thread by adding it as a scheduled task
IThreadListener threadListener = EffortlessBuilding.proxy.getThreadListenerFromContext(ctx);
threadListener.addScheduledTask(() -> {
EntityPlayer player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
ModeOptions.performAction(player, action);
}); });
// No response packet ctx.get().setPacketHandled(true);
return null;
} }
} }
} }

View File

@@ -1,21 +1,19 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer;
import net.minecraft.util.IThreadListener; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager; import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager.ModeSettings;
import static nl.requios.effortlessbuilding.buildmode.ModeSettingsManager.*; import java.util.function.Supplier;
/** /**
* Shares mode settings (see ModeSettingsManager) between server and client * Shares mode settings (see ModeSettingsManager) between server and client
*/ */
public class ModeSettingsMessage implements IMessage { public class ModeSettingsMessage {
private ModeSettings modeSettings; private ModeSettings modeSettings;
@@ -26,41 +24,29 @@ public class ModeSettingsMessage implements IMessage {
this.modeSettings = modeSettings; this.modeSettings = modeSettings;
} }
@Override public static void encode(ModeSettingsMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) { buf.writeInt(message.modeSettings.getBuildMode().ordinal());
buf.writeInt(modeSettings.getBuildMode().ordinal());
} }
@Override public static ModeSettingsMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) {
BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.values()[buf.readInt()]; BuildModes.BuildModeEnum buildMode = BuildModes.BuildModeEnum.values()[buf.readInt()];
modeSettings = new ModeSettings(buildMode); return new ModeSettingsMessage(new ModeSettings(buildMode));
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<ModeSettingsMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(ModeSettingsMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(ModeSettingsMessage message, MessageContext ctx) { PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
//EffortlessBuilding.log("message received on " + ctx.side + " side");
// The value that was sent
ModeSettings modeSettings = message.modeSettings;
// Execute the action on the main server thread by adding it as a scheduled task
IThreadListener threadListener = EffortlessBuilding.proxy.getThreadListenerFromContext(ctx);
threadListener.addScheduledTask(() -> {
EntityPlayer player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
// Sanitize // Sanitize
ModeSettingsManager.sanitize(modeSettings, player); ModeSettingsManager.sanitize(message.modeSettings, player);
ModeSettingsManager.setModeSettings(player, modeSettings); ModeSettingsManager.setModeSettings(player, message.modeSettings);
}); });
// No response packet ctx.get().setPacketHandled(true);
return null;
} }
} }
} }

View File

@@ -1,25 +1,24 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.PacketBuffer;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.Array; import nl.requios.effortlessbuilding.buildmodifier.Array;
import nl.requios.effortlessbuilding.buildmodifier.Mirror; import nl.requios.effortlessbuilding.buildmodifier.Mirror;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.RadialMirror; import nl.requios.effortlessbuilding.buildmodifier.RadialMirror;
import static nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager.*; import java.util.function.Supplier;
import static nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager.ModifierSettings;
/** /**
* Shares modifier settings (see ModifierSettingsManager) between server and client * Shares modifier settings (see ModifierSettingsManager) between server and client
*/ */
public class ModifierSettingsMessage implements IMessage { public class ModifierSettingsMessage {
private ModifierSettings modifierSettings; private ModifierSettings modifierSettings;
@@ -30,10 +29,9 @@ public class ModifierSettingsMessage implements IMessage {
this.modifierSettings = modifierSettings; this.modifierSettings = modifierSettings;
} }
@Override public static void encode(ModifierSettingsMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) {
//MIRROR //MIRROR
Mirror.MirrorSettings m = modifierSettings.getMirrorSettings(); Mirror.MirrorSettings m = message.modifierSettings.getMirrorSettings();
buf.writeBoolean(m != null); buf.writeBoolean(m != null);
if (m != null) { if (m != null) {
buf.writeBoolean(m.enabled); buf.writeBoolean(m.enabled);
@@ -49,7 +47,7 @@ public class ModifierSettingsMessage implements IMessage {
} }
//ARRAY //ARRAY
Array.ArraySettings a = modifierSettings.getArraySettings(); Array.ArraySettings a = message.modifierSettings.getArraySettings();
buf.writeBoolean(a != null); buf.writeBoolean(a != null);
if (a != null) { if (a != null) {
buf.writeBoolean(a.enabled); buf.writeBoolean(a.enabled);
@@ -59,12 +57,12 @@ public class ModifierSettingsMessage implements IMessage {
buf.writeInt(a.count); buf.writeInt(a.count);
} }
buf.writeBoolean(modifierSettings.doQuickReplace()); buf.writeBoolean(message.modifierSettings.doQuickReplace());
buf.writeInt(modifierSettings.getReachUpgrade()); buf.writeInt(message.modifierSettings.getReachUpgrade());
//RADIAL MIRROR //RADIAL MIRROR
RadialMirror.RadialMirrorSettings r = modifierSettings.getRadialMirrorSettings(); RadialMirror.RadialMirrorSettings r = message.modifierSettings.getRadialMirrorSettings();
buf.writeBoolean(r != null); buf.writeBoolean(r != null);
if (r != null) { if (r != null) {
buf.writeBoolean(r.enabled); buf.writeBoolean(r.enabled);
@@ -79,8 +77,7 @@ public class ModifierSettingsMessage implements IMessage {
} }
} }
@Override public static ModifierSettingsMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) {
//MIRROR //MIRROR
Mirror.MirrorSettings m = new Mirror.MirrorSettings(); Mirror.MirrorSettings m = new Mirror.MirrorSettings();
if (buf.readBoolean()) { if (buf.readBoolean()) {
@@ -123,32 +120,23 @@ public class ModifierSettingsMessage implements IMessage {
radialMirrorAlternate, radialMirrorRadius, radialMirrorDrawLines, radialMirrorDrawPlanes); radialMirrorAlternate, radialMirrorRadius, radialMirrorDrawLines, radialMirrorDrawPlanes);
} }
modifierSettings = new ModifierSettings(m, a, r, quickReplace, reachUpgrade); ModifierSettings modifierSettings = new ModifierSettings(m, a, r, quickReplace, reachUpgrade);
return new ModifierSettingsMessage(modifierSettings);
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<ModifierSettingsMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(ModifierSettingsMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(ModifierSettingsMessage message, MessageContext ctx) { PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
//EffortlessBuilding.log("message received on " + ctx.side + " side");
// The value that was sent
ModifierSettings modifierSettings = message.modifierSettings;
// Execute the action on the main server thread by adding it as a scheduled task
IThreadListener threadListener = EffortlessBuilding.proxy.getThreadListenerFromContext(ctx);
threadListener.addScheduledTask(() -> {
EntityPlayer player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
// Sanitize // Sanitize
ModifierSettingsManager.sanitize(modifierSettings, player); ModifierSettingsManager.sanitize(message.modifierSettings, player);
ModifierSettingsManager.setModifierSettings(player, modifierSettings); ModifierSettingsManager.setModifierSettings(player, message.modifierSettings);
}); });
// No response packet ctx.get().setPacketHandled(true);
return null;
} }
} }
} }

View File

@@ -0,0 +1,32 @@
package nl.requios.effortlessbuilding.network;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import nl.requios.effortlessbuilding.EffortlessBuilding;
public class PacketHandler {
private static final String PROTOCOL_VERSION = "1";
public static final SimpleChannel INSTANCE = NetworkRegistry.ChannelBuilder
.named(new ResourceLocation(EffortlessBuilding.MODID, "main_channel"))
.clientAcceptedVersions(PROTOCOL_VERSION::equals)
.serverAcceptedVersions(PROTOCOL_VERSION::equals)
.networkProtocolVersion(() -> PROTOCOL_VERSION)
.simpleChannel();
public static void register() {
int id = 0;
INSTANCE.registerMessage(id++, ModifierSettingsMessage.class, ModifierSettingsMessage::encode, ModifierSettingsMessage::decode, ModifierSettingsMessage.Handler::handle);
INSTANCE.registerMessage(id++, ModeSettingsMessage.class, ModeSettingsMessage::encode, ModeSettingsMessage::decode, ModeSettingsMessage.Handler::handle);
INSTANCE.registerMessage(id++, ModeActionMessage.class, ModeActionMessage::encode, ModeActionMessage::decode, ModeActionMessage.Handler::handle);
INSTANCE.registerMessage(id++, BlockPlacedMessage.class, BlockPlacedMessage::encode, BlockPlacedMessage::decode, BlockPlacedMessage.Handler::handle);
INSTANCE.registerMessage(id++, BlockBrokenMessage.class, BlockBrokenMessage::encode, BlockBrokenMessage::decode, BlockBrokenMessage.Handler::handle);
INSTANCE.registerMessage(id++, CancelModeMessage.class, CancelModeMessage::encode, CancelModeMessage::decode, CancelModeMessage.Handler::handle);
INSTANCE.registerMessage(id++, RequestLookAtMessage.class, RequestLookAtMessage::encode, RequestLookAtMessage::decode, RequestLookAtMessage.Handler::handle);
INSTANCE.registerMessage(id++, AddUndoMessage.class, AddUndoMessage::encode, AddUndoMessage::decode, AddUndoMessage.Handler::handle);
INSTANCE.registerMessage(id++, ClearUndoMessage.class, ClearUndoMessage::encode, ClearUndoMessage::decode, ClearUndoMessage.Handler::handle);
}
}

View File

@@ -1,27 +1,21 @@
package nl.requios.effortlessbuilding.network; package nl.requios.effortlessbuilding.network;
import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.block.Block; import net.minecraft.network.PacketBuffer;
import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.LogicalSide;
import net.minecraft.util.math.Vec3d; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.BlockSet;
import nl.requios.effortlessbuilding.buildmodifier.UndoRedo;
import nl.requios.effortlessbuilding.proxy.ClientProxy; import nl.requios.effortlessbuilding.proxy.ClientProxy;
import java.util.ArrayList; import java.util.function.Supplier;
/*** /***
* Sends a message to the client asking for its lookat (objectmouseover) data. * Sends a message to the client asking for its lookat (objectmouseover) data.
* This is then sent back with a BlockPlacedMessage. * This is then sent back with a BlockPlacedMessage.
*/ */
public class RequestLookAtMessage implements IMessage { public class RequestLookAtMessage {
private boolean placeStartPos; private boolean placeStartPos;
public RequestLookAtMessage() { public RequestLookAtMessage() {
@@ -36,38 +30,35 @@ public class RequestLookAtMessage implements IMessage {
return placeStartPos; return placeStartPos;
} }
@Override public static void encode(RequestLookAtMessage message, PacketBuffer buf) {
public void toBytes(ByteBuf buf) { buf.writeBoolean(message.placeStartPos);
buf.writeBoolean(this.placeStartPos);
} }
@Override public static RequestLookAtMessage decode(PacketBuffer buf) {
public void fromBytes(ByteBuf buf) { boolean placeStartPos = buf.readBoolean();
placeStartPos = buf.readBoolean(); return new RequestLookAtMessage(placeStartPos);
} }
// The params of the IMessageHandler are <REQ, REPLY> public static class Handler
public static class MessageHandler implements IMessageHandler<RequestLookAtMessage, IMessage> { {
// Do note that the default constructor is required, but implicitly defined in this case public static void handle(RequestLookAtMessage message, Supplier<NetworkEvent.Context> ctx)
{
@Override ctx.get().enqueueWork(() -> {
public IMessage onMessage(RequestLookAtMessage message, MessageContext ctx) { if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
//EffortlessBuilding.log("message received on " + ctx.side + " side");
if (ctx.side == Side.CLIENT){
//Received clientside //Received clientside
//Send back your info //Send back your info
PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
// EffortlessBuilding.proxy.getThreadListenerFromContext(ctx).addScheduledTask(() -> { //Prevent double placing in normal mode with placeStartPos false
// EntityPlayer player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
//
// });
//Prevent double placing in normal mode with placeStartPos false.
//Unless QuickReplace is on, then we do need to place start pos. //Unless QuickReplace is on, then we do need to place start pos.
return new BlockPlacedMessage(ClientProxy.previousLookAt, message.getPlaceStartPos()); if (ClientProxy.previousLookAt.getType() == RayTraceResult.Type.BLOCK) {
PacketHandler.INSTANCE.sendToServer(new BlockPlacedMessage((BlockRayTraceResult) ClientProxy.previousLookAt, message.getPlaceStartPos()));
} else {
PacketHandler.INSTANCE.sendToServer(new BlockPlacedMessage());
} }
return null; }
});
ctx.get().setPacketHandled(true);
} }
} }
} }

View File

@@ -0,0 +1,79 @@
package nl.requios.effortlessbuilding.network;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.network.NetworkEvent;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmodifier.BlockSet;
import nl.requios.effortlessbuilding.buildmodifier.UndoRedo;
import java.util.ArrayList;
import java.util.function.Supplier;
public class TranslatedLogMessage {
private String prefix;
private String translationKey;
private String suffix;
private boolean actionBar;
public TranslatedLogMessage(){
prefix = "";
translationKey = "";
suffix = "";
actionBar = false;
}
public TranslatedLogMessage(String prefix, String translationKey, String suffix, boolean actionBar) {
this.prefix = prefix;
this.translationKey = translationKey;
this.suffix = suffix;
this.actionBar = actionBar;
}
public String getPrefix() {
return prefix;
}
public String getTranslationKey() {
return translationKey;
}
public String getSuffix() {
return suffix;
}
public boolean isActionBar() {
return actionBar;
}
public static void encode(TranslatedLogMessage message, PacketBuffer buf) {
buf.writeString(message.prefix);
buf.writeString(message.translationKey);
buf.writeString(message.suffix);
buf.writeBoolean(message.actionBar);
}
public static TranslatedLogMessage decode(PacketBuffer buf) {
return new TranslatedLogMessage(buf.readString(), buf.readString(), buf.readString(), buf.readBoolean());
}
public static class Handler
{
public static void handle(TranslatedLogMessage message, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
//Received clientside
PlayerEntity player = EffortlessBuilding.proxy.getPlayerEntityFromContext(ctx);
EffortlessBuilding.logTranslate(player, message.prefix, message.translationKey, message.suffix, message.actionBar);
}
});
ctx.get().setPacketHandled(true);
}
}
}

View File

@@ -1,173 +1,104 @@
package nl.requios.effortlessbuilding.proxy; package nl.requios.effortlessbuilding.proxy;
import net.minecraft.block.Block; import net.minecraft.block.BlockState;
import net.minecraft.block.SoundType; import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScreenManager;
import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.client.util.InputMappings;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item; import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand; import net.minecraft.util.Hand;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.*;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.settings.IKeyConflictContext;
import net.minecraftforge.client.settings.KeyConflictContext; import net.minecraftforge.client.settings.KeyConflictContext;
import net.minecraftforge.client.settings.KeyModifier; import net.minecraftforge.client.settings.KeyModifier;
import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DeferredWorkQueue;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.buildmode.ModeOptions;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager; import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.compatibility.CompatHelper;
import nl.requios.effortlessbuilding.gui.RandomizerBagScreen;
import nl.requios.effortlessbuilding.gui.buildmode.PlayerSettingsGui;
import nl.requios.effortlessbuilding.gui.buildmode.RadialMenu; import nl.requios.effortlessbuilding.gui.buildmode.RadialMenu;
import nl.requios.effortlessbuilding.gui.buildmodifier.ModifierSettingsGui; import nl.requios.effortlessbuilding.gui.buildmodifier.ModifierSettingsGui;
import nl.requios.effortlessbuilding.compatibility.CompatHelper;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import nl.requios.effortlessbuilding.render.RenderHandler;
import nl.requios.effortlessbuilding.render.ShaderHandler;
import nl.requios.effortlessbuilding.network.*; import nl.requios.effortlessbuilding.network.*;
import org.lwjgl.input.Keyboard; import nl.requios.effortlessbuilding.render.ShaderHandler;
import org.lwjgl.glfw.GLFW;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.HashMap; import java.util.HashMap;
import java.util.function.Supplier;
@Mod.EventBusSubscriber(Side.CLIENT) @Mod.EventBusSubscriber(value = {Dist.CLIENT})
public class ClientProxy implements IProxy { public class ClientProxy implements IProxy {
public static KeyBinding[] keyBindings; public static KeyBinding[] keyBindings;
public static RayTraceResult previousLookAt; public static RayTraceResult previousLookAt;
public static RayTraceResult currentLookAt; public static RayTraceResult currentLookAt;
private static int placeCooldown = 0; private static int placeCooldown = 0;
private static int breakCooldown = 0; private static int breakCooldown = 0;
private static boolean shadersInitialized = false;
public static int ticksInGame = 0; public static int ticksInGame = 0;
private static final HashMap<BuildModes.BuildModeEnum, TextureAtlasSprite> buildModeIcons = new HashMap<>(); @Override
private static final HashMap<ModeOptions.ActionEnum, TextureAtlasSprite> modeOptionIcons = new HashMap<>(); public void setup(FMLCommonSetupEvent event) {}
@Override @Override
public void preInit(FMLPreInitializationEvent event) { public void clientSetup(FMLClientSetupEvent event) {
ShaderHandler.init();
}
@Override
public void init(FMLInitializationEvent event) {
// register key bindings // register key bindings
keyBindings = new KeyBinding[7]; keyBindings = new KeyBinding[7];
// instantiate the key bindings // instantiate the key bindings
keyBindings[0] = new KeyBinding("key.effortlessbuilding.hud.desc", KeyConflictContext.UNIVERSAL, Keyboard.KEY_ADD, "key.effortlessbuilding.category"); keyBindings[0] = new KeyBinding("key.effortlessbuilding.hud.desc", KeyConflictContext.UNIVERSAL, InputMappings.getInputByCode(GLFW.GLFW_KEY_KP_ADD, 0), "key.effortlessbuilding.category");
keyBindings[1] = new KeyBinding("key.effortlessbuilding.replace.desc", KeyConflictContext.IN_GAME, Keyboard.KEY_SUBTRACT, "key.effortlessbuilding.category"); keyBindings[1] = new KeyBinding("key.effortlessbuilding.replace.desc", KeyConflictContext.IN_GAME, InputMappings.getInputByCode(GLFW.GLFW_KEY_KP_SUBTRACT, 0), "key.effortlessbuilding.category");
keyBindings[2] = new KeyBinding("key.effortlessbuilding.creative.desc", KeyConflictContext.IN_GAME, Keyboard.KEY_NONE, "key.effortlessbuilding.category"); keyBindings[2] = new KeyBinding("key.effortlessbuilding.creative.desc", KeyConflictContext.IN_GAME, InputMappings.getInputByCode(GLFW.GLFW_KEY_F4, 0), "key.effortlessbuilding.category");
keyBindings[3] = new KeyBinding("key.effortlessbuilding.mode.desc", KeyConflictContext.IN_GAME, Keyboard.KEY_LMENU, "key.effortlessbuilding.category") { keyBindings[3] = new KeyBinding("key.effortlessbuilding.mode.desc", KeyConflictContext.IN_GAME, InputMappings.getInputByCode(GLFW.GLFW_KEY_LEFT_ALT, 0), "key.effortlessbuilding.category") {
@Override @Override
public boolean conflicts(KeyBinding other) { public boolean conflicts(KeyBinding other) {
//Does not conflict with Chisels and Bits radial menu //Does not conflict with Chisels and Bits radial menu
if (other.getKeyCode() == getKeyCode() && other.getKeyDescription().equals("mod.chiselsandbits.other.mode")) return false; if (other.getKey().getKeyCode() == getKey().getKeyCode() && other.getKeyDescription().equals("mod.chiselsandbits.other.mode")) return false;
return super.conflicts(other); return super.conflicts(other);
} }
}; };
keyBindings[4] = new KeyBinding("key.effortlessbuilding.undo.desc", KeyConflictContext.IN_GAME, KeyModifier.CONTROL, Keyboard.KEY_Z, "key.effortlessbuilding.category"); keyBindings[4] = new KeyBinding("key.effortlessbuilding.undo.desc", KeyConflictContext.IN_GAME, KeyModifier.CONTROL, InputMappings.getInputByCode(GLFW.GLFW_KEY_Z, 0), "key.effortlessbuilding.category");
keyBindings[5] = new KeyBinding("key.effortlessbuilding.redo.desc", KeyConflictContext.IN_GAME, KeyModifier.CONTROL, Keyboard.KEY_Y, "key.effortlessbuilding.category"); keyBindings[5] = new KeyBinding("key.effortlessbuilding.redo.desc", KeyConflictContext.IN_GAME, KeyModifier.CONTROL, InputMappings.getInputByCode(GLFW.GLFW_KEY_Y, 0), "key.effortlessbuilding.category");
keyBindings[6] = new KeyBinding("key.effortlessbuilding.altplacement.desc", KeyConflictContext.IN_GAME, Keyboard.KEY_LCONTROL, "key.effortlessbuilding.category"); keyBindings[6] = new KeyBinding("key.effortlessbuilding.altplacement.desc", KeyConflictContext.IN_GAME, InputMappings.getInputByCode(GLFW.GLFW_KEY_LEFT_CONTROL, 0), "key.effortlessbuilding.category");
// keyBindings[7] = new KeyBinding("Reload shaders", Keyboard.KEY_TAB, "key.effortlessbuilding.category"); //keyBindings[7] = new KeyBinding("Reload shaders", KeyConflictContext.UNIVERSAL, InputMappings.getInputByCode(GLFW.GLFW_KEY_TAB, 0), "key.effortlessbuilding.category");
// register all the key bindings // register all the key bindings
for (int i = 0; i < keyBindings.length; ++i) { for (int i = 0; i < keyBindings.length; ++i) {
ClientRegistry.registerKeyBinding(keyBindings[i]); ClientRegistry.registerKeyBinding(keyBindings[i]);
} }
DeferredWorkQueue.runLater( () -> ScreenManager.registerFactory(EffortlessBuilding.RANDOMIZER_BAG_CONTAINER, RandomizerBagScreen::new));
} }
@Override public PlayerEntity getPlayerEntityFromContext(Supplier<NetworkEvent.Context> ctx){
public void postInit(FMLPostInitializationEvent event) { return (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT ? Minecraft.getInstance().player : ctx.get().getSender());
}
@Override
public EntityPlayer getPlayerEntityFromContext(MessageContext ctx) {
return (ctx.side.isClient() ? Minecraft.getMinecraft().player : ctx.getServerHandler().player);
}
@Override
public IThreadListener getThreadListenerFromContext(MessageContext ctx) {
return (ctx.side.isClient() ? Minecraft.getMinecraft() : ((EntityPlayerMP) getPlayerEntityFromContext(ctx)).getServerWorld());
}
@Override
public void serverStarting(FMLServerStartingEvent event) {
//This will get called clientside
}
@SubscribeEvent
public static void registerModels(ModelRegistryEvent event) {
for (Block block : EffortlessBuilding.BLOCKS) {
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(block), 0, new ModelResourceLocation(block.getRegistryName(), "inventory"));
}
for (Item item : EffortlessBuilding.ITEMS) {
ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(item.getRegistryName(), "inventory"));
}
}
@SubscribeEvent
public static void onEntityJoinWorld(EntityJoinWorldEvent event) {
if (event.getEntity() == Minecraft.getMinecraft().player) {
event.getWorld().addEventListener(new RenderHandler());
}
}
@SubscribeEvent
public static void onTextureStitch(final TextureStitchEvent.Pre event) {
//register icon textures
final TextureMap map = event.getMap();
for ( final BuildModes.BuildModeEnum mode : BuildModes.BuildModeEnum.values() )
{
final ResourceLocation sprite = new ResourceLocation("effortlessbuilding", "icons/" + mode.name().toLowerCase());
buildModeIcons.put( mode, map.registerSprite(sprite));
}
for ( final ModeOptions.ActionEnum action : ModeOptions.ActionEnum.values() )
{
final ResourceLocation sprite = new ResourceLocation("effortlessbuilding", "icons/" + action.name().toLowerCase());
modeOptionIcons.put( action, map.registerSprite(sprite));
}
}
public static TextureAtlasSprite getBuildModeIcon(BuildModes.BuildModeEnum mode) {
return buildModeIcons.get(mode);
}
public static TextureAtlasSprite getModeOptionIcon(ModeOptions.ActionEnum action) {
return modeOptionIcons.get(action);
} }
@SubscribeEvent @SubscribeEvent
@@ -177,7 +108,7 @@ public class ClientProxy implements IProxy {
onMouseInput(); onMouseInput();
//Update previousLookAt //Update previousLookAt
RayTraceResult objectMouseOver = Minecraft.getMinecraft().objectMouseOver; RayTraceResult objectMouseOver = Minecraft.getInstance().objectMouseOver;
//Checking for null is necessary! Even in vanilla when looking down ladders it is occasionally null (instead of Type MISS) //Checking for null is necessary! Even in vanilla when looking down ladders it is occasionally null (instead of Type MISS)
if (objectMouseOver == null) return; if (objectMouseOver == null) return;
@@ -187,69 +118,84 @@ public class ClientProxy implements IProxy {
return; return;
} }
if (objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) { if (objectMouseOver.getType() == RayTraceResult.Type.BLOCK) {
if (currentLookAt.typeOfHit != RayTraceResult.Type.BLOCK) { if (currentLookAt.getType() != RayTraceResult.Type.BLOCK) {
currentLookAt = objectMouseOver; currentLookAt = objectMouseOver;
previousLookAt = objectMouseOver; previousLookAt = objectMouseOver;
} else { } else {
if (currentLookAt.getBlockPos() != objectMouseOver.getBlockPos()) { if (((BlockRayTraceResult) currentLookAt).getPos() != ((BlockRayTraceResult) objectMouseOver).getPos()) {
previousLookAt = currentLookAt; previousLookAt = currentLookAt;
currentLookAt = objectMouseOver; currentLookAt = objectMouseOver;
} }
} }
} }
} else if (event.phase == TickEvent.Phase.END){ } else if (event.phase == TickEvent.Phase.END){
GuiScreen gui = Minecraft.getMinecraft().currentScreen; Screen gui = Minecraft.getInstance().currentScreen;
if(gui == null || !gui.doesGuiPauseGame()) { if(gui == null || !gui.isPauseScreen()) {
ticksInGame++; ticksInGame++;
} }
//Init shaders in the first tick. Doing it anywhere before this seems to crash the game.
if (!shadersInitialized) {
ShaderHandler.init();
shadersInitialized = true;
}
} }
} }
private static void onMouseInput() { private static void onMouseInput() {
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getInstance();
EntityPlayerSP player = mc.player; ClientPlayerEntity player = mc.player;
if (player == null) return; if (player == null) return;
BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode(); BuildModes.BuildModeEnum buildMode = ModeSettingsManager.getModeSettings(player).getBuildMode();
if (Minecraft.getMinecraft().currentScreen != null || if (Minecraft.getInstance().currentScreen != null ||
buildMode == BuildModes.BuildModeEnum.NORMAL || buildMode == BuildModes.BuildModeEnum.NORMAL ||
RadialMenu.instance.isVisible()) { RadialMenu.instance.isVisible()) {
return; return;
} }
if (mc.gameSettings.keyBindUseItem.isKeyDown()) { if (mc.gameSettings.keyBindUseItem.isKeyDown()) {
//KeyBinding.setKeyBindState(mc.gameSettings.keyBindUseItem.getKeyCode(), false); //KeyBinding.setKeyBindState(mc.gameSettings.keyBindUseItem.getKeyCode(), false);
if (placeCooldown <= 0) { if (placeCooldown <= 0) {
placeCooldown = 4; placeCooldown = 4;
ItemStack currentItemStack = player.getHeldItem(EnumHand.MAIN_HAND); ItemStack currentItemStack = player.getHeldItem(Hand.MAIN_HAND);
if (currentItemStack.getItem() instanceof ItemBlock || if (currentItemStack.getItem() instanceof BlockItem ||
(CompatHelper.isItemBlockProxy(currentItemStack) && !player.isSneaking())) { (CompatHelper.isItemBlockProxy(currentItemStack) && !player.isSneaking())) {
ItemStack itemStack = CompatHelper.getItemBlockFromStack(currentItemStack); ItemStack itemStack = CompatHelper.getItemBlockFromStack(currentItemStack);
//find position in distance //find position in distance
RayTraceResult lookingAt = getLookingAt(player); RayTraceResult lookingAt = getLookingAt(player);
BuildModes.onBlockPlacedMessage(player, lookingAt == null ? new BlockPlacedMessage() : new BlockPlacedMessage(lookingAt, true)); if (lookingAt != null && lookingAt.getType() == RayTraceResult.Type.BLOCK) {
EffortlessBuilding.packetHandler.sendToServer(lookingAt == null ? new BlockPlacedMessage() : new BlockPlacedMessage(lookingAt, true)); BlockRayTraceResult blockLookingAt = (BlockRayTraceResult) lookingAt;
BuildModes.onBlockPlacedMessage(player, new BlockPlacedMessage(blockLookingAt, true));
PacketHandler.INSTANCE.sendToServer(new BlockPlacedMessage(blockLookingAt, true));
//play sound if further than normal //play sound if further than normal
if (lookingAt != null && lookingAt.typeOfHit == RayTraceResult.Type.BLOCK && if ((blockLookingAt.getHitVec().subtract(player.getEyePosition(1f))).lengthSquared() > 25f &&
(lookingAt.hitVec.subtract(player.getPositionEyes(1f))).lengthSquared() > 25f && itemStack.getItem() instanceof BlockItem) {
itemStack.getItem() instanceof ItemBlock) {
IBlockState state = ((ItemBlock) itemStack.getItem()).getBlock().getDefaultState(); BlockState state = ((BlockItem) itemStack.getItem()).getBlock().getDefaultState();
BlockPos blockPos = lookingAt.getBlockPos(); BlockPos blockPos = blockLookingAt.getPos();
SoundType soundType = state.getBlock().getSoundType(state, player.world, blockPos, player); SoundType soundType = state.getBlock().getSoundType(state, player.world, blockPos, player);
player.world.playSound(player, player.getPosition(), soundType.getPlaceSound(), SoundCategory.BLOCKS, player.world.playSound(player, player.getPosition(), soundType.getPlaceSound(), SoundCategory.BLOCKS,
0.4f, soundType.getPitch() * 1f); 0.4f, soundType.getPitch() * 1f);
player.swingArm(EnumHand.MAIN_HAND); player.swingArm(Hand.MAIN_HAND);
}
} else {
BuildModes.onBlockPlacedMessage(player, new BlockPlacedMessage());
PacketHandler.INSTANCE.sendToServer(new BlockPlacedMessage());
} }
} }
} else if (buildMode == BuildModes.BuildModeEnum.NORMAL_PLUS) { }
else if (buildMode == BuildModes.BuildModeEnum.NORMAL_PLUS) {
placeCooldown--; placeCooldown--;
if (ModeOptions.getBuildSpeed() == ModeOptions.ActionEnum.FAST_SPEED) placeCooldown = 0; if (ModeOptions.getBuildSpeed() == ModeOptions.ActionEnum.FAST_SPEED) placeCooldown = 0;
} }
@@ -270,21 +216,28 @@ public class ClientProxy implements IProxy {
if (!ReachHelper.canBreakFar(player)) return; if (!ReachHelper.canBreakFar(player)) return;
RayTraceResult lookingAt = getLookingAt(player); RayTraceResult lookingAt = getLookingAt(player);
BuildModes.onBlockBrokenMessage(player, lookingAt == null ? new BlockBrokenMessage() : new BlockBrokenMessage(lookingAt)); if (lookingAt != null && lookingAt.getType() == RayTraceResult.Type.BLOCK) {
EffortlessBuilding.packetHandler.sendToServer(lookingAt == null ? new BlockBrokenMessage() : new BlockBrokenMessage(lookingAt)); BlockRayTraceResult blockLookingAt = (BlockRayTraceResult) lookingAt;
BuildModes.onBlockBrokenMessage(player, new BlockBrokenMessage(blockLookingAt));
PacketHandler.INSTANCE.sendToServer(new BlockBrokenMessage(blockLookingAt));
//play sound if further than normal //play sound if further than normal
if (lookingAt != null && lookingAt.typeOfHit == RayTraceResult.Type.BLOCK && if ((blockLookingAt.getHitVec().subtract(player.getEyePosition(1f))).lengthSquared() > 25f) {
(lookingAt.hitVec.subtract(player.getPositionEyes(1f))).lengthSquared() > 25f) {
BlockPos blockPos = lookingAt.getBlockPos(); BlockPos blockPos = blockLookingAt.getPos();
IBlockState state = player.world.getBlockState(blockPos); BlockState state = player.world.getBlockState(blockPos);
SoundType soundtype = state.getBlock().getSoundType(state, player.world, blockPos, player); SoundType soundtype = state.getBlock().getSoundType(state, player.world, blockPos, player);
player.world.playSound(player, player.getPosition(), soundtype.getBreakSound(), SoundCategory.BLOCKS, player.world.playSound(player, player.getPosition(), soundtype.getBreakSound(), SoundCategory.BLOCKS,
0.4f, soundtype.getPitch() * 1f); 0.4f, soundtype.getPitch() * 1f);
player.swingArm(EnumHand.MAIN_HAND); player.swingArm(Hand.MAIN_HAND);
} }
} else if (buildMode == BuildModes.BuildModeEnum.NORMAL_PLUS) { } else {
BuildModes.onBlockBrokenMessage(player, new BlockBrokenMessage());
PacketHandler.INSTANCE.sendToServer(new BlockBrokenMessage());
}
}
else if (buildMode == BuildModes.BuildModeEnum.NORMAL_PLUS) {
breakCooldown--; breakCooldown--;
if (ModeOptions.getBuildSpeed() == ModeOptions.ActionEnum.FAST_SPEED) breakCooldown = 0; if (ModeOptions.getBuildSpeed() == ModeOptions.ActionEnum.FAST_SPEED) breakCooldown = 0;
} }
@@ -294,18 +247,11 @@ public class ClientProxy implements IProxy {
} else { } else {
breakCooldown = 0; breakCooldown = 0;
} }
if (mc.gameSettings.keyBindAttack.isPressed()) {
if (RadialMenu.instance.isVisible()) {
EffortlessBuilding.log(player, "mouse click");
}
} }
} @SubscribeEvent(receiveCanceled = true)
@SubscribeEvent(priority = EventPriority.NORMAL, receiveCanceled = true)
public static void onKeyPress(InputEvent.KeyInputEvent event) { public static void onKeyPress(InputEvent.KeyInputEvent event) {
EntityPlayerSP player = Minecraft.getMinecraft().player; ClientPlayerEntity player = Minecraft.getInstance().player;
//Remember to send packet to server if necessary //Remember to send packet to server if necessary
//Show Modifier Settings GUI //Show Modifier Settings GUI
@@ -319,15 +265,15 @@ public class ClientProxy implements IProxy {
modifierSettings.setQuickReplace(!modifierSettings.doQuickReplace()); modifierSettings.setQuickReplace(!modifierSettings.doQuickReplace());
EffortlessBuilding.log(player, "Set " + TextFormatting.GOLD + "Quick Replace " + TextFormatting.RESET + ( EffortlessBuilding.log(player, "Set " + TextFormatting.GOLD + "Quick Replace " + TextFormatting.RESET + (
modifierSettings.doQuickReplace() ? "on" : "off")); modifierSettings.doQuickReplace() ? "on" : "off"));
EffortlessBuilding.packetHandler.sendToServer(new ModifierSettingsMessage(modifierSettings)); PacketHandler.INSTANCE.sendToServer(new ModifierSettingsMessage(modifierSettings));
} }
//Creative/survival mode toggle //Creative/survival mode toggle
if (keyBindings[2].isPressed()) { if (keyBindings[2].isPressed()) {
if (player.isCreative()) { if (player.isCreative()) {
player.sendChatMessage("/gamemode 0"); player.sendChatMessage("/gamemode survival");
} else { } else {
player.sendChatMessage("/gamemode 1"); player.sendChatMessage("/gamemode creative");
} }
} }
@@ -335,14 +281,14 @@ public class ClientProxy implements IProxy {
if (keyBindings[4].isPressed()) { if (keyBindings[4].isPressed()) {
ModeOptions.ActionEnum action = ModeOptions.ActionEnum.UNDO; ModeOptions.ActionEnum action = ModeOptions.ActionEnum.UNDO;
ModeOptions.performAction(player, action); ModeOptions.performAction(player, action);
EffortlessBuilding.packetHandler.sendToServer(new ModeActionMessage(action)); PacketHandler.INSTANCE.sendToServer(new ModeActionMessage(action));
} }
//Redo (Ctrl+Y) //Redo (Ctrl+Y)
if (keyBindings[5].isPressed()) { if (keyBindings[5].isPressed()) {
ModeOptions.ActionEnum action = ModeOptions.ActionEnum.REDO; ModeOptions.ActionEnum action = ModeOptions.ActionEnum.REDO;
ModeOptions.performAction(player, action); ModeOptions.performAction(player, action);
EffortlessBuilding.packetHandler.sendToServer(new ModeActionMessage(action)); PacketHandler.INSTANCE.sendToServer(new ModeActionMessage(action));
} }
//Change placement mode //Change placement mode
@@ -354,10 +300,10 @@ public class ClientProxy implements IProxy {
if (option.actions.length >= 2) { if (option.actions.length >= 2) {
if (ModeOptions.getOptionSetting(option) == option.actions[0]) { if (ModeOptions.getOptionSetting(option) == option.actions[0]) {
ModeOptions.performAction(player, option.actions[1]); ModeOptions.performAction(player, option.actions[1]);
EffortlessBuilding.packetHandler.sendToServer(new ModeActionMessage(option.actions[1])); PacketHandler.INSTANCE.sendToServer(new ModeActionMessage(option.actions[1]));
} else { } else {
ModeOptions.performAction(player, option.actions[0]); ModeOptions.performAction(player, option.actions[0]);
EffortlessBuilding.packetHandler.sendToServer(new ModeActionMessage(option.actions[0])); PacketHandler.INSTANCE.sendToServer(new ModeActionMessage(option.actions[0]));
} }
} }
} }
@@ -372,8 +318,8 @@ public class ClientProxy implements IProxy {
} }
public static void openModifierSettings() { public static void openModifierSettings() {
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getInstance();
EntityPlayerSP player = mc.player; ClientPlayerEntity player = mc.player;
RadialMenu.instance.setVisibility(0f); RadialMenu.instance.setVisibility(0f);
@@ -389,29 +335,45 @@ public class ClientProxy implements IProxy {
} }
} }
public static void openPlayerSettings() {
Minecraft mc = Minecraft.getInstance();
ClientPlayerEntity player = mc.player;
RadialMenu.instance.setVisibility(0f);
//Disabled if max reach is 0, might be set in the config that way.
if (mc.currentScreen == null) {
mc.displayGuiScreen(new PlayerSettingsGui());
} else {
player.closeScreen();
}
}
@SubscribeEvent @SubscribeEvent
public static void onGuiOpen(GuiOpenEvent event) { public static void onGuiOpen(GuiOpenEvent event) {
EntityPlayer player = Minecraft.getMinecraft().player; PlayerEntity player = Minecraft.getInstance().player;
if (player != null) { if (player != null) {
BuildModes.initializeMode(player); BuildModes.initializeMode(player);
} }
} }
@Nullable @Nullable
public static RayTraceResult getLookingAt(EntityPlayer player) { public static RayTraceResult getLookingAt(PlayerEntity player) {
// World world = player.world; World world = player.world;
//base distance off of player ability (config) //base distance off of player ability (config)
float raytraceRange = ReachHelper.getPlacementReach(player); float raytraceRange = ReachHelper.getPlacementReach(player);
// Vec3d look = player.getLookVec(); Vec3d look = player.getLookVec();
// Vec3d start = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ); Vec3d start = new Vec3d(player.getPosX(), player.getPosY() + player.getEyeHeight(), player.getPosZ());
// Vec3d end = new Vec3d(player.posX + look.x * raytraceRange, player.posY + player.getEyeHeight() + look.y * raytraceRange, player.posZ + look.z * raytraceRange); Vec3d end = new Vec3d(player.getPosX() + look.x * raytraceRange, player.getPosY() + player.getEyeHeight() + look.y * raytraceRange, player.getPosZ() + look.z * raytraceRange);
return player.rayTrace(raytraceRange, 1f); // return player.rayTrace(raytraceRange, 1f, RayTraceFluidMode.NEVER);
// return world.rayTraceBlocks(start, end, false, false, false); //TODO 1.14 check if correct
return world.rayTraceBlocks(new RayTraceContext(start, end, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, player));
} }
public static void logTranslate(String key) { @Override
EffortlessBuilding.log(Minecraft.getMinecraft().player, I18n.format(key), true); public void logTranslate(PlayerEntity player, String prefix, String translationKey, String suffix, boolean actionBar) {
EffortlessBuilding.log(Minecraft.getInstance().player, prefix + I18n.format(translationKey) + suffix, actionBar);
} }
} }

View File

@@ -1,43 +1,18 @@
package nl.requios.effortlessbuilding.proxy; package nl.requios.effortlessbuilding.proxy;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.IThreadListener; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public interface IProxy import java.util.function.Supplier;
{
/**
* Register entities and networking.
*/
void preInit(FMLPreInitializationEvent event);
/** public interface IProxy {
* Register event listeners, recipes and advancements. void setup(final FMLCommonSetupEvent event);
*/
void init(FMLInitializationEvent event);
/** void clientSetup(final FMLClientSetupEvent event);
* For doing inter-mod stuff like checking which mods are loaded or if you want a complete view of things across
* mods like having a list of all registered items to aid random item generation.
*/
void postInit(FMLPostInitializationEvent event);
/** PlayerEntity getPlayerEntityFromContext(Supplier<NetworkEvent.Context> ctx);
* Server commands should be registered here.
*/
void serverStarting(FMLServerStartingEvent event);
/** void logTranslate(PlayerEntity player, String prefix, String translationKey, String suffix, boolean actionBar);
* Returns a side-appropriate EntityPlayer for use during message handling.
*
* @param ctx the context
* @return the player entity from context
*/
EntityPlayer getPlayerEntityFromContext(MessageContext ctx);
IThreadListener getThreadListenerFromContext(MessageContext ctx);
} }

View File

@@ -1,45 +1,32 @@
package nl.requios.effortlessbuilding.proxy; package nl.requios.effortlessbuilding.proxy;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.IThreadListener; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.network.PacketDistributor;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import nl.requios.effortlessbuilding.network.PacketHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import nl.requios.effortlessbuilding.network.TranslatedLogMessage;
public class ServerProxy implements IProxy import java.util.function.Supplier;
{
public class ServerProxy implements IProxy {
//Only physical server! Singleplayer server is seen as clientproxy //Only physical server! Singleplayer server is seen as clientproxy
@Override @Override
public void preInit(FMLPreInitializationEvent event) public void setup(FMLCommonSetupEvent event) {
{
} }
@Override @Override
public void init(FMLInitializationEvent event) public void clientSetup(FMLClientSetupEvent event) {}
{
public PlayerEntity getPlayerEntityFromContext(Supplier<NetworkEvent.Context> ctx){
return ctx.get().getSender();
} }
@Override @Override
public void postInit(FMLPostInitializationEvent event) public void logTranslate(PlayerEntity player, String prefix, String translationKey, String suffix, boolean actionBar) {
{ PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), new TranslatedLogMessage(prefix, translationKey, suffix, actionBar));
}
@Override
public void serverStarting(FMLServerStartingEvent event)
{
}
@Override
public EntityPlayer getPlayerEntityFromContext(MessageContext ctx)
{
return ctx.getServerHandler().player;
}
@Override
public IThreadListener getThreadListenerFromContext(MessageContext ctx) {
return ((EntityPlayerMP) getPlayerEntityFromContext(ctx)).getServerWorld();
} }
} }

View File

@@ -1,21 +1,23 @@
package nl.requios.effortlessbuilding.render; package nl.requios.effortlessbuilding.render;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import net.minecraft.block.BlockState;
import net.minecraft.block.SoundType; import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.renderer.BlockRendererDispatcher; import net.minecraft.client.renderer.BlockRendererDispatcher;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.texture.AtlasTexture;
import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.*; import net.minecraft.util.math.*;
import net.minecraftforge.fml.relauncher.Side; import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.BuildModes; import nl.requios.effortlessbuilding.buildmode.BuildModes;
@@ -26,24 +28,21 @@ import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager.ModifierSettings; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager.ModifierSettings;
import nl.requios.effortlessbuilding.compatibility.CompatHelper; import nl.requios.effortlessbuilding.compatibility.CompatHelper;
import nl.requios.effortlessbuilding.helper.InventoryHelper;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import nl.requios.effortlessbuilding.helper.SurvivalHelper; import nl.requios.effortlessbuilding.helper.SurvivalHelper;
import nl.requios.effortlessbuilding.item.ItemRandomizerBag; import nl.requios.effortlessbuilding.item.ItemRandomizerBag;
import nl.requios.effortlessbuilding.proxy.ClientProxy; import nl.requios.effortlessbuilding.proxy.ClientProxy;
import org.lwjgl.opengl.ARBMultitexture; import org.lwjgl.opengl.*;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
@SideOnly(Side.CLIENT) @OnlyIn(Dist.CLIENT)
public class BlockPreviewRenderer { public class BlockPreviewRenderer {
private static List<BlockPos> previousCoordinates; private static List<BlockPos> previousCoordinates;
private static List<IBlockState> previousBlockStates; private static List<BlockState> previousBlockStates;
private static List<ItemStack> previousItemStacks; private static List<ItemStack> previousItemStacks;
private static BlockPos previousFirstPos; private static BlockPos previousFirstPos;
private static BlockPos previousSecondPos; private static BlockPos previousSecondPos;
@@ -52,13 +51,13 @@ public class BlockPreviewRenderer {
static class PlacedData { static class PlacedData {
float time; float time;
List<BlockPos> coordinates; List<BlockPos> coordinates;
List<IBlockState> blockStates; List<BlockState> blockStates;
List<ItemStack> itemStacks; List<ItemStack> itemStacks;
BlockPos firstPos; BlockPos firstPos;
BlockPos secondPos; BlockPos secondPos;
boolean breaking; boolean breaking;
public PlacedData(float time, List<BlockPos> coordinates, List<IBlockState> blockStates, public PlacedData(float time, List<BlockPos> coordinates, List<BlockState> blockStates,
List<ItemStack> itemStacks, BlockPos firstPos, BlockPos secondPos, boolean breaking) { List<ItemStack> itemStacks, BlockPos firstPos, BlockPos secondPos, boolean breaking) {
this.time = time; this.time = time;
this.coordinates = coordinates; this.coordinates = coordinates;
@@ -72,52 +71,49 @@ public class BlockPreviewRenderer {
private static List<PlacedData> placedDataList = new ArrayList<>(); private static List<PlacedData> placedDataList = new ArrayList<>();
private static final int primaryTextureUnit = 0; public static void render(MatrixStack matrixStack, IRenderTypeBuffer.Impl renderTypeBuffer, PlayerEntity player, ModifierSettings modifierSettings, ModeSettings modeSettings) {
private static final int secondaryTextureUnit = 2;
public static void render(EntityPlayer player, ModifierSettings modifierSettings, ModeSettings modeSettings) {
//Render placed blocks with dissolve effect //Render placed blocks with dissolve effect
//Use fancy shader if config allows, otherwise no dissolve //Use fancy shader if config allows, otherwise no dissolve
if (BuildConfig.visuals.useShaders) { if (BuildConfig.visuals.useShaders.get()) {
RenderHandler.beginBlockPreviews();
for (int i = 0; i < placedDataList.size(); i++) { for (int i = 0; i < placedDataList.size(); i++) {
PlacedData placed = placedDataList.get(i); PlacedData placed = placedDataList.get(i);
if (placed.coordinates != null && !placed.coordinates.isEmpty()) { if (placed.coordinates != null && !placed.coordinates.isEmpty()) {
double totalTime = MathHelper.clampedLerp(30, 60, placed.firstPos.distanceSq(placed.secondPos) / 100.0) * BuildConfig.visuals.dissolveTimeMultiplier; double totalTime = MathHelper.clampedLerp(30, 60, placed.firstPos.distanceSq(placed.secondPos) / 100.0) * BuildConfig.visuals.dissolveTimeMultiplier.get();
float dissolve = (ClientProxy.ticksInGame - placed.time) / (float) totalTime; float dissolve = (ClientProxy.ticksInGame - placed.time) / (float) totalTime;
renderBlockPreviews(placed.coordinates, placed.blockStates, placed.itemStacks, dissolve, placed.firstPos, placed.secondPos, false, placed.breaking); renderBlockPreviews(matrixStack, renderTypeBuffer, placed.coordinates, placed.blockStates, placed.itemStacks, dissolve, placed.firstPos, placed.secondPos, false, placed.breaking);
} }
} }
RenderHandler.endBlockPreviews();
} }
//Expire //Expire
placedDataList.removeIf(placed -> { placedDataList.removeIf(placed -> {
double totalTime = MathHelper.clampedLerp(30, 60, placed.firstPos.distanceSq(placed.secondPos) / 100.0) * BuildConfig.visuals.dissolveTimeMultiplier; double totalTime = MathHelper.clampedLerp(30, 60, placed.firstPos.distanceSq(placed.secondPos) / 100.0) * BuildConfig.visuals.dissolveTimeMultiplier.get();
return placed.time + totalTime < ClientProxy.ticksInGame; return placed.time + totalTime < ClientProxy.ticksInGame;
}); });
//Render block previews //Render block previews
RayTraceResult lookingAt = ClientProxy.getLookingAt(player); RayTraceResult lookingAt = ClientProxy.getLookingAt(player);
if (modeSettings.getBuildMode() == BuildModes.BuildModeEnum.NORMAL) lookingAt = Minecraft.getMinecraft().objectMouseOver; if (modeSettings.getBuildMode() == BuildModes.BuildModeEnum.NORMAL) lookingAt = Minecraft.getInstance().objectMouseOver;
ItemStack mainhand = player.getHeldItemMainhand(); ItemStack mainhand = player.getHeldItemMainhand();
boolean toolInHand = !(!mainhand.isEmpty() && CompatHelper.isItemBlockProxy(mainhand)); boolean toolInHand = !(!mainhand.isEmpty() && CompatHelper.isItemBlockProxy(mainhand));
BlockPos startPos = null; BlockPos startPos = null;
EnumFacing sideHit = null; Direction sideHit = null;
Vec3d hitVec = null; Vec3d hitVec = null;
//Checking for null is necessary! Even in vanilla when looking down ladders it is occasionally null (instead of Type MISS) //Checking for null is necessary! Even in vanilla when looking down ladders it is occasionally null (instead of Type MISS)
if (lookingAt != null && lookingAt.typeOfHit == RayTraceResult.Type.BLOCK) { if (lookingAt != null && lookingAt.getType() == RayTraceResult.Type.BLOCK) {
startPos = lookingAt.getBlockPos(); BlockRayTraceResult blockLookingAt = (BlockRayTraceResult) lookingAt;
startPos = blockLookingAt.getPos();
//Check if tool (or none) in hand //Check if tool (or none) in hand
boolean replaceable = player.world.getBlockState(startPos).getBlock().isReplaceable(player.world, startPos); //TODO 1.13 replaceable
boolean becomesDoubleSlab = SurvivalHelper.doesBecomeDoubleSlab(player, startPos, lookingAt.sideHit); boolean replaceable = player.world.getBlockState(startPos).getBlock().getMaterial(player.world.getBlockState(startPos)).isReplaceable();
boolean becomesDoubleSlab = SurvivalHelper.doesBecomeDoubleSlab(player, startPos, blockLookingAt.getFace());
if (!modifierSettings.doQuickReplace() && !toolInHand && !replaceable && !becomesDoubleSlab) { if (!modifierSettings.doQuickReplace() && !toolInHand && !replaceable && !becomesDoubleSlab) {
startPos = startPos.offset(lookingAt.sideHit); startPos = startPos.offset(blockLookingAt.getFace());
} }
//Get under tall grass and other replaceable blocks //Get under tall grass and other replaceable blocks
@@ -125,8 +121,8 @@ public class BlockPreviewRenderer {
startPos = startPos.down(); startPos = startPos.down();
} }
sideHit = lookingAt.sideHit; sideHit = blockLookingAt.getFace();
hitVec = lookingAt.hitVec; hitVec = blockLookingAt.getHitVec();
} }
//Dont render if in normal mode and modifiers are disabled //Dont render if in normal mode and modifiers are disabled
@@ -149,8 +145,8 @@ public class BlockPreviewRenderer {
//get coordinates //get coordinates
List<BlockPos> startCoordinates = BuildModes.findCoordinates(player, startPos, breaking || modifierSettings.doQuickReplace()); List<BlockPos> startCoordinates = BuildModes.findCoordinates(player, startPos, breaking || modifierSettings.doQuickReplace());
BlockPos firstPos = BlockPos.ORIGIN, secondPos = BlockPos.ORIGIN; //Remember first and last point for the shader
//Remember first and last pos for the shader BlockPos firstPos = BlockPos.ZERO, secondPos = BlockPos.ZERO;
if (!startCoordinates.isEmpty()) { if (!startCoordinates.isEmpty()) {
firstPos = startCoordinates.get(0); firstPos = startCoordinates.get(0);
secondPos = startCoordinates.get(startCoordinates.size() - 1); secondPos = startCoordinates.get(startCoordinates.size() - 1);
@@ -171,7 +167,7 @@ public class BlockPreviewRenderer {
//Get blockstates //Get blockstates
List<ItemStack> itemStacks = new ArrayList<>(); List<ItemStack> itemStacks = new ArrayList<>();
List<IBlockState> blockStates = new ArrayList<>(); List<BlockState> blockStates = new ArrayList<>();
if (breaking) { if (breaking) {
//Find blockstate of world //Find blockstate of world
for (BlockPos coordinate : newCoordinates) { for (BlockPos coordinate : newCoordinates) {
@@ -212,26 +208,20 @@ public class BlockPreviewRenderer {
int blockCount; int blockCount;
//Use fancy shader if config allows, otherwise outlines //Use fancy shader if config allows, otherwise outlines
if (BuildConfig.visuals.useShaders && newCoordinates.size() < BuildConfig.visuals.shaderTreshold) { if (BuildConfig.visuals.useShaders.get() && newCoordinates.size() < BuildConfig.visuals.shaderTreshold.get()) {
blockCount = renderBlockPreviews(matrixStack, renderTypeBuffer, newCoordinates, blockStates, itemStacks, 0f, firstPos, secondPos, !breaking, breaking);
RenderHandler.beginBlockPreviews();
blockCount = renderBlockPreviews(newCoordinates, blockStates, itemStacks, 0f, firstPos, secondPos, !breaking, breaking);
RenderHandler.endBlockPreviews();
} else { } else {
IVertexBuilder buffer = RenderHandler.beginLines(renderTypeBuffer);
RenderHandler.beginLines();
Vec3d color = new Vec3d(1f, 1f, 1f); Vec3d color = new Vec3d(1f, 1f, 1f);
if (breaking) color = new Vec3d(1f, 0f, 0f); if (breaking) color = new Vec3d(1f, 0f, 0f);
for (int i = newCoordinates.size() - 1; i >= 0; i--) { for (int i = newCoordinates.size() - 1; i >= 0; i--) {
AxisAlignedBB boundingBox = blockStates.get(i).getBoundingBox(player.world, newCoordinates.get(i)); VoxelShape collisionShape = blockStates.get(i).getCollisionShape(player.world, newCoordinates.get(i));
RenderHandler.renderBlockOutline(newCoordinates.get(i), boundingBox, color); RenderHandler.renderBlockOutline(matrixStack, buffer, newCoordinates.get(i), collisionShape, color);
} }
RenderHandler.endLines(); RenderHandler.endLines(renderTypeBuffer);
blockCount = newCoordinates.size(); blockCount = newCoordinates.size();
} }
@@ -267,29 +257,30 @@ public class BlockPreviewRenderer {
} }
RenderHandler.beginLines(); IVertexBuilder buffer = RenderHandler.beginLines(renderTypeBuffer);
//Draw outlines if tool in hand //Draw outlines if tool in hand
//Find proper raytrace: either normal range or increased range depending on canBreakFar //Find proper raytrace: either normal range or increased range depending on canBreakFar
RayTraceResult objectMouseOver = Minecraft.getMinecraft().objectMouseOver; RayTraceResult objectMouseOver = Minecraft.getInstance().objectMouseOver;
RayTraceResult breakingRaytrace = ReachHelper.canBreakFar(player) ? lookingAt : objectMouseOver; RayTraceResult breakingRaytrace = ReachHelper.canBreakFar(player) ? lookingAt : objectMouseOver;
if (toolInHand && breakingRaytrace != null && breakingRaytrace.typeOfHit == RayTraceResult.Type.BLOCK) { if (toolInHand && breakingRaytrace != null && breakingRaytrace.getType() == RayTraceResult.Type.BLOCK) {
List<BlockPos> breakCoordinates = BuildModifiers.findCoordinates(player, breakingRaytrace.getBlockPos()); BlockRayTraceResult blockBreakingRaytrace = (BlockRayTraceResult) breakingRaytrace;
List<BlockPos> breakCoordinates = BuildModifiers.findCoordinates(player, blockBreakingRaytrace.getPos());
//Only render first outline if further than normal reach //Only render first outline if further than normal reach
boolean excludeFirst = objectMouseOver != null && objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK; boolean excludeFirst = objectMouseOver != null && objectMouseOver.getType() == RayTraceResult.Type.BLOCK;
for (int i = excludeFirst ? 1 : 0; i < breakCoordinates.size(); i++) { for (int i = excludeFirst ? 1 : 0; i < breakCoordinates.size(); i++) {
BlockPos coordinate = breakCoordinates.get(i); BlockPos coordinate = breakCoordinates.get(i);
IBlockState blockState = player.world.getBlockState(coordinate); BlockState blockState = player.world.getBlockState(coordinate);
if (!blockState.getBlock().isAir(blockState, player.world, coordinate)) { if (!blockState.getBlock().isAir(blockState, player.world, coordinate)) {
if (SurvivalHelper.canBreak(player.world, player, coordinate) || i == 0) { if (SurvivalHelper.canBreak(player.world, player, coordinate) || i == 0) {
AxisAlignedBB boundingBox = blockState.getBoundingBox(player.world, coordinate); VoxelShape collisionShape = blockState.getCollisionShape(player.world, coordinate);
RenderHandler.renderBlockOutline(coordinate, boundingBox, new Vec3d(0f, 0f, 0f)); RenderHandler.renderBlockOutline(matrixStack, buffer, coordinate, collisionShape, new Vec3d(0f, 0f, 0f));
} }
} }
} }
} }
RenderHandler.endLines(); RenderHandler.endLines(renderTypeBuffer);
} }
} }
@@ -297,35 +288,32 @@ public class BlockPreviewRenderer {
public static boolean doRenderBlockPreviews(ModifierSettings modifierSettings, ModeSettings modeSettings, BlockPos startPos) { public static boolean doRenderBlockPreviews(ModifierSettings modifierSettings, ModeSettings modeSettings, BlockPos startPos) {
return modeSettings.getBuildMode() != BuildModes.BuildModeEnum.NORMAL || return modeSettings.getBuildMode() != BuildModes.BuildModeEnum.NORMAL ||
(startPos != null && BuildModifiers.isEnabled(modifierSettings, startPos)) || (startPos != null && BuildModifiers.isEnabled(modifierSettings, startPos)) ||
BuildConfig.visuals.alwaysShowBlockPreview; BuildConfig.visuals.alwaysShowBlockPreview.get();
} }
protected static int renderBlockPreviews(List<BlockPos> coordinates, List<IBlockState> blockStates, protected static int renderBlockPreviews(MatrixStack matrixStack, IRenderTypeBuffer.Impl renderTypeBuffer, List<BlockPos> coordinates, List<BlockState> blockStates,
List<ItemStack> itemStacks, float dissolve, BlockPos firstPos, List<ItemStack> itemStacks, float dissolve, BlockPos firstPos,
BlockPos secondPos, boolean checkCanPlace, boolean red) { BlockPos secondPos, boolean checkCanPlace, boolean red) {
EntityPlayer player = Minecraft.getMinecraft().player; PlayerEntity player = Minecraft.getInstance().player;
ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
BlockRendererDispatcher dispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); BlockRendererDispatcher dispatcher = Minecraft.getInstance().getBlockRendererDispatcher();
int blocksValid = 0; int blocksValid = 0;
if (coordinates.isEmpty()) return blocksValid; if (coordinates.isEmpty()) return blocksValid;
for (int i = coordinates.size() - 1; i >= 0; i--) { for (int i = coordinates.size() - 1; i >= 0; i--) {
BlockPos blockPos = coordinates.get(i); BlockPos blockPos = coordinates.get(i);
IBlockState blockState = blockStates.get(i); BlockState blockState = blockStates.get(i);
ItemStack itemstack = itemStacks.isEmpty() ? ItemStack.EMPTY : itemStacks.get(i); ItemStack itemstack = itemStacks.isEmpty() ? ItemStack.EMPTY : itemStacks.get(i);
if (CompatHelper.isItemBlockProxy(itemstack)) if (CompatHelper.isItemBlockProxy(itemstack))
itemstack = CompatHelper.getItemBlockByState(itemstack, blockState); itemstack = CompatHelper.getItemBlockByState(itemstack, blockState);
//Check if can place //Check if can place
//If check is turned off, check if blockstate is the same (for dissolve effect) //If check is turned off, check if blockstate is the same (for dissolve effect)
if ((!checkCanPlace /*&& player.world.getNewBlockState(blockPos) == blockState*/) || //TODO enable (breaks breaking shader) if ((!checkCanPlace /*&& player.world.getNewBlockState(blockPos) == blockState*/) || //TODO enable (breaks the breaking shader)
SurvivalHelper.canPlace(player.world, player, blockPos, blockState, itemstack, modifierSettings.doQuickReplace(), EnumFacing.UP)) { SurvivalHelper.canPlace(player.world, player, blockPos, blockState, itemstack, modifierSettings.doQuickReplace(), Direction.UP)) {
ShaderHandler.useShader(ShaderHandler.dissolve, generateShaderCallback(dissolve, RenderHandler.renderBlockPreview(matrixStack, renderTypeBuffer, dispatcher, blockPos, blockState, dissolve, firstPos, secondPos, red);
new Vec3d(blockPos), new Vec3d(firstPos), new Vec3d(secondPos),
blockPos == secondPos, red));
RenderHandler.renderBlockPreview(dispatcher, blockPos, blockState);
blocksValid++; blocksValid++;
} }
} }
@@ -336,9 +324,9 @@ public class BlockPreviewRenderer {
onBlocksPlaced(previousCoordinates, previousItemStacks, previousBlockStates, previousFirstPos, previousSecondPos); onBlocksPlaced(previousCoordinates, previousItemStacks, previousBlockStates, previousFirstPos, previousSecondPos);
} }
public static void onBlocksPlaced(List<BlockPos> coordinates, List<ItemStack> itemStacks, List<IBlockState> blockStates, public static void onBlocksPlaced(List<BlockPos> coordinates, List<ItemStack> itemStacks, List<BlockState> blockStates,
BlockPos firstPos, BlockPos secondPos) { BlockPos firstPos, BlockPos secondPos) {
EntityPlayerSP player = Minecraft.getMinecraft().player; ClientPlayerEntity player = Minecraft.getInstance().player;
ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player);
@@ -347,7 +335,7 @@ public class BlockPreviewRenderer {
//Save current coordinates, blockstates and itemstacks //Save current coordinates, blockstates and itemstacks
if (!coordinates.isEmpty() && blockStates.size() == coordinates.size() && if (!coordinates.isEmpty() && blockStates.size() == coordinates.size() &&
coordinates.size() > 1 && coordinates.size() < BuildConfig.visuals.shaderTreshold) { coordinates.size() > 1 && coordinates.size() < BuildConfig.visuals.shaderTreshold.get()) {
placedDataList.add(new PlacedData(ClientProxy.ticksInGame, coordinates, blockStates, placedDataList.add(new PlacedData(ClientProxy.ticksInGame, coordinates, blockStates,
itemStacks, firstPos, secondPos, false)); itemStacks, firstPos, secondPos, false));
@@ -360,9 +348,9 @@ public class BlockPreviewRenderer {
onBlocksBroken(previousCoordinates, previousItemStacks, previousBlockStates, previousFirstPos, previousSecondPos); onBlocksBroken(previousCoordinates, previousItemStacks, previousBlockStates, previousFirstPos, previousSecondPos);
} }
public static void onBlocksBroken(List<BlockPos> coordinates, List<ItemStack> itemStacks, List<IBlockState> blockStates, public static void onBlocksBroken(List<BlockPos> coordinates, List<ItemStack> itemStacks, List<BlockState> blockStates,
BlockPos firstPos, BlockPos secondPos) { BlockPos firstPos, BlockPos secondPos) {
EntityPlayerSP player = Minecraft.getMinecraft().player; ClientPlayerEntity player = Minecraft.getInstance().player;
ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player);
@@ -371,7 +359,7 @@ public class BlockPreviewRenderer {
//Save current coordinates, blockstates and itemstacks //Save current coordinates, blockstates and itemstacks
if (!coordinates.isEmpty() && blockStates.size() == coordinates.size() && if (!coordinates.isEmpty() && blockStates.size() == coordinates.size() &&
coordinates.size() > 1 && coordinates.size() < BuildConfig.visuals.shaderTreshold) { coordinates.size() > 1 && coordinates.size() < BuildConfig.visuals.shaderTreshold.get()) {
sortOnDistanceToPlayer(coordinates, player); sortOnDistanceToPlayer(coordinates, player);
@@ -382,53 +370,13 @@ public class BlockPreviewRenderer {
} }
private static Consumer<Integer> generateShaderCallback(final float dissolve, final Vec3d blockpos,
final Vec3d firstpos, final Vec3d secondpos,
final boolean highlight, final boolean red) {
Minecraft mc = Minecraft.getMinecraft();
return (Integer shader) -> {
int percentileUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "dissolve");
int highlightUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "highlight");
int redUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "red");
int blockposUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "blockpos");
int firstposUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "firstpos");
int secondposUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "secondpos");
int imageUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "image");
int maskUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "mask");
GlStateManager.enableTexture2D(); private static void sortOnDistanceToPlayer(List<BlockPos> coordinates, PlayerEntity player) {
GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
//mask
ARBShaderObjects.glUniform1iARB(maskUniform, secondaryTextureUnit);
OpenGlHelper.setActiveTexture(ARBMultitexture.GL_TEXTURE0_ARB + secondaryTextureUnit);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture(ShaderHandler.shaderMaskTextureLocation).getGlTextureId());
//image
ARBShaderObjects.glUniform1iARB(imageUniform, primaryTextureUnit);
OpenGlHelper.setActiveTexture(ARBMultitexture.GL_TEXTURE0_ARB + primaryTextureUnit);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture(TextureMap.LOCATION_BLOCKS_TEXTURE).getGlTextureId());
//blockpos
ARBShaderObjects.glUniform3fARB(blockposUniform, (float) blockpos.x, (float) blockpos.y, (float) blockpos.z);
ARBShaderObjects.glUniform3fARB(firstposUniform, (float) firstpos.x, (float) firstpos.y, (float) firstpos.z);
ARBShaderObjects.glUniform3fARB(secondposUniform, (float) secondpos.x, (float) secondpos.y, (float) secondpos.z);
//dissolve
ARBShaderObjects.glUniform1fARB(percentileUniform, dissolve);
//highlight
ARBShaderObjects.glUniform1iARB(highlightUniform, highlight ? 1 : 0);
//red
ARBShaderObjects.glUniform1iARB(redUniform, red ? 1 : 0);
};
}
private static void sortOnDistanceToPlayer(List<BlockPos> coordinates, EntityPlayer player) {
Collections.sort(coordinates, (lhs, rhs) -> { Collections.sort(coordinates, (lhs, rhs) -> {
// -1 - less than, 1 - greater than, 0 - equal // -1 - less than, 1 - greater than, 0 - equal
double lhsDistanceToPlayer = new Vec3d(lhs).subtract(player.getPositionEyes(1f)).lengthSquared(); double lhsDistanceToPlayer = new Vec3d(lhs).subtract(player.getEyePosition(1f)).lengthSquared();
double rhsDistanceToPlayer = new Vec3d(rhs).subtract(player.getPositionEyes(1f)).lengthSquared(); double rhsDistanceToPlayer = new Vec3d(rhs).subtract(player.getEyePosition(1f)).lengthSquared();
return (int) Math.signum(lhsDistanceToPlayer - rhsDistanceToPlayer); return (int) Math.signum(lhsDistanceToPlayer - rhsDistanceToPlayer);
}); });

View File

@@ -0,0 +1,245 @@
package nl.requios.effortlessbuilding.render;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderState;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.texture.AtlasTexture;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import nl.requios.effortlessbuilding.EffortlessBuilding;
import org.lwjgl.opengl.*;
import java.util.OptionalDouble;
import java.util.function.Consumer;
public class BuildRenderTypes {
public static final RenderState.TransparencyState TRANSLUCENT_TRANSPARENCY;
public static final RenderState.TransparencyState NO_TRANSPARENCY;
public static final RenderState.DiffuseLightingState DIFFUSE_LIGHTING_ENABLED;
public static final RenderState.DiffuseLightingState DIFFUSE_LIGHTING_DISABLED;
public static final RenderState.LayerState PROJECTION_LAYERING;
public static final RenderState.CullState CULL_DISABLED;
public static final RenderState.AlphaState DEFAULT_ALPHA;
public static final RenderState.WriteMaskState WRITE_TO_DEPTH_AND_COLOR;
public static final RenderState.WriteMaskState COLOR_WRITE;
public static final RenderType LINES;
public static final RenderType PLANES;
private static final int primaryTextureUnit = 0;
private static final int secondaryTextureUnit = 2;
static {
TRANSLUCENT_TRANSPARENCY = ObfuscationReflectionHelper.getPrivateValue(RenderState.class, null, "field_228515_g_");
NO_TRANSPARENCY = ObfuscationReflectionHelper.getPrivateValue(RenderState.class, null, "field_228510_b_");
DIFFUSE_LIGHTING_ENABLED = new RenderState.DiffuseLightingState(true);
DIFFUSE_LIGHTING_DISABLED = new RenderState.DiffuseLightingState(false);
PROJECTION_LAYERING = ObfuscationReflectionHelper.getPrivateValue(RenderState.class, null, "field_228500_J_");
CULL_DISABLED = new RenderState.CullState(false);
DEFAULT_ALPHA = new RenderState.AlphaState(0.003921569F);
final boolean ENABLE_DEPTH_WRITING = true;
final boolean ENABLE_COLOUR_COMPONENTS_WRITING = true;
WRITE_TO_DEPTH_AND_COLOR = new RenderState.WriteMaskState(ENABLE_COLOUR_COMPONENTS_WRITING, ENABLE_DEPTH_WRITING);
COLOR_WRITE = new RenderState.WriteMaskState(true, false);
final int INITIAL_BUFFER_SIZE = 128;
RenderType.State renderState;
//LINES
// RenderSystem.pushLightingAttributes();
// RenderSystem.pushTextureAttributes();
// RenderSystem.disableCull();
// RenderSystem.disableLighting();
// RenderSystem.disableTexture();
//
// RenderSystem.enableBlend();
// RenderSystem.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//
// RenderSystem.lineWidth(2);
renderState = RenderType.State.getBuilder()
.line(new RenderState.LineState(OptionalDouble.of(2)))
.layer(PROJECTION_LAYERING)
.transparency(TRANSLUCENT_TRANSPARENCY)
.writeMask(WRITE_TO_DEPTH_AND_COLOR)
.cull(CULL_DISABLED)
.build(false);
LINES = RenderType.makeType("eb_lines",
DefaultVertexFormats.POSITION_COLOR, GL11.GL_LINES, INITIAL_BUFFER_SIZE, renderState);
renderState = RenderType.State.getBuilder()
.line(new RenderState.LineState(OptionalDouble.of(2)))
.layer(PROJECTION_LAYERING)
.transparency(TRANSLUCENT_TRANSPARENCY)
.writeMask(COLOR_WRITE)
.cull(CULL_DISABLED)
.build(false);
PLANES = RenderType.makeType("eb_planes",
DefaultVertexFormats.POSITION_COLOR, GL11.GL_TRIANGLE_STRIP, INITIAL_BUFFER_SIZE, renderState);
}
private class ShaderInfo {
float dissolve;
Vec3d blockPos;
Vec3d firstPos;
Vec3d secondPos;
boolean red;
public ShaderInfo(float dissolve, Vec3d blockPos, Vec3d firstPos, Vec3d secondPos, boolean red) {
this.dissolve = dissolve;
this.blockPos = blockPos;
this.firstPos = firstPos;
this.secondPos = secondPos;
this.red = red;
}
}
public static RenderType getBlockPreviewRenderType(float dissolve, BlockPos blockPos, BlockPos firstPos,
BlockPos secondPos, boolean red) {
// RenderSystem.pushLightingAttributes();
// RenderSystem.pushTextureAttributes();
// RenderSystem.enableCull();
// RenderSystem.enableTexture();
// Minecraft.getInstance().textureManager.bindTexture(ShaderHandler.shaderMaskTextureLocation);
//
// RenderSystem.enableBlend();
// RenderSystem.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
// RenderSystem.blendColor(1f, 1f, 1f, 0.8f);
//end
// ShaderHandler.releaseShader();
//highjacking texturing state (which does nothing by default) to do my own things
String stateName = "eb_texturing_" + dissolve + "_" + blockPos + "_" + firstPos + "_" + secondPos + "_" + red;
RenderState.TexturingState MY_TEXTURING = new RenderState.TexturingState(stateName, () -> {
// RenderSystem.pushLightingAttributes();
// RenderSystem.pushTextureAttributes();
ShaderHandler.useShader(ShaderHandler.dissolve, generateShaderCallback(dissolve, new Vec3d(blockPos), new Vec3d(firstPos), new Vec3d(secondPos), blockPos == secondPos, red));
RenderSystem.blendColor(1f, 1f, 1f, 0.8f);
}, () -> {
ShaderHandler.releaseShader();
});
RenderType.State renderState = RenderType.State.getBuilder()
.texture(new RenderState.TextureState(ShaderHandler.shaderMaskTextureLocation, false, false))
.texturing(MY_TEXTURING)
.transparency(TRANSLUCENT_TRANSPARENCY)
.diffuseLighting(DIFFUSE_LIGHTING_DISABLED)
.alpha(DEFAULT_ALPHA)
.cull(new RenderState.CullState(true))
.lightmap(new RenderState.LightmapState(false))
.overlay(new RenderState.OverlayState(false))
.build(true);
//Unique name for every combination, otherwise it will reuse the previous one
String name = "eb_block_previews_" + dissolve + "_" + blockPos + "_" + firstPos + "_" + secondPos + "_" + red;
return RenderType.makeType(name,
DefaultVertexFormats.BLOCK, GL11.GL_QUADS, 256, true, true, renderState);
}
private static Consumer<Integer> generateShaderCallback(final float dissolve, final Vec3d blockpos,
final Vec3d firstpos, final Vec3d secondpos,
final boolean highlight, final boolean red) {
Minecraft mc = Minecraft.getInstance();
return (Integer shader) -> {
int percentileUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "dissolve");
int highlightUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "highlight");
int redUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "red");
int blockposUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "blockpos");
int firstposUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "firstpos");
int secondposUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "secondpos");
int imageUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "image");
int maskUniform = ARBShaderObjects.glGetUniformLocationARB(shader, "mask");
RenderSystem.enableTexture();
GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
//mask
ARBShaderObjects.glUniform1iARB(maskUniform, secondaryTextureUnit);
glActiveTexture(ARBMultitexture.GL_TEXTURE0_ARB + secondaryTextureUnit);
mc.getTextureManager().bindTexture(ShaderHandler.shaderMaskTextureLocation);//getTexture(ShaderHandler.shaderMaskTextureLocation).bindTexture();
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.getTextureManager().getTexture(ShaderHandler.shaderMaskTextureLocation).getGlTextureId());
//image
ARBShaderObjects.glUniform1iARB(imageUniform, primaryTextureUnit);
glActiveTexture(ARBMultitexture.GL_TEXTURE0_ARB + primaryTextureUnit);
mc.getTextureManager().bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE);//.getTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).bindTexture();
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.getTextureManager().getTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE).getGlTextureId());
//blockpos
ARBShaderObjects.glUniform3fARB(blockposUniform, (float) blockpos.x, (float) blockpos.y, (float) blockpos.z);
ARBShaderObjects.glUniform3fARB(firstposUniform, (float) firstpos.x, (float) firstpos.y, (float) firstpos.z);
ARBShaderObjects.glUniform3fARB(secondposUniform, (float) secondpos.x, (float) secondpos.y, (float) secondpos.z);
//dissolve
ARBShaderObjects.glUniform1fARB(percentileUniform, dissolve);
//highlight
ARBShaderObjects.glUniform1iARB(highlightUniform, highlight ? 1 : 0);
//red
ARBShaderObjects.glUniform1iARB(redUniform, red ? 1 : 0);
};
}
public static void glActiveTexture(int texture) {
if (GL.getCapabilities().GL_ARB_multitexture && !GL.getCapabilities().OpenGL13) {
ARBMultitexture.glActiveTextureARB(texture);
} else {
GL13.glActiveTexture(texture);
}
}
// public static class MyTexturingState extends RenderState.TexturingState {
//
// public float dissolve;
// public Vec3d blockPos;
// public Vec3d firstPos;
// public Vec3d secondPos;
// public boolean highlight;
// public boolean red;
//
// public MyTexturingState(String p_i225989_1_, float dissolve, Vec3d blockPos, Vec3d firstPos,
// Vec3d secondPos, boolean highlight, boolean red, Runnable p_i225989_2_, Runnable p_i225989_3_) {
// super(p_i225989_1_, p_i225989_2_, p_i225989_3_);
// this.dissolve = dissolve;
// this.blockPos = blockPos;
// this.firstPos = firstPos;
// this.secondPos = secondPos;
// this.highlight = highlight;
// this.red = red;
// }
//
// @Override
// public boolean equals(Object p_equals_1_) {
// if (this == p_equals_1_) {
// return true;
// } else if (p_equals_1_ != null && this.getClass() == p_equals_1_.getClass()) {
// MyTexturingState other = (MyTexturingState)p_equals_1_;
// return this.dissolve == other.dissolve && this.blockPos == other.blockPos && this.firstPos == other.firstPos
// && this.secondPos == other.secondPos && this.highlight == other.highlight && this.red == other.red;
// } else {
// return false;
// }
// }
//
// @Override
// public int hashCode() {
//
// }
// }
}

View File

@@ -1,18 +1,23 @@
package nl.requios.effortlessbuilding.render; package nl.requios.effortlessbuilding.render;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.Matrix4f;
import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.api.distmarker.OnlyIn;
import nl.requios.effortlessbuilding.buildmodifier.Mirror; import nl.requios.effortlessbuilding.buildmodifier.Mirror;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.RadialMirror; import nl.requios.effortlessbuilding.buildmodifier.RadialMirror;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.util.Color;
@SideOnly(Side.CLIENT) import java.awt.*;
@OnlyIn(Dist.CLIENT)
public class ModifierRenderer { public class ModifierRenderer {
protected static final Color colorX = new Color(255, 72, 52); protected static final Color colorX = new Color(255, 72, 52);
@@ -23,9 +28,7 @@ public class ModifierRenderer {
protected static final int planeAlpha = 75; protected static final int planeAlpha = 75;
protected static final Vec3d epsilon = new Vec3d(0.001, 0.001, 0.001); //prevents z-fighting protected static final Vec3d epsilon = new Vec3d(0.001, 0.001, 0.001); //prevents z-fighting
public static void render(ModifierSettingsManager.ModifierSettings modifierSettings) { public static void render(MatrixStack matrixStack, IRenderTypeBuffer.Impl renderTypeBuffer, ModifierSettingsManager.ModifierSettings modifierSettings) {
RenderHandler.beginLines();
//Mirror lines and areas //Mirror lines and areas
Mirror.MirrorSettings m = modifierSettings.getMirrorSettings(); Mirror.MirrorSettings m = modifierSettings.getMirrorSettings();
if (m != null && m.enabled && (m.mirrorX || m.mirrorY || m.mirrorZ)) if (m != null && m.enabled && (m.mirrorX || m.mirrorY || m.mirrorZ))
@@ -38,28 +41,28 @@ public class ModifierRenderer {
Vec3d posA = new Vec3d(pos.x, pos.y - radius, pos.z - radius); Vec3d posA = new Vec3d(pos.x, pos.y - radius, pos.z - radius);
Vec3d posB = new Vec3d(pos.x, pos.y + radius, pos.z + radius); Vec3d posB = new Vec3d(pos.x, pos.y + radius, pos.z + radius);
drawMirrorPlane(posA, posB, colorX, m.drawLines, m.drawPlanes, true); drawMirrorPlane(matrixStack, renderTypeBuffer, posA, posB, colorX, m.drawLines, m.drawPlanes, true);
} }
if (m.mirrorY) if (m.mirrorY)
{ {
Vec3d posA = new Vec3d(pos.x - radius, pos.y, pos.z - radius); Vec3d posA = new Vec3d(pos.x - radius, pos.y, pos.z - radius);
Vec3d posB = new Vec3d(pos.x + radius, pos.y, pos.z + radius); Vec3d posB = new Vec3d(pos.x + radius, pos.y, pos.z + radius);
drawMirrorPlaneY(posA, posB, colorY, m.drawLines, m.drawPlanes); drawMirrorPlaneY(matrixStack, renderTypeBuffer, posA, posB, colorY, m.drawLines, m.drawPlanes);
} }
if (m.mirrorZ) if (m.mirrorZ)
{ {
Vec3d posA = new Vec3d(pos.x - radius, pos.y - radius, pos.z); Vec3d posA = new Vec3d(pos.x - radius, pos.y - radius, pos.z);
Vec3d posB = new Vec3d(pos.x + radius, pos.y + radius, pos.z); Vec3d posB = new Vec3d(pos.x + radius, pos.y + radius, pos.z);
drawMirrorPlane(posA, posB, colorZ, m.drawLines, m.drawPlanes, true); drawMirrorPlane(matrixStack, renderTypeBuffer, posA, posB, colorZ, m.drawLines, m.drawPlanes, true);
} }
//Draw axis coordinated colors if two or more axes are enabled //Draw axis coordinated colors if two or more axes are enabled
//(If only one is enabled the lines are that planes color) //(If only one is enabled the lines are that planes color)
if (m.drawLines && ((m.mirrorX && m.mirrorY) || (m.mirrorX && m.mirrorZ) || (m.mirrorY && m.mirrorZ))) if (m.drawLines && ((m.mirrorX && m.mirrorY) || (m.mirrorX && m.mirrorZ) || (m.mirrorY && m.mirrorZ)))
{ {
drawMirrorLines(m); drawMirrorLines(matrixStack, renderTypeBuffer, m);
} }
} }
@@ -80,96 +83,95 @@ public class ModifierRenderer {
Vec3d posA = new Vec3d(pos.x, pos.y - radius, pos.z); Vec3d posA = new Vec3d(pos.x, pos.y - radius, pos.z);
Vec3d posB = new Vec3d(newVec.x, pos.y + radius, newVec.z); Vec3d posB = new Vec3d(newVec.x, pos.y + radius, newVec.z);
drawMirrorPlane(posA, posB, colorRadial, r.drawLines, r.drawPlanes, false); drawMirrorPlane(matrixStack, renderTypeBuffer, posA, posB, colorRadial, r.drawLines, r.drawPlanes, false);
} }
} }
RenderHandler.endLines();
} }
//----Mirror---- //----Mirror----
protected static void drawMirrorPlane(Vec3d posA, Vec3d posB, Color c, boolean drawLines, boolean drawPlanes, boolean drawVerticalLines) { protected static void drawMirrorPlane(MatrixStack matrixStack, IRenderTypeBuffer.Impl renderTypeBuffer, Vec3d posA, Vec3d posB, Color c, boolean drawLines, boolean drawPlanes, boolean drawVerticalLines) {
GL11.glColor4d(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha); // GL11.glColor4d(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha);
Tessellator tessellator = Tessellator.getInstance(); Matrix4f matrixPos = matrixStack.getLast().getMatrix();
BufferBuilder bufferBuilder = tessellator.getBuffer();
if (drawPlanes) { if (drawPlanes) {
bufferBuilder.begin(GL11.GL_TRIANGLE_STRIP, DefaultVertexFormats.POSITION_COLOR); IVertexBuilder buffer = RenderHandler.beginPlanes(renderTypeBuffer);
bufferBuilder.pos(posA.x, posA.y, posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posA.x, (float) posA.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
bufferBuilder.pos(posA.x, posB.y, posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posA.x, (float) posB.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
bufferBuilder.pos(posB.x, posA.y, posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posB.x, (float) posA.y, (float) posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
bufferBuilder.pos(posB.x, posB.y, posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posB.x, (float) posB.y, (float) posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
//backface (using triangle strip)
buffer.pos(matrixPos, (float) posA.x, (float) posA.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
buffer.pos(matrixPos, (float) posA.x, (float) posB.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
tessellator.draw(); RenderHandler.endPlanes(renderTypeBuffer);
} }
if (drawLines) { if (drawLines) {
Vec3d middle = posA.add(posB).scale(0.5); IVertexBuilder buffer = RenderHandler.beginLines(renderTypeBuffer);
bufferBuilder.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR);
bufferBuilder.pos(posA.x, middle.y, posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex(); Vec3d middle = posA.add(posB).scale(0.5);
bufferBuilder.pos(posB.x, middle.y, posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex(); buffer.pos(matrixPos, (float) posA.x, (float) middle.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
buffer.pos(matrixPos, (float) posB.x, (float) middle.y, (float) posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
if (drawVerticalLines) { if (drawVerticalLines) {
bufferBuilder.pos(middle.x, posA.y, middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex(); buffer.pos(matrixPos, (float) middle.x, (float) posA.y, (float) middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(middle.x, posB.y, middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex(); buffer.pos(matrixPos, (float) middle.x, (float) posB.y, (float) middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
} }
tessellator.draw(); RenderHandler.endLines(renderTypeBuffer);
} }
} }
protected static void drawMirrorPlaneY(Vec3d posA, Vec3d posB, Color c, boolean drawLines, boolean drawPlanes) { protected static void drawMirrorPlaneY(MatrixStack matrixStack, IRenderTypeBuffer.Impl renderTypeBuffer, Vec3d posA, Vec3d posB, Color c, boolean drawLines, boolean drawPlanes) {
GL11.glColor4d(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); // GL11.glColor4d(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
Tessellator tessellator = Tessellator.getInstance(); Matrix4f matrixPos = matrixStack.getLast().getMatrix();
BufferBuilder bufferBuilder = tessellator.getBuffer();
if (drawPlanes) { if (drawPlanes) {
bufferBuilder.begin(GL11.GL_TRIANGLE_STRIP, DefaultVertexFormats.POSITION_COLOR); IVertexBuilder buffer = RenderHandler.beginPlanes(renderTypeBuffer);
bufferBuilder.pos(posA.x, posA.y, posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posA.x, (float) posA.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
bufferBuilder.pos(posA.x, posA.y, posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posA.x, (float) posA.y, (float) posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
bufferBuilder.pos(posB.x, posA.y, posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posB.x, (float) posA.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
bufferBuilder.pos(posB.x, posA.y, posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex(); buffer.pos(matrixPos, (float) posB.x, (float) posA.y, (float) posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
//backface (using triangle strip)
buffer.pos(matrixPos, (float) posA.x, (float) posA.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
buffer.pos(matrixPos, (float) posA.x, (float) posA.y, (float) posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), planeAlpha).endVertex();
tessellator.draw(); RenderHandler.endPlanes(renderTypeBuffer);
} }
if (drawLines) { if (drawLines) {
IVertexBuilder buffer = RenderHandler.beginLines(renderTypeBuffer);
Vec3d middle = posA.add(posB).scale(0.5); Vec3d middle = posA.add(posB).scale(0.5);
bufferBuilder.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR); buffer.pos(matrixPos, (float) middle.x, (float) middle.y, (float) posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
buffer.pos(matrixPos, (float) middle.x, (float) middle.y, (float) posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
buffer.pos(matrixPos, (float) posA.x, (float) middle.y, (float) middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
buffer.pos(matrixPos, (float) posB.x, (float) middle.y, (float) middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(middle.x, middle.y, posA.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex(); RenderHandler.endLines(renderTypeBuffer);
bufferBuilder.pos(middle.x, middle.y, posB.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(posA.x, middle.y, middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(posB.x, middle.y, middle.z).color(c.getRed(), c.getGreen(), c.getBlue(), lineAlpha).endVertex();
tessellator.draw();
} }
} }
protected static void drawMirrorLines(Mirror.MirrorSettings m) { protected static void drawMirrorLines(MatrixStack matrixStack, IRenderTypeBuffer.Impl renderTypeBuffer, Mirror.MirrorSettings m) {
// GL11.glColor4d(100, 100, 100, 255);
IVertexBuilder buffer = RenderHandler.beginLines(renderTypeBuffer);
Matrix4f matrixPos = matrixStack.getLast().getMatrix();
Vec3d pos = m.position.add(epsilon); Vec3d pos = m.position.add(epsilon);
GL11.glColor4d(100, 100, 100, 255); buffer.pos(matrixPos, (float) pos.x - m.radius, (float) pos.y, (float) pos.z).color(colorX.getRed(), colorX.getGreen(), colorX.getBlue(), lineAlpha).endVertex();
GL11.glLineWidth(2); buffer.pos(matrixPos, (float) pos.x + m.radius, (float) pos.y, (float) pos.z).color(colorX.getRed(), colorX.getGreen(), colorX.getBlue(), lineAlpha).endVertex();
Tessellator tessellator = Tessellator.getInstance(); buffer.pos(matrixPos, (float) pos.x, (float) pos.y - m.radius, (float) pos.z).color(colorY.getRed(), colorY.getGreen(), colorY.getBlue(), lineAlpha).endVertex();
BufferBuilder bufferBuilder = tessellator.getBuffer(); buffer.pos(matrixPos, (float) pos.x, (float) pos.y + m.radius, (float) pos.z).color(colorY.getRed(), colorY.getGreen(), colorY.getBlue(), lineAlpha).endVertex();
buffer.pos(matrixPos, (float) pos.x, (float) pos.y, (float) pos.z - m.radius).color(colorZ.getRed(), colorZ.getGreen(), colorZ.getBlue(), lineAlpha).endVertex();
buffer.pos(matrixPos, (float) pos.x, (float) pos.y, (float) pos.z + m.radius).color(colorZ.getRed(), colorZ.getGreen(), colorZ.getBlue(), lineAlpha).endVertex();
bufferBuilder.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR); RenderHandler.endLines(renderTypeBuffer);
bufferBuilder.pos(pos.x - m.radius, pos.y, pos.z).color(colorX.getRed(), colorX.getGreen(), colorX.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(pos.x + m.radius, pos.y, pos.z).color(colorX.getRed(), colorX.getGreen(), colorX.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(pos.x, pos.y - m.radius, pos.z).color(colorY.getRed(), colorY.getGreen(), colorY.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(pos.x, pos.y + m.radius, pos.z).color(colorY.getRed(), colorY.getGreen(), colorY.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(pos.x, pos.y, pos.z - m.radius).color(colorZ.getRed(), colorZ.getGreen(), colorZ.getBlue(), lineAlpha).endVertex();
bufferBuilder.pos(pos.x, pos.y, pos.z + m.radius).color(colorZ.getRed(), colorZ.getGreen(), colorZ.getBlue(), lineAlpha).endVertex();
tessellator.draw();
} }
} }

View File

@@ -1,86 +1,93 @@
package nl.requios.effortlessbuilding.render; package nl.requios.effortlessbuilding.render;
import net.minecraft.block.state.IBlockState; import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.audio.SimpleSound;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.BlockRendererDispatcher; import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer;
import net.minecraft.init.SoundEvents;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent; import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IWorldEventListener; import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
import nl.requios.effortlessbuilding.buildmode.ModeOptions; import nl.requios.effortlessbuilding.buildmode.ModeOptions;
import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager; import nl.requios.effortlessbuilding.buildmode.ModeSettingsManager;
import nl.requios.effortlessbuilding.buildmodifier.BuildModifiers;
import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager; import nl.requios.effortlessbuilding.buildmodifier.ModifierSettingsManager;
import nl.requios.effortlessbuilding.gui.buildmode.RadialMenu; import nl.requios.effortlessbuilding.gui.buildmode.RadialMenu;
import nl.requios.effortlessbuilding.compatibility.CompatHelper;
import nl.requios.effortlessbuilding.helper.ReachHelper; import nl.requios.effortlessbuilding.helper.ReachHelper;
import nl.requios.effortlessbuilding.helper.SurvivalHelper;
import nl.requios.effortlessbuilding.network.ModeActionMessage; import nl.requios.effortlessbuilding.network.ModeActionMessage;
import nl.requios.effortlessbuilding.network.ModeSettingsMessage; import nl.requios.effortlessbuilding.network.ModeSettingsMessage;
import nl.requios.effortlessbuilding.network.PacketHandler;
import nl.requios.effortlessbuilding.proxy.ClientProxy; import nl.requios.effortlessbuilding.proxy.ClientProxy;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import javax.annotation.Nullable;
import java.util.List;
/*** /***
* Main render class for Effortless Building * Main render class for Effortless Building
*/ */
@Mod.EventBusSubscriber(Side.CLIENT) @Mod.EventBusSubscriber(value = Dist.CLIENT)
public class RenderHandler implements IWorldEventListener { public class RenderHandler {
@SubscribeEvent @SubscribeEvent
public static void onRender(RenderWorldLastEvent event) { public static void onRender(RenderWorldLastEvent event) {
EntityPlayer player = Minecraft.getMinecraft().player; if(event.getPhase() != EventPriority.NORMAL)
return;
MatrixStack matrixStack = event.getMatrixStack();
BufferBuilder bufferBuilder = Tessellator.getInstance().getBuffer();
IRenderTypeBuffer.Impl renderTypeBuffer = IRenderTypeBuffer.getImpl(bufferBuilder);
PlayerEntity player = Minecraft.getInstance().player;
ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player); ModeSettingsManager.ModeSettings modeSettings = ModeSettingsManager.getModeSettings(player);
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player); ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(player);
begin(event.getPartialTicks()); Vec3d projectedView = Minecraft.getInstance().gameRenderer.getActiveRenderInfo().getProjectedView();
matrixStack.push();
matrixStack.translate(-projectedView.x, -projectedView.y, -projectedView.z);
//Mirror and radial mirror lines and areas //Mirror and radial mirror lines and areas
ModifierRenderer.render(modifierSettings); ModifierRenderer.render(matrixStack, renderTypeBuffer, modifierSettings);
//Render block previews //Render block previews
BlockPreviewRenderer.render(player, modifierSettings, modeSettings); BlockPreviewRenderer.render(matrixStack, renderTypeBuffer, player, modifierSettings, modeSettings);
end(); matrixStack.pop();
} }
@SubscribeEvent @SubscribeEvent
//Display Radial Menu //Display Radial Menu
public static void onRenderGameOverlay(final RenderGameOverlayEvent.Post event) { public static void onRenderGameOverlay(final RenderGameOverlayEvent.Post event) {
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getInstance();
EntityPlayerSP player = mc.player; ClientPlayerEntity player = mc.player;
//check if chisel and bits tool in hand (and has menu) //check if chisel and bits tool in hand (and has menu)
final boolean hasChiselInHand = CompatHelper.chiselsAndBitsProxy.isHoldingChiselTool(EnumHand.MAIN_HAND); // final boolean hasChiselInHand = CompatHelper.chiselsAndBitsProxy.isHoldingChiselTool(EnumHand.MAIN_HAND);
final RenderGameOverlayEvent.ElementType type = event.getType(); final RenderGameOverlayEvent.ElementType type = event.getType();
if (type == RenderGameOverlayEvent.ElementType.ALL && !hasChiselInHand) { //TODO 1.13 compatibility
if (type == RenderGameOverlayEvent.ElementType.ALL /*&& !hasChiselInHand*/) {
final boolean wasVisible = RadialMenu.instance.isVisible(); final boolean wasVisible = RadialMenu.instance.isVisible();
if (ClientProxy.keyBindings[3].isKeyDown()) { if (ClientProxy.keyBindings[3].isKeyDown()) {
@@ -98,7 +105,7 @@ public class RenderHandler implements IWorldEventListener {
playRadialMenuSound(); playRadialMenuSound();
modeSettings.setBuildMode(RadialMenu.instance.switchTo); modeSettings.setBuildMode(RadialMenu.instance.switchTo);
ModeSettingsManager.setModeSettings(player, modeSettings); ModeSettingsManager.setModeSettings(player, modeSettings);
EffortlessBuilding.packetHandler.sendToServer(new ModeSettingsMessage(modeSettings)); PacketHandler.INSTANCE.sendToServer(new ModeSettingsMessage(modeSettings));
EffortlessBuilding.log(player, I18n.format(modeSettings.getBuildMode().name), true); EffortlessBuilding.log(player, I18n.format(modeSettings.getBuildMode().name), true);
} }
@@ -107,7 +114,7 @@ public class RenderHandler implements IWorldEventListener {
ModeOptions.ActionEnum action = RadialMenu.instance.doAction; ModeOptions.ActionEnum action = RadialMenu.instance.doAction;
if (action != null) { if (action != null) {
ModeOptions.performAction(player, action); ModeOptions.performAction(player, action);
EffortlessBuilding.packetHandler.sendToServer(new ModeActionMessage(action)); PacketHandler.INSTANCE.sendToServer(new ModeActionMessage(action));
} }
playRadialMenuSound(); playRadialMenuSound();
@@ -119,25 +126,27 @@ public class RenderHandler implements IWorldEventListener {
if (RadialMenu.instance.isVisible()) { if (RadialMenu.instance.isVisible()) {
final ScaledResolution res = event.getResolution(); int scaledWidth = mc.getMainWindow().getScaledWidth();
RadialMenu.instance.configure(res.getScaledWidth(), res.getScaledHeight()); int scaledHeight = mc.getMainWindow().getScaledHeight();
RadialMenu.instance.configure(scaledWidth, scaledHeight);
if (!wasVisible) { if (!wasVisible) {
mc.inGameHasFocus = false; mc.mouseHelper.ungrabMouse();
mc.mouseHelper.ungrabMouseCursor();
} }
if (mc.inGameHasFocus) { if (mc.mouseHelper.isMouseGrabbed()) {
KeyBinding.unPressAllKeys(); KeyBinding.unPressAllKeys();
} }
final int mouseX = Mouse.getX() * res.getScaledWidth() / mc.displayWidth; final int mouseX = ((int) mc.mouseHelper.getMouseX()) * scaledWidth / mc.getMainWindow().getFramebufferWidth();
final int mouseY = res.getScaledHeight() - Mouse.getY() * res.getScaledHeight() / mc.displayHeight - 1; final int mouseY = scaledHeight - ((int) mc.mouseHelper.getMouseY()) * scaledHeight / mc.getMainWindow().getFramebufferHeight() - 1;
net.minecraftforge.client.ForgeHooksClient.drawScreen(RadialMenu.instance, mouseX, mouseY, event.getPartialTicks()); net.minecraftforge.client.ForgeHooksClient.drawScreen(RadialMenu.instance, mouseX, mouseY, event.getPartialTicks());
} else { } else {
if (wasVisible && RadialMenu.instance.doAction != ModeOptions.ActionEnum.OPEN_MODIFIER_SETTINGS) { if (wasVisible &&
mc.setIngameFocus(); RadialMenu.instance.doAction != ModeOptions.ActionEnum.OPEN_MODIFIER_SETTINGS &&
RadialMenu.instance.doAction != ModeOptions.ActionEnum.OPEN_PLAYER_SETTINGS) {
mc.mouseHelper.grabMouse();
} }
} }
} }
@@ -146,191 +155,103 @@ public class RenderHandler implements IWorldEventListener {
public static void playRadialMenuSound() { public static void playRadialMenuSound() {
final float volume = 0.1f; final float volume = 0.1f;
if (volume >= 0.0001f) { if (volume >= 0.0001f) {
final PositionedSoundRecord psr = new PositionedSoundRecord(SoundEvents.UI_BUTTON_CLICK, SoundCategory.MASTER, SimpleSound sound = new SimpleSound(SoundEvents.UI_BUTTON_CLICK, SoundCategory.MASTER, volume, 1.0f, Minecraft.getInstance().player.getPosition());
volume, 1.0f, Minecraft.getMinecraft().player.getPosition()); Minecraft.getInstance().getSoundHandler().play(sound);
Minecraft.getMinecraft().getSoundHandler().playSound(psr);
} }
} }
private static void begin(float partialTicks) { protected static IVertexBuilder beginLines(IRenderTypeBuffer.Impl renderTypeBuffer) {
EntityPlayer player = Minecraft.getMinecraft().player; return renderTypeBuffer.getBuffer(BuildRenderTypes.LINES);
double playerX = player.prevPosX + (player.posX - player.prevPosX) * partialTicks;
double playerY = player.prevPosY + (player.posY - player.prevPosY) * partialTicks;
double playerZ = player.prevPosZ + (player.posZ - player.prevPosZ) * partialTicks;
Vec3d playerPos = new Vec3d(playerX, playerY, playerZ);
GL11.glPushMatrix();
GL11.glTranslated(-playerPos.x, -playerPos.y, -playerPos.z);
GL11.glDepthMask(false);
} }
protected static void beginLines() { protected static void endLines(IRenderTypeBuffer.Impl renderTypeBuffer) {
GL11.glPushAttrib(GL11.GL_ENABLE_BIT); renderTypeBuffer.finish();
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glLineWidth(2);
} }
protected static void endLines() { protected static IVertexBuilder beginPlanes(IRenderTypeBuffer.Impl renderTypeBuffer){
GL11.glPopAttrib(); return renderTypeBuffer.getBuffer(BuildRenderTypes.PLANES);
} }
protected static void beginBlockPreviews() { protected static void endPlanes(IRenderTypeBuffer.Impl renderTypeBuffer){
GL11.glPushAttrib(GL11.GL_ENABLE_BIT); renderTypeBuffer.finish();
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_TEXTURE_2D);
// Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
Minecraft.getMinecraft().renderEngine.bindTexture(ShaderHandler.shaderMaskTextureLocation);
GlStateManager.enableBlend();
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL14.glBlendColor(1F, 1F, 1F, 0.8f);
} }
protected static void endBlockPreviews() { protected static void renderBlockPreview(MatrixStack matrixStack, IRenderTypeBuffer.Impl renderTypeBuffer, BlockRendererDispatcher dispatcher,
ShaderHandler.releaseShader(); BlockPos blockPos, BlockState blockState, float dissolve, BlockPos firstPos, BlockPos secondPos, boolean red) {
GlStateManager.disableBlend();
GL11.glPopAttrib();
}
private static void end() {
GL11.glDepthMask(true);
GL11.glPopMatrix();
}
protected static void renderBlockPreview(BlockRendererDispatcher dispatcher, BlockPos blockPos, IBlockState blockState) {
if (blockState == null) return; if (blockState == null) return;
GlStateManager.pushMatrix(); matrixStack.push();
GlStateManager.translate(blockPos.getX(), blockPos.getY(), blockPos.getZ()); matrixStack.translate(blockPos.getX(), blockPos.getY(), blockPos.getZ());
GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F); // matrixStack.rotate(Vector3f.YP.rotationDegrees(-90f));
GlStateManager.translate(-0.01f, -0.01f, 0.01f); matrixStack.translate(-0.01f, -0.01f, -0.01f);
GlStateManager.scale(1.02f, 1.02f, 1.02f); matrixStack.scale(1.02f, 1.02f, 1.02f);
//Begin block preview rendering
RenderType blockPreviewRenderType = BuildRenderTypes.getBlockPreviewRenderType(dissolve, blockPos, firstPos, secondPos, red);
IVertexBuilder buffer = renderTypeBuffer.getBuffer(blockPreviewRenderType);
// MinecraftServer server = Minecraft.getInstance().getIntegratedServer();
// World world = DimensionManager.getWorld(server, DimensionType.OVERWORLD, false, true);
try { try {
dispatcher.renderBlockBrightness(blockState, 0.85f); IBakedModel model = dispatcher.getModelForState(blockState);
dispatcher.getBlockModelRenderer().renderModelBrightnessColor(matrixStack.getLast(), buffer,
blockState, model, 1f, 1f, 1f, 0, OverlayTexture.NO_OVERLAY);
// blockRendererDispatcher.getBlockModelRenderer().renderModel(world, blockRendererDispatcher.getModelForState(blockState),
// blockState, logicPos, matrixStack, renderTypeBuffer.getBuffer(renderType), true, new Random(), blockState.getPositionRandom(logicPos), i);
} catch (NullPointerException e) { } catch (NullPointerException e) {
EffortlessBuilding.logger.warn("RenderHandler::renderBlockPreview cannot render " + blockState.getBlock().toString()); EffortlessBuilding.logger.warn("RenderHandler::renderBlockPreview cannot render " + blockState.getBlock().toString());
//Render outline as backup //Render outline as backup, escape out of the current renderstack
GlStateManager.popMatrix(); matrixStack.pop();
// ShaderHandler.releaseShader(); renderTypeBuffer.finish();
GL11.glDisable(GL11.GL_LIGHTING); IVertexBuilder lineBuffer = beginLines(renderTypeBuffer);
renderBlockOutline(blockPos, new Vec3d(1f, 1f, 1f)); renderBlockOutline(matrixStack, lineBuffer, blockPos, new Vec3d(1f, 1f, 1f));
GL11.glEnable(GL11.GL_LIGHTING); endLines(renderTypeBuffer);
GlStateManager.pushMatrix(); buffer = renderTypeBuffer.getBuffer(Atlases.getTranslucentBlockType()); //any type will do, as long as we have something on the stack
matrixStack.push();
} }
GlStateManager.popMatrix(); renderTypeBuffer.finish();
matrixStack.pop();
} }
protected static void renderBlockOutline(BlockPos pos, Vec3d color) { protected static void renderBlockOutline(MatrixStack matrixStack, IVertexBuilder buffer, BlockPos pos, Vec3d color) {
renderBlockOutline(pos, pos, color); renderBlockOutline(matrixStack, buffer, pos, pos, color);
} }
//Renders outline. Pos1 has to be minimal x,y,z and pos2 maximal x,y,z //Renders outline. Pos1 has to be minimal x,y,z and pos2 maximal x,y,z
protected static void renderBlockOutline(BlockPos pos1, BlockPos pos2, Vec3d color) { protected static void renderBlockOutline(MatrixStack matrixStack, IVertexBuilder buffer, BlockPos pos1, BlockPos pos2, Vec3d color) {
GL11.glLineWidth(2);
AxisAlignedBB aabb = new AxisAlignedBB(pos1, pos2.add(1, 1, 1)).grow(0.0020000000949949026); AxisAlignedBB aabb = new AxisAlignedBB(pos1, pos2.add(1, 1, 1)).grow(0.0020000000949949026);
RenderGlobal.drawSelectionBoundingBox(aabb, (float) color.x, (float) color.y, (float) color.z, 0.4f); WorldRenderer.drawBoundingBox(matrixStack, buffer, aabb, (float) color.x, (float) color.y, (float) color.z, 0.4f);
// WorldRenderer.drawSelectionBoundingBox(aabb, (float) color.x, (float) color.y, (float) color.z, 0.4f);
} }
//Renders outline with given bounding box //Renders outline with given bounding box
protected static void renderBlockOutline(BlockPos pos, AxisAlignedBB boundingBox, Vec3d color) { protected static void renderBlockOutline(MatrixStack matrixStack, IVertexBuilder buffer, BlockPos pos, VoxelShape collisionShape, Vec3d color) {
GL11.glLineWidth(2); // WorldRenderer.drawShape(collisionShape, pos.getX(), pos.getY(), pos.getZ(), (float) color.x, (float) color.y, (float) color.z, 0.4f);
WorldRenderer.drawVoxelShapeParts(matrixStack, buffer, collisionShape, pos.getX(), pos.getY(), pos.getZ(), (float) color.x, (float) color.y, (float) color.z, 0.4f);
AxisAlignedBB aabb = boundingBox.offset(pos).grow(0.0020000000949949026);
RenderGlobal.drawSelectionBoundingBox(aabb, (float) color.x, (float) color.y, (float) color.z, 0.4f);
}
//IWORLDEVENTLISTENER IMPLEMENTATION
@Override
public void notifyBlockUpdate(World worldIn, BlockPos pos, IBlockState oldState, IBlockState newState, int flags) {
}
@Override
public void notifyLightSet(BlockPos pos) {
}
@Override
public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) {
}
@Override
public void playSoundToAllNearExcept(@Nullable EntityPlayer player, SoundEvent soundIn, SoundCategory category,
double x, double y, double z, float volume, float pitch) {
}
@Override
public void playRecord(SoundEvent soundIn, BlockPos pos) {
}
@Override
public void spawnParticle(int particleID, boolean ignoreRange, double xCoord, double yCoord, double zCoord,
double xSpeed, double ySpeed, double zSpeed, int... parameters) {
}
@Override
public void spawnParticle(int id, boolean ignoreRange, boolean p_190570_3_, double x, double y, double z,
double xSpeed, double ySpeed, double zSpeed, int... parameters) {
}
@Override
public void onEntityAdded(Entity entityIn) {
}
@Override
public void onEntityRemoved(Entity entityIn) {
}
@Override
public void broadcastSound(int soundID, BlockPos pos, int data) {
}
@Override
public void playEvent(EntityPlayer player, int type, BlockPos blockPosIn, int data) {
} }
//TODO 1.14
//Sends breaking progress for all coordinates to renderglobal, so all blocks get visually broken //Sends breaking progress for all coordinates to renderglobal, so all blocks get visually broken
@Override // @Override
public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) { // public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) {
Minecraft mc = Minecraft.getMinecraft(); // Minecraft mc = Minecraft.getInstance();
//
ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(mc.player); // ModifierSettingsManager.ModifierSettings modifierSettings = ModifierSettingsManager.getModifierSettings(mc.player);
if (!BuildModifiers.isEnabled(modifierSettings, pos)) return; // if (!BuildModifiers.isEnabled(modifierSettings, pos)) return;
//
List<BlockPos> coordinates = BuildModifiers.findCoordinates(mc.player, pos); // List<BlockPos> coordinates = BuildModifiers.findCoordinates(mc.player, pos);
for (int i = 1; i < coordinates.size(); i++) { // for (int i = 1; i < coordinates.size(); i++) {
BlockPos coordinate = coordinates.get(i); // BlockPos coordinate = coordinates.get(i);
if (SurvivalHelper.canBreak(mc.world, mc.player, coordinate)) { // if (SurvivalHelper.canBreak(mc.world, mc.player, coordinate)) {
//Send i as entity id because only one block can be broken per id // //Send i as entity id because only one block can be broken per id
//Unless i happens to be the player id, then take something else // //Unless i happens to be the player id, then take something else
int fakeId = mc.player.getEntityId() != i ? i : coordinates.size(); // int fakeId = mc.player.getEntityId() != i ? i : coordinates.size();
mc.renderGlobal.sendBlockBreakProgress(fakeId, coordinate, progress); // mc.renderGlobal.sendBlockBreakProgress(fakeId, coordinate, progress);
} // }
} // }
} // }
} }

View File

@@ -12,7 +12,6 @@
*/ */
package nl.requios.effortlessbuilding.render; package nl.requios.effortlessbuilding.render;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import nl.requios.effortlessbuilding.BuildConfig; import nl.requios.effortlessbuilding.BuildConfig;
import nl.requios.effortlessbuilding.EffortlessBuilding; import nl.requios.effortlessbuilding.EffortlessBuilding;
@@ -46,7 +45,7 @@ public final class ShaderHandler {
if(!doUseShaders()) if(!doUseShaders())
return; return;
rawColor = createProgram("/assets/effortlessbuilding/shaders/raw_color", FRAG); // rawColor = createProgram("/assets/effortlessbuilding/shaders/raw_color", FRAG);
dissolve = createProgram("/assets/effortlessbuilding/shaders/dissolve", VERT + FRAG); dissolve = createProgram("/assets/effortlessbuilding/shaders/dissolve", VERT + FRAG);
} }
@@ -74,7 +73,15 @@ public final class ShaderHandler {
} }
public static boolean doUseShaders() { public static boolean doUseShaders() {
return BuildConfig.visuals.useShaders && OpenGlHelper.shadersSupported; //Extracted from OpenGLHelper in 1.13 and earlier
//Can probably be simplified
GLCapabilities glcapabilities = GL.getCapabilities();
boolean openGL14 = glcapabilities.OpenGL14 || glcapabilities.GL_EXT_blend_func_separate;
boolean openGL21 = glcapabilities.OpenGL21;
boolean framebufferSupported = openGL14 && (glcapabilities.GL_ARB_framebuffer_object || glcapabilities.GL_EXT_framebuffer_object || glcapabilities.OpenGL30);
boolean shadersAvailable = openGL21 || glcapabilities.GL_ARB_vertex_shader && glcapabilities.GL_ARB_fragment_shader && glcapabilities.GL_ARB_shader_objects;
boolean shadersSupported = framebufferSupported && shadersAvailable;
return BuildConfig.visuals.useShaders.get() && shadersSupported;
} }
private static int createProgram(String s, int sides) { private static int createProgram(String s, int sides) {

View File

@@ -0,0 +1,52 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="[31,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# A URL to refer people to when problems occur with this mod
issueTrackerURL="http://my.issue.tracker/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="effortlessbuilding" #mandatory
# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
version="${file.jarVersion}" #mandatory
# A display name for the mod
displayName="Effortless Building" #mandatory
# A URL to query for updates for this mod. See the JSON update specification <here>
#updateJSONURL="example.com" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
displayURL="https://minecraft.curseforge.com/projects/effortless-building" #optional
# A file name (in the root of the mod JAR) containing a logo for display
logoFile="logo.png" #optional
# A text field displayed in the mod UI
credits="" #optional
# A text field displayed in the mod UI
authors="Requios" #optional
# The description text for the mod (multi line!) (#mandatory)
description='''
Makes building easier by providing tools like mirrors, arrays, QuickReplace and a block randomizer. For survival and creative mode.
'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.examplemod]] #optional
# the modid of the dependency
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory
# The version range of the dependency
versionRange="[31,)" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.examplemod]]
modId="minecraft"
mandatory=true
versionRange="[1.15.2]"
ordering="NONE"
side="BOTH"

View File

@@ -0,0 +1,60 @@
{
"effortlessbuilding.screen.modifier_settings": "Modifier Settings",
"effortlessbuilding.screen.radial_menu": "Build Modes",
"effortlessbuilding.screen.randomizer_bag": "Randomizer Bag",
"effortlessbuilding.screen.player_settings": "Player Settings",
"key.effortlessbuilding.category": "Effortless Building",
"key.effortlessbuilding.hud.desc": "Modifier Menu",
"key.effortlessbuilding.replace.desc": "Toggle QuickReplace",
"key.effortlessbuilding.creative.desc": "Toggle Survival/Creative Mode",
"key.effortlessbuilding.mode.desc": "Radial Menu",
"key.effortlessbuilding.undo.desc": "Undo",
"key.effortlessbuilding.redo.desc": "Redo",
"key.effortlessbuilding.altplacement.desc": "Alternative placement",
"effortlessbuilding:randomizer_bag": "Randomizer Bag",
"effortlessbuilding:reach_upgrade1": "Reach Upgrade 1",
"effortlessbuilding:reach_upgrade2": "Reach Upgrade 2",
"effortlessbuilding:reach_upgrade3": "Reach Upgrade 3",
"effortlessbuilding.mode.normal": "Normal",
"effortlessbuilding.mode.normal_plus": "Normal+",
"effortlessbuilding.mode.line": "Line",
"effortlessbuilding.mode.wall": "Wall",
"effortlessbuilding.mode.floor": "Floor",
"effortlessbuilding.mode.diagonal_line": "Diagonal Line",
"effortlessbuilding.mode.diagonal_wall": "Diagonal Wall",
"effortlessbuilding.mode.slope_floor": "Slope Floor",
"effortlessbuilding.mode.cube": "Cube",
"effortlessbuilding.mode.circle": "Circle",
"effortlessbuilding.mode.cylinder": "Cylinder",
"effortlessbuilding.mode.sphere": "Sphere",
"effortlessbuilding.action.undo": "Undo",
"effortlessbuilding.action.redo": "Redo",
"effortlessbuilding.action.replace": "Replace",
"effortlessbuilding.action.open_modifier_settings": "Open Modifier Settings",
"effortlessbuilding.action.open_player_settings": "Open Settings",
"effortlessbuilding.action.build_speed": "Build Speed",
"effortlessbuilding.action.filling": "Filling",
"effortlessbuilding.action.raised_edge": "Raised Edge",
"effortlessbuilding.action.thickness": "Line Thickness",
"effortlessbuilding.action.circle_start": "Start Point",
"effortlessbuilding.action.normal_speed": "Normal",
"effortlessbuilding.action.fast_speed": "Fast",
"effortlessbuilding.action.full": "Filled",
"effortlessbuilding.action.hollow": "Hollow",
"effortlessbuilding.action.skeleton": "Skeleton",
"effortlessbuilding.action.short_edge": "Short Edge",
"effortlessbuilding.action.long_edge": "Long Edge",
"effortlessbuilding.action.thickness_1": "1 Block Thick",
"effortlessbuilding.action.thickness_3": "3 Blocks Thick",
"effortlessbuilding.action.thickness_5": "5 Blocks Thick",
"effortlessbuilding.action.start_center": "Middle",
"effortlessbuilding.action.start_corner": "Corner",
"commands.reach.usage": "/reach <level>"
}

View File

@@ -1,52 +0,0 @@
key.effortlessbuilding.category=Effortless Building
key.effortlessbuilding.hud.desc=Modifier Menu
key.effortlessbuilding.replace.desc=Toggle QuickReplace
key.effortlessbuilding.creative.desc=Toggle Survival/Creative Mode
key.effortlessbuilding.mode.desc=Radial Menu
key.effortlessbuilding.undo.desc=Undo
key.effortlessbuilding.redo.desc=Redo
key.effortlessbuilding.altplacement.desc=Alternative placement
item.effortlessbuilding:randomizer_bag.name=Randomizer Bag
item.effortlessbuilding:reach_upgrade1.name=Reach Upgrade 1
item.effortlessbuilding:reach_upgrade2.name=Reach Upgrade 2
item.effortlessbuilding:reach_upgrade3.name=Reach Upgrade 3
effortlessbuilding.mode.normal=Normal
effortlessbuilding.mode.normal_plus=Normal+
effortlessbuilding.mode.line=Line
effortlessbuilding.mode.wall=Wall
effortlessbuilding.mode.floor=Floor
effortlessbuilding.mode.diagonal_line=Diagonal Line
effortlessbuilding.mode.diagonal_wall=Diagonal Wall
effortlessbuilding.mode.slope_floor=Slope Floor
effortlessbuilding.mode.cube=Cube
effortlessbuilding.mode.circle=Circle
effortlessbuilding.mode.cylinder=Cylinder
effortlessbuilding.mode.sphere=Sphere
effortlessbuilding.action.undo=Undo
effortlessbuilding.action.redo=Redo
effortlessbuilding.action.replace=Replace
effortlessbuilding.action.open_modifier_settings=Open Modifier Settings
effortlessbuilding.action.build_speed=Build Speed
effortlessbuilding.action.filling=Filling
effortlessbuilding.action.raised_edge=Raised Edge
effortlessbuilding.action.thickness=Line Thickness
effortlessbuilding.action.circle_start=Start Point
effortlessbuilding.action.normal_speed=Normal
effortlessbuilding.action.fast_speed=Fast
effortlessbuilding.action.full=Filled
effortlessbuilding.action.hollow=Hollow
effortlessbuilding.action.skeleton=Skeleton
effortlessbuilding.action.short_edge=Short Edge
effortlessbuilding.action.long_edge=Long Edge
effortlessbuilding.action.thickness_1=1 Block Thick
effortlessbuilding.action.thickness_3=3 Blocks Thick
effortlessbuilding.action.thickness_5=5 Blocks Thick
effortlessbuilding.action.start_center=Middle
effortlessbuilding.action.start_corner=Corner
commands.reach.usage=/reach <level>

View File

@@ -1,5 +0,0 @@
{
"conditions": {
"enable_reach_upgrades": "nl.requios.effortlessbuilding.helper.ReachConditionFactory"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -10,8 +10,7 @@
"item": "minecraft:leather" "item": "minecraft:leather"
}, },
"O": { "O": {
"item": "minecraft:planks", "tag": "minecraft:planks"
"data": 32767
} }
}, },
"result": { "result": {

View File

@@ -1,7 +1,4 @@
{ {
"conditions": [{
"type": "effortlessbuilding:enable_reach_upgrades"
}],
"type": "minecraft:crafting_shaped", "type": "minecraft:crafting_shaped",
"pattern": [ "pattern": [
" S", " S",

View File

@@ -1,7 +1,4 @@
{ {
"conditions": [{
"type": "effortlessbuilding:enable_reach_upgrades"
}],
"type": "minecraft:crafting_shaped", "type": "minecraft:crafting_shaped",
"pattern": [ "pattern": [
" M", " M",

View File

@@ -1,7 +1,4 @@
{ {
"conditions": [{
"type": "effortlessbuilding:enable_reach_upgrades"
}],
"type": "minecraft:crafting_shaped", "type": "minecraft:crafting_shaped",
"pattern": [ "pattern": [
" FE", " FE",

BIN
src/main/resources/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

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