Add builder GUI, stricter checks, GPL-3 license and English comments
- GUI (phases 7-8): BuilderScreen, Panel, NumberSlider, CycleButton, BuilderUi keybinds (Right Shift menu, P pause macro), lang entries, README - ConfigStore.loadOrEmpty/saveQuietly; BuildSettings.Range; BuilderFeature settings()/stage()/togglePause() - Checks: ~60 Checkstyle rules (errors), PMD with 7 categories, checkArchitecture (layer rules + max 4 files per package, with baseline), javac -Xlint:all -Werror, rule rejecting non-English comments - File length limit raised to 250 lines - License: GPL-3.0-only (LICENSE, fabric.mod.json) - All code comments and log messages translated to English
This commit is contained in:
parent
b26dfbbade
commit
d9df098064
130 changed files with 1779 additions and 267 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -26,5 +26,4 @@ logs/
|
|||
todo.md
|
||||
|
||||
# Локальные заметки
|
||||
NOTICE.md
|
||||
todo.md
|
||||
|
|
|
|||
674
LICENSE
Normal file
674
LICENSE
Normal file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
88
README.md
Normal file
88
README.md
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
# Satura — авто-билдер для Minecraft (Fabric)
|
||||
|
||||
Клиентский мод: выделяешь область — мод сам ходит/летает и строит заданную форму.
|
||||
GUI-меню, команды `.pos1/.pos2/.sel/.build`, навигация через Baritone (Aethereal),
|
||||
инкрементальный подсчёт прогресса, ремонтные проходы по дырам.
|
||||
|
||||
| Что | Версия |
|
||||
|---|---|
|
||||
| Minecraft | 1.21.11 |
|
||||
| Fabric Loader | 0.20.1 |
|
||||
| Fabric API | 0.141.6+1.21.11 |
|
||||
| Yarn mappings | 1.21.11+build.6 |
|
||||
| Loom | 1.18.4 (нужна JVM 25 для запуска Gradle) |
|
||||
| Java | 21 (target), 25 (JVM сборки) |
|
||||
|
||||
## Сборка и запуск
|
||||
|
||||
```bash
|
||||
./gradlew build # jar в build/libs/satura-<версия>.jar
|
||||
./gradlew check # тесты + checkstyle + pmd (гейт проекта)
|
||||
./gradlew runClient # dev-запуск игры с модом
|
||||
```
|
||||
|
||||
Gradle запускается на JVM 25: если дефолтная JVM другой версии, укажи её в
|
||||
`gradle.properties` (`org.gradle.java.home`) или ключом `-Dorg.gradle.java.home=...`.
|
||||
Для dev-запуска с Baritone положи `aethereal-1.21.11.jar` в `libs/`.
|
||||
|
||||
## Использование
|
||||
|
||||
### Клавиши (настраиваются в ванильных «Управлении», категория Satura)
|
||||
|
||||
| Клавиша | Действие |
|
||||
|---|---|
|
||||
| Right Shift | открыть/закрыть меню билдера |
|
||||
| P | макрос: пауза / продолжить текущий билд |
|
||||
|
||||
### Команды (префикс `.`)
|
||||
|
||||
| Команда | Действие |
|
||||
|---|---|
|
||||
| `.pos1` / `.pos2` | задать углы области по позиции ног |
|
||||
| `.sel clear` | сбросить выделение |
|
||||
| `.build start` / `pause` / `resume` / `stop` / `status` | управление стройкой |
|
||||
| `.build block <id>` | блок (`stone`, `minecraft:glass` или `hand` — блок из руки) |
|
||||
| `.build shape box\|checker\|walls` | форма застройки области |
|
||||
| `.build layers 1..3` | слоёв за один проход колонны |
|
||||
| `.build strategy <id>` | стратегия постановки (`band_stack`, `column_drop`) |
|
||||
| `.build set <ключ> <знач>` | параметр стратегии (`delayMs`, `reach`, `hover`, `flySpeed`, `bandLayers`) |
|
||||
|
||||
### GUI (Right Shift)
|
||||
|
||||
Pos1/Pos2 — зафиксировать текущую позицию ног; Старт/Пауза/Продолжить/Стоп;
|
||||
форма; слои; задержка установки; ID блока (Enter — применить). Внизу — живой
|
||||
статус: этап, прогресс, блоков/с, дыры. Во время стройки тот же статус раз в
|
||||
секунду дублируется над хотбаром.
|
||||
|
||||
### Стратегии постановки
|
||||
|
||||
- **BandStack** (дефолт) — за один визит колонны ставится 1–3 слоя снизу вверх.
|
||||
- **ColumnDrop** — по одному слою за визит.
|
||||
Обе летают над слоем и ставят в колонну под собой. Для серверов с жёстким
|
||||
анти-читом используй меньший `delayMs` и без полёта (наземные стратегии — план
|
||||
Фазы 9, S5/S6).
|
||||
|
||||
Настройки хранятся в `config/satura/default.json` и применяются при старте.
|
||||
|
||||
## Архитектура
|
||||
|
||||
Слои зависимостей направлены строго вниз, циклы запрещены:
|
||||
|
||||
```
|
||||
mixin → feature → interaction → core → util
|
||||
gui → feature (только через фасад BuilderFeature)
|
||||
```
|
||||
|
||||
- `core` — событие/команды/конфиг, ничего не знает о фичах;
|
||||
- `feature/builder` — селекция, план (формы), скан (ColumnCache), движок, Baritone-мост;
|
||||
- `interaction` — «руки»: постановка блоков (стратегии), инвентарь, движение;
|
||||
- `gui` — экран и виджеты, общается с фичей только через фасад;
|
||||
- `render` — GUI-рендер (rect/blur/outline/MSDF-текст) и рамка выделения в мире.
|
||||
|
||||
Правила кода: максимум 250 строк на `.java`-файл, максимум 4 файла на пакет,
|
||||
магические числа — в константы, гейт сборки — `./gradlew check` (Checkstyle +
|
||||
PMD). Подробный план развития — `todo.md`.
|
||||
|
||||
## Лицензия
|
||||
|
||||
GPL-3.0-only, см. `LICENSE`.
|
||||
|
|
@ -44,6 +44,7 @@ java {
|
|||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.encoding = "UTF-8"
|
||||
options.release.set(21)
|
||||
options.compilerArgs.addAll(listOf("-Xlint:all,-processing,-serial,-classfile", "-Werror"))
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
|
|
@ -53,7 +54,7 @@ tasks.processResources {
|
|||
}
|
||||
}
|
||||
|
||||
// Правило проекта: файл максимум 200 строк — FileLength (severity=error валит check)
|
||||
// Правило проекта: файл максимум 250 строк — FileLength (severity=error валит check)
|
||||
checkstyle {
|
||||
toolVersion = "10.21.2"
|
||||
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
|
||||
|
|
@ -74,3 +75,48 @@ tasks.test {
|
|||
tasks.named("pmdTest") {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
// Архитектура (правила 6 и 11): максимум 4 файла в папке, слои зависят только вниз
|
||||
val maxFilesPerDir = 4
|
||||
val layerRules = mapOf(
|
||||
"util" to setOf<String>(),
|
||||
"core" to setOf("util"),
|
||||
"interaction" to setOf("core", "util"),
|
||||
"render" to setOf("util"),
|
||||
"feature" to setOf("core", "interaction", "render", "util"),
|
||||
"gui" to setOf("core", "feature", "render", "util"),
|
||||
)
|
||||
|
||||
tasks.register("checkArchitecture") {
|
||||
group = "verification"
|
||||
description = "Лимит файлов в папке и направление зависимостей между слоями"
|
||||
val srcRoot = layout.projectDirectory.dir("src/main/java/dev/loki/satura").asFile
|
||||
val baselineFile = layout.projectDirectory.file("config/architecture/baseline.txt").asFile
|
||||
doLast {
|
||||
val errors = mutableListOf<String>()
|
||||
srcRoot.walkTopDown().filter { it.isDirectory }.forEach { dir ->
|
||||
val count = dir.listFiles { f -> f.extension == "java" }?.size ?: 0
|
||||
if (count > maxFilesPerDir) {
|
||||
errors += "${dir.relativeTo(srcRoot)}: $count файлов (максимум $maxFilesPerDir)"
|
||||
}
|
||||
}
|
||||
val baseline = baselineFile.readLines().filter { it.isNotBlank() && !it.startsWith("#") }.toSet()
|
||||
val importRe = Regex("^import (?:static )?dev\\.loki\\.satura\\.([a-z]+)")
|
||||
srcRoot.walkTopDown().filter { it.extension == "java" }.forEach { file ->
|
||||
val rel = file.relativeTo(srcRoot).invariantSeparatorsPath
|
||||
val layer = rel.substringBefore('/')
|
||||
val allowed = layerRules[layer] ?: return@forEach
|
||||
file.readLines().mapNotNull { importRe.find(it)?.groupValues?.get(1) }.distinct()
|
||||
.filter { it != layer && it !in allowed }
|
||||
.filter { "$rel -> $it" !in baseline }
|
||||
.forEach { errors += "$rel: слой '$layer' не может импортировать '$it'" }
|
||||
}
|
||||
if (errors.isNotEmpty()) {
|
||||
throw GradleException("Нарушения архитектуры:\n" + errors.joinToString("\n") { " $it" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named("check") {
|
||||
dependsOn("checkArchitecture")
|
||||
}
|
||||
|
|
|
|||
7
config/architecture/baseline.txt
Normal file
7
config/architecture/baseline.txt
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
# Известные нарушения слоёв (долг). Новые нарушения валят check; этот список только уменьшается.
|
||||
# Формат: путь-к-файлу -> пакет, который импортируется
|
||||
interaction/place/PlaceStrategy.java -> feature
|
||||
interaction/place/option/CommonOptions.java -> feature
|
||||
interaction/place/strategy/BandStack.java -> feature
|
||||
interaction/place/strategy/ColumnDrop.java -> feature
|
||||
interaction/place/strategy/ColumnPlacing.java -> feature
|
||||
|
|
@ -3,41 +3,194 @@
|
|||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
|
||||
<!-- Правила проекта satura: FileLength 200 — единственный жёсткий (error) гейт,
|
||||
остальное — предупреждения. -->
|
||||
<!-- Правила проекта satura. Любое нарушение — error и валит ./gradlew check. -->
|
||||
<module name="Checker">
|
||||
<property name="charset" value="UTF-8"/>
|
||||
<property name="severity" value="warning"/>
|
||||
<property name="severity" value="error"/>
|
||||
|
||||
<!-- ===== Файл ===== -->
|
||||
<module name="FileLength">
|
||||
<property name="max" value="200"/>
|
||||
<property name="severity" value="error"/>
|
||||
<property name="max" value="250"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
</module>
|
||||
|
||||
<module name="FileTabCharacter">
|
||||
<property name="eachLine" value="true"/>
|
||||
</module>
|
||||
|
||||
<module name="NewlineAtEndOfFile"/>
|
||||
|
||||
<module name="LineLength">
|
||||
<property name="max" value="120"/>
|
||||
<property name="ignorePattern" value="^package.*|^import.*|https?://"/>
|
||||
</module>
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="\s+$"/>
|
||||
<property name="message" value="Пробелы в конце строки"/>
|
||||
</module>
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="^\s*(//|/\*|\*).*[А-Яа-яЁё]|\s//.*[А-Яа-яЁё]"/>
|
||||
<property name="message" value="Comments must be in English (Russian only in user-facing strings)"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
</module>
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="System\.(out|err)\.print|printStackTrace\("/>
|
||||
<property name="message" value="Вывод в консоль запрещён — используй логгер"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
</module>
|
||||
|
||||
<!-- Тесты: упрощённые правила (магические числа, поля-стабы, однострочные лямбды) -->
|
||||
<module name="SuppressionFilter">
|
||||
<property name="file" value="${config_loc}/suppressions.xml"/>
|
||||
</module>
|
||||
|
||||
<module name="TreeWalker">
|
||||
<!-- ===== Импорты ===== -->
|
||||
<module name="UnusedImports"/>
|
||||
<module name="RedundantImport"/>
|
||||
<module name="AvoidStarImport"/>
|
||||
<module name="IllegalImport"/>
|
||||
|
||||
<!-- ===== Нейминг ===== -->
|
||||
<module name="PackageName">
|
||||
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
|
||||
</module>
|
||||
<module name="TypeName"/>
|
||||
<module name="MethodName">
|
||||
<property name="format" value="^[a-z][a-zA-Z0-9]*(\$[a-z][a-zA-Z0-9]*)?$"/>
|
||||
</module>
|
||||
<module name="MemberName"/>
|
||||
<module name="LocalVariableName"/>
|
||||
<module name="LocalFinalVariableName"/>
|
||||
<module name="ParameterName"/>
|
||||
<module name="LambdaParameterName"/>
|
||||
<module name="StaticVariableName"/>
|
||||
<module name="ConstantName"/>
|
||||
<module name="ClassTypeParameterName"/>
|
||||
<module name="MethodTypeParameterName"/>
|
||||
<module name="RecordComponentName"/>
|
||||
<module name="AbbreviationAsWordInName">
|
||||
<property name="allowedAbbreviationLength" value="2"/>
|
||||
<property name="ignoreFinal" value="false"/>
|
||||
<property name="ignoreStaticFinal" value="true"/>
|
||||
</module>
|
||||
|
||||
<!-- ===== Структура и инкапсуляция ===== -->
|
||||
<module name="OneTopLevelClass"/>
|
||||
<module name="OuterTypeFilename"/>
|
||||
<module name="FinalClass"/>
|
||||
<module name="HideUtilityClassConstructor"/>
|
||||
<module name="InterfaceIsType"/>
|
||||
<module name="VisibilityModifier">
|
||||
<property name="packageAllowed" value="false"/>
|
||||
<property name="protectedAllowed" value="false"/>
|
||||
<property name="ignoreAnnotationCanonicalNames" value="Shadow, org.spongepowered.asm.mixin.Shadow"/>
|
||||
</module>
|
||||
<module name="ModifierOrder"/>
|
||||
<module name="RedundantModifier"/>
|
||||
<module name="MutableException"/>
|
||||
<module name="ThrowsCount">
|
||||
<property name="max" value="2"/>
|
||||
</module>
|
||||
|
||||
<!-- ===== Размер и сложность (KISS) ===== -->
|
||||
<module name="MethodLength">
|
||||
<property name="max" value="50"/>
|
||||
<property name="countEmpty" value="false"/>
|
||||
</module>
|
||||
<module name="ParameterNumber">
|
||||
<property name="max" value="8"/>
|
||||
<property name="ignoreOverriddenMethods" value="true"/>
|
||||
</module>
|
||||
<module name="RecordComponentNumber">
|
||||
<property name="max" value="14"/>
|
||||
</module>
|
||||
<module name="AnonInnerLength">
|
||||
<property name="max" value="30"/>
|
||||
</module>
|
||||
<module name="CyclomaticComplexity">
|
||||
<property name="max" value="10"/>
|
||||
</module>
|
||||
<module name="NPathComplexity">
|
||||
<property name="max" value="100"/>
|
||||
</module>
|
||||
<module name="BooleanExpressionComplexity">
|
||||
<property name="max" value="4"/>
|
||||
</module>
|
||||
<module name="NestedIfDepth">
|
||||
<property name="max" value="2"/>
|
||||
</module>
|
||||
<module name="NestedForDepth">
|
||||
<property name="max" value="2"/>
|
||||
</module>
|
||||
<module name="NestedTryDepth">
|
||||
<property name="max" value="1"/>
|
||||
</module>
|
||||
<module name="ReturnCount">
|
||||
<property name="max" value="5"/>
|
||||
<property name="maxForVoid" value="3"/>
|
||||
</module>
|
||||
|
||||
<!-- ===== Магические числа (правило 7) ===== -->
|
||||
<module name="MagicNumber">
|
||||
<property name="ignoreNumbers" value="-1, 0, 1, 2"/>
|
||||
<property name="ignoreHashCodeMethod" value="true"/>
|
||||
<property name="ignoreAnnotation" value="true"/>
|
||||
<property name="ignoreFieldDeclaration" value="false"/>
|
||||
<property name="constantWaiverParentToken"
|
||||
value="TYPECAST, METHOD_CALL, EXPR, ARRAY_INIT, UNARY_MINUS, UNARY_PLUS,
|
||||
ELIST, STAR, ASSIGN, PLUS, MINUS, DIV, LITERAL_NEW"/>
|
||||
</module>
|
||||
|
||||
<!-- ===== Корректность ===== -->
|
||||
<module name="StringLiteralEquality"/>
|
||||
<module name="EqualsHashCode"/>
|
||||
<module name="CovariantEquals"/>
|
||||
<module name="EmptyBlock">
|
||||
<property name="option" value="text"/>
|
||||
</module>
|
||||
<module name="EmptyCatchBlock">
|
||||
<property name="exceptionVariableName" value="expected|ignore|ignored"/>
|
||||
</module>
|
||||
<module name="EmptyStatement"/>
|
||||
<module name="FallThrough"/>
|
||||
<module name="MissingSwitchDefault"/>
|
||||
<module name="DefaultComesLast"/>
|
||||
<module name="InnerAssignment"/>
|
||||
<module name="MultipleVariableDeclarations"/>
|
||||
<module name="OneStatementPerLine"/>
|
||||
<module name="IllegalInstantiation">
|
||||
<property name="classes" value="java.lang.Boolean, java.lang.Integer, java.lang.Long,
|
||||
java.lang.Double, java.lang.Float"/>
|
||||
</module>
|
||||
<module name="IllegalCatch">
|
||||
<property name="illegalClassNames" value="Throwable, Error"/>
|
||||
</module>
|
||||
<module name="IllegalThrows"/>
|
||||
<module name="ExplicitInitialization"/>
|
||||
<module name="UnnecessaryParentheses"/>
|
||||
<module name="SimplifyBooleanExpression"/>
|
||||
<module name="SimplifyBooleanReturn"/>
|
||||
<module name="OverloadMethodsDeclarationOrder"/>
|
||||
<module name="PackageDeclaration"/>
|
||||
<module name="MissingOverride"/>
|
||||
|
||||
<!-- ===== Оформление ===== -->
|
||||
<module name="NeedBraces"/>
|
||||
<module name="LeftCurly"/>
|
||||
<module name="RightCurly"/>
|
||||
<module name="UpperEll"/>
|
||||
<module name="ArrayTypeStyle"/>
|
||||
<module name="GenericWhitespace"/>
|
||||
<module name="MethodParamPad"/>
|
||||
<module name="NoWhitespaceAfter"/>
|
||||
<module name="NoWhitespaceBefore"/>
|
||||
<module name="WhitespaceAround">
|
||||
<property name="allowEmptyLambdas" value="true"/>
|
||||
<property name="allowEmptyMethods" value="true"/>
|
||||
<property name="allowEmptyTypes" value="true"/>
|
||||
<property name="allowEmptyConstructors" value="true"/>
|
||||
</module>
|
||||
<module name="CommentsIndentation"/>
|
||||
<module name="TodoComment">
|
||||
<property name="format" value="FIXME|XXX"/>
|
||||
</module>
|
||||
</module>
|
||||
</module>
|
||||
|
|
|
|||
12
config/checkstyle/suppressions.xml
Normal file
12
config/checkstyle/suppressions.xml
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?xml version="1.0"?>
|
||||
<!DOCTYPE suppressions PUBLIC
|
||||
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
|
||||
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
|
||||
|
||||
<suppressions>
|
||||
<suppress checks="MagicNumber|VisibilityModifier|LeftCurly|AnonInnerLength|MethodLength|ParameterNumber|RightCurly"
|
||||
files="[\\/]src[\\/]test[\\/]"/>
|
||||
<!-- Рендер: константы GPU/цветов/вершин, много параметров у draw-вызовов -->
|
||||
<suppress checks="MagicNumber|ParameterNumber"
|
||||
files="[\\/]satura[\\/]render[\\/]"/>
|
||||
</suppressions>
|
||||
|
|
@ -5,21 +5,69 @@
|
|||
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0
|
||||
https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
||||
|
||||
<description>Satura base ruleset: errorprone + bestpractices + design (без шума)</description>
|
||||
<description>Satura ruleset: errorprone, bestpractices, design, codestyle, performance, multithreading, security</description>
|
||||
|
||||
<rule ref="category/java/errorprone.xml"/>
|
||||
|
||||
<rule ref="category/java/bestpractices.xml">
|
||||
<exclude name="GuardLogStatements"/>
|
||||
<exclude name="GuardLogStatement"/>
|
||||
<exclude name="AccessorMethodGeneration"/>
|
||||
<exclude name="UnusedPrivateMethod"/>
|
||||
</rule>
|
||||
|
||||
<rule ref="category/java/design.xml">
|
||||
<exclude name="TooManyMethods"/>
|
||||
<exclude name="CyclomaticComplexity"/>
|
||||
<exclude name="CognitiveComplexity"/>
|
||||
<exclude name="ExcessiveImports"/>
|
||||
<exclude name="LawOfDemeter"/>
|
||||
<exclude name="LoosePackageCoupling"/>
|
||||
<exclude name="UseUtilityClass"/>
|
||||
</rule>
|
||||
|
||||
<rule ref="category/java/codestyle.xml">
|
||||
<exclude name="AtLeastOneConstructor"/>
|
||||
<exclude name="OnlyOneReturn"/>
|
||||
<exclude name="ShortVariable"/>
|
||||
<exclude name="LongVariable"/>
|
||||
<exclude name="ShortClassName"/>
|
||||
<exclude name="ShortMethodName"/>
|
||||
<exclude name="CommentDefaultAccessModifier"/>
|
||||
<exclude name="LocalVariableCouldBeFinal"/>
|
||||
<exclude name="MethodArgumentCouldBeFinal"/>
|
||||
<exclude name="PrematureDeclaration"/>
|
||||
<exclude name="UselessParentheses"/>
|
||||
<exclude name="TooManyStaticImports"/>
|
||||
<exclude name="FieldDeclarationsShouldBeAtStartOfClass"/>
|
||||
<exclude name="UnnecessaryBoxing"/>
|
||||
<exclude name="LinguisticNaming"/>
|
||||
<exclude name="ConfusingTernary"/>
|
||||
<exclude name="UnnecessaryConstructor"/>
|
||||
<exclude name="UnnecessaryAnnotationValueElement"/>
|
||||
<exclude name="UseExplicitTypes"/>
|
||||
</rule>
|
||||
|
||||
<rule ref="category/java/performance.xml">
|
||||
<exclude name="AvoidInstantiatingObjectsInLoops"/>
|
||||
</rule>
|
||||
|
||||
<rule ref="category/java/multithreading.xml">
|
||||
<exclude name="DoNotUseThreads"/>
|
||||
<exclude name="UseConcurrentHashMap"/>
|
||||
<exclude name="AvoidSynchronizedAtMethodLevel"/>
|
||||
</rule>
|
||||
|
||||
<rule ref="category/java/security.xml"/>
|
||||
|
||||
<!-- Порог сложности строже дефолта -->
|
||||
<rule ref="category/java/design.xml/CyclomaticComplexity">
|
||||
<properties>
|
||||
<property name="methodReportLevel" value="10"/>
|
||||
</properties>
|
||||
</rule>
|
||||
<rule ref="category/java/design.xml/CognitiveComplexity">
|
||||
<properties>
|
||||
<property name="reportLevel" value="15"/>
|
||||
</properties>
|
||||
</rule>
|
||||
</ruleset>
|
||||
|
|
|
|||
|
|
@ -6,10 +6,12 @@ import dev.loki.satura.core.command.builtin.HelpCommand;
|
|||
import dev.loki.satura.core.config.ConfigStore;
|
||||
import dev.loki.satura.core.event.EventBus;
|
||||
import dev.loki.satura.feature.builder.BuilderFeature;
|
||||
import dev.loki.satura.gui.BuilderUi;
|
||||
import dev.loki.satura.render.RenderDebug;
|
||||
import dev.loki.satura.render.Renderer;
|
||||
import dev.loki.satura.render.world.Marks;
|
||||
import dev.loki.satura.render.world.SelectionRenderer;
|
||||
import dev.loki.satura.util.ActionBarOut;
|
||||
import dev.loki.satura.util.ChatOut;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||
|
|
@ -18,7 +20,7 @@ import org.slf4j.Logger;
|
|||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Точка входа клиента. Только сборка компонентов — вся логика в feature-пакетах.
|
||||
* Client entry point. Only wires components together; all logic lives in the feature packages.
|
||||
*/
|
||||
public final class SaturaClient implements ClientModInitializer {
|
||||
|
||||
|
|
@ -39,6 +41,7 @@ public final class SaturaClient implements ClientModInitializer {
|
|||
RenderDebug.installIfEnabled(Renderer.shared());
|
||||
new SelectionRenderer(() -> new Marks(builder.selection().pos1(), builder.selection().pos2()),
|
||||
SELECTION_SEE_THROUGH).register();
|
||||
new BuilderUi(builder, new ActionBarOut()).register();
|
||||
LOG.info("[satura] client init");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import dev.loki.satura.core.command.CommandRegistry;
|
|||
import dev.loki.satura.core.config.ConfigStore;
|
||||
import dev.loki.satura.core.event.EventBus;
|
||||
|
||||
/** Собранное ядро; доступ для миксинов (они не могут получить зависимости через конструктор). */
|
||||
/** Assembled core; exposed to mixins (they cannot receive dependencies through a constructor). */
|
||||
public record CoreServices(EventBus events, CommandRegistry commands, ConfigStore config) {
|
||||
|
||||
private static CoreServices current;
|
||||
|
|
@ -13,7 +13,7 @@ public record CoreServices(EventBus events, CommandRegistry commands, ConfigStor
|
|||
current = services;
|
||||
}
|
||||
|
||||
/** Ядро или null, если мод ещё не инициализирован. */
|
||||
/** The core, or null if the mod is not initialized yet. */
|
||||
public static CoreServices get() {
|
||||
return current;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.core.command;
|
|||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Чат-команда с префиксом {@code .}. */
|
||||
/** Chat command with the {@code .} prefix. */
|
||||
public interface Command {
|
||||
|
||||
String name();
|
||||
|
|
@ -11,17 +11,17 @@ public interface Command {
|
|||
String description();
|
||||
|
||||
/**
|
||||
* Выполнить команду.
|
||||
* Execute the command.
|
||||
*
|
||||
* @param args токены после имени
|
||||
* @param reply куда писать ответ пользователю
|
||||
* @param args tokens after the name
|
||||
* @param reply where to write the reply for the user
|
||||
*/
|
||||
void execute(List<String> args, Consumer<String> reply);
|
||||
|
||||
/**
|
||||
* Кандидаты для последнего (редактируемого) токена.
|
||||
* Candidates for the last (currently edited) token.
|
||||
*
|
||||
* @param args токены после имени; последний — недописанный (может быть пустым)
|
||||
* @param args tokens after the name; the last one is unfinished (may be empty)
|
||||
*/
|
||||
default List<String> suggest(List<String> args) {
|
||||
return List.of();
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.core.command;
|
|||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Разбиение строки на токены по пробелам; кавычки группируют; хвостовой пробел даёт пустой токен. */
|
||||
/** Splits a line into tokens by spaces; quotes group; a trailing space yields an empty token. */
|
||||
final class CommandParser {
|
||||
|
||||
private static final char QUOTE = '"';
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import java.util.Map;
|
|||
import java.util.TreeMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Реестр команд: регистрация, выполнение строки и подсказки. */
|
||||
/** Command registry: registration, line execution and suggestions. */
|
||||
@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidCatchingGenericException"})
|
||||
public final class CommandRegistry {
|
||||
|
||||
|
|
@ -29,7 +29,7 @@ public final class CommandRegistry {
|
|||
return commands.values();
|
||||
}
|
||||
|
||||
/** Выполняет строку без префикса, например {@code "help"}. */
|
||||
/** Executes a line without the prefix, e.g. {@code "help"}. */
|
||||
public void execute(String line) {
|
||||
List<String> tokens = CommandParser.tokenize(line.strip());
|
||||
Command command = commands.get(tokens.get(0).toLowerCase(Locale.ROOT));
|
||||
|
|
@ -44,7 +44,7 @@ public final class CommandRegistry {
|
|||
}
|
||||
}
|
||||
|
||||
/** Подсказки для текста до курсора (с префиксом). */
|
||||
/** Suggestions for the text before the cursor (with the prefix). */
|
||||
public List<String> suggest(String toCursor) {
|
||||
String body = toCursor.startsWith(SuggestHelper.PREFIX)
|
||||
? toCursor.substring(SuggestHelper.PREFIX.length()) : toCursor;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.core.command;
|
|||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Фильтрация подсказок по префиксу и позиция начала редактируемого токена. */
|
||||
/** Suggestion filtering by prefix and the start position of the edited token. */
|
||||
public final class SuggestHelper {
|
||||
|
||||
public static final String PREFIX = ".";
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import dev.loki.satura.core.command.SuggestHelper;
|
|||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** {@code .help} — список зарегистрированных команд. */
|
||||
/** {@code .help} — list of registered commands. */
|
||||
public final class HelpCommand implements Command {
|
||||
|
||||
private final CommandRegistry registry;
|
||||
|
|
|
|||
|
|
@ -11,10 +11,14 @@ import java.nio.file.Path;
|
|||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** Хранение профилей как json-файлов в каталоге (config/satura/). */
|
||||
/** Stores profiles as json files in a directory (config/satura/). */
|
||||
@SuppressWarnings("PMD.GuardLogStatement")
|
||||
public final class ConfigStore {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ConfigStore.class);
|
||||
private static final String EXTENSION = ".json";
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
|
|
@ -41,6 +45,26 @@ public final class ConfigStore {
|
|||
}
|
||||
}
|
||||
|
||||
/** Loads the profile or an empty default; read errors never propagate to the caller. */
|
||||
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.CloseResource"})
|
||||
public Profile loadOrEmpty(final String name) {
|
||||
try {
|
||||
return load(name).orElse(Profile.empty(name));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
LOG.warn("[satura] profile {} not loaded: {}", name, e.toString());
|
||||
return Profile.empty(name);
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves the profile, swallowing I/O errors (for GUI/click handlers that cannot throw). */
|
||||
public void saveQuietly(final Profile profile) {
|
||||
try {
|
||||
save(profile);
|
||||
} catch (IOException e) {
|
||||
LOG.warn("[satura] profile {} not saved: {}", profile.name(), e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> list() throws IOException {
|
||||
if (!Files.isDirectory(dir)) {
|
||||
return List.of();
|
||||
|
|
|
|||
|
|
@ -4,10 +4,10 @@ import java.util.HashMap;
|
|||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Иммутабельный профиль настроек.
|
||||
* Immutable settings profile.
|
||||
*
|
||||
* @param name имя профиля (имя файла)
|
||||
* @param settings ключ → значение
|
||||
* @param name profile name (file name)
|
||||
* @param settings key → value
|
||||
*/
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public record Profile(String name, Map<String, String> settings) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.core.event;
|
||||
|
||||
/** Событие, обработку которого можно отменить; после отмены цепочка слушателей прерывается. */
|
||||
/** An event whose handling can be cancelled; once cancelled, the listener chain is interrupted. */
|
||||
public interface Cancellable extends Event {
|
||||
|
||||
boolean isCancelled();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
package dev.loki.satura.core.event;
|
||||
|
||||
/** Маркер события. Тип события = его класс. */
|
||||
/** Event marker. The event type is its class. */
|
||||
public interface Event {
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import java.util.Map;
|
|||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/** Шина событий: подписка с приоритетами, отписка, остановка цепочки на отменённом событии. */
|
||||
/** Event bus: prioritized subscription, unsubscription, chain stops on a cancelled event. */
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public final class EventBus {
|
||||
|
||||
|
|
|
|||
|
|
@ -3,12 +3,12 @@ package dev.loki.satura.core.event;
|
|||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Подписка на событие. Меньший priority вызывается раньше.
|
||||
* Event subscription. A lower priority is called earlier.
|
||||
*
|
||||
* @param type класс события
|
||||
* @param priority порядок вызова
|
||||
* @param handler обработчик
|
||||
* @param <T> тип события
|
||||
* @param type event class
|
||||
* @param priority call order
|
||||
* @param handler handler
|
||||
* @param <T> event type
|
||||
*/
|
||||
public record Listener<T extends Event>(Class<T> type, int priority, Consumer<T> handler) {
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,6 @@ package dev.loki.satura.core.event.world;
|
|||
import dev.loki.satura.core.event.Event;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** В клиентском мире изменился блок. */
|
||||
/** A block changed in the client world. */
|
||||
public record BlockChangeEvent(BlockPos pos) implements Event {
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,11 +13,16 @@ import java.util.LinkedHashMap;
|
|||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Настройки билдера; читаются из {@link Profile} и в него же сериализуются. */
|
||||
/** Builder settings; read from and serialized back into a {@link Profile}. */
|
||||
@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidFieldNameMatchingMethodName"})
|
||||
public final class BuildSettings {
|
||||
|
||||
/** Range and current value of a strategy parameter, for a GUI slider. */
|
||||
public record Range(double min, double max, double step, double value) {
|
||||
}
|
||||
|
||||
static final String KEY_BLOCK = "block";
|
||||
static final String KEY_SHAPE = "shape";
|
||||
static final String KEY_LAYERS = "layers";
|
||||
|
|
@ -87,7 +92,7 @@ public final class BuildSettings {
|
|||
strategy = id;
|
||||
}
|
||||
|
||||
/** Слоёв за проход: значение опции стратегии bandLayers, если она её объявляет. */
|
||||
/** Layers per pass: the strategy's bandLayers option value, if it declares one. */
|
||||
public int layers() {
|
||||
final PlaceStrategy s = strategy();
|
||||
return s.options().contains(CommonOptions.BAND_LAYERS)
|
||||
|
|
@ -105,6 +110,12 @@ public final class BuildSettings {
|
|||
return strategy().options().stream().map(Option::key).toList();
|
||||
}
|
||||
|
||||
/** Range of a current-strategy parameter; empty if the strategy does not declare it. */
|
||||
public Optional<Range> optionRange(final String key) {
|
||||
return strategy().options().stream().filter(o -> o.key().equals(key)).findFirst()
|
||||
.map(o -> new Range(o.min(), o.max(), o.step(), strategy().values().get(o)));
|
||||
}
|
||||
|
||||
public void setOption(final String key, final String value) {
|
||||
final double number;
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -22,22 +22,17 @@ import dev.loki.satura.interaction.place.support.Cooldown;
|
|||
import dev.loki.satura.interaction.place.support.SupportFinder;
|
||||
import dev.loki.satura.util.ActionBarOut;
|
||||
import dev.loki.satura.util.ChatOut;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** Фасад фичи «авто-билдер»: единственная точка входа для GUI, команд и рендера. */
|
||||
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"})
|
||||
/** Facade of the auto-builder feature: the single entry point for GUI, commands and rendering. */
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.LooseCoupling"})
|
||||
public final class BuilderFeature implements BuildControl {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BuilderFeature.class);
|
||||
|
||||
private final Selection current = new Selection();
|
||||
private final BuildSettings settings;
|
||||
private final EngineAssembler assembler;
|
||||
|
|
@ -56,7 +51,7 @@ public final class BuilderFeature implements BuildControl {
|
|||
commands.register(new BuildCommand(this));
|
||||
}
|
||||
|
||||
/** Фасад на клиенте Minecraft; ходок «нет» (мост Baritone подключается через перегрузку). */
|
||||
/** Facade on the Minecraft client; no walker (the Baritone bridge is attached through an overload). */
|
||||
public static BuilderFeature create(final CommandRegistry commands, final EventBus events,
|
||||
final ConfigStore store) {
|
||||
return create(commands, events, store, new NoWalker());
|
||||
|
|
@ -68,17 +63,16 @@ public final class BuilderFeature implements BuildControl {
|
|||
final MinecraftClient client = MinecraftClient.getInstance();
|
||||
final BlockPlacer placer = new BlockPlacer(new SupportFinder(), new Cooldown());
|
||||
final List<PlaceStrategy> strategies = List.of(new BandStack(placer), new ColumnDrop(placer));
|
||||
final Profile profile = load(store);
|
||||
return new BuilderFeature(commands, () -> client.player == null ? null : client.player.getBlockPos(),
|
||||
new EngineAssembler(client, events, walker, new ChatOut(), new ActionBarOut()),
|
||||
new BuildSettings(profile, strategies), p -> save(store, p));
|
||||
new BuildSettings(store.loadOrEmpty(Profile.DEFAULT_NAME), strategies), store::saveQuietly);
|
||||
}
|
||||
|
||||
public Selection selection() {
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Вызывать каждый клиентский тик. */
|
||||
/** Call on every client tick. */
|
||||
public void tick() {
|
||||
if (engine != null) {
|
||||
engine.tick();
|
||||
|
|
@ -119,6 +113,24 @@ public final class BuilderFeature implements BuildControl {
|
|||
return engine == null ? "IDLE" : engine.snapshot().describe();
|
||||
}
|
||||
|
||||
/** Session stage, for GUI labels (the Pause/Resume button). */
|
||||
public Stage stage() {
|
||||
return engine == null ? Stage.IDLE : engine.stage();
|
||||
}
|
||||
|
||||
/** Settings for reading from the GUI; changes only via {@link BuildControl} methods. */
|
||||
public BuildSettings settings() {
|
||||
return settings;
|
||||
}
|
||||
|
||||
/** Macro key: pause/resume the current build. */
|
||||
public String togglePause() {
|
||||
if (engine == null) {
|
||||
return "билд не запущен";
|
||||
}
|
||||
return engine.stage() == Stage.PAUSED ? resume() : pause();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String setBlock(final String id) {
|
||||
assembler.blocks().resolve(id);
|
||||
|
|
@ -180,21 +192,4 @@ public final class BuilderFeature implements BuildControl {
|
|||
persist.accept(settings.toProfile(Profile.DEFAULT_NAME));
|
||||
return message;
|
||||
}
|
||||
|
||||
private static Profile load(final ConfigStore store) {
|
||||
try {
|
||||
return store.load(Profile.DEFAULT_NAME).orElse(Profile.empty(Profile.DEFAULT_NAME));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
LOG.warn("[satura] профиль не загружен: {}", e.toString());
|
||||
return Profile.empty(Profile.DEFAULT_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
private static void save(final ConfigStore store, final Profile profile) {
|
||||
try {
|
||||
store.save(profile);
|
||||
} catch (IOException e) {
|
||||
LOG.warn("[satura] профиль не сохранён: {}", e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,8 +22,8 @@ import java.util.random.RandomGenerator;
|
|||
import net.minecraft.block.Block;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
|
||||
/** Thin assembler of the engine from settings and the Minecraft client. */
|
||||
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
|
||||
/** Тонкий сборщик движка из настроек и клиента Minecraft. */
|
||||
public final class EngineAssembler {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
|
|
|||
|
|
@ -5,8 +5,9 @@ import net.fabricmc.loader.api.FabricLoader;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** Мост к Baritone (Aethereal): только рефлексия, любая ошибка отключает мост одной записью в лог. */
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"})
|
||||
/** Bridge to Baritone (Aethereal): reflection only; any error disables the bridge with a single log entry. */
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException",
|
||||
"PMD.GuardLogStatement"})
|
||||
public final class BaritoneBridge implements WalkerPort {
|
||||
|
||||
static final String MOD_ID = "baritone-meteor";
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import java.lang.reflect.Field;
|
|||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
/** Кэш рефлексивных дескрипторов Baritone API; создаётся один раз. */
|
||||
/** Cache of reflective Baritone API descriptors; created once. */
|
||||
final class BaritoneLink {
|
||||
|
||||
private static final String PKG = "baritone.api.";
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
package dev.loki.satura.feature.builder.baritone;
|
||||
|
||||
/** Порт перемещения: движок видит только его, а не Baritone. */
|
||||
/** Movement port: the engine sees only this, not Baritone. */
|
||||
public interface WalkerPort {
|
||||
|
||||
/** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */
|
||||
/** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */
|
||||
boolean walkTo(double x, double z);
|
||||
|
||||
void cancel();
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import java.util.Map;
|
|||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** {@code .build} — диспетчер подкоманд. */
|
||||
/** {@code .build} — subcommand dispatcher. */
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public final class BuildCommand implements Command {
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.commands;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
/** Что команды {@code .build} умеют просить у фичи. Ошибки — исключения с текстом для пользователя. */
|
||||
/** What the {@code .build} commands can ask of the feature. Errors are exceptions with user-facing text. */
|
||||
public interface BuildControl {
|
||||
|
||||
String start();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.commands;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
/** Набор подкоманд {@code .build}, привязанных к {@link BuildControl}. */
|
||||
/** Set of {@code .build} subcommands bound to {@link BuildControl}. */
|
||||
final class BuildSubs {
|
||||
|
||||
private static final int SET_ARGS = 2;
|
||||
|
|
|
|||
|
|
@ -5,11 +5,11 @@ import java.util.function.Function;
|
|||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Подкоманда {@code .build <name>}.
|
||||
* Subcommand {@code .build <name>}.
|
||||
*
|
||||
* @param usage справка по аргументам
|
||||
* @param options кандидаты для подсказки по токену номер index (после имени)
|
||||
* @param run выполнить с аргументами после имени, вернуть ответ
|
||||
* @param usage argument help text
|
||||
* @param options suggestion candidates for the token at index (after the name)
|
||||
* @param run execute with the arguments after the name, return the reply
|
||||
*/
|
||||
public record SubCommand(String name, String usage, Function<Integer, List<String>> options,
|
||||
Function<List<String>, String> run) {
|
||||
|
|
|
|||
|
|
@ -8,11 +8,11 @@ import dev.loki.satura.interaction.inventory.HotbarRefill;
|
|||
import dev.loki.satura.interaction.place.PlaceResult;
|
||||
import java.util.Optional;
|
||||
|
||||
@SuppressWarnings("PMD.CompareObjectsWithEquals")
|
||||
/**
|
||||
* Тик билдера: planner → стратегия → пополнение хотбара. Паузы (экран, смерть, смена мира)
|
||||
* снимаются сами, «нет блоков» — только вручную. Дыры чинятся ремонтными проходами.
|
||||
* Builder tick: planner → strategy → hotbar refill. Pauses (screen, death, world change)
|
||||
* lift on their own, "no blocks" only manually. Holes are fixed by repair passes.
|
||||
*/
|
||||
@SuppressWarnings("PMD.CompareObjectsWithEquals")
|
||||
public final class BuildEngine {
|
||||
|
||||
public static final int PROGRESS_INTERVAL_TICKS = 20;
|
||||
|
|
@ -37,7 +37,7 @@ public final class BuildEngine {
|
|||
session.start();
|
||||
}
|
||||
|
||||
/** Ручная пауза: авто-резюм не сработает. */
|
||||
/** Manual pause: auto-resume will not trigger. */
|
||||
public void pause() {
|
||||
if (session.stage() == Stage.BUILD || session.stage() == Stage.PAUSED) {
|
||||
session.pause("пауза", false);
|
||||
|
|
|
|||
|
|
@ -5,17 +5,17 @@ import java.util.Locale;
|
|||
import java.util.Optional;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Session state: stage, pause reason, position, counters and statistics (progress comes from ColumnCache). */
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"})
|
||||
/** Состояние сессии: этап, причина паузы, позиция, счётчики и статистика (прогресс — из ColumnCache). */
|
||||
public final class BuildSession {
|
||||
|
||||
private static final long MAX_STEP_MS = 250;
|
||||
private static final double MS_PER_SECOND = 1000.0;
|
||||
|
||||
/**
|
||||
* Снимок статистики.
|
||||
* Statistics snapshot.
|
||||
*
|
||||
* @param holes колонны, которые не удалось достроить
|
||||
* @param holes columns that could not be completed
|
||||
*/
|
||||
public record Snapshot(Stage stage, String reason, int done, int total, double percent, int holes,
|
||||
int placed, int failed, double blocksPerSecond, Optional<BlockPos> column) {
|
||||
|
|
@ -80,7 +80,7 @@ public final class BuildSession {
|
|||
column = null;
|
||||
}
|
||||
|
||||
/** Учёт времени: считается только время в BUILD, паузы не входят. */
|
||||
/** Time accounting: only time in BUILD counts, pauses are excluded. */
|
||||
public void advance(final long nowMs) {
|
||||
if (stage == Stage.BUILD && lastTickMs >= 0) {
|
||||
activeMs += Math.min(nowMs - lastTickMs, MAX_STEP_MS);
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import java.util.HashSet;
|
|||
import java.util.Set;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Holes: columns that could not be completed; skipping, failure counters and repair passes. */
|
||||
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
|
||||
/** Дыры: колонны, которые не удалось достроить; пропуск, счётчики отказов и ремонтные проходы. */
|
||||
public final class RepairTracker {
|
||||
|
||||
public static final int MAX_FAILURES = 3;
|
||||
|
|
@ -37,7 +37,7 @@ public final class RepairTracker {
|
|||
return passes;
|
||||
}
|
||||
|
||||
/** Сбрасывает счётчики, если сменилась колонна или прибавился прогресс. */
|
||||
/** Resets counters when the column changed or progress was made. */
|
||||
public void observe(final BlockPos target, final int done) {
|
||||
if (!target.equals(column) || done != lastDone) {
|
||||
column = target;
|
||||
|
|
@ -47,12 +47,12 @@ public final class RepairTracker {
|
|||
}
|
||||
}
|
||||
|
||||
/** Отказ стратегии; true — лимит исчерпан. */
|
||||
/** Strategy failure; true when the limit is exhausted. */
|
||||
public boolean failure() {
|
||||
return ++failures >= MAX_FAILURES;
|
||||
}
|
||||
|
||||
/** Ожидание без прогресса; true — колонна зависла. */
|
||||
/** Waiting without progress; true when the column is stuck. */
|
||||
public boolean stall() {
|
||||
return ++waits >= STALL_TICKS;
|
||||
}
|
||||
|
|
@ -61,7 +61,7 @@ public final class RepairTracker {
|
|||
skipped.add(target.withY(0));
|
||||
}
|
||||
|
||||
/** Ремонтный проход: вернуть пропущенные колонны в план; false — дыр нет или проходы кончились. */
|
||||
/** Repair pass: put skipped columns back into the plan; false when there are no holes or passes ran out. */
|
||||
public boolean startRepair(final Planner planner) {
|
||||
if (skipped.isEmpty() || passes >= maxPasses) {
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.feature.builder.engine;
|
||||
|
||||
/** Этап сессии. TRANSIT и SUPPLY — точки расширения (переход к области, вылазка за блоками). */
|
||||
/** Session stage. TRANSIT and SUPPLY are extension points (travel to the area, supply run). */
|
||||
public enum Stage {
|
||||
IDLE,
|
||||
BUILD,
|
||||
|
|
|
|||
|
|
@ -13,10 +13,10 @@ import dev.loki.satura.interaction.place.PlaceStrategy;
|
|||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Все зависимости движка (собираются снаружи, движок ничего не создаёт сам).
|
||||
* All engine dependencies (assembled outside; the engine creates nothing itself).
|
||||
*
|
||||
* @param chat сообщения пользователю
|
||||
* @param bar строка прогресса (actionBar)
|
||||
* @param chat messages to the user
|
||||
* @param bar progress line (actionBar)
|
||||
*/
|
||||
@SuppressWarnings("PMD.ExcessiveParameterList")
|
||||
public record EngineDeps(Planner planner, ColumnCache cache, RepairTracker tracker, PlaceStrategy strategy,
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@ package dev.loki.satura.feature.builder.engine.host;
|
|||
|
||||
import java.util.Optional;
|
||||
|
||||
/** Состояние игры, влияющее на работу движка; отделяет движок от клиента Minecraft. */
|
||||
/** Game state affecting the engine; decouples the engine from the Minecraft client. */
|
||||
public interface GameState {
|
||||
|
||||
/** Причина, по которой строить сейчас нельзя (экран, смерть, нет мира); пусто — можно. */
|
||||
/** Reason why building is not possible now (screen, death, no world); empty when it is possible. */
|
||||
Optional<String> blockReason();
|
||||
|
||||
/** Токен текущего мира: смена токена = смена мира. */
|
||||
/** Token of the current world: a token change means a world change. */
|
||||
Object worldToken();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import net.minecraft.item.BlockItem;
|
|||
import net.minecraft.registry.Registries;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
/** Поиск блоков: по ID из реестра или по предмету в основной руке. */
|
||||
/** Block lookup: by registry ID or by the item in the main hand. */
|
||||
public final class MinecraftBlocks {
|
||||
|
||||
public static final String HAND = "hand";
|
||||
|
|
@ -19,7 +19,7 @@ public final class MinecraftBlocks {
|
|||
this.client = client;
|
||||
}
|
||||
|
||||
/** Блок по ID ({@code stone} или {@code minecraft:stone}) либо из руки при {@link #HAND}. */
|
||||
/** Block by ID ({@code stone} or {@code minecraft:stone}) or from the hand for {@link #HAND}. */
|
||||
public Block resolve(final String id) {
|
||||
if (HAND.equalsIgnoreCase(id)) {
|
||||
return fromHand();
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.engine.host;
|
|||
import java.util.Optional;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
|
||||
/** Тонкий адаптер {@link GameState} к клиенту Minecraft. */
|
||||
/** Thin adapter of {@link GameState} to the Minecraft client. */
|
||||
public final class MinecraftGameState implements GameState {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.feature.builder.engine.walk;
|
||||
|
||||
/** Ходок «нет»: ничего не умеет. */
|
||||
/** Null walker: does nothing. */
|
||||
public final class NoWalker implements Walker {
|
||||
|
||||
@Override
|
||||
|
|
@ -10,6 +10,6 @@ public final class NoWalker implements Walker {
|
|||
|
||||
@Override
|
||||
public void cancel() {
|
||||
// нечего отменять
|
||||
// nothing to cancel
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
package dev.loki.satura.feature.builder.engine.walk;
|
||||
|
||||
/** Ходок для наземных стратегий (S5/S6); мост к Baritone подключается позже. */
|
||||
/** Walker for ground strategies (S5/S6); the Baritone bridge is attached later. */
|
||||
public interface Walker {
|
||||
|
||||
/** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */
|
||||
/** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */
|
||||
boolean walkTo(double x, double z);
|
||||
|
||||
void cancel();
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan;
|
|||
import java.util.List;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Колонна с ещё не построенными ячейками текущего Y-окна (по возрастанию Y). */
|
||||
/** Column with not yet built cells of the current Y window (ascending Y). */
|
||||
public record ColumnTarget(BlockPos column, List<BlockPos> cells) {
|
||||
|
||||
public ColumnTarget {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import java.util.Optional;
|
|||
import java.util.function.Predicate;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Режет область на Y-окна и отдаёт следующую недостроенную колонну по змейке. */
|
||||
/** Slices the area into Y windows and returns the next unfinished column in snake order. */
|
||||
public final class Planner {
|
||||
|
||||
public static final int MIN_BAND_LAYERS = 1;
|
||||
|
|
@ -31,7 +31,7 @@ public final class Planner {
|
|||
this.bandFloor = area.min().getY();
|
||||
}
|
||||
|
||||
/** Следующая цель; окно сдвигается вверх, когда текущее достроено. Пусто = всё готово. */
|
||||
/** Next target; the window moves up once the current one is complete. Empty = all done. */
|
||||
public Optional<ColumnTarget> next() {
|
||||
final int top = area.max().getY();
|
||||
while (bandFloor <= top) {
|
||||
|
|
@ -47,12 +47,12 @@ public final class Planner {
|
|||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** Нижний Y текущего окна. */
|
||||
/** Lowest Y of the current window. */
|
||||
public int bandStart() {
|
||||
return bandFloor;
|
||||
}
|
||||
|
||||
/** Вернуться к нижнему окну (для ремонтного прохода). */
|
||||
/** Go back to the lowest window (for a repair pass). */
|
||||
public void reset() {
|
||||
bandFloor = area.min().getY();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
|
|||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Сплошной параллелепипед. */
|
||||
/** Solid cuboid. */
|
||||
public final class BoxShape implements Shape {
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
|
|||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Шахматка: чётность x+z относительно угла min области. */
|
||||
/** Checkerboard: parity of x+z relative to the area's min corner. */
|
||||
public final class CheckerShape implements Shape {
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
|
|||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Какие ячейки области нужно строить. */
|
||||
/** Which cells of the area must be built. */
|
||||
public interface Shape {
|
||||
|
||||
boolean includes(Area area, BlockPos pos);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
|
|||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Только внешний периметр (стены) по всей высоте. */
|
||||
/** Outer perimeter only (walls) over the full height. */
|
||||
public final class WallsShape implements Shape {
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.scan;
|
|||
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Источник состояния блоков; отделяет подсчёт от клиента Minecraft. */
|
||||
/** Source of block states; decouples counting from the Minecraft client. */
|
||||
public interface BlockProbe {
|
||||
|
||||
boolean isFilled(BlockPos pos);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import dev.loki.satura.feature.builder.selection.Area;
|
|||
import java.util.Arrays;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Инкрементальные счётчики заполненности по колоннам области (вместо полного X*Y*Z-скана). */
|
||||
/** Incremental per-column fill counters of the area (instead of a full X*Y*Z scan). */
|
||||
public final class ColumnCache {
|
||||
|
||||
private static final double PERCENT_FULL = 100.0;
|
||||
|
|
@ -28,7 +28,7 @@ public final class ColumnCache {
|
|||
fullRescan();
|
||||
}
|
||||
|
||||
/** Полный пересчёт всей области. */
|
||||
/** Full recount of the whole area. */
|
||||
public void fullRescan() {
|
||||
doneTotal = 0;
|
||||
requiredTotal = 0;
|
||||
|
|
@ -39,7 +39,7 @@ public final class ColumnCache {
|
|||
}
|
||||
}
|
||||
|
||||
/** Пересчитывает только колонну изменённого блока; вне области — игнор. */
|
||||
/** Recounts only the column of the changed block; ignored outside the area. */
|
||||
public void onBlockChanged(final BlockPos pos) {
|
||||
if (area.contains(pos)) {
|
||||
recount(pos.getX(), pos.getZ());
|
||||
|
|
@ -62,12 +62,12 @@ public final class ColumnCache {
|
|||
return requiredTotal - doneTotal;
|
||||
}
|
||||
|
||||
/** Построено клеток формы в колонне (x, z). */
|
||||
/** Shape cells already built in column (x, z). */
|
||||
public int builtIn(final int x, final int z) {
|
||||
return built[index(x, z)];
|
||||
}
|
||||
|
||||
/** Осталось построить в колонне (x, z). */
|
||||
/** Cells still to build in column (x, z). */
|
||||
public int remainingIn(final int x, final int z) {
|
||||
final int i = index(x, z);
|
||||
return required[i] - built[i];
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import net.minecraft.block.BlockState;
|
|||
import net.minecraft.client.world.ClientWorld;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Заполнено = не воздух и не заменяемое (трава, вода и т.п.). Мир берётся лениво. */
|
||||
/** Filled = not air and not replaceable (grass, water, etc.). The world is obtained lazily. */
|
||||
@SuppressWarnings("PMD.CloseResource")
|
||||
public final class WorldBlockProbe implements BlockProbe {
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import java.util.ArrayList;
|
|||
import java.util.List;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Прямоугольная область мира (границы включительно). */
|
||||
/** Rectangular world area (bounds inclusive). */
|
||||
public record Area(BlockPos min, BlockPos max) {
|
||||
|
||||
private static final int EVEN_DIVISOR = 2;
|
||||
|
|
@ -18,9 +18,13 @@ public record Area(BlockPos min, BlockPos max) {
|
|||
}
|
||||
|
||||
public boolean contains(BlockPos p) {
|
||||
return p.getX() >= min.getX() && p.getX() <= max.getX()
|
||||
&& p.getY() >= min.getY() && p.getY() <= max.getY()
|
||||
&& p.getZ() >= min.getZ() && p.getZ() <= max.getZ();
|
||||
return within(p.getX(), min.getX(), max.getX())
|
||||
&& within(p.getY(), min.getY(), max.getY())
|
||||
&& within(p.getZ(), min.getZ(), max.getZ());
|
||||
}
|
||||
|
||||
private static boolean within(int v, int lo, int hi) {
|
||||
return v >= lo && v <= hi;
|
||||
}
|
||||
|
||||
public long volume() {
|
||||
|
|
@ -39,7 +43,7 @@ public record Area(BlockPos min, BlockPos max) {
|
|||
return max.getZ() - min.getZ() + 1;
|
||||
}
|
||||
|
||||
/** Колонны на y = min.y: ряды по z, чётные ряды по x вверх, нечётные вниз. */
|
||||
/** Columns at y = min.y: rows along z, even rows go up along x, odd rows go down. */
|
||||
public List<BlockPos> columns() {
|
||||
int sx = sizeX();
|
||||
int sz = sizeZ();
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import java.util.function.Consumer;
|
|||
import java.util.function.Supplier;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** {@code .pos1} / {@code .pos2} — запомнить позицию ног игрока. */
|
||||
/** {@code .pos1} / {@code .pos2} — remember the player's feet position. */
|
||||
public final class PosCommand implements Command {
|
||||
|
||||
private final String label;
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import dev.loki.satura.core.command.Command;
|
|||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** {@code .sel clear} — сбросить выделение. */
|
||||
/** {@code .sel clear} — reset the selection. */
|
||||
public final class SelCommand implements Command {
|
||||
|
||||
private static final String CLEAR = "clear";
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.selection;
|
|||
import java.util.Optional;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Две точки выделения; область существует, когда заданы обе. */
|
||||
/** Two selection points; the area exists once both are set. */
|
||||
public final class Selection {
|
||||
|
||||
private Optional<BlockPos> first = Optional.empty();
|
||||
|
|
|
|||
53
src/main/java/dev/loki/satura/gui/BuilderUi.java
Normal file
53
src/main/java/dev/loki/satura/gui/BuilderUi.java
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package dev.loki.satura.gui;
|
||||
|
||||
import dev.loki.satura.feature.builder.BuilderFeature;
|
||||
import dev.loki.satura.gui.screen.BuilderScreen;
|
||||
import java.util.function.Consumer;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.option.KeyBinding;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
/**
|
||||
* Mod keys (Satura category, configurable in the vanilla Controls screen):
|
||||
* Right Shift opens/closes the menu, the pause macro uses the key from the settings.
|
||||
*/
|
||||
public final class BuilderUi {
|
||||
|
||||
private static final Identifier CATEGORY_ID = Identifier.of("satura", "main");
|
||||
private static final KeyBinding.Category CATEGORY = KeyBinding.Category.create(CATEGORY_ID);
|
||||
private static final String KEY_MENU = "key.satura.open_menu";
|
||||
private static final String KEY_TOGGLE = "key.satura.toggle";
|
||||
|
||||
private final BuilderFeature builder;
|
||||
private final Consumer<String> bar;
|
||||
private final KeyBinding openMenu;
|
||||
private final KeyBinding toggleBuild;
|
||||
|
||||
public BuilderUi(final BuilderFeature builder, final Consumer<String> bar) {
|
||||
this.builder = builder;
|
||||
this.bar = bar;
|
||||
this.openMenu = KeyBindingHelper.registerKeyBinding(
|
||||
new KeyBinding(KEY_MENU, GLFW.GLFW_KEY_RIGHT_SHIFT, CATEGORY));
|
||||
this.toggleBuild = KeyBindingHelper.registerKeyBinding(
|
||||
new KeyBinding(KEY_TOGGLE, GLFW.GLFW_KEY_P, CATEGORY));
|
||||
}
|
||||
|
||||
/** Subscribes to client ticks; call once during initialization. */
|
||||
public void register() {
|
||||
ClientTickEvents.END_CLIENT_TICK.register(this::tick);
|
||||
}
|
||||
|
||||
private void tick(final MinecraftClient client) {
|
||||
while (openMenu.wasPressed()) {
|
||||
if (client.currentScreen == null) {
|
||||
client.setScreen(new BuilderScreen(builder, openMenu));
|
||||
}
|
||||
}
|
||||
while (toggleBuild.wasPressed()) {
|
||||
bar.accept(builder.togglePause());
|
||||
}
|
||||
}
|
||||
}
|
||||
201
src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java
Normal file
201
src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
package dev.loki.satura.gui.screen;
|
||||
|
||||
import dev.loki.satura.feature.builder.BuildSettings;
|
||||
import dev.loki.satura.feature.builder.BuilderFeature;
|
||||
import dev.loki.satura.feature.builder.engine.Stage;
|
||||
import dev.loki.satura.feature.builder.plan.Planner;
|
||||
import dev.loki.satura.gui.widget.CycleButton;
|
||||
import dev.loki.satura.gui.widget.NumberSlider;
|
||||
import dev.loki.satura.render.Renderer;
|
||||
import dev.loki.satura.render.Theme;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.client.gui.DrawContext;
|
||||
import net.minecraft.client.gui.screen.Screen;
|
||||
import net.minecraft.client.gui.widget.ButtonWidget;
|
||||
import net.minecraft.client.gui.widget.TextFieldWidget;
|
||||
import net.minecraft.client.input.KeyInput;
|
||||
import net.minecraft.client.option.KeyBinding;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Builder screen: selection, start/pause/stop, shape, layers, delay, block, status line. */
|
||||
@SuppressWarnings("PMD.AvoidCatchingGenericException")
|
||||
public final class BuilderScreen extends Screen {
|
||||
|
||||
private static final int FIXED_ROWS = 5;
|
||||
private static final int NOTICE_TICKS = 100;
|
||||
private static final int MAX_BLOCK_LEN = 64;
|
||||
private static final int POS1 = 1;
|
||||
private static final int POS2 = 2;
|
||||
private static final String OPT_DELAY = "delayMs";
|
||||
private static final String LANG_POS1 = "satura.gui.pos1";
|
||||
private static final String LANG_POS2 = "satura.gui.pos2";
|
||||
private static final String LANG_PAUSE = "satura.gui.pause";
|
||||
private static final String LANG_RESUME = "satura.gui.resume";
|
||||
|
||||
private final BuilderFeature builder;
|
||||
private final KeyBinding openMenu;
|
||||
private Panel panel;
|
||||
private ButtonWidget pos1Button;
|
||||
private ButtonWidget pos2Button;
|
||||
private ButtonWidget pauseButton;
|
||||
private TextFieldWidget blockField;
|
||||
private Text notice = Text.empty();
|
||||
private int noticeTicks;
|
||||
|
||||
public BuilderScreen(final BuilderFeature builder, final KeyBinding openMenu) {
|
||||
super(Text.translatable("satura.title"));
|
||||
this.builder = builder;
|
||||
this.openMenu = openMenu;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void init() {
|
||||
final Optional<BuildSettings.Range> delay = builder.settings().optionRange(OPT_DELAY);
|
||||
panel = new Panel(width, height, FIXED_ROWS + (delay.isPresent() ? 1 : 0));
|
||||
final int inner = panel.inner();
|
||||
final int left = panel.left();
|
||||
final int half = (inner - Panel.GAP) / 2;
|
||||
final int third = (inner - Panel.GAP * 2) / 3;
|
||||
int y = panel.top() + Panel.PAD + Panel.TITLE_H + Panel.GAP;
|
||||
pos1Button = addDrawableChild(button(LANG_POS1, () -> capture(POS1), left, y, half));
|
||||
pos2Button = addDrawableChild(button(LANG_POS2, () -> capture(POS2), left + half + Panel.GAP, y, half));
|
||||
y += Panel.WIDGET_H + Panel.GAP;
|
||||
addDrawableChild(button("satura.gui.start", () -> run(builder::start), left, y, third));
|
||||
pauseButton = addDrawableChild(button(LANG_PAUSE,
|
||||
() -> run(() -> builder.stage() == Stage.PAUSED ? builder.resume() : builder.pause()),
|
||||
left + third + Panel.GAP, y, third));
|
||||
addDrawableChild(button("satura.gui.stop", () -> run(builder::stop),
|
||||
left + (third + Panel.GAP) * 2, y, third));
|
||||
y += Panel.WIDGET_H + Panel.GAP;
|
||||
addDrawableChild(new CycleButton(left, y, inner, Panel.WIDGET_H, "satura.gui.shape",
|
||||
builder.shapeIds(), builder.settings().shapeId(), id -> run(() -> builder.setShape(id))));
|
||||
y += Panel.WIDGET_H + Panel.GAP;
|
||||
addDrawableChild(new NumberSlider(left, y, inner, Panel.WIDGET_H,
|
||||
new NumberSlider.Spec(Planner.MIN_BAND_LAYERS, Planner.MAX_BAND_LAYERS, 1,
|
||||
builder.settings().layers()),
|
||||
v -> Text.translatable("satura.gui.layers", formatInt(v)),
|
||||
v -> run(() -> builder.setLayers((int) Math.round(v)))));
|
||||
y += Panel.WIDGET_H + Panel.GAP;
|
||||
if (delay.isPresent()) {
|
||||
final BuildSettings.Range r = delay.get();
|
||||
addDrawableChild(new NumberSlider(left, y, inner, Panel.WIDGET_H,
|
||||
new NumberSlider.Spec(r.min(), r.max(), r.step(), r.value()),
|
||||
v -> Text.translatable("satura.gui.delay", formatInt(v)),
|
||||
v -> run(() -> builder.setOption(OPT_DELAY, formatInt(v)))));
|
||||
y += Panel.WIDGET_H + Panel.GAP;
|
||||
}
|
||||
blockField = new TextFieldWidget(textRenderer, left, y, inner, Panel.WIDGET_H,
|
||||
Text.translatable("satura.gui.block"));
|
||||
blockField.setMaxLength(MAX_BLOCK_LEN);
|
||||
blockField.setText(builder.settings().block());
|
||||
addSelectableChild(blockField);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
if (noticeTicks > 0) {
|
||||
noticeTicks--;
|
||||
}
|
||||
pos1Button.setMessage(posLabel(LANG_POS1, builder.selection().pos1()));
|
||||
pos2Button.setMessage(posLabel(LANG_POS2, builder.selection().pos2()));
|
||||
pauseButton.setMessage(Text.translatable(
|
||||
builder.stage() == Stage.PAUSED ? LANG_RESUME : LANG_PAUSE));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(final DrawContext context, final int mouseX, final int mouseY, final float delta) {
|
||||
super.render(context, mouseX, mouseY, delta);
|
||||
context.drawCenteredTextWithShadow(textRenderer, title, width / 2,
|
||||
panel.top() + Panel.PAD, Theme.TEXT);
|
||||
final String status = trim(builder.status());
|
||||
context.drawTextWithShadow(textRenderer, trim(notice.getString()),
|
||||
panel.left(), panel.statusY(), Theme.ACCENT_HOVER);
|
||||
context.drawTextWithShadow(textRenderer, status,
|
||||
panel.left(), panel.statusY() + Panel.LINE_H, Theme.TEXT_MUTED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderBackground(final DrawContext context, final int mouseX, final int mouseY,
|
||||
final float delta) {
|
||||
super.renderBackground(context, mouseX, mouseY, delta);
|
||||
panel.paint(Renderer.shared());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean keyPressed(final KeyInput input) {
|
||||
if (openMenu.matchesKey(input)) {
|
||||
close();
|
||||
return true;
|
||||
}
|
||||
if (blockField.isFocused() && input.isEnter()) {
|
||||
commitBlock();
|
||||
return true;
|
||||
}
|
||||
return super.keyPressed(input);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removed() {
|
||||
commitBlock();
|
||||
super.removed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldPause() {
|
||||
return false;
|
||||
}
|
||||
|
||||
private void run(final Supplier<String> action) {
|
||||
try {
|
||||
showNotice(action.get());
|
||||
} catch (RuntimeException e) {
|
||||
showNotice(e.getMessage() == null ? "ошибка" : e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void showNotice(final String text) {
|
||||
notice = Text.literal(text);
|
||||
noticeTicks = NOTICE_TICKS;
|
||||
}
|
||||
|
||||
private void commitBlock() {
|
||||
final String id = blockField.getText().strip();
|
||||
if (!id.isEmpty() && !id.equals(builder.settings().block())) {
|
||||
run(() -> builder.setBlock(id));
|
||||
}
|
||||
}
|
||||
|
||||
private void capture(final int which) {
|
||||
if (client.player == null) {
|
||||
showNotice("зайди в мир");
|
||||
return;
|
||||
}
|
||||
final BlockPos pos = client.player.getBlockPos();
|
||||
if (which == POS1) {
|
||||
builder.selection().setPos1(pos);
|
||||
} else {
|
||||
builder.selection().setPos2(pos);
|
||||
}
|
||||
showNotice("Pos" + which + ": " + pos.toShortString());
|
||||
}
|
||||
|
||||
private Text posLabel(final String key, final Optional<BlockPos> pos) {
|
||||
return Text.translatable(key, pos.<String>map(BlockPos::toShortString).orElse("-"));
|
||||
}
|
||||
|
||||
private static String formatInt(final double value) {
|
||||
return String.valueOf(Math.round(value));
|
||||
}
|
||||
|
||||
private String trim(final String text) {
|
||||
return textRenderer.trimToWidth(text, Panel.WIDTH - Panel.PAD * 2);
|
||||
}
|
||||
|
||||
private static ButtonWidget button(final String key, final Runnable action,
|
||||
final int x, final int y, final int w) {
|
||||
return ButtonWidget.builder(Text.translatable(key), b -> action.run())
|
||||
.dimensions(x, y, w, Panel.WIDGET_H).build();
|
||||
}
|
||||
}
|
||||
62
src/main/java/dev/loki/satura/gui/screen/Panel.java
Normal file
62
src/main/java/dev/loki/satura/gui/screen/Panel.java
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
package dev.loki.satura.gui.screen;
|
||||
|
||||
import dev.loki.satura.render.Renderer;
|
||||
import dev.loki.satura.render.Theme;
|
||||
import dev.loki.satura.render.geom.Bounds;
|
||||
|
||||
/** Geometry and drawing of the screen's dark panel (blur, backdrop, outline). */
|
||||
final class Panel {
|
||||
|
||||
static final int WIDTH = 240;
|
||||
static final int PAD = 10;
|
||||
static final int WIDGET_H = 20;
|
||||
static final int GAP = 4;
|
||||
static final int TITLE_H = 14;
|
||||
static final int LINE_H = 11;
|
||||
static final int STATUS_ROWS = 2;
|
||||
private static final float BLUR_STRENGTH = 1.0f;
|
||||
|
||||
private final int screenW;
|
||||
private final int screenH;
|
||||
private final int rows;
|
||||
|
||||
Panel(final int screenW, final int screenH, final int rows) {
|
||||
this.screenW = screenW;
|
||||
this.screenH = screenH;
|
||||
this.rows = rows;
|
||||
}
|
||||
|
||||
/** Left edge of the content (padding already applied). */
|
||||
int left() {
|
||||
return (screenW - WIDTH) / 2 + PAD;
|
||||
}
|
||||
|
||||
int inner() {
|
||||
return WIDTH - PAD * 2;
|
||||
}
|
||||
|
||||
int top() {
|
||||
return (screenH - height()) / 2;
|
||||
}
|
||||
|
||||
int height() {
|
||||
return PAD + TITLE_H + GAP + rows * (WIDGET_H + GAP) + GAP + STATUS_ROWS * LINE_H + PAD;
|
||||
}
|
||||
|
||||
/** Y of the first status line (at the bottom of the panel). */
|
||||
int statusY() {
|
||||
return top() + height() - PAD - STATUS_ROWS * LINE_H;
|
||||
}
|
||||
|
||||
Bounds bounds() {
|
||||
return new Bounds((screenW - WIDTH) / 2f, top(), WIDTH, height());
|
||||
}
|
||||
|
||||
/** Draws the panel backdrop; called after the vanilla background, before the widgets. */
|
||||
void paint(final Renderer renderer) {
|
||||
final Bounds b = bounds();
|
||||
renderer.blur(b, Theme.RADIUS, BLUR_STRENGTH);
|
||||
renderer.rect(b, Theme.RADIUS, Theme.PANEL);
|
||||
renderer.outline(b, Theme.RADIUS, Theme.BORDER_WIDTH, Theme.BORDER);
|
||||
}
|
||||
}
|
||||
49
src/main/java/dev/loki/satura/gui/widget/CycleButton.java
Normal file
49
src/main/java/dev/loki/satura/gui/widget/CycleButton.java
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
package dev.loki.satura.gui.widget;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import net.minecraft.client.gui.widget.ButtonWidget;
|
||||
import net.minecraft.client.input.AbstractInput;
|
||||
|
||||
/**
|
||||
* Cycle button: a click steps through the values and hands the chosen one to the owner.
|
||||
* The label is a translatable string with {@code %s} in place of the value. Rendering is vanilla
|
||||
* (inherited from ButtonWidget.Text).
|
||||
*/
|
||||
public final class CycleButton extends ButtonWidget.Text {
|
||||
|
||||
private final List<String> values;
|
||||
private final String labelKey;
|
||||
private final Consumer<String> onChange;
|
||||
private int index;
|
||||
|
||||
public CycleButton(final int x, final int y, final int width, final int height,
|
||||
final String labelKey, final List<String> values,
|
||||
final String initial, final Consumer<String> onChange) {
|
||||
super(x, y, width, height, net.minecraft.text.Text.empty(), b -> { }, DEFAULT_NARRATION_SUPPLIER);
|
||||
if (values.isEmpty()) {
|
||||
throw new IllegalArgumentException("cycle without values: " + labelKey);
|
||||
}
|
||||
this.values = List.copyOf(values);
|
||||
this.labelKey = labelKey;
|
||||
this.onChange = onChange;
|
||||
this.index = Math.max(0, this.values.indexOf(initial));
|
||||
refresh();
|
||||
}
|
||||
|
||||
/** Currently selected value. */
|
||||
public String value() {
|
||||
return values.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPress(final AbstractInput input) {
|
||||
index = (index + 1) % values.size();
|
||||
refresh();
|
||||
onChange.accept(values.get(index));
|
||||
}
|
||||
|
||||
private void refresh() {
|
||||
setMessage(net.minecraft.text.Text.translatable(labelKey, values.get(index)));
|
||||
}
|
||||
}
|
||||
56
src/main/java/dev/loki/satura/gui/widget/NumberSlider.java
Normal file
56
src/main/java/dev/loki/satura/gui/widget/NumberSlider.java
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
package dev.loki.satura.gui.widget;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.DoubleFunction;
|
||||
import net.minecraft.client.gui.widget.SliderWidget;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
/** Number slider (int/float) with a step; range, label and receiver are set by the owner. */
|
||||
public final class NumberSlider extends SliderWidget {
|
||||
|
||||
private static final double NO_STEP = 0.0;
|
||||
|
||||
/** Slider range: bounds, step (0 = continuous) and the initial value. */
|
||||
public record Spec(double min, double max, double step, double initial) {
|
||||
}
|
||||
|
||||
private final double min;
|
||||
private final double max;
|
||||
private final double step;
|
||||
private final DoubleFunction<Text> label;
|
||||
private final Consumer<Double> onChange;
|
||||
|
||||
public NumberSlider(final int x, final int y, final int width, final int height, final Spec spec,
|
||||
final DoubleFunction<Text> label, final Consumer<Double> onChange) {
|
||||
super(x, y, width, height, Text.empty(), normalized(spec.min(), spec.max(), spec.initial()));
|
||||
this.min = spec.min();
|
||||
this.max = spec.max();
|
||||
this.step = spec.step();
|
||||
this.label = label;
|
||||
this.onChange = onChange;
|
||||
updateMessage();
|
||||
}
|
||||
|
||||
/** Current value in range units (step applied). */
|
||||
public double current() {
|
||||
final double raw = min + (max - min) * value;
|
||||
return step == NO_STEP ? raw : Math.round(raw / step) * step;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateMessage() {
|
||||
setMessage(label.apply(current()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void applyValue() {
|
||||
onChange.accept(current());
|
||||
}
|
||||
|
||||
private static double normalized(final double min, final double max, final double value) {
|
||||
if (max <= min) {
|
||||
return 0.0;
|
||||
}
|
||||
return Math.clamp((value - min) / (max - min), 0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
|
@ -3,12 +3,12 @@ package dev.loki.satura.interaction.click;
|
|||
import java.util.random.RandomGenerator;
|
||||
|
||||
/**
|
||||
* Настройки темпа кликов по контейнерам.
|
||||
* Pacing settings for container clicks.
|
||||
*
|
||||
* @param minDelayMs базовая пауза между кликами
|
||||
* @param jitter доля случайного разброса паузы (0.3 = плюс-минус 30%)
|
||||
* @param confirmTimeoutMs сколько ждать подтверждения клика до повтора
|
||||
* @param maxAttempts сколько раз кликнуть, прежде чем сдаться
|
||||
* @param minDelayMs base pause between clicks
|
||||
* @param jitter random spread share of the pause (0.3 = plus or minus 30%)
|
||||
* @param confirmTimeoutMs how long to wait for click confirmation before retrying
|
||||
* @param maxAttempts how many times to click before giving up
|
||||
*/
|
||||
public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs, int maxAttempts) {
|
||||
|
||||
|
|
@ -30,7 +30,7 @@ public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs,
|
|||
return new ClickConfig(delayMs, jitter, confirmTimeoutMs, maxAttempts);
|
||||
}
|
||||
|
||||
/** Следующая пауза: minDelayMs * (1 +- jitter), равномерно. */
|
||||
/** Next pause: minDelayMs * (1 +- jitter), uniformly distributed. */
|
||||
public long nextDelay(RandomGenerator random) {
|
||||
double factor = 1 + jitter * (2 * random.nextDouble() - 1);
|
||||
return Math.round(minDelayMs * factor);
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import java.util.Deque;
|
|||
import java.util.random.RandomGenerator;
|
||||
|
||||
/**
|
||||
* Единая очередь контейнерных кликов: пауза с джиттером между кликами и подтверждение
|
||||
* каждого клика по синхронизации слотов (таймаут, повтор). Тикается владельцем раз в тик.
|
||||
* Single queue of container clicks: jittered pause between clicks and confirmation
|
||||
* of every click via slot sync (timeout, retry). Ticked by the owner once per tick.
|
||||
*/
|
||||
public final class ClickScheduler {
|
||||
|
||||
|
|
@ -42,7 +42,7 @@ public final class ClickScheduler {
|
|||
return queue.size() + (current == null ? 0 : 1);
|
||||
}
|
||||
|
||||
/** Отложить следующий клик минимум на delayMs (пауза «человека» после открытия экрана). */
|
||||
/** Delay the next click by at least delayMs (a "human" pause after a screen opens). */
|
||||
public void delayNext(long delayMs) {
|
||||
nextClickAt = Math.max(nextClickAt, clock.nowMillis() + delayMs);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,15 +4,15 @@ import java.util.function.BooleanSupplier;
|
|||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Один клик по контейнеру.
|
||||
* A single container click.
|
||||
*
|
||||
* @param click действие клика (вызов clickSlot)
|
||||
* @param confirmed true, когда результат клика виден в слотах (синхронизация пришла)
|
||||
* @param onDone итог задачи
|
||||
* @param click click action (the clickSlot call)
|
||||
* @param confirmed true when the click result is visible in the slots (sync arrived)
|
||||
* @param onDone task outcome
|
||||
*/
|
||||
public record ClickTask(Runnable click, BooleanSupplier confirmed, Consumer<Outcome> onDone) {
|
||||
|
||||
/** Итог задачи. */
|
||||
/** Task outcome. */
|
||||
public enum Outcome { CONFIRMED, FAILED }
|
||||
|
||||
public static ClickTask of(Runnable click, BooleanSupplier confirmed) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.interaction.click;
|
||||
|
||||
/** Источник времени; подменяется в тестах. */
|
||||
/** Time source; replaced in tests. */
|
||||
@FunctionalInterface
|
||||
public interface Clock {
|
||||
|
||||
|
|
|
|||
|
|
@ -4,15 +4,15 @@ import dev.loki.satura.interaction.click.ClickScheduler;
|
|||
import dev.loki.satura.interaction.click.ClickTask;
|
||||
|
||||
/**
|
||||
* Пополнение хотбара: когда в выбранном слоте осталось не больше порога, самый полный стак
|
||||
* из инвентаря меняется с пустеющим слотом хотбара (SWAP) через общий ClickScheduler.
|
||||
* Hotbar refill: when the selected slot holds no more than the threshold, the fullest stack
|
||||
* from the inventory is swapped with the emptying hotbar slot (SWAP) via the shared ClickScheduler.
|
||||
*/
|
||||
public final class HotbarRefill {
|
||||
|
||||
/** Порог: слот с таким или меньшим числом блоков считается пустым. */
|
||||
/** Threshold: a slot with this many blocks or fewer counts as empty. */
|
||||
public static final int LOW = 2;
|
||||
|
||||
/** Состояние пополнения. */
|
||||
/** Refill state. */
|
||||
public enum State { READY, REFILLING, EMPTY }
|
||||
|
||||
private final InventoryView inventory;
|
||||
|
|
@ -30,7 +30,7 @@ public final class HotbarRefill {
|
|||
this.planner = new RefillPlanner(low);
|
||||
}
|
||||
|
||||
/** Один тик логики; сам планировщик кликов тикает владелец. */
|
||||
/** One logic tick; the owner ticks the click scheduler itself. */
|
||||
public State tick() {
|
||||
if (swapPending) {
|
||||
return State.REFILLING;
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
package dev.loki.satura.interaction.inventory;
|
||||
|
||||
/** Вид на инвентарь игрока относительно целевого предмета. Слоты 0-8 хотбар, 9-35 инвентарь. */
|
||||
/** View of the player's inventory relative to the target item. Slots 0-8 hotbar, 9-35 inventory. */
|
||||
public interface InventoryView {
|
||||
|
||||
int SLOTS = 36;
|
||||
int HOTBAR_SIZE = 9;
|
||||
|
||||
/** Сколько целевых предметов в слоте (0, если слот пуст или там другое). */
|
||||
/** How many target items are in the slot (0 if empty or holds something else). */
|
||||
int count(int slot);
|
||||
|
||||
int selectedSlot();
|
||||
|
||||
void select(int slot);
|
||||
|
||||
/** Клик SWAP: стак из слота инвентаря src меняется местами со слотом хотбара hotbarSlot. */
|
||||
/** SWAP click: the stack from inventory slot src is swapped with hotbar slot hotbarSlot. */
|
||||
void swapToHotbar(int src, int hotbarSlot);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import net.minecraft.item.BlockItem;
|
|||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.screen.slot.SlotActionType;
|
||||
|
||||
/** Тонкий адаптер к клиенту Minecraft: инвентарь игрока относительно одного блока. */
|
||||
/** Thin adapter to the Minecraft client: the player's inventory relative to one block. */
|
||||
public final class MinecraftInventoryView implements InventoryView {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
package dev.loki.satura.interaction.inventory;
|
||||
|
||||
/** Чистый выбор действия по заполненности слотов. */
|
||||
/** Pure action choice based on slot fill levels. */
|
||||
public final class RefillPlanner {
|
||||
|
||||
/** Тип решения. */
|
||||
/** Decision type. */
|
||||
public enum Kind { READY, SELECT, SWAP, EMPTY }
|
||||
|
||||
/**
|
||||
* Решение: SELECT - выбрать хотбар-слот from; SWAP - обменять from (инвентарь) на to (хотбар).
|
||||
* Decision: SELECT - select hotbar slot from; SWAP - swap from (inventory) with to (hotbar).
|
||||
*/
|
||||
public record Decision(Kind kind, int from, int to) {
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.interaction.movement;
|
||||
|
||||
/** Чистая математика углов (градусы, система Minecraft). */
|
||||
/** Pure angle math (degrees, Minecraft convention). */
|
||||
public final class Angles {
|
||||
|
||||
private static final float FULL_TURN = 360f;
|
||||
|
|
@ -33,7 +33,7 @@ public final class Angles {
|
|||
return Math.max(-limit, Math.min(limit, value));
|
||||
}
|
||||
|
||||
/** Шаг от current к target не больше maxStep по кратчайшей дуге. */
|
||||
/** Step from current towards target of at most maxStep along the shortest arc. */
|
||||
public static float approachYaw(float current, float target, float maxStep) {
|
||||
return current + clamp(wrap(target - current), maxStep);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.satura.interaction.movement;
|
|||
|
||||
import dev.loki.satura.interaction.movement.io.PlayerPose;
|
||||
|
||||
/** Управление взглядом: плавный доворот с клампом °/тик и мгновенный взгляд вниз. */
|
||||
/** Look control: smooth turn clamped in degrees/tick and an instant look down. */
|
||||
public final class LookController {
|
||||
|
||||
public static final float MAX_YAW_STEP = 25f;
|
||||
|
|
@ -16,7 +16,7 @@ public final class LookController {
|
|||
this.pose = pose;
|
||||
}
|
||||
|
||||
/** Доворот к точке за один тик; true, когда взгляд уже на цели. */
|
||||
/** Turn towards a point in one tick; true when already looking at the target. */
|
||||
public boolean lookAtSmooth(double x, double y, double z) {
|
||||
double dx = x - pose.x();
|
||||
double dz = z - pose.z();
|
||||
|
|
@ -34,7 +34,7 @@ public final class LookController {
|
|||
return false;
|
||||
}
|
||||
|
||||
/** Мгновенно смотреть строго вниз (для стратегий столбика/пола). */
|
||||
/** Instantly look straight down (for pillar/floor strategies). */
|
||||
public void lookDown() {
|
||||
pose.setPitch(DOWN_PITCH);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.interaction.movement;
|
|||
import dev.loki.satura.interaction.movement.io.KeyInput;
|
||||
import dev.loki.satura.interaction.movement.io.PlayerPose;
|
||||
|
||||
/** Ходьба к точке фейк-клавишами: кламп поворота, прыжок на препятствии, сайдстеп при застревании. */
|
||||
/** Walking to a point with fake keys: turn clamp, jump at obstacles, sidestep when stuck. */
|
||||
public final class MovementController {
|
||||
|
||||
public static final float MAX_TURN_STEP = 35f;
|
||||
|
|
@ -42,7 +42,7 @@ public final class MovementController {
|
|||
keys.setJump(true);
|
||||
}
|
||||
|
||||
/** Один тик ходьбы к (x, z); true, когда дошли (клавиши отпущены). */
|
||||
/** One walking tick towards (x, z); true on arrival (keys released). */
|
||||
public boolean walkTo(double x, double z) {
|
||||
double dx = x - pose.x();
|
||||
double dz = z - pose.z();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.interaction.movement.io;
|
||||
|
||||
/** Фейковые клавиши движения. */
|
||||
/** Fake movement keys. */
|
||||
public interface KeyInput {
|
||||
|
||||
void setForward(boolean pressed);
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.satura.interaction.movement.io;
|
|||
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
|
||||
/** Адаптер клавиш к настройкам клиента Minecraft. */
|
||||
/** Adapter of keys to the Minecraft client options. */
|
||||
public final class MinecraftKeyInput implements KeyInput {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.interaction.movement.io;
|
|||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.network.ClientPlayerEntity;
|
||||
|
||||
/** Адаптер позы к ClientPlayerEntity; без игрока (мир не загружен) работает как заглушка. */
|
||||
/** Adapter of the pose to ClientPlayerEntity; without a player (world not loaded) acts as a stub. */
|
||||
public final class MinecraftPlayerPose implements PlayerPose {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.interaction.movement.io;
|
||||
|
||||
/** Положение и взгляд игрока (градусы по Minecraft: yaw 0 = юг, pitch + вниз). */
|
||||
/** Player position and look direction (Minecraft degrees: yaw 0 = south, positive pitch = down). */
|
||||
public interface PlayerPose {
|
||||
|
||||
double x();
|
||||
|
|
|
|||
|
|
@ -4,29 +4,29 @@ import net.minecraft.util.hit.BlockHitResult;
|
|||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Всё, чем стратегия касается игры. Узкий интерфейс, чтобы логику можно было тестировать фейком. */
|
||||
/** Everything a strategy touches in the game. A narrow interface so the logic can be tested with a fake. */
|
||||
public interface PlaceContext {
|
||||
|
||||
/** Позиция ног игрока. */
|
||||
/** Player's feet position. */
|
||||
Vec3d feetPos();
|
||||
|
||||
/** Позиция глаз игрока. */
|
||||
/** Player's eye position. */
|
||||
Vec3d eyePos();
|
||||
|
||||
/** Годится ли блок как опора. */
|
||||
/** Whether the block is usable as a support. */
|
||||
boolean isSolid(BlockPos pos);
|
||||
|
||||
/** Клик ПКМ по блоку; true - клиент принял действие. */
|
||||
/** Right-click on a block; true if the client accepted the action. */
|
||||
boolean interact(BlockHitResult hit);
|
||||
|
||||
void swing();
|
||||
|
||||
/** Мгновенно взгляд строго вниз. */
|
||||
/** Instantly look straight down. */
|
||||
void lookDown();
|
||||
|
||||
void setVelocity(double x, double y, double z);
|
||||
|
||||
/** Включить полёт, если он разрешён. */
|
||||
/** Enable flight if it is allowed. */
|
||||
void enableFlight();
|
||||
|
||||
long nowMs();
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
package dev.loki.satura.interaction.place;
|
||||
|
||||
/** Итог одного тика стратегии. */
|
||||
/** Outcome of a single strategy tick. */
|
||||
public enum PlaceResult {
|
||||
/** Блок поставлен в этом тике. */
|
||||
/** A block was placed this tick. */
|
||||
PLACED,
|
||||
/** Ничего не делали: летим, кулдаун, ждём ответ сервера. */
|
||||
/** Did nothing: flying, cooldown, waiting for the server reply. */
|
||||
WAIT,
|
||||
/** Цель сейчас не поставить (нет опоры / вне досягаемости): движок вправе пересчитать цель. */
|
||||
/** The target cannot be placed now (no support / out of reach): the engine may pick another target. */
|
||||
FAILED
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,19 +5,19 @@ import dev.loki.satura.interaction.place.option.Option;
|
|||
import dev.loki.satura.interaction.place.option.OptionValues;
|
||||
import java.util.List;
|
||||
|
||||
/** Способ ставить блоки в колонну. Движок вызывает {@link #tick} каждый тик, пока колонна не достроена. */
|
||||
/** A way to place blocks into a column. The engine calls {@link #tick} every tick until the column is complete. */
|
||||
public interface PlaceStrategy {
|
||||
|
||||
/** Стабильный ключ для конфига. */
|
||||
/** Stable key for the config. */
|
||||
String id();
|
||||
|
||||
/** Название для GUI. */
|
||||
/** Display name for the GUI. */
|
||||
String label();
|
||||
|
||||
/** Объявление параметров; GUI рисует их генерично. */
|
||||
/** Parameter declarations; the GUI renders them generically. */
|
||||
List<Option> options();
|
||||
|
||||
/** Текущие значения параметров (живые - GUI может менять). */
|
||||
/** Current parameter values (live: the GUI may change them). */
|
||||
OptionValues values();
|
||||
|
||||
PlaceResult tick(PlaceContext ctx, ColumnTarget target);
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import net.minecraft.util.math.Direction;
|
|||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/**
|
||||
* Один клик: ставим блок в {@code target}, кликая по грани {@code face} опоры {@code support}.
|
||||
* {@code standPos} - откуда кликать (может быть {@code null}, если стратегии это не важно).
|
||||
* One click: place a block at {@code target} by clicking face {@code face} of the support {@code support}.
|
||||
* {@code standPos} is where to click from (may be {@code null} if the strategy does not care).
|
||||
*/
|
||||
public record Placement(BlockPos target, BlockPos support, Direction face, Vec3d hitVec, Vec3d standPos) {
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import net.minecraft.util.hit.BlockHitResult;
|
|||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Реальный игрок и мир за интерфейсом {@link PlaceContext}. Клиент передаётся в конструктор. */
|
||||
/** The real player and world behind {@link PlaceContext}. The client is passed to the constructor. */
|
||||
public final class MinecraftPlaceContext implements PlaceContext {
|
||||
|
||||
private static final float PITCH_DOWN = 90.0F;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package dev.loki.satura.interaction.place.option;
|
|||
|
||||
import dev.loki.satura.feature.builder.plan.Planner;
|
||||
|
||||
/** Параметры, общие для нескольких стратегий (значения по yatwinkle BaseBuilder). */
|
||||
/** Parameters shared by several strategies (values follow yatwinkle BaseBuilder). */
|
||||
@SuppressWarnings("PMD.DataClass")
|
||||
public final class CommonOptions {
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.interaction.place.option;
|
||||
|
||||
/** Описание параметра стратегии. Для BOOL: min=0, max=1. */
|
||||
/** Description of a strategy parameter. For BOOL: min=0, max=1. */
|
||||
public record Option(String key, String label, OptionType type,
|
||||
double min, double max, double step, double def) {
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.interaction.place.option;
|
||||
|
||||
/** Вид виджета для параметра. */
|
||||
/** Widget kind for a parameter. */
|
||||
public enum OptionType {
|
||||
INT,
|
||||
DOUBLE,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import java.util.HashMap;
|
|||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Значения параметров стратегии по ключам; всегда в пределах диапазона опции. */
|
||||
/** Strategy parameter values by key; always within the option's range. */
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public final class OptionValues {
|
||||
|
||||
|
|
@ -29,7 +29,7 @@ public final class OptionValues {
|
|||
return get(option) >= 1.0;
|
||||
}
|
||||
|
||||
/** Записать значение по ключу; false - такого параметра нет. */
|
||||
/** Set the value by key; false if there is no such parameter. */
|
||||
public boolean set(final String key, final double value) {
|
||||
final Option option = known.get(key);
|
||||
if (option == null) {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import dev.loki.satura.interaction.place.option.OptionValues;
|
|||
import dev.loki.satura.interaction.place.support.BlockPlacer;
|
||||
import java.util.List;
|
||||
|
||||
/** S2: за один визит колонны ставим 1..3 слоя подряд снизу вверх (yatwinkle bandLayers). */
|
||||
/** S2: place 1..3 layers in a row from bottom to top per column visit (yatwinkle bandLayers). */
|
||||
public final class BandStack implements PlaceStrategy {
|
||||
|
||||
private static final List<Option> DECLARED = List.of(
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import dev.loki.satura.interaction.place.option.OptionValues;
|
|||
import dev.loki.satura.interaction.place.support.BlockPlacer;
|
||||
import java.util.List;
|
||||
|
||||
/** S1: полёт над слоем, pitch=90, по одному слою за визит колонны (yatwinkle без bandLayers). */
|
||||
/** S1: fly above the layer, pitch=90, one layer per column visit (yatwinkle without bandLayers). */
|
||||
public final class ColumnDrop implements PlaceStrategy {
|
||||
|
||||
private static final List<Option> DECLARED = List.of(
|
||||
|
|
|
|||
|
|
@ -12,12 +12,12 @@ import java.util.function.IntSupplier;
|
|||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Ядро yatwinkle-стиля: висим над колонной, смотрим вниз, ставим слои band снизу вверх. */
|
||||
/** Core of the yatwinkle style: hover above the column, look down, place band layers bottom to top. */
|
||||
final class ColumnPlacing {
|
||||
|
||||
/** Запас: глаза 1.62 + ~0.08 (yatwinkle {@code layerY + reach - 1.7}). */
|
||||
/** Margin: eyes 1.62 + ~0.08 (yatwinkle {@code layerY + reach - 1.7}). */
|
||||
static final double EYE_MARGIN = 1.7;
|
||||
/** Столько тиков не повторяем клик в ту же ячейку, пока сервер не ответил. */
|
||||
/** For this many ticks we do not repeat a click on the same cell until the server replies. */
|
||||
static final int PENDING_TTL_TICKS = 2;
|
||||
private static final double FEET_EPS = 0.1;
|
||||
private static final double CENTER = 0.5;
|
||||
|
|
@ -68,7 +68,7 @@ final class ColumnPlacing {
|
|||
return result;
|
||||
}
|
||||
|
||||
/** Ячейки окна: от самой нижней до {@code layers} слоёв вверх (cells - по возрастанию Y). */
|
||||
/** Window cells: from the lowest up to {@code layers} layers (cells are in ascending Y). */
|
||||
static List<BlockPos> band(final List<BlockPos> cells, final int layers) {
|
||||
final List<BlockPos> band = new ArrayList<>();
|
||||
if (cells.isEmpty()) {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package dev.loki.satura.interaction.place.strategy;
|
|||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Скорость полёта setVelocity как в yatwinkle BaseBuilder.flyTo: прямой вектор к точке, без физики клавиш. */
|
||||
/** setVelocity flight speed as in yatwinkle BaseBuilder.flyTo: straight vector to the point, no key physics. */
|
||||
final class FlightControl {
|
||||
|
||||
private static final double ARRIVE_EPS = 0.05;
|
||||
|
|
@ -26,7 +26,7 @@ final class FlightControl {
|
|||
return new Vec3d(vx, vy, vz);
|
||||
}
|
||||
|
||||
/** Высота полёта: min(bandTop+hover, layerY+reach-1.7), но не ниже верха слоя (чтобы не стоять в блоке). */
|
||||
/** Flight height: min(bandTop+hover, layerY+reach-1.7), but not below the layer top (no standing in a block). */
|
||||
static double height(final int layerY, final int bandTop, final double hover,
|
||||
final double reach, final double eyeMargin) {
|
||||
final double capped = Math.min(bandTop + hover, layerY + reach - eyeMargin);
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import dev.loki.satura.interaction.place.Placement;
|
|||
import java.util.Optional;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Общая часть всех стратегий: кулдаун, поиск опоры, клик и взмах руки. */
|
||||
/** Common part of all strategies: cooldown, support lookup, click and hand swing. */
|
||||
public final class BlockPlacer {
|
||||
|
||||
private final SupportFinder finder;
|
||||
|
|
@ -17,7 +17,7 @@ public final class BlockPlacer {
|
|||
this.cooldown = cooldown;
|
||||
}
|
||||
|
||||
/** WAIT - кулдаун; FAILED - нет опоры в досягаемости или клиент отклонил клик; иначе PLACED. */
|
||||
/** WAIT - cooldown; FAILED - no support in reach or the client rejected the click; otherwise PLACED. */
|
||||
public PlaceResult place(final PlaceContext ctx, final BlockPos target,
|
||||
final double reach, final long delayMs) {
|
||||
final long now = ctx.nowMs();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.interaction.place.support;
|
||||
|
||||
/** Кулдаун между постановками в миллисекундах. */
|
||||
/** Cooldown between placements in milliseconds. */
|
||||
public final class Cooldown {
|
||||
|
||||
private long lastMs = Long.MIN_VALUE / 2;
|
||||
|
|
|
|||
|
|
@ -7,10 +7,10 @@ import net.minecraft.util.math.BlockPos;
|
|||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Выбор опоры: сначала снизу, затем остальные 5 направлений (кроме низа). */
|
||||
/** Support selection: below first, then the other 5 directions. */
|
||||
public final class SupportFinder {
|
||||
|
||||
/** Клик по боковой грани чуть ниже верха блока, чтобы не попасть в стык. */
|
||||
/** Click a side face slightly below the block top so as not to hit the seam. */
|
||||
public static final double SIDE_CLICK_Y = 0.94;
|
||||
private static final double HALF = 0.5;
|
||||
|
||||
|
|
@ -30,7 +30,7 @@ public final class SupportFinder {
|
|||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** Порядок осмотра соседей цели: DOWN, затем UP и 4 стороны. */
|
||||
/** Order in which target neighbours are inspected: DOWN, then UP and the 4 sides. */
|
||||
static Direction[] searchOrder() {
|
||||
return new Direction[] {
|
||||
Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST, Direction.UP
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import org.spongepowered.asm.mixin.injection.Inject;
|
|||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ChatInputSuggestor.class)
|
||||
@SuppressWarnings({"PMD.AvoidDollarSigns", "PMD.MethodNamingConventions"})
|
||||
public abstract class ChatInputSuggestorMixin {
|
||||
|
||||
@Shadow @Final TextFieldWidget textField;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,8 @@ import org.spongepowered.asm.mixin.injection.Inject;
|
|||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ChatScreen.class)
|
||||
@SuppressWarnings("PMD.AbstractClassWithoutAbstractMethod")
|
||||
@SuppressWarnings({"PMD.AbstractClassWithoutAbstractMethod", "PMD.AvoidDollarSigns",
|
||||
"PMD.MethodNamingConventions"})
|
||||
public abstract class ChatScreenMixin {
|
||||
|
||||
@Inject(method = "sendMessage", at = @At("HEAD"), cancellable = true)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import dev.loki.satura.render.geom.Bounds;
|
|||
import dev.loki.satura.render.msdf.MsdfFont;
|
||||
import dev.loki.satura.render.msdf.MsdfFonts;
|
||||
|
||||
/** Тестовая отрисовка возможностей рендера; только при -Dsatura.renderDebug=true. */
|
||||
/** Test drawing of render capabilities; only with -Dsatura.renderDebug=true. */
|
||||
public final class RenderDebug {
|
||||
|
||||
private static final String FLAG = "satura.renderDebug";
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import java.util.ArrayList;
|
|||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Очереди отрисовки "поверх GUI": постоянные оверлеи и разовые задачи на кадр.
|
||||
* Вызывается из GameRenderer после того, как ванильный GUI уже нарисован.
|
||||
* Draw queues "above the GUI": persistent overlays and one-off per-frame tasks.
|
||||
* Called from GameRenderer after the vanilla GUI has already been drawn.
|
||||
*/
|
||||
public final class RenderHooks {
|
||||
|
||||
|
|
|
|||
|
|
@ -18,9 +18,9 @@ import net.minecraft.client.MinecraftClient;
|
|||
import net.minecraft.util.Identifier;
|
||||
|
||||
/**
|
||||
* Фасад рендера: скруглённые прямоугольники, обводка, свечение, тень, блюр, текстуры, MSDF-текст, scissor.
|
||||
* Координаты — GUI (как у DrawContext), цвета — ARGB int. Рисует прямо в главный фреймбуфер,
|
||||
* поэтому для отображения поверх ванильного GUI вызывать из {@link #onFrame} / {@link #defer}.
|
||||
* Render facade: rounded rectangles, outline, glow, shadow, blur, textures, MSDF text, scissor.
|
||||
* Coordinates are GUI (like DrawContext), colors are ARGB int. Draws straight into the main framebuffer,
|
||||
* so to render above the vanilla GUI call it from {@link #onFrame} / {@link #defer}.
|
||||
*/
|
||||
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
|
||||
public final class Renderer {
|
||||
|
|
@ -119,12 +119,12 @@ public final class Renderer {
|
|||
scissor.pop();
|
||||
}
|
||||
|
||||
/** Постоянный оверлей: вызывается каждый кадр поверх всего GUI. */
|
||||
/** Persistent overlay: called every frame above the whole GUI. */
|
||||
public void onFrame(Runnable overlay) {
|
||||
hooks.addOverlay(overlay);
|
||||
}
|
||||
|
||||
/** Разовая задача: выполнится в конце текущего кадра поверх GUI (для вызова из HUD/Screen). */
|
||||
/** One-off task: runs at the end of the current frame above the GUI (for calls from HUD/Screen). */
|
||||
public void defer(Runnable task) {
|
||||
hooks.defer(task);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
package dev.loki.satura.render;
|
||||
|
||||
/** Палитра и размеры оформления (минимализм): цвета ARGB, радиусы в GUI-единицах. */
|
||||
/** Palette and styling sizes (minimalism): ARGB colors, radii in GUI units. */
|
||||
@SuppressWarnings("PMD.DataClass")
|
||||
public final class Theme {
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import dev.loki.satura.render.gpu.UniformData;
|
|||
import java.nio.ByteBuffer;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/** Запись юниформа BlurData для промежуточных проходов и финального вывода. */
|
||||
/** Writes the BlurData uniform for intermediate passes and the final output. */
|
||||
final class BlurData {
|
||||
|
||||
static final int SIZE = 256;
|
||||
|
|
|
|||
|
|
@ -32,8 +32,8 @@ import org.slf4j.Logger;
|
|||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Блюр фона под прямоугольником: копия кадра, даунсэмпл, N проходов размытия, вывод со скруглением.
|
||||
* Размытие пересчитывается раз в кадр, остальные вызовы переиспользуют результат.
|
||||
* Background blur under a rectangle: frame copy, downsample, N blur passes, output with rounding.
|
||||
* The blur is recomputed once per frame; other calls reuse the result.
|
||||
*/
|
||||
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.InvalidLogMessageFormat", "PMD.CloseResource"})
|
||||
public final class BlurPipeline {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import com.mojang.blaze3d.textures.GpuTexture;
|
|||
import com.mojang.blaze3d.textures.GpuTextureView;
|
||||
import com.mojang.blaze3d.textures.TextureFormat;
|
||||
|
||||
/** Текстуры блюра: копия кадра полного размера и два буфера половинного размера (ping-pong). */
|
||||
/** Blur textures: a full-size frame copy and two half-size buffers (ping-pong). */
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"})
|
||||
final class BlurTargets {
|
||||
|
||||
|
|
@ -19,7 +19,7 @@ final class BlurTargets {
|
|||
private int width;
|
||||
private int height;
|
||||
|
||||
/** Пересоздаёт текстуры при смене размера; true — если пересоздали. */
|
||||
/** Recreates the textures on a size change; true if they were recreated. */
|
||||
boolean ensure(int fbWidth, int fbHeight) {
|
||||
if (copy != null && fbWidth == width && fbHeight == height) {
|
||||
return false;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue